* config/i386/i386.c (ix86_legitimize_address): Declare
[official-gcc.git] / gcc / tree-eh.c
blob5d151f721e4cfd799b2bdda223e5cd682ba84c12
1 /* Exception handling semantics and decomposition for trees.
2 Copyright (C) 2003-2014 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 "hash-table.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "expr.h"
27 #include "calls.h"
28 #include "flags.h"
29 #include "hashtab.h"
30 #include "hash-set.h"
31 #include "vec.h"
32 #include "machmode.h"
33 #include "hard-reg-set.h"
34 #include "input.h"
35 #include "function.h"
36 #include "except.h"
37 #include "predict.h"
38 #include "dominance.h"
39 #include "cfg.h"
40 #include "cfganal.h"
41 #include "cfgcleanup.h"
42 #include "basic-block.h"
43 #include "tree-ssa-alias.h"
44 #include "internal-fn.h"
45 #include "tree-eh.h"
46 #include "gimple-expr.h"
47 #include "is-a.h"
48 #include "gimple.h"
49 #include "gimple-iterator.h"
50 #include "gimple-ssa.h"
51 #include "hash-map.h"
52 #include "plugin-api.h"
53 #include "ipa-ref.h"
54 #include "cgraph.h"
55 #include "tree-cfg.h"
56 #include "tree-phinodes.h"
57 #include "ssa-iterators.h"
58 #include "stringpool.h"
59 #include "tree-ssanames.h"
60 #include "tree-into-ssa.h"
61 #include "tree-ssa.h"
62 #include "tree-inline.h"
63 #include "tree-pass.h"
64 #include "langhooks.h"
65 #include "diagnostic-core.h"
66 #include "target.h"
67 #include "cfgloop.h"
68 #include "gimple-low.h"
70 /* In some instances a tree and a gimple need to be stored in a same table,
71 i.e. in hash tables. This is a structure to do this. */
72 typedef union {tree *tp; tree t; gimple g;} treemple;
74 /* Misc functions used in this file. */
76 /* Remember and lookup EH landing pad data for arbitrary statements.
77 Really this means any statement that could_throw_p. We could
78 stuff this information into the stmt_ann data structure, but:
80 (1) We absolutely rely on this information being kept until
81 we get to rtl. Once we're done with lowering here, if we lose
82 the information there's no way to recover it!
84 (2) There are many more statements that *cannot* throw as
85 compared to those that can. We should be saving some amount
86 of space by only allocating memory for those that can throw. */
88 /* Add statement T in function IFUN to landing pad NUM. */
90 static void
91 add_stmt_to_eh_lp_fn (struct function *ifun, gimple t, int num)
93 gcc_assert (num != 0);
95 if (!get_eh_throw_stmt_table (ifun))
96 set_eh_throw_stmt_table (ifun, hash_map<gimple, int>::create_ggc (31));
98 gcc_assert (!get_eh_throw_stmt_table (ifun)->put (t, num));
101 /* Add statement T in the current function (cfun) to EH landing pad NUM. */
103 void
104 add_stmt_to_eh_lp (gimple t, int num)
106 add_stmt_to_eh_lp_fn (cfun, t, num);
109 /* Add statement T to the single EH landing pad in REGION. */
111 static void
112 record_stmt_eh_region (eh_region region, gimple t)
114 if (region == NULL)
115 return;
116 if (region->type == ERT_MUST_NOT_THROW)
117 add_stmt_to_eh_lp_fn (cfun, t, -region->index);
118 else
120 eh_landing_pad lp = region->landing_pads;
121 if (lp == NULL)
122 lp = gen_eh_landing_pad (region);
123 else
124 gcc_assert (lp->next_lp == NULL);
125 add_stmt_to_eh_lp_fn (cfun, t, lp->index);
130 /* Remove statement T in function IFUN from its EH landing pad. */
132 bool
133 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple t)
135 if (!get_eh_throw_stmt_table (ifun))
136 return false;
138 if (!get_eh_throw_stmt_table (ifun)->get (t))
139 return false;
141 get_eh_throw_stmt_table (ifun)->remove (t);
142 return true;
146 /* Remove statement T in the current function (cfun) from its
147 EH landing pad. */
149 bool
150 remove_stmt_from_eh_lp (gimple t)
152 return remove_stmt_from_eh_lp_fn (cfun, t);
155 /* Determine if statement T is inside an EH region in function IFUN.
156 Positive numbers indicate a landing pad index; negative numbers
157 indicate a MUST_NOT_THROW region index; zero indicates that the
158 statement is not recorded in the region table. */
161 lookup_stmt_eh_lp_fn (struct function *ifun, gimple t)
163 if (ifun->eh->throw_stmt_table == NULL)
164 return 0;
166 int *lp_nr = ifun->eh->throw_stmt_table->get (t);
167 return lp_nr ? *lp_nr : 0;
170 /* Likewise, but always use the current function. */
173 lookup_stmt_eh_lp (gimple t)
175 /* We can get called from initialized data when -fnon-call-exceptions
176 is on; prevent crash. */
177 if (!cfun)
178 return 0;
179 return lookup_stmt_eh_lp_fn (cfun, t);
182 /* First pass of EH node decomposition. Build up a tree of GIMPLE_TRY_FINALLY
183 nodes and LABEL_DECL nodes. We will use this during the second phase to
184 determine if a goto leaves the body of a TRY_FINALLY_EXPR node. */
186 struct finally_tree_node
188 /* When storing a GIMPLE_TRY, we have to record a gimple. However
189 when deciding whether a GOTO to a certain LABEL_DECL (which is a
190 tree) leaves the TRY block, its necessary to record a tree in
191 this field. Thus a treemple is used. */
192 treemple child;
193 gtry *parent;
196 /* Hashtable helpers. */
198 struct finally_tree_hasher : typed_free_remove <finally_tree_node>
200 typedef finally_tree_node value_type;
201 typedef finally_tree_node compare_type;
202 static inline hashval_t hash (const value_type *);
203 static inline bool equal (const value_type *, const compare_type *);
206 inline hashval_t
207 finally_tree_hasher::hash (const value_type *v)
209 return (intptr_t)v->child.t >> 4;
212 inline bool
213 finally_tree_hasher::equal (const value_type *v, const compare_type *c)
215 return v->child.t == c->child.t;
218 /* Note that this table is *not* marked GTY. It is short-lived. */
219 static hash_table<finally_tree_hasher> *finally_tree;
221 static void
222 record_in_finally_tree (treemple child, gtry *parent)
224 struct finally_tree_node *n;
225 finally_tree_node **slot;
227 n = XNEW (struct finally_tree_node);
228 n->child = child;
229 n->parent = parent;
231 slot = finally_tree->find_slot (n, INSERT);
232 gcc_assert (!*slot);
233 *slot = n;
236 static void
237 collect_finally_tree (gimple stmt, gtry *region);
239 /* Go through the gimple sequence. Works with collect_finally_tree to
240 record all GIMPLE_LABEL and GIMPLE_TRY statements. */
242 static void
243 collect_finally_tree_1 (gimple_seq seq, gtry *region)
245 gimple_stmt_iterator gsi;
247 for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
248 collect_finally_tree (gsi_stmt (gsi), region);
251 static void
252 collect_finally_tree (gimple stmt, gtry *region)
254 treemple temp;
256 switch (gimple_code (stmt))
258 case GIMPLE_LABEL:
259 temp.t = gimple_label_label (as_a <glabel *> (stmt));
260 record_in_finally_tree (temp, region);
261 break;
263 case GIMPLE_TRY:
264 if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
266 temp.g = stmt;
267 record_in_finally_tree (temp, region);
268 collect_finally_tree_1 (gimple_try_eval (stmt),
269 as_a <gtry *> (stmt));
270 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
272 else if (gimple_try_kind (stmt) == GIMPLE_TRY_CATCH)
274 collect_finally_tree_1 (gimple_try_eval (stmt), region);
275 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
277 break;
279 case GIMPLE_CATCH:
280 collect_finally_tree_1 (gimple_catch_handler (
281 as_a <gcatch *> (stmt)),
282 region);
283 break;
285 case GIMPLE_EH_FILTER:
286 collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
287 break;
289 case GIMPLE_EH_ELSE:
291 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
292 collect_finally_tree_1 (gimple_eh_else_n_body (eh_else_stmt), region);
293 collect_finally_tree_1 (gimple_eh_else_e_body (eh_else_stmt), region);
295 break;
297 default:
298 /* A type, a decl, or some kind of statement that we're not
299 interested in. Don't walk them. */
300 break;
305 /* Use the finally tree to determine if a jump from START to TARGET
306 would leave the try_finally node that START lives in. */
308 static bool
309 outside_finally_tree (treemple start, gimple target)
311 struct finally_tree_node n, *p;
315 n.child = start;
316 p = finally_tree->find (&n);
317 if (!p)
318 return true;
319 start.g = p->parent;
321 while (start.g != target);
323 return false;
326 /* Second pass of EH node decomposition. Actually transform the GIMPLE_TRY
327 nodes into a set of gotos, magic labels, and eh regions.
328 The eh region creation is straight-forward, but frobbing all the gotos
329 and such into shape isn't. */
331 /* The sequence into which we record all EH stuff. This will be
332 placed at the end of the function when we're all done. */
333 static gimple_seq eh_seq;
335 /* Record whether an EH region contains something that can throw,
336 indexed by EH region number. */
337 static bitmap eh_region_may_contain_throw_map;
339 /* The GOTO_QUEUE is is an array of GIMPLE_GOTO and GIMPLE_RETURN
340 statements that are seen to escape this GIMPLE_TRY_FINALLY node.
341 The idea is to record a gimple statement for everything except for
342 the conditionals, which get their labels recorded. Since labels are
343 of type 'tree', we need this node to store both gimple and tree
344 objects. REPL_STMT is the sequence used to replace the goto/return
345 statement. CONT_STMT is used to store the statement that allows
346 the return/goto to jump to the original destination. */
348 struct goto_queue_node
350 treemple stmt;
351 location_t location;
352 gimple_seq repl_stmt;
353 gimple cont_stmt;
354 int index;
355 /* This is used when index >= 0 to indicate that stmt is a label (as
356 opposed to a goto stmt). */
357 int is_label;
360 /* State of the world while lowering. */
362 struct leh_state
364 /* What's "current" while constructing the eh region tree. These
365 correspond to variables of the same name in cfun->eh, which we
366 don't have easy access to. */
367 eh_region cur_region;
369 /* What's "current" for the purposes of __builtin_eh_pointer. For
370 a CATCH, this is the associated TRY. For an EH_FILTER, this is
371 the associated ALLOWED_EXCEPTIONS, etc. */
372 eh_region ehp_region;
374 /* Processing of TRY_FINALLY requires a bit more state. This is
375 split out into a separate structure so that we don't have to
376 copy so much when processing other nodes. */
377 struct leh_tf_state *tf;
380 struct leh_tf_state
382 /* Pointer to the GIMPLE_TRY_FINALLY node under discussion. The
383 try_finally_expr is the original GIMPLE_TRY_FINALLY. We need to retain
384 this so that outside_finally_tree can reliably reference the tree used
385 in the collect_finally_tree data structures. */
386 gtry *try_finally_expr;
387 gtry *top_p;
389 /* While lowering a top_p usually it is expanded into multiple statements,
390 thus we need the following field to store them. */
391 gimple_seq top_p_seq;
393 /* The state outside this try_finally node. */
394 struct leh_state *outer;
396 /* The exception region created for it. */
397 eh_region region;
399 /* The goto queue. */
400 struct goto_queue_node *goto_queue;
401 size_t goto_queue_size;
402 size_t goto_queue_active;
404 /* Pointer map to help in searching goto_queue when it is large. */
405 hash_map<gimple, goto_queue_node *> *goto_queue_map;
407 /* The set of unique labels seen as entries in the goto queue. */
408 vec<tree> dest_array;
410 /* A label to be added at the end of the completed transformed
411 sequence. It will be set if may_fallthru was true *at one time*,
412 though subsequent transformations may have cleared that flag. */
413 tree fallthru_label;
415 /* True if it is possible to fall out the bottom of the try block.
416 Cleared if the fallthru is converted to a goto. */
417 bool may_fallthru;
419 /* True if any entry in goto_queue is a GIMPLE_RETURN. */
420 bool may_return;
422 /* True if the finally block can receive an exception edge.
423 Cleared if the exception case is handled by code duplication. */
424 bool may_throw;
427 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gtry *);
429 /* Search for STMT in the goto queue. Return the replacement,
430 or null if the statement isn't in the queue. */
432 #define LARGE_GOTO_QUEUE 20
434 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq *seq);
436 static gimple_seq
437 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
439 unsigned int i;
441 if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
443 for (i = 0; i < tf->goto_queue_active; i++)
444 if ( tf->goto_queue[i].stmt.g == stmt.g)
445 return tf->goto_queue[i].repl_stmt;
446 return NULL;
449 /* If we have a large number of entries in the goto_queue, create a
450 pointer map and use that for searching. */
452 if (!tf->goto_queue_map)
454 tf->goto_queue_map = new hash_map<gimple, goto_queue_node *>;
455 for (i = 0; i < tf->goto_queue_active; i++)
457 bool existed = tf->goto_queue_map->put (tf->goto_queue[i].stmt.g,
458 &tf->goto_queue[i]);
459 gcc_assert (!existed);
463 goto_queue_node **slot = tf->goto_queue_map->get (stmt.g);
464 if (slot != NULL)
465 return ((*slot)->repl_stmt);
467 return NULL;
470 /* A subroutine of replace_goto_queue_1. Handles the sub-clauses of a
471 lowered GIMPLE_COND. If, by chance, the replacement is a simple goto,
472 then we can just splat it in, otherwise we add the new stmts immediately
473 after the GIMPLE_COND and redirect. */
475 static void
476 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
477 gimple_stmt_iterator *gsi)
479 tree label;
480 gimple_seq new_seq;
481 treemple temp;
482 location_t loc = gimple_location (gsi_stmt (*gsi));
484 temp.tp = tp;
485 new_seq = find_goto_replacement (tf, temp);
486 if (!new_seq)
487 return;
489 if (gimple_seq_singleton_p (new_seq)
490 && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
492 *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
493 return;
496 label = create_artificial_label (loc);
497 /* Set the new label for the GIMPLE_COND */
498 *tp = label;
500 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
501 gsi_insert_seq_after (gsi, gimple_seq_copy (new_seq), GSI_CONTINUE_LINKING);
504 /* The real work of replace_goto_queue. Returns with TSI updated to
505 point to the next statement. */
507 static void replace_goto_queue_stmt_list (gimple_seq *, struct leh_tf_state *);
509 static void
510 replace_goto_queue_1 (gimple stmt, struct leh_tf_state *tf,
511 gimple_stmt_iterator *gsi)
513 gimple_seq seq;
514 treemple temp;
515 temp.g = NULL;
517 switch (gimple_code (stmt))
519 case GIMPLE_GOTO:
520 case GIMPLE_RETURN:
521 temp.g = stmt;
522 seq = find_goto_replacement (tf, temp);
523 if (seq)
525 gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
526 gsi_remove (gsi, false);
527 return;
529 break;
531 case GIMPLE_COND:
532 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 2), tf, gsi);
533 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 3), tf, gsi);
534 break;
536 case GIMPLE_TRY:
537 replace_goto_queue_stmt_list (gimple_try_eval_ptr (stmt), tf);
538 replace_goto_queue_stmt_list (gimple_try_cleanup_ptr (stmt), tf);
539 break;
540 case GIMPLE_CATCH:
541 replace_goto_queue_stmt_list (gimple_catch_handler_ptr (
542 as_a <gcatch *> (stmt)),
543 tf);
544 break;
545 case GIMPLE_EH_FILTER:
546 replace_goto_queue_stmt_list (gimple_eh_filter_failure_ptr (stmt), tf);
547 break;
548 case GIMPLE_EH_ELSE:
550 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
551 replace_goto_queue_stmt_list (gimple_eh_else_n_body_ptr (eh_else_stmt),
552 tf);
553 replace_goto_queue_stmt_list (gimple_eh_else_e_body_ptr (eh_else_stmt),
554 tf);
556 break;
558 default:
559 /* These won't have gotos in them. */
560 break;
563 gsi_next (gsi);
566 /* A subroutine of replace_goto_queue. Handles GIMPLE_SEQ. */
568 static void
569 replace_goto_queue_stmt_list (gimple_seq *seq, struct leh_tf_state *tf)
571 gimple_stmt_iterator gsi = gsi_start (*seq);
573 while (!gsi_end_p (gsi))
574 replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
577 /* Replace all goto queue members. */
579 static void
580 replace_goto_queue (struct leh_tf_state *tf)
582 if (tf->goto_queue_active == 0)
583 return;
584 replace_goto_queue_stmt_list (&tf->top_p_seq, tf);
585 replace_goto_queue_stmt_list (&eh_seq, tf);
588 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
589 data to be added, IS_LABEL indicates whether NEW_STMT is a label or
590 a gimple return. */
592 static void
593 record_in_goto_queue (struct leh_tf_state *tf,
594 treemple new_stmt,
595 int index,
596 bool is_label,
597 location_t location)
599 size_t active, size;
600 struct goto_queue_node *q;
602 gcc_assert (!tf->goto_queue_map);
604 active = tf->goto_queue_active;
605 size = tf->goto_queue_size;
606 if (active >= size)
608 size = (size ? size * 2 : 32);
609 tf->goto_queue_size = size;
610 tf->goto_queue
611 = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
614 q = &tf->goto_queue[active];
615 tf->goto_queue_active = active + 1;
617 memset (q, 0, sizeof (*q));
618 q->stmt = new_stmt;
619 q->index = index;
620 q->location = location;
621 q->is_label = is_label;
624 /* Record the LABEL label in the goto queue contained in TF.
625 TF is not null. */
627 static void
628 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label,
629 location_t location)
631 int index;
632 treemple temp, new_stmt;
634 if (!label)
635 return;
637 /* Computed and non-local gotos do not get processed. Given
638 their nature we can neither tell whether we've escaped the
639 finally block nor redirect them if we knew. */
640 if (TREE_CODE (label) != LABEL_DECL)
641 return;
643 /* No need to record gotos that don't leave the try block. */
644 temp.t = label;
645 if (!outside_finally_tree (temp, tf->try_finally_expr))
646 return;
648 if (! tf->dest_array.exists ())
650 tf->dest_array.create (10);
651 tf->dest_array.quick_push (label);
652 index = 0;
654 else
656 int n = tf->dest_array.length ();
657 for (index = 0; index < n; ++index)
658 if (tf->dest_array[index] == label)
659 break;
660 if (index == n)
661 tf->dest_array.safe_push (label);
664 /* In the case of a GOTO we want to record the destination label,
665 since with a GIMPLE_COND we have an easy access to the then/else
666 labels. */
667 new_stmt = stmt;
668 record_in_goto_queue (tf, new_stmt, index, true, location);
671 /* For any GIMPLE_GOTO or GIMPLE_RETURN, decide whether it leaves a try_finally
672 node, and if so record that fact in the goto queue associated with that
673 try_finally node. */
675 static void
676 maybe_record_in_goto_queue (struct leh_state *state, gimple stmt)
678 struct leh_tf_state *tf = state->tf;
679 treemple new_stmt;
681 if (!tf)
682 return;
684 switch (gimple_code (stmt))
686 case GIMPLE_COND:
688 gcond *cond_stmt = as_a <gcond *> (stmt);
689 new_stmt.tp = gimple_op_ptr (cond_stmt, 2);
690 record_in_goto_queue_label (tf, new_stmt,
691 gimple_cond_true_label (cond_stmt),
692 EXPR_LOCATION (*new_stmt.tp));
693 new_stmt.tp = gimple_op_ptr (cond_stmt, 3);
694 record_in_goto_queue_label (tf, new_stmt,
695 gimple_cond_false_label (cond_stmt),
696 EXPR_LOCATION (*new_stmt.tp));
698 break;
699 case GIMPLE_GOTO:
700 new_stmt.g = stmt;
701 record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt),
702 gimple_location (stmt));
703 break;
705 case GIMPLE_RETURN:
706 tf->may_return = true;
707 new_stmt.g = stmt;
708 record_in_goto_queue (tf, new_stmt, -1, false, gimple_location (stmt));
709 break;
711 default:
712 gcc_unreachable ();
717 #ifdef ENABLE_CHECKING
718 /* We do not process GIMPLE_SWITCHes for now. As long as the original source
719 was in fact structured, and we've not yet done jump threading, then none
720 of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this. */
722 static void
723 verify_norecord_switch_expr (struct leh_state *state,
724 gswitch *switch_expr)
726 struct leh_tf_state *tf = state->tf;
727 size_t i, n;
729 if (!tf)
730 return;
732 n = gimple_switch_num_labels (switch_expr);
734 for (i = 0; i < n; ++i)
736 treemple temp;
737 tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
738 temp.t = lab;
739 gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
742 #else
743 #define verify_norecord_switch_expr(state, switch_expr)
744 #endif
746 /* Redirect a RETURN_EXPR pointed to by Q to FINLAB. If MOD is
747 non-null, insert it before the new branch. */
749 static void
750 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod)
752 gimple x;
754 /* In the case of a return, the queue node must be a gimple statement. */
755 gcc_assert (!q->is_label);
757 /* Note that the return value may have already been computed, e.g.,
759 int x;
760 int foo (void)
762 x = 0;
763 try {
764 return x;
765 } finally {
766 x++;
770 should return 0, not 1. We don't have to do anything to make
771 this happens because the return value has been placed in the
772 RESULT_DECL already. */
774 q->cont_stmt = q->stmt.g;
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 /* Similar, but easier, for GIMPLE_GOTO. */
786 static void
787 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
788 struct leh_tf_state *tf)
790 ggoto *x;
792 gcc_assert (q->is_label);
794 q->cont_stmt = gimple_build_goto (tf->dest_array[q->index]);
796 if (mod)
797 gimple_seq_add_seq (&q->repl_stmt, mod);
799 x = gimple_build_goto (finlab);
800 gimple_set_location (x, q->location);
801 gimple_seq_add_stmt (&q->repl_stmt, x);
804 /* Emit a standard landing pad sequence into SEQ for REGION. */
806 static void
807 emit_post_landing_pad (gimple_seq *seq, eh_region region)
809 eh_landing_pad lp = region->landing_pads;
810 glabel *x;
812 if (lp == NULL)
813 lp = gen_eh_landing_pad (region);
815 lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
816 EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
818 x = gimple_build_label (lp->post_landing_pad);
819 gimple_seq_add_stmt (seq, x);
822 /* Emit a RESX statement into SEQ for REGION. */
824 static void
825 emit_resx (gimple_seq *seq, eh_region region)
827 gresx *x = gimple_build_resx (region->index);
828 gimple_seq_add_stmt (seq, x);
829 if (region->outer)
830 record_stmt_eh_region (region->outer, x);
833 /* Emit an EH_DISPATCH statement into SEQ for REGION. */
835 static void
836 emit_eh_dispatch (gimple_seq *seq, eh_region region)
838 geh_dispatch *x = gimple_build_eh_dispatch (region->index);
839 gimple_seq_add_stmt (seq, x);
842 /* Note that the current EH region may contain a throw, or a
843 call to a function which itself may contain a throw. */
845 static void
846 note_eh_region_may_contain_throw (eh_region region)
848 while (bitmap_set_bit (eh_region_may_contain_throw_map, region->index))
850 if (region->type == ERT_MUST_NOT_THROW)
851 break;
852 region = region->outer;
853 if (region == NULL)
854 break;
858 /* Check if REGION has been marked as containing a throw. If REGION is
859 NULL, this predicate is false. */
861 static inline bool
862 eh_region_may_contain_throw (eh_region r)
864 return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
867 /* We want to transform
868 try { body; } catch { stuff; }
870 normal_seqence:
871 body;
872 over:
873 eh_seqence:
874 landing_pad:
875 stuff;
876 goto over;
878 TP is a GIMPLE_TRY node. REGION is the region whose post_landing_pad
879 should be placed before the second operand, or NULL. OVER is
880 an existing label that should be put at the exit, or NULL. */
882 static gimple_seq
883 frob_into_branch_around (gtry *tp, eh_region region, tree over)
885 gimple x;
886 gimple_seq cleanup, result;
887 location_t loc = gimple_location (tp);
889 cleanup = gimple_try_cleanup (tp);
890 result = gimple_try_eval (tp);
892 if (region)
893 emit_post_landing_pad (&eh_seq, region);
895 if (gimple_seq_may_fallthru (cleanup))
897 if (!over)
898 over = create_artificial_label (loc);
899 x = gimple_build_goto (over);
900 gimple_set_location (x, loc);
901 gimple_seq_add_stmt (&cleanup, x);
903 gimple_seq_add_seq (&eh_seq, cleanup);
905 if (over)
907 x = gimple_build_label (over);
908 gimple_seq_add_stmt (&result, x);
910 return result;
913 /* A subroutine of lower_try_finally. Duplicate the tree rooted at T.
914 Make sure to record all new labels found. */
916 static gimple_seq
917 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state,
918 location_t loc)
920 gtry *region = NULL;
921 gimple_seq new_seq;
922 gimple_stmt_iterator gsi;
924 new_seq = copy_gimple_seq_and_replace_locals (seq);
926 for (gsi = gsi_start (new_seq); !gsi_end_p (gsi); gsi_next (&gsi))
928 gimple stmt = gsi_stmt (gsi);
929 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
931 tree block = gimple_block (stmt);
932 gimple_set_location (stmt, loc);
933 gimple_set_block (stmt, block);
937 if (outer_state->tf)
938 region = outer_state->tf->try_finally_expr;
939 collect_finally_tree_1 (new_seq, region);
941 return new_seq;
944 /* A subroutine of lower_try_finally. Create a fallthru label for
945 the given try_finally state. The only tricky bit here is that
946 we have to make sure to record the label in our outer context. */
948 static tree
949 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
951 tree label = tf->fallthru_label;
952 treemple temp;
954 if (!label)
956 label = create_artificial_label (gimple_location (tf->try_finally_expr));
957 tf->fallthru_label = label;
958 if (tf->outer->tf)
960 temp.t = label;
961 record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
964 return label;
967 /* A subroutine of lower_try_finally. If FINALLY consits of a
968 GIMPLE_EH_ELSE node, return it. */
970 static inline geh_else *
971 get_eh_else (gimple_seq finally)
973 gimple x = gimple_seq_first_stmt (finally);
974 if (gimple_code (x) == GIMPLE_EH_ELSE)
976 gcc_assert (gimple_seq_singleton_p (finally));
977 return as_a <geh_else *> (x);
979 return NULL;
982 /* A subroutine of lower_try_finally. If the eh_protect_cleanup_actions
983 langhook returns non-null, then the language requires that the exception
984 path out of a try_finally be treated specially. To wit: the code within
985 the finally block may not itself throw an exception. We have two choices
986 here. First we can duplicate the finally block and wrap it in a
987 must_not_throw region. Second, we can generate code like
989 try {
990 finally_block;
991 } catch {
992 if (fintmp == eh_edge)
993 protect_cleanup_actions;
996 where "fintmp" is the temporary used in the switch statement generation
997 alternative considered below. For the nonce, we always choose the first
998 option.
1000 THIS_STATE may be null if this is a try-cleanup, not a try-finally. */
1002 static void
1003 honor_protect_cleanup_actions (struct leh_state *outer_state,
1004 struct leh_state *this_state,
1005 struct leh_tf_state *tf)
1007 tree protect_cleanup_actions;
1008 gimple_stmt_iterator gsi;
1009 bool finally_may_fallthru;
1010 gimple_seq finally;
1011 gimple x;
1012 geh_mnt *eh_mnt;
1013 gtry *try_stmt;
1014 geh_else *eh_else;
1016 /* First check for nothing to do. */
1017 if (lang_hooks.eh_protect_cleanup_actions == NULL)
1018 return;
1019 protect_cleanup_actions = lang_hooks.eh_protect_cleanup_actions ();
1020 if (protect_cleanup_actions == NULL)
1021 return;
1023 finally = gimple_try_cleanup (tf->top_p);
1024 eh_else = get_eh_else (finally);
1026 /* Duplicate the FINALLY block. Only need to do this for try-finally,
1027 and not for cleanups. If we've got an EH_ELSE, extract it now. */
1028 if (eh_else)
1030 finally = gimple_eh_else_e_body (eh_else);
1031 gimple_try_set_cleanup (tf->top_p, gimple_eh_else_n_body (eh_else));
1033 else if (this_state)
1034 finally = lower_try_finally_dup_block (finally, outer_state,
1035 gimple_location (tf->try_finally_expr));
1036 finally_may_fallthru = gimple_seq_may_fallthru (finally);
1038 /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1039 set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1040 to be in an enclosing scope, but needs to be implemented at this level
1041 to avoid a nesting violation (see wrap_temporary_cleanups in
1042 cp/decl.c). Since it's logically at an outer level, we should call
1043 terminate before we get to it, so strip it away before adding the
1044 MUST_NOT_THROW filter. */
1045 gsi = gsi_start (finally);
1046 x = gsi_stmt (gsi);
1047 if (gimple_code (x) == GIMPLE_TRY
1048 && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1049 && gimple_try_catch_is_cleanup (x))
1051 gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1052 gsi_remove (&gsi, false);
1055 /* Wrap the block with protect_cleanup_actions as the action. */
1056 eh_mnt = gimple_build_eh_must_not_throw (protect_cleanup_actions);
1057 try_stmt = gimple_build_try (finally, gimple_seq_alloc_with_stmt (eh_mnt),
1058 GIMPLE_TRY_CATCH);
1059 finally = lower_eh_must_not_throw (outer_state, try_stmt);
1061 /* Drop all of this into the exception sequence. */
1062 emit_post_landing_pad (&eh_seq, tf->region);
1063 gimple_seq_add_seq (&eh_seq, finally);
1064 if (finally_may_fallthru)
1065 emit_resx (&eh_seq, tf->region);
1067 /* Having now been handled, EH isn't to be considered with
1068 the rest of the outgoing edges. */
1069 tf->may_throw = false;
1072 /* A subroutine of lower_try_finally. We have determined that there is
1073 no fallthru edge out of the finally block. This means that there is
1074 no outgoing edge corresponding to any incoming edge. Restructure the
1075 try_finally node for this special case. */
1077 static void
1078 lower_try_finally_nofallthru (struct leh_state *state,
1079 struct leh_tf_state *tf)
1081 tree lab;
1082 gimple x;
1083 geh_else *eh_else;
1084 gimple_seq finally;
1085 struct goto_queue_node *q, *qe;
1087 lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1089 /* We expect that tf->top_p is a GIMPLE_TRY. */
1090 finally = gimple_try_cleanup (tf->top_p);
1091 tf->top_p_seq = gimple_try_eval (tf->top_p);
1093 x = gimple_build_label (lab);
1094 gimple_seq_add_stmt (&tf->top_p_seq, x);
1096 q = tf->goto_queue;
1097 qe = q + tf->goto_queue_active;
1098 for (; q < qe; ++q)
1099 if (q->index < 0)
1100 do_return_redirection (q, lab, NULL);
1101 else
1102 do_goto_redirection (q, lab, NULL, tf);
1104 replace_goto_queue (tf);
1106 /* Emit the finally block into the stream. Lower EH_ELSE at this time. */
1107 eh_else = get_eh_else (finally);
1108 if (eh_else)
1110 finally = gimple_eh_else_n_body (eh_else);
1111 lower_eh_constructs_1 (state, &finally);
1112 gimple_seq_add_seq (&tf->top_p_seq, finally);
1114 if (tf->may_throw)
1116 finally = gimple_eh_else_e_body (eh_else);
1117 lower_eh_constructs_1 (state, &finally);
1119 emit_post_landing_pad (&eh_seq, tf->region);
1120 gimple_seq_add_seq (&eh_seq, finally);
1123 else
1125 lower_eh_constructs_1 (state, &finally);
1126 gimple_seq_add_seq (&tf->top_p_seq, finally);
1128 if (tf->may_throw)
1130 emit_post_landing_pad (&eh_seq, tf->region);
1132 x = gimple_build_goto (lab);
1133 gimple_set_location (x, gimple_location (tf->try_finally_expr));
1134 gimple_seq_add_stmt (&eh_seq, x);
1139 /* A subroutine of lower_try_finally. We have determined that there is
1140 exactly one destination of the finally block. Restructure the
1141 try_finally node for this special case. */
1143 static void
1144 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1146 struct goto_queue_node *q, *qe;
1147 geh_else *eh_else;
1148 glabel *label_stmt;
1149 gimple x;
1150 gimple_seq finally;
1151 gimple_stmt_iterator gsi;
1152 tree finally_label;
1153 location_t loc = gimple_location (tf->try_finally_expr);
1155 finally = gimple_try_cleanup (tf->top_p);
1156 tf->top_p_seq = gimple_try_eval (tf->top_p);
1158 /* Since there's only one destination, and the destination edge can only
1159 either be EH or non-EH, that implies that all of our incoming edges
1160 are of the same type. Therefore we can lower EH_ELSE immediately. */
1161 eh_else = get_eh_else (finally);
1162 if (eh_else)
1164 if (tf->may_throw)
1165 finally = gimple_eh_else_e_body (eh_else);
1166 else
1167 finally = gimple_eh_else_n_body (eh_else);
1170 lower_eh_constructs_1 (state, &finally);
1172 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1174 gimple stmt = gsi_stmt (gsi);
1175 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
1177 tree block = gimple_block (stmt);
1178 gimple_set_location (stmt, gimple_location (tf->try_finally_expr));
1179 gimple_set_block (stmt, block);
1183 if (tf->may_throw)
1185 /* Only reachable via the exception edge. Add the given label to
1186 the head of the FINALLY block. Append a RESX at the end. */
1187 emit_post_landing_pad (&eh_seq, tf->region);
1188 gimple_seq_add_seq (&eh_seq, finally);
1189 emit_resx (&eh_seq, tf->region);
1190 return;
1193 if (tf->may_fallthru)
1195 /* Only reachable via the fallthru edge. Do nothing but let
1196 the two blocks run together; we'll fall out the bottom. */
1197 gimple_seq_add_seq (&tf->top_p_seq, finally);
1198 return;
1201 finally_label = create_artificial_label (loc);
1202 label_stmt = gimple_build_label (finally_label);
1203 gimple_seq_add_stmt (&tf->top_p_seq, label_stmt);
1205 gimple_seq_add_seq (&tf->top_p_seq, finally);
1207 q = tf->goto_queue;
1208 qe = q + tf->goto_queue_active;
1210 if (tf->may_return)
1212 /* Reachable by return expressions only. Redirect them. */
1213 for (; q < qe; ++q)
1214 do_return_redirection (q, finally_label, NULL);
1215 replace_goto_queue (tf);
1217 else
1219 /* Reachable by goto expressions only. Redirect them. */
1220 for (; q < qe; ++q)
1221 do_goto_redirection (q, finally_label, NULL, tf);
1222 replace_goto_queue (tf);
1224 if (tf->dest_array[0] == tf->fallthru_label)
1226 /* Reachable by goto to fallthru label only. Redirect it
1227 to the new label (already created, sadly), and do not
1228 emit the final branch out, or the fallthru label. */
1229 tf->fallthru_label = NULL;
1230 return;
1234 /* Place the original return/goto to the original destination
1235 immediately after the finally block. */
1236 x = tf->goto_queue[0].cont_stmt;
1237 gimple_seq_add_stmt (&tf->top_p_seq, x);
1238 maybe_record_in_goto_queue (state, x);
1241 /* A subroutine of lower_try_finally. There are multiple edges incoming
1242 and outgoing from the finally block. Implement this by duplicating the
1243 finally block for every destination. */
1245 static void
1246 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1248 gimple_seq finally;
1249 gimple_seq new_stmt;
1250 gimple_seq seq;
1251 gimple x;
1252 geh_else *eh_else;
1253 tree tmp;
1254 location_t tf_loc = gimple_location (tf->try_finally_expr);
1256 finally = gimple_try_cleanup (tf->top_p);
1258 /* Notice EH_ELSE, and simplify some of the remaining code
1259 by considering FINALLY to be the normal return path only. */
1260 eh_else = get_eh_else (finally);
1261 if (eh_else)
1262 finally = gimple_eh_else_n_body (eh_else);
1264 tf->top_p_seq = gimple_try_eval (tf->top_p);
1265 new_stmt = NULL;
1267 if (tf->may_fallthru)
1269 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1270 lower_eh_constructs_1 (state, &seq);
1271 gimple_seq_add_seq (&new_stmt, seq);
1273 tmp = lower_try_finally_fallthru_label (tf);
1274 x = gimple_build_goto (tmp);
1275 gimple_set_location (x, tf_loc);
1276 gimple_seq_add_stmt (&new_stmt, x);
1279 if (tf->may_throw)
1281 /* We don't need to copy the EH path of EH_ELSE,
1282 since it is only emitted once. */
1283 if (eh_else)
1284 seq = gimple_eh_else_e_body (eh_else);
1285 else
1286 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1287 lower_eh_constructs_1 (state, &seq);
1289 emit_post_landing_pad (&eh_seq, tf->region);
1290 gimple_seq_add_seq (&eh_seq, seq);
1291 emit_resx (&eh_seq, tf->region);
1294 if (tf->goto_queue)
1296 struct goto_queue_node *q, *qe;
1297 int return_index, index;
1298 struct labels_s
1300 struct goto_queue_node *q;
1301 tree label;
1302 } *labels;
1304 return_index = tf->dest_array.length ();
1305 labels = XCNEWVEC (struct labels_s, return_index + 1);
1307 q = tf->goto_queue;
1308 qe = q + tf->goto_queue_active;
1309 for (; q < qe; q++)
1311 index = q->index < 0 ? return_index : q->index;
1313 if (!labels[index].q)
1314 labels[index].q = q;
1317 for (index = 0; index < return_index + 1; index++)
1319 tree lab;
1321 q = labels[index].q;
1322 if (! q)
1323 continue;
1325 lab = labels[index].label
1326 = create_artificial_label (tf_loc);
1328 if (index == return_index)
1329 do_return_redirection (q, lab, NULL);
1330 else
1331 do_goto_redirection (q, lab, NULL, tf);
1333 x = gimple_build_label (lab);
1334 gimple_seq_add_stmt (&new_stmt, x);
1336 seq = lower_try_finally_dup_block (finally, state, q->location);
1337 lower_eh_constructs_1 (state, &seq);
1338 gimple_seq_add_seq (&new_stmt, seq);
1340 gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1341 maybe_record_in_goto_queue (state, q->cont_stmt);
1344 for (q = tf->goto_queue; q < qe; q++)
1346 tree lab;
1348 index = q->index < 0 ? return_index : q->index;
1350 if (labels[index].q == q)
1351 continue;
1353 lab = labels[index].label;
1355 if (index == return_index)
1356 do_return_redirection (q, lab, NULL);
1357 else
1358 do_goto_redirection (q, lab, NULL, tf);
1361 replace_goto_queue (tf);
1362 free (labels);
1365 /* Need to link new stmts after running replace_goto_queue due
1366 to not wanting to process the same goto stmts twice. */
1367 gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1370 /* A subroutine of lower_try_finally. There are multiple edges incoming
1371 and outgoing from the finally block. Implement this by instrumenting
1372 each incoming edge and creating a switch statement at the end of the
1373 finally block that branches to the appropriate destination. */
1375 static void
1376 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1378 struct goto_queue_node *q, *qe;
1379 tree finally_tmp, finally_label;
1380 int return_index, eh_index, fallthru_index;
1381 int nlabels, ndests, j, last_case_index;
1382 tree last_case;
1383 vec<tree> case_label_vec;
1384 gimple_seq switch_body = NULL;
1385 gimple x;
1386 geh_else *eh_else;
1387 tree tmp;
1388 gimple switch_stmt;
1389 gimple_seq finally;
1390 hash_map<tree, gimple> *cont_map = NULL;
1391 /* The location of the TRY_FINALLY stmt. */
1392 location_t tf_loc = gimple_location (tf->try_finally_expr);
1393 /* The location of the finally block. */
1394 location_t finally_loc;
1396 finally = gimple_try_cleanup (tf->top_p);
1397 eh_else = get_eh_else (finally);
1399 /* Mash the TRY block to the head of the chain. */
1400 tf->top_p_seq = gimple_try_eval (tf->top_p);
1402 /* The location of the finally is either the last stmt in the finally
1403 block or the location of the TRY_FINALLY itself. */
1404 x = gimple_seq_last_stmt (finally);
1405 finally_loc = x ? gimple_location (x) : tf_loc;
1407 /* Prepare for switch statement generation. */
1408 nlabels = tf->dest_array.length ();
1409 return_index = nlabels;
1410 eh_index = return_index + tf->may_return;
1411 fallthru_index = eh_index + (tf->may_throw && !eh_else);
1412 ndests = fallthru_index + tf->may_fallthru;
1414 finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1415 finally_label = create_artificial_label (finally_loc);
1417 /* We use vec::quick_push on case_label_vec throughout this function,
1418 since we know the size in advance and allocate precisely as muce
1419 space as needed. */
1420 case_label_vec.create (ndests);
1421 last_case = NULL;
1422 last_case_index = 0;
1424 /* Begin inserting code for getting to the finally block. Things
1425 are done in this order to correspond to the sequence the code is
1426 laid out. */
1428 if (tf->may_fallthru)
1430 x = gimple_build_assign (finally_tmp,
1431 build_int_cst (integer_type_node,
1432 fallthru_index));
1433 gimple_seq_add_stmt (&tf->top_p_seq, x);
1435 tmp = build_int_cst (integer_type_node, fallthru_index);
1436 last_case = build_case_label (tmp, NULL,
1437 create_artificial_label (tf_loc));
1438 case_label_vec.quick_push (last_case);
1439 last_case_index++;
1441 x = gimple_build_label (CASE_LABEL (last_case));
1442 gimple_seq_add_stmt (&switch_body, x);
1444 tmp = lower_try_finally_fallthru_label (tf);
1445 x = gimple_build_goto (tmp);
1446 gimple_set_location (x, tf_loc);
1447 gimple_seq_add_stmt (&switch_body, x);
1450 /* For EH_ELSE, emit the exception path (plus resx) now, then
1451 subsequently we only need consider the normal path. */
1452 if (eh_else)
1454 if (tf->may_throw)
1456 finally = gimple_eh_else_e_body (eh_else);
1457 lower_eh_constructs_1 (state, &finally);
1459 emit_post_landing_pad (&eh_seq, tf->region);
1460 gimple_seq_add_seq (&eh_seq, finally);
1461 emit_resx (&eh_seq, tf->region);
1464 finally = gimple_eh_else_n_body (eh_else);
1466 else if (tf->may_throw)
1468 emit_post_landing_pad (&eh_seq, tf->region);
1470 x = gimple_build_assign (finally_tmp,
1471 build_int_cst (integer_type_node, eh_index));
1472 gimple_seq_add_stmt (&eh_seq, x);
1474 x = gimple_build_goto (finally_label);
1475 gimple_set_location (x, tf_loc);
1476 gimple_seq_add_stmt (&eh_seq, x);
1478 tmp = build_int_cst (integer_type_node, eh_index);
1479 last_case = build_case_label (tmp, NULL,
1480 create_artificial_label (tf_loc));
1481 case_label_vec.quick_push (last_case);
1482 last_case_index++;
1484 x = gimple_build_label (CASE_LABEL (last_case));
1485 gimple_seq_add_stmt (&eh_seq, x);
1486 emit_resx (&eh_seq, tf->region);
1489 x = gimple_build_label (finally_label);
1490 gimple_seq_add_stmt (&tf->top_p_seq, x);
1492 lower_eh_constructs_1 (state, &finally);
1493 gimple_seq_add_seq (&tf->top_p_seq, finally);
1495 /* Redirect each incoming goto edge. */
1496 q = tf->goto_queue;
1497 qe = q + tf->goto_queue_active;
1498 j = last_case_index + tf->may_return;
1499 /* Prepare the assignments to finally_tmp that are executed upon the
1500 entrance through a particular edge. */
1501 for (; q < qe; ++q)
1503 gimple_seq mod = NULL;
1504 int switch_id;
1505 unsigned int case_index;
1507 if (q->index < 0)
1509 x = gimple_build_assign (finally_tmp,
1510 build_int_cst (integer_type_node,
1511 return_index));
1512 gimple_seq_add_stmt (&mod, x);
1513 do_return_redirection (q, finally_label, mod);
1514 switch_id = return_index;
1516 else
1518 x = gimple_build_assign (finally_tmp,
1519 build_int_cst (integer_type_node, q->index));
1520 gimple_seq_add_stmt (&mod, x);
1521 do_goto_redirection (q, finally_label, mod, tf);
1522 switch_id = q->index;
1525 case_index = j + q->index;
1526 if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1528 tree case_lab;
1529 tmp = build_int_cst (integer_type_node, switch_id);
1530 case_lab = build_case_label (tmp, NULL,
1531 create_artificial_label (tf_loc));
1532 /* We store the cont_stmt in the pointer map, so that we can recover
1533 it in the loop below. */
1534 if (!cont_map)
1535 cont_map = new hash_map<tree, gimple>;
1536 cont_map->put (case_lab, q->cont_stmt);
1537 case_label_vec.quick_push (case_lab);
1540 for (j = last_case_index; j < last_case_index + nlabels; j++)
1542 gimple cont_stmt;
1544 last_case = case_label_vec[j];
1546 gcc_assert (last_case);
1547 gcc_assert (cont_map);
1549 cont_stmt = *cont_map->get (last_case);
1551 x = gimple_build_label (CASE_LABEL (last_case));
1552 gimple_seq_add_stmt (&switch_body, x);
1553 gimple_seq_add_stmt (&switch_body, cont_stmt);
1554 maybe_record_in_goto_queue (state, cont_stmt);
1556 if (cont_map)
1557 delete cont_map;
1559 replace_goto_queue (tf);
1561 /* Make sure that the last case is the default label, as one is required.
1562 Then sort the labels, which is also required in GIMPLE. */
1563 CASE_LOW (last_case) = NULL;
1564 tree tem = case_label_vec.pop ();
1565 gcc_assert (tem == last_case);
1566 sort_case_labels (case_label_vec);
1568 /* Build the switch statement, setting last_case to be the default
1569 label. */
1570 switch_stmt = gimple_build_switch (finally_tmp, last_case,
1571 case_label_vec);
1572 gimple_set_location (switch_stmt, finally_loc);
1574 /* Need to link SWITCH_STMT after running replace_goto_queue
1575 due to not wanting to process the same goto stmts twice. */
1576 gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1577 gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1580 /* Decide whether or not we are going to duplicate the finally block.
1581 There are several considerations.
1583 First, if this is Java, then the finally block contains code
1584 written by the user. It has line numbers associated with it,
1585 so duplicating the block means it's difficult to set a breakpoint.
1586 Since controlling code generation via -g is verboten, we simply
1587 never duplicate code without optimization.
1589 Second, we'd like to prevent egregious code growth. One way to
1590 do this is to estimate the size of the finally block, multiply
1591 that by the number of copies we'd need to make, and compare against
1592 the estimate of the size of the switch machinery we'd have to add. */
1594 static bool
1595 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1597 int f_estimate, sw_estimate;
1598 geh_else *eh_else;
1600 /* If there's an EH_ELSE involved, the exception path is separate
1601 and really doesn't come into play for this computation. */
1602 eh_else = get_eh_else (finally);
1603 if (eh_else)
1605 ndests -= may_throw;
1606 finally = gimple_eh_else_n_body (eh_else);
1609 if (!optimize)
1611 gimple_stmt_iterator gsi;
1613 if (ndests == 1)
1614 return true;
1616 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1618 gimple stmt = gsi_stmt (gsi);
1619 if (!is_gimple_debug (stmt) && !gimple_clobber_p (stmt))
1620 return false;
1622 return true;
1625 /* Finally estimate N times, plus N gotos. */
1626 f_estimate = count_insns_seq (finally, &eni_size_weights);
1627 f_estimate = (f_estimate + 1) * ndests;
1629 /* Switch statement (cost 10), N variable assignments, N gotos. */
1630 sw_estimate = 10 + 2 * ndests;
1632 /* Optimize for size clearly wants our best guess. */
1633 if (optimize_function_for_size_p (cfun))
1634 return f_estimate < sw_estimate;
1636 /* ??? These numbers are completely made up so far. */
1637 if (optimize > 1)
1638 return f_estimate < 100 || f_estimate < sw_estimate * 2;
1639 else
1640 return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1643 /* REG is the enclosing region for a possible cleanup region, or the region
1644 itself. Returns TRUE if such a region would be unreachable.
1646 Cleanup regions within a must-not-throw region aren't actually reachable
1647 even if there are throwing stmts within them, because the personality
1648 routine will call terminate before unwinding. */
1650 static bool
1651 cleanup_is_dead_in (eh_region reg)
1653 while (reg && reg->type == ERT_CLEANUP)
1654 reg = reg->outer;
1655 return (reg && reg->type == ERT_MUST_NOT_THROW);
1658 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_FINALLY nodes
1659 to a sequence of labels and blocks, plus the exception region trees
1660 that record all the magic. This is complicated by the need to
1661 arrange for the FINALLY block to be executed on all exits. */
1663 static gimple_seq
1664 lower_try_finally (struct leh_state *state, gtry *tp)
1666 struct leh_tf_state this_tf;
1667 struct leh_state this_state;
1668 int ndests;
1669 gimple_seq old_eh_seq;
1671 /* Process the try block. */
1673 memset (&this_tf, 0, sizeof (this_tf));
1674 this_tf.try_finally_expr = tp;
1675 this_tf.top_p = tp;
1676 this_tf.outer = state;
1677 if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1679 this_tf.region = gen_eh_region_cleanup (state->cur_region);
1680 this_state.cur_region = this_tf.region;
1682 else
1684 this_tf.region = NULL;
1685 this_state.cur_region = state->cur_region;
1688 this_state.ehp_region = state->ehp_region;
1689 this_state.tf = &this_tf;
1691 old_eh_seq = eh_seq;
1692 eh_seq = NULL;
1694 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1696 /* Determine if the try block is escaped through the bottom. */
1697 this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1699 /* Determine if any exceptions are possible within the try block. */
1700 if (this_tf.region)
1701 this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1702 if (this_tf.may_throw)
1703 honor_protect_cleanup_actions (state, &this_state, &this_tf);
1705 /* Determine how many edges (still) reach the finally block. Or rather,
1706 how many destinations are reached by the finally block. Use this to
1707 determine how we process the finally block itself. */
1709 ndests = this_tf.dest_array.length ();
1710 ndests += this_tf.may_fallthru;
1711 ndests += this_tf.may_return;
1712 ndests += this_tf.may_throw;
1714 /* If the FINALLY block is not reachable, dike it out. */
1715 if (ndests == 0)
1717 gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1718 gimple_try_set_cleanup (tp, NULL);
1720 /* If the finally block doesn't fall through, then any destination
1721 we might try to impose there isn't reached either. There may be
1722 some minor amount of cleanup and redirection still needed. */
1723 else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1724 lower_try_finally_nofallthru (state, &this_tf);
1726 /* We can easily special-case redirection to a single destination. */
1727 else if (ndests == 1)
1728 lower_try_finally_onedest (state, &this_tf);
1729 else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1730 gimple_try_cleanup (tp)))
1731 lower_try_finally_copy (state, &this_tf);
1732 else
1733 lower_try_finally_switch (state, &this_tf);
1735 /* If someone requested we add a label at the end of the transformed
1736 block, do so. */
1737 if (this_tf.fallthru_label)
1739 /* This must be reached only if ndests == 0. */
1740 gimple x = gimple_build_label (this_tf.fallthru_label);
1741 gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1744 this_tf.dest_array.release ();
1745 free (this_tf.goto_queue);
1746 if (this_tf.goto_queue_map)
1747 delete this_tf.goto_queue_map;
1749 /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1750 If there was no old eh_seq, then the append is trivially already done. */
1751 if (old_eh_seq)
1753 if (eh_seq == NULL)
1754 eh_seq = old_eh_seq;
1755 else
1757 gimple_seq new_eh_seq = eh_seq;
1758 eh_seq = old_eh_seq;
1759 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1763 return this_tf.top_p_seq;
1766 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_CATCH with a
1767 list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1768 exception region trees that records all the magic. */
1770 static gimple_seq
1771 lower_catch (struct leh_state *state, gtry *tp)
1773 eh_region try_region = NULL;
1774 struct leh_state this_state = *state;
1775 gimple_stmt_iterator gsi;
1776 tree out_label;
1777 gimple_seq new_seq, cleanup;
1778 gimple x;
1779 location_t try_catch_loc = gimple_location (tp);
1781 if (flag_exceptions)
1783 try_region = gen_eh_region_try (state->cur_region);
1784 this_state.cur_region = try_region;
1787 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1789 if (!eh_region_may_contain_throw (try_region))
1790 return gimple_try_eval (tp);
1792 new_seq = NULL;
1793 emit_eh_dispatch (&new_seq, try_region);
1794 emit_resx (&new_seq, try_region);
1796 this_state.cur_region = state->cur_region;
1797 this_state.ehp_region = try_region;
1799 out_label = NULL;
1800 cleanup = gimple_try_cleanup (tp);
1801 for (gsi = gsi_start (cleanup);
1802 !gsi_end_p (gsi);
1803 gsi_next (&gsi))
1805 eh_catch c;
1806 gcatch *catch_stmt;
1807 gimple_seq handler;
1809 catch_stmt = as_a <gcatch *> (gsi_stmt (gsi));
1810 c = gen_eh_region_catch (try_region, gimple_catch_types (catch_stmt));
1812 handler = gimple_catch_handler (catch_stmt);
1813 lower_eh_constructs_1 (&this_state, &handler);
1815 c->label = create_artificial_label (UNKNOWN_LOCATION);
1816 x = gimple_build_label (c->label);
1817 gimple_seq_add_stmt (&new_seq, x);
1819 gimple_seq_add_seq (&new_seq, handler);
1821 if (gimple_seq_may_fallthru (new_seq))
1823 if (!out_label)
1824 out_label = create_artificial_label (try_catch_loc);
1826 x = gimple_build_goto (out_label);
1827 gimple_seq_add_stmt (&new_seq, x);
1829 if (!c->type_list)
1830 break;
1833 gimple_try_set_cleanup (tp, new_seq);
1835 return frob_into_branch_around (tp, try_region, out_label);
1838 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with a
1839 GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1840 region trees that record all the magic. */
1842 static gimple_seq
1843 lower_eh_filter (struct leh_state *state, gtry *tp)
1845 struct leh_state this_state = *state;
1846 eh_region this_region = NULL;
1847 gimple inner, x;
1848 gimple_seq new_seq;
1850 inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1852 if (flag_exceptions)
1854 this_region = gen_eh_region_allowed (state->cur_region,
1855 gimple_eh_filter_types (inner));
1856 this_state.cur_region = this_region;
1859 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1861 if (!eh_region_may_contain_throw (this_region))
1862 return gimple_try_eval (tp);
1864 new_seq = NULL;
1865 this_state.cur_region = state->cur_region;
1866 this_state.ehp_region = this_region;
1868 emit_eh_dispatch (&new_seq, this_region);
1869 emit_resx (&new_seq, this_region);
1871 this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1872 x = gimple_build_label (this_region->u.allowed.label);
1873 gimple_seq_add_stmt (&new_seq, x);
1875 lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1876 gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1878 gimple_try_set_cleanup (tp, new_seq);
1880 return frob_into_branch_around (tp, this_region, NULL);
1883 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with
1884 an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1885 plus the exception region trees that record all the magic. */
1887 static gimple_seq
1888 lower_eh_must_not_throw (struct leh_state *state, gtry *tp)
1890 struct leh_state this_state = *state;
1892 if (flag_exceptions)
1894 gimple inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1895 eh_region this_region;
1897 this_region = gen_eh_region_must_not_throw (state->cur_region);
1898 this_region->u.must_not_throw.failure_decl
1899 = gimple_eh_must_not_throw_fndecl (
1900 as_a <geh_mnt *> (inner));
1901 this_region->u.must_not_throw.failure_loc
1902 = LOCATION_LOCUS (gimple_location (tp));
1904 /* In order to get mangling applied to this decl, we must mark it
1905 used now. Otherwise, pass_ipa_free_lang_data won't think it
1906 needs to happen. */
1907 TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1909 this_state.cur_region = this_region;
1912 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1914 return gimple_try_eval (tp);
1917 /* Implement a cleanup expression. This is similar to try-finally,
1918 except that we only execute the cleanup block for exception edges. */
1920 static gimple_seq
1921 lower_cleanup (struct leh_state *state, gtry *tp)
1923 struct leh_state this_state = *state;
1924 eh_region this_region = NULL;
1925 struct leh_tf_state fake_tf;
1926 gimple_seq result;
1927 bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1929 if (flag_exceptions && !cleanup_dead)
1931 this_region = gen_eh_region_cleanup (state->cur_region);
1932 this_state.cur_region = this_region;
1935 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1937 if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1938 return gimple_try_eval (tp);
1940 /* Build enough of a try-finally state so that we can reuse
1941 honor_protect_cleanup_actions. */
1942 memset (&fake_tf, 0, sizeof (fake_tf));
1943 fake_tf.top_p = fake_tf.try_finally_expr = tp;
1944 fake_tf.outer = state;
1945 fake_tf.region = this_region;
1946 fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1947 fake_tf.may_throw = true;
1949 honor_protect_cleanup_actions (state, NULL, &fake_tf);
1951 if (fake_tf.may_throw)
1953 /* In this case honor_protect_cleanup_actions had nothing to do,
1954 and we should process this normally. */
1955 lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1956 result = frob_into_branch_around (tp, this_region,
1957 fake_tf.fallthru_label);
1959 else
1961 /* In this case honor_protect_cleanup_actions did nearly all of
1962 the work. All we have left is to append the fallthru_label. */
1964 result = gimple_try_eval (tp);
1965 if (fake_tf.fallthru_label)
1967 gimple x = gimple_build_label (fake_tf.fallthru_label);
1968 gimple_seq_add_stmt (&result, x);
1971 return result;
1974 /* Main loop for lowering eh constructs. Also moves gsi to the next
1975 statement. */
1977 static void
1978 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1980 gimple_seq replace;
1981 gimple x;
1982 gimple stmt = gsi_stmt (*gsi);
1984 switch (gimple_code (stmt))
1986 case GIMPLE_CALL:
1988 tree fndecl = gimple_call_fndecl (stmt);
1989 tree rhs, lhs;
1991 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1992 switch (DECL_FUNCTION_CODE (fndecl))
1994 case BUILT_IN_EH_POINTER:
1995 /* The front end may have generated a call to
1996 __builtin_eh_pointer (0) within a catch region. Replace
1997 this zero argument with the current catch region number. */
1998 if (state->ehp_region)
2000 tree nr = build_int_cst (integer_type_node,
2001 state->ehp_region->index);
2002 gimple_call_set_arg (stmt, 0, nr);
2004 else
2006 /* The user has dome something silly. Remove it. */
2007 rhs = null_pointer_node;
2008 goto do_replace;
2010 break;
2012 case BUILT_IN_EH_FILTER:
2013 /* ??? This should never appear, but since it's a builtin it
2014 is accessible to abuse by users. Just remove it and
2015 replace the use with the arbitrary value zero. */
2016 rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2017 do_replace:
2018 lhs = gimple_call_lhs (stmt);
2019 x = gimple_build_assign (lhs, rhs);
2020 gsi_insert_before (gsi, x, GSI_SAME_STMT);
2021 /* FALLTHRU */
2023 case BUILT_IN_EH_COPY_VALUES:
2024 /* Likewise this should not appear. Remove it. */
2025 gsi_remove (gsi, true);
2026 return;
2028 default:
2029 break;
2032 /* FALLTHRU */
2034 case GIMPLE_ASSIGN:
2035 /* If the stmt can throw use a new temporary for the assignment
2036 to a LHS. This makes sure the old value of the LHS is
2037 available on the EH edge. Only do so for statements that
2038 potentially fall through (no noreturn calls e.g.), otherwise
2039 this new assignment might create fake fallthru regions. */
2040 if (stmt_could_throw_p (stmt)
2041 && gimple_has_lhs (stmt)
2042 && gimple_stmt_may_fallthru (stmt)
2043 && !tree_could_throw_p (gimple_get_lhs (stmt))
2044 && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2046 tree lhs = gimple_get_lhs (stmt);
2047 tree tmp = create_tmp_var (TREE_TYPE (lhs));
2048 gimple s = gimple_build_assign (lhs, tmp);
2049 gimple_set_location (s, gimple_location (stmt));
2050 gimple_set_block (s, gimple_block (stmt));
2051 gimple_set_lhs (stmt, tmp);
2052 if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2053 || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2054 DECL_GIMPLE_REG_P (tmp) = 1;
2055 gsi_insert_after (gsi, s, GSI_SAME_STMT);
2057 /* Look for things that can throw exceptions, and record them. */
2058 if (state->cur_region && stmt_could_throw_p (stmt))
2060 record_stmt_eh_region (state->cur_region, stmt);
2061 note_eh_region_may_contain_throw (state->cur_region);
2063 break;
2065 case GIMPLE_COND:
2066 case GIMPLE_GOTO:
2067 case GIMPLE_RETURN:
2068 maybe_record_in_goto_queue (state, stmt);
2069 break;
2071 case GIMPLE_SWITCH:
2072 verify_norecord_switch_expr (state, as_a <gswitch *> (stmt));
2073 break;
2075 case GIMPLE_TRY:
2077 gtry *try_stmt = as_a <gtry *> (stmt);
2078 if (gimple_try_kind (try_stmt) == GIMPLE_TRY_FINALLY)
2079 replace = lower_try_finally (state, try_stmt);
2080 else
2082 x = gimple_seq_first_stmt (gimple_try_cleanup (try_stmt));
2083 if (!x)
2085 replace = gimple_try_eval (try_stmt);
2086 lower_eh_constructs_1 (state, &replace);
2088 else
2089 switch (gimple_code (x))
2091 case GIMPLE_CATCH:
2092 replace = lower_catch (state, try_stmt);
2093 break;
2094 case GIMPLE_EH_FILTER:
2095 replace = lower_eh_filter (state, try_stmt);
2096 break;
2097 case GIMPLE_EH_MUST_NOT_THROW:
2098 replace = lower_eh_must_not_throw (state, try_stmt);
2099 break;
2100 case GIMPLE_EH_ELSE:
2101 /* This code is only valid with GIMPLE_TRY_FINALLY. */
2102 gcc_unreachable ();
2103 default:
2104 replace = lower_cleanup (state, try_stmt);
2105 break;
2110 /* Remove the old stmt and insert the transformed sequence
2111 instead. */
2112 gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2113 gsi_remove (gsi, true);
2115 /* Return since we don't want gsi_next () */
2116 return;
2118 case GIMPLE_EH_ELSE:
2119 /* We should be eliminating this in lower_try_finally et al. */
2120 gcc_unreachable ();
2122 default:
2123 /* A type, a decl, or some kind of statement that we're not
2124 interested in. Don't walk them. */
2125 break;
2128 gsi_next (gsi);
2131 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2133 static void
2134 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2136 gimple_stmt_iterator gsi;
2137 for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2138 lower_eh_constructs_2 (state, &gsi);
2141 namespace {
2143 const pass_data pass_data_lower_eh =
2145 GIMPLE_PASS, /* type */
2146 "eh", /* name */
2147 OPTGROUP_NONE, /* optinfo_flags */
2148 TV_TREE_EH, /* tv_id */
2149 PROP_gimple_lcf, /* properties_required */
2150 PROP_gimple_leh, /* properties_provided */
2151 0, /* properties_destroyed */
2152 0, /* todo_flags_start */
2153 0, /* todo_flags_finish */
2156 class pass_lower_eh : public gimple_opt_pass
2158 public:
2159 pass_lower_eh (gcc::context *ctxt)
2160 : gimple_opt_pass (pass_data_lower_eh, ctxt)
2163 /* opt_pass methods: */
2164 virtual unsigned int execute (function *);
2166 }; // class pass_lower_eh
2168 unsigned int
2169 pass_lower_eh::execute (function *fun)
2171 struct leh_state null_state;
2172 gimple_seq bodyp;
2174 bodyp = gimple_body (current_function_decl);
2175 if (bodyp == NULL)
2176 return 0;
2178 finally_tree = new hash_table<finally_tree_hasher> (31);
2179 eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2180 memset (&null_state, 0, sizeof (null_state));
2182 collect_finally_tree_1 (bodyp, NULL);
2183 lower_eh_constructs_1 (&null_state, &bodyp);
2184 gimple_set_body (current_function_decl, bodyp);
2186 /* We assume there's a return statement, or something, at the end of
2187 the function, and thus ploping the EH sequence afterward won't
2188 change anything. */
2189 gcc_assert (!gimple_seq_may_fallthru (bodyp));
2190 gimple_seq_add_seq (&bodyp, eh_seq);
2192 /* We assume that since BODYP already existed, adding EH_SEQ to it
2193 didn't change its value, and we don't have to re-set the function. */
2194 gcc_assert (bodyp == gimple_body (current_function_decl));
2196 delete finally_tree;
2197 finally_tree = NULL;
2198 BITMAP_FREE (eh_region_may_contain_throw_map);
2199 eh_seq = NULL;
2201 /* If this function needs a language specific EH personality routine
2202 and the frontend didn't already set one do so now. */
2203 if (function_needs_eh_personality (fun) == eh_personality_lang
2204 && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2205 DECL_FUNCTION_PERSONALITY (current_function_decl)
2206 = lang_hooks.eh_personality ();
2208 return 0;
2211 } // anon namespace
2213 gimple_opt_pass *
2214 make_pass_lower_eh (gcc::context *ctxt)
2216 return new pass_lower_eh (ctxt);
2219 /* Create the multiple edges from an EH_DISPATCH statement to all of
2220 the possible handlers for its EH region. Return true if there's
2221 no fallthru edge; false if there is. */
2223 bool
2224 make_eh_dispatch_edges (geh_dispatch *stmt)
2226 eh_region r;
2227 eh_catch c;
2228 basic_block src, dst;
2230 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2231 src = gimple_bb (stmt);
2233 switch (r->type)
2235 case ERT_TRY:
2236 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2238 dst = label_to_block (c->label);
2239 make_edge (src, dst, 0);
2241 /* A catch-all handler doesn't have a fallthru. */
2242 if (c->type_list == NULL)
2243 return false;
2245 break;
2247 case ERT_ALLOWED_EXCEPTIONS:
2248 dst = label_to_block (r->u.allowed.label);
2249 make_edge (src, dst, 0);
2250 break;
2252 default:
2253 gcc_unreachable ();
2256 return true;
2259 /* Create the single EH edge from STMT to its nearest landing pad,
2260 if there is such a landing pad within the current function. */
2262 void
2263 make_eh_edges (gimple stmt)
2265 basic_block src, dst;
2266 eh_landing_pad lp;
2267 int lp_nr;
2269 lp_nr = lookup_stmt_eh_lp (stmt);
2270 if (lp_nr <= 0)
2271 return;
2273 lp = get_eh_landing_pad_from_number (lp_nr);
2274 gcc_assert (lp != NULL);
2276 src = gimple_bb (stmt);
2277 dst = label_to_block (lp->post_landing_pad);
2278 make_edge (src, dst, EDGE_EH);
2281 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2282 do not actually perform the final edge redirection.
2284 CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2285 we intend to change the destination EH region as well; this means
2286 EH_LANDING_PAD_NR must already be set on the destination block label.
2287 If false, we're being called from generic cfg manipulation code and we
2288 should preserve our place within the region tree. */
2290 static void
2291 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2293 eh_landing_pad old_lp, new_lp;
2294 basic_block old_bb;
2295 gimple throw_stmt;
2296 int old_lp_nr, new_lp_nr;
2297 tree old_label, new_label;
2298 edge_iterator ei;
2299 edge e;
2301 old_bb = edge_in->dest;
2302 old_label = gimple_block_label (old_bb);
2303 old_lp_nr = EH_LANDING_PAD_NR (old_label);
2304 gcc_assert (old_lp_nr > 0);
2305 old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2307 throw_stmt = last_stmt (edge_in->src);
2308 gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2310 new_label = gimple_block_label (new_bb);
2312 /* Look for an existing region that might be using NEW_BB already. */
2313 new_lp_nr = EH_LANDING_PAD_NR (new_label);
2314 if (new_lp_nr)
2316 new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2317 gcc_assert (new_lp);
2319 /* Unless CHANGE_REGION is true, the new and old landing pad
2320 had better be associated with the same EH region. */
2321 gcc_assert (change_region || new_lp->region == old_lp->region);
2323 else
2325 new_lp = NULL;
2326 gcc_assert (!change_region);
2329 /* Notice when we redirect the last EH edge away from OLD_BB. */
2330 FOR_EACH_EDGE (e, ei, old_bb->preds)
2331 if (e != edge_in && (e->flags & EDGE_EH))
2332 break;
2334 if (new_lp)
2336 /* NEW_LP already exists. If there are still edges into OLD_LP,
2337 there's nothing to do with the EH tree. If there are no more
2338 edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2339 If CHANGE_REGION is true, then our caller is expecting to remove
2340 the landing pad. */
2341 if (e == NULL && !change_region)
2342 remove_eh_landing_pad (old_lp);
2344 else
2346 /* No correct landing pad exists. If there are no more edges
2347 into OLD_LP, then we can simply re-use the existing landing pad.
2348 Otherwise, we have to create a new landing pad. */
2349 if (e == NULL)
2351 EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2352 new_lp = old_lp;
2354 else
2355 new_lp = gen_eh_landing_pad (old_lp->region);
2356 new_lp->post_landing_pad = new_label;
2357 EH_LANDING_PAD_NR (new_label) = new_lp->index;
2360 /* Maybe move the throwing statement to the new region. */
2361 if (old_lp != new_lp)
2363 remove_stmt_from_eh_lp (throw_stmt);
2364 add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2368 /* Redirect EH edge E to NEW_BB. */
2370 edge
2371 redirect_eh_edge (edge edge_in, basic_block new_bb)
2373 redirect_eh_edge_1 (edge_in, new_bb, false);
2374 return ssa_redirect_edge (edge_in, new_bb);
2377 /* This is a subroutine of gimple_redirect_edge_and_branch. Update the
2378 labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2379 The actual edge update will happen in the caller. */
2381 void
2382 redirect_eh_dispatch_edge (geh_dispatch *stmt, edge e, basic_block new_bb)
2384 tree new_lab = gimple_block_label (new_bb);
2385 bool any_changed = false;
2386 basic_block old_bb;
2387 eh_region r;
2388 eh_catch c;
2390 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2391 switch (r->type)
2393 case ERT_TRY:
2394 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2396 old_bb = label_to_block (c->label);
2397 if (old_bb == e->dest)
2399 c->label = new_lab;
2400 any_changed = true;
2403 break;
2405 case ERT_ALLOWED_EXCEPTIONS:
2406 old_bb = label_to_block (r->u.allowed.label);
2407 gcc_assert (old_bb == e->dest);
2408 r->u.allowed.label = new_lab;
2409 any_changed = true;
2410 break;
2412 default:
2413 gcc_unreachable ();
2416 gcc_assert (any_changed);
2419 /* Helper function for operation_could_trap_p and stmt_could_throw_p. */
2421 bool
2422 operation_could_trap_helper_p (enum tree_code op,
2423 bool fp_operation,
2424 bool honor_trapv,
2425 bool honor_nans,
2426 bool honor_snans,
2427 tree divisor,
2428 bool *handled)
2430 *handled = true;
2431 switch (op)
2433 case TRUNC_DIV_EXPR:
2434 case CEIL_DIV_EXPR:
2435 case FLOOR_DIV_EXPR:
2436 case ROUND_DIV_EXPR:
2437 case EXACT_DIV_EXPR:
2438 case CEIL_MOD_EXPR:
2439 case FLOOR_MOD_EXPR:
2440 case ROUND_MOD_EXPR:
2441 case TRUNC_MOD_EXPR:
2442 case RDIV_EXPR:
2443 if (honor_snans || honor_trapv)
2444 return true;
2445 if (fp_operation)
2446 return flag_trapping_math;
2447 if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2448 return true;
2449 return false;
2451 case LT_EXPR:
2452 case LE_EXPR:
2453 case GT_EXPR:
2454 case GE_EXPR:
2455 case LTGT_EXPR:
2456 /* Some floating point comparisons may trap. */
2457 return honor_nans;
2459 case EQ_EXPR:
2460 case NE_EXPR:
2461 case UNORDERED_EXPR:
2462 case ORDERED_EXPR:
2463 case UNLT_EXPR:
2464 case UNLE_EXPR:
2465 case UNGT_EXPR:
2466 case UNGE_EXPR:
2467 case UNEQ_EXPR:
2468 return honor_snans;
2470 case NEGATE_EXPR:
2471 case ABS_EXPR:
2472 case CONJ_EXPR:
2473 /* These operations don't trap with floating point. */
2474 if (honor_trapv)
2475 return true;
2476 return false;
2478 case PLUS_EXPR:
2479 case MINUS_EXPR:
2480 case MULT_EXPR:
2481 /* Any floating arithmetic may trap. */
2482 if (fp_operation && flag_trapping_math)
2483 return true;
2484 if (honor_trapv)
2485 return true;
2486 return false;
2488 case COMPLEX_EXPR:
2489 case CONSTRUCTOR:
2490 /* Constructing an object cannot trap. */
2491 return false;
2493 default:
2494 /* Any floating arithmetic may trap. */
2495 if (fp_operation && flag_trapping_math)
2496 return true;
2498 *handled = false;
2499 return false;
2503 /* Return true if operation OP may trap. FP_OPERATION is true if OP is applied
2504 on floating-point values. HONOR_TRAPV is true if OP is applied on integer
2505 type operands that may trap. If OP is a division operator, DIVISOR contains
2506 the value of the divisor. */
2508 bool
2509 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2510 tree divisor)
2512 bool honor_nans = (fp_operation && flag_trapping_math
2513 && !flag_finite_math_only);
2514 bool honor_snans = fp_operation && flag_signaling_nans != 0;
2515 bool handled;
2517 if (TREE_CODE_CLASS (op) != tcc_comparison
2518 && TREE_CODE_CLASS (op) != tcc_unary
2519 && TREE_CODE_CLASS (op) != tcc_binary)
2520 return false;
2522 return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2523 honor_nans, honor_snans, divisor,
2524 &handled);
2528 /* Returns true if it is possible to prove that the index of
2529 an array access REF (an ARRAY_REF expression) falls into the
2530 array bounds. */
2532 static bool
2533 in_array_bounds_p (tree ref)
2535 tree idx = TREE_OPERAND (ref, 1);
2536 tree min, max;
2538 if (TREE_CODE (idx) != INTEGER_CST)
2539 return false;
2541 min = array_ref_low_bound (ref);
2542 max = array_ref_up_bound (ref);
2543 if (!min
2544 || !max
2545 || TREE_CODE (min) != INTEGER_CST
2546 || TREE_CODE (max) != INTEGER_CST)
2547 return false;
2549 if (tree_int_cst_lt (idx, min)
2550 || tree_int_cst_lt (max, idx))
2551 return false;
2553 return true;
2556 /* Returns true if it is possible to prove that the range of
2557 an array access REF (an ARRAY_RANGE_REF expression) falls
2558 into the array bounds. */
2560 static bool
2561 range_in_array_bounds_p (tree ref)
2563 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2564 tree range_min, range_max, min, max;
2566 range_min = TYPE_MIN_VALUE (domain_type);
2567 range_max = TYPE_MAX_VALUE (domain_type);
2568 if (!range_min
2569 || !range_max
2570 || TREE_CODE (range_min) != INTEGER_CST
2571 || TREE_CODE (range_max) != INTEGER_CST)
2572 return false;
2574 min = array_ref_low_bound (ref);
2575 max = array_ref_up_bound (ref);
2576 if (!min
2577 || !max
2578 || TREE_CODE (min) != INTEGER_CST
2579 || TREE_CODE (max) != INTEGER_CST)
2580 return false;
2582 if (tree_int_cst_lt (range_min, min)
2583 || tree_int_cst_lt (max, range_max))
2584 return false;
2586 return true;
2589 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2590 location or floating point arithmetic. C.f. the rtl version, may_trap_p.
2591 This routine expects only GIMPLE lhs or rhs input. */
2593 bool
2594 tree_could_trap_p (tree expr)
2596 enum tree_code code;
2597 bool fp_operation = false;
2598 bool honor_trapv = false;
2599 tree t, base, div = NULL_TREE;
2601 if (!expr)
2602 return false;
2604 code = TREE_CODE (expr);
2605 t = TREE_TYPE (expr);
2607 if (t)
2609 if (COMPARISON_CLASS_P (expr))
2610 fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2611 else
2612 fp_operation = FLOAT_TYPE_P (t);
2613 honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2616 if (TREE_CODE_CLASS (code) == tcc_binary)
2617 div = TREE_OPERAND (expr, 1);
2618 if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2619 return true;
2621 restart:
2622 switch (code)
2624 case COMPONENT_REF:
2625 case REALPART_EXPR:
2626 case IMAGPART_EXPR:
2627 case BIT_FIELD_REF:
2628 case VIEW_CONVERT_EXPR:
2629 case WITH_SIZE_EXPR:
2630 expr = TREE_OPERAND (expr, 0);
2631 code = TREE_CODE (expr);
2632 goto restart;
2634 case ARRAY_RANGE_REF:
2635 base = TREE_OPERAND (expr, 0);
2636 if (tree_could_trap_p (base))
2637 return true;
2638 if (TREE_THIS_NOTRAP (expr))
2639 return false;
2640 return !range_in_array_bounds_p (expr);
2642 case ARRAY_REF:
2643 base = TREE_OPERAND (expr, 0);
2644 if (tree_could_trap_p (base))
2645 return true;
2646 if (TREE_THIS_NOTRAP (expr))
2647 return false;
2648 return !in_array_bounds_p (expr);
2650 case TARGET_MEM_REF:
2651 case MEM_REF:
2652 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR
2653 && tree_could_trap_p (TREE_OPERAND (TREE_OPERAND (expr, 0), 0)))
2654 return true;
2655 if (TREE_THIS_NOTRAP (expr))
2656 return false;
2657 /* We cannot prove that the access is in-bounds when we have
2658 variable-index TARGET_MEM_REFs. */
2659 if (code == TARGET_MEM_REF
2660 && (TMR_INDEX (expr) || TMR_INDEX2 (expr)))
2661 return true;
2662 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2664 tree base = TREE_OPERAND (TREE_OPERAND (expr, 0), 0);
2665 offset_int off = mem_ref_offset (expr);
2666 if (wi::neg_p (off, SIGNED))
2667 return true;
2668 if (TREE_CODE (base) == STRING_CST)
2669 return wi::leu_p (TREE_STRING_LENGTH (base), off);
2670 else if (DECL_SIZE_UNIT (base) == NULL_TREE
2671 || TREE_CODE (DECL_SIZE_UNIT (base)) != INTEGER_CST
2672 || wi::leu_p (wi::to_offset (DECL_SIZE_UNIT (base)), off))
2673 return true;
2674 /* Now we are sure the first byte of the access is inside
2675 the object. */
2676 return false;
2678 return true;
2680 case INDIRECT_REF:
2681 return !TREE_THIS_NOTRAP (expr);
2683 case ASM_EXPR:
2684 return TREE_THIS_VOLATILE (expr);
2686 case CALL_EXPR:
2687 t = get_callee_fndecl (expr);
2688 /* Assume that calls to weak functions may trap. */
2689 if (!t || !DECL_P (t))
2690 return true;
2691 if (DECL_WEAK (t))
2692 return tree_could_trap_p (t);
2693 return false;
2695 case FUNCTION_DECL:
2696 /* Assume that accesses to weak functions may trap, unless we know
2697 they are certainly defined in current TU or in some other
2698 LTO partition. */
2699 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2701 cgraph_node *node = cgraph_node::get (expr);
2702 if (node)
2703 node = node->function_symbol ();
2704 return !(node && node->in_other_partition);
2706 return false;
2708 case VAR_DECL:
2709 /* Assume that accesses to weak vars may trap, unless we know
2710 they are certainly defined in current TU or in some other
2711 LTO partition. */
2712 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2714 varpool_node *node = varpool_node::get (expr);
2715 if (node)
2716 node = node->ultimate_alias_target ();
2717 return !(node && node->in_other_partition);
2719 return false;
2721 default:
2722 return false;
2727 /* Helper for stmt_could_throw_p. Return true if STMT (assumed to be a
2728 an assignment or a conditional) may throw. */
2730 static bool
2731 stmt_could_throw_1_p (gimple stmt)
2733 enum tree_code code = gimple_expr_code (stmt);
2734 bool honor_nans = false;
2735 bool honor_snans = false;
2736 bool fp_operation = false;
2737 bool honor_trapv = false;
2738 tree t;
2739 size_t i;
2740 bool handled, ret;
2742 if (TREE_CODE_CLASS (code) == tcc_comparison
2743 || TREE_CODE_CLASS (code) == tcc_unary
2744 || TREE_CODE_CLASS (code) == tcc_binary)
2746 if (is_gimple_assign (stmt)
2747 && TREE_CODE_CLASS (code) == tcc_comparison)
2748 t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2749 else if (gimple_code (stmt) == GIMPLE_COND)
2750 t = TREE_TYPE (gimple_cond_lhs (stmt));
2751 else
2752 t = gimple_expr_type (stmt);
2753 fp_operation = FLOAT_TYPE_P (t);
2754 if (fp_operation)
2756 honor_nans = flag_trapping_math && !flag_finite_math_only;
2757 honor_snans = flag_signaling_nans != 0;
2759 else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2760 honor_trapv = true;
2763 /* Check if the main expression may trap. */
2764 t = is_gimple_assign (stmt) ? gimple_assign_rhs2 (stmt) : NULL;
2765 ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2766 honor_nans, honor_snans, t,
2767 &handled);
2768 if (handled)
2769 return ret;
2771 /* If the expression does not trap, see if any of the individual operands may
2772 trap. */
2773 for (i = 0; i < gimple_num_ops (stmt); i++)
2774 if (tree_could_trap_p (gimple_op (stmt, i)))
2775 return true;
2777 return false;
2781 /* Return true if statement STMT could throw an exception. */
2783 bool
2784 stmt_could_throw_p (gimple stmt)
2786 if (!flag_exceptions)
2787 return false;
2789 /* The only statements that can throw an exception are assignments,
2790 conditionals, calls, resx, and asms. */
2791 switch (gimple_code (stmt))
2793 case GIMPLE_RESX:
2794 return true;
2796 case GIMPLE_CALL:
2797 return !gimple_call_nothrow_p (as_a <gcall *> (stmt));
2799 case GIMPLE_ASSIGN:
2800 case GIMPLE_COND:
2801 if (!cfun->can_throw_non_call_exceptions)
2802 return false;
2803 return stmt_could_throw_1_p (stmt);
2805 case GIMPLE_ASM:
2806 if (!cfun->can_throw_non_call_exceptions)
2807 return false;
2808 return gimple_asm_volatile_p (as_a <gasm *> (stmt));
2810 default:
2811 return false;
2816 /* Return true if expression T could throw an exception. */
2818 bool
2819 tree_could_throw_p (tree t)
2821 if (!flag_exceptions)
2822 return false;
2823 if (TREE_CODE (t) == MODIFY_EXPR)
2825 if (cfun->can_throw_non_call_exceptions
2826 && tree_could_trap_p (TREE_OPERAND (t, 0)))
2827 return true;
2828 t = TREE_OPERAND (t, 1);
2831 if (TREE_CODE (t) == WITH_SIZE_EXPR)
2832 t = TREE_OPERAND (t, 0);
2833 if (TREE_CODE (t) == CALL_EXPR)
2834 return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2835 if (cfun->can_throw_non_call_exceptions)
2836 return tree_could_trap_p (t);
2837 return false;
2840 /* Return true if STMT can throw an exception that is not caught within
2841 the current function (CFUN). */
2843 bool
2844 stmt_can_throw_external (gimple stmt)
2846 int lp_nr;
2848 if (!stmt_could_throw_p (stmt))
2849 return false;
2851 lp_nr = lookup_stmt_eh_lp (stmt);
2852 return lp_nr == 0;
2855 /* Return true if STMT can throw an exception that is caught within
2856 the current function (CFUN). */
2858 bool
2859 stmt_can_throw_internal (gimple stmt)
2861 int lp_nr;
2863 if (!stmt_could_throw_p (stmt))
2864 return false;
2866 lp_nr = lookup_stmt_eh_lp (stmt);
2867 return lp_nr > 0;
2870 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2871 remove any entry it might have from the EH table. Return true if
2872 any change was made. */
2874 bool
2875 maybe_clean_eh_stmt_fn (struct function *ifun, gimple stmt)
2877 if (stmt_could_throw_p (stmt))
2878 return false;
2879 return remove_stmt_from_eh_lp_fn (ifun, stmt);
2882 /* Likewise, but always use the current function. */
2884 bool
2885 maybe_clean_eh_stmt (gimple stmt)
2887 return maybe_clean_eh_stmt_fn (cfun, stmt);
2890 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2891 OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2892 in the table if it should be in there. Return TRUE if a replacement was
2893 done that my require an EH edge purge. */
2895 bool
2896 maybe_clean_or_replace_eh_stmt (gimple old_stmt, gimple new_stmt)
2898 int lp_nr = lookup_stmt_eh_lp (old_stmt);
2900 if (lp_nr != 0)
2902 bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2904 if (new_stmt == old_stmt && new_stmt_could_throw)
2905 return false;
2907 remove_stmt_from_eh_lp (old_stmt);
2908 if (new_stmt_could_throw)
2910 add_stmt_to_eh_lp (new_stmt, lp_nr);
2911 return false;
2913 else
2914 return true;
2917 return false;
2920 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2921 in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT. The MAP
2922 operand is the return value of duplicate_eh_regions. */
2924 bool
2925 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple new_stmt,
2926 struct function *old_fun, gimple old_stmt,
2927 hash_map<void *, void *> *map,
2928 int default_lp_nr)
2930 int old_lp_nr, new_lp_nr;
2932 if (!stmt_could_throw_p (new_stmt))
2933 return false;
2935 old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2936 if (old_lp_nr == 0)
2938 if (default_lp_nr == 0)
2939 return false;
2940 new_lp_nr = default_lp_nr;
2942 else if (old_lp_nr > 0)
2944 eh_landing_pad old_lp, new_lp;
2946 old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2947 new_lp = static_cast<eh_landing_pad> (*map->get (old_lp));
2948 new_lp_nr = new_lp->index;
2950 else
2952 eh_region old_r, new_r;
2954 old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2955 new_r = static_cast<eh_region> (*map->get (old_r));
2956 new_lp_nr = -new_r->index;
2959 add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2960 return true;
2963 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2964 and thus no remapping is required. */
2966 bool
2967 maybe_duplicate_eh_stmt (gimple new_stmt, gimple old_stmt)
2969 int lp_nr;
2971 if (!stmt_could_throw_p (new_stmt))
2972 return false;
2974 lp_nr = lookup_stmt_eh_lp (old_stmt);
2975 if (lp_nr == 0)
2976 return false;
2978 add_stmt_to_eh_lp (new_stmt, lp_nr);
2979 return true;
2982 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2983 GIMPLE_TRY) that are similar enough to be considered the same. Currently
2984 this only handles handlers consisting of a single call, as that's the
2985 important case for C++: a destructor call for a particular object showing
2986 up in multiple handlers. */
2988 static bool
2989 same_handler_p (gimple_seq oneh, gimple_seq twoh)
2991 gimple_stmt_iterator gsi;
2992 gimple ones, twos;
2993 unsigned int ai;
2995 gsi = gsi_start (oneh);
2996 if (!gsi_one_before_end_p (gsi))
2997 return false;
2998 ones = gsi_stmt (gsi);
3000 gsi = gsi_start (twoh);
3001 if (!gsi_one_before_end_p (gsi))
3002 return false;
3003 twos = gsi_stmt (gsi);
3005 if (!is_gimple_call (ones)
3006 || !is_gimple_call (twos)
3007 || gimple_call_lhs (ones)
3008 || gimple_call_lhs (twos)
3009 || gimple_call_chain (ones)
3010 || gimple_call_chain (twos)
3011 || !gimple_call_same_target_p (ones, twos)
3012 || gimple_call_num_args (ones) != gimple_call_num_args (twos))
3013 return false;
3015 for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
3016 if (!operand_equal_p (gimple_call_arg (ones, ai),
3017 gimple_call_arg (twos, ai), 0))
3018 return false;
3020 return true;
3023 /* Optimize
3024 try { A() } finally { try { ~B() } catch { ~A() } }
3025 try { ... } finally { ~A() }
3026 into
3027 try { A() } catch { ~B() }
3028 try { ~B() ... } finally { ~A() }
3030 This occurs frequently in C++, where A is a local variable and B is a
3031 temporary used in the initializer for A. */
3033 static void
3034 optimize_double_finally (gtry *one, gtry *two)
3036 gimple oneh;
3037 gimple_stmt_iterator gsi;
3038 gimple_seq cleanup;
3040 cleanup = gimple_try_cleanup (one);
3041 gsi = gsi_start (cleanup);
3042 if (!gsi_one_before_end_p (gsi))
3043 return;
3045 oneh = gsi_stmt (gsi);
3046 if (gimple_code (oneh) != GIMPLE_TRY
3047 || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3048 return;
3050 if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3052 gimple_seq seq = gimple_try_eval (oneh);
3054 gimple_try_set_cleanup (one, seq);
3055 gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3056 seq = copy_gimple_seq_and_replace_locals (seq);
3057 gimple_seq_add_seq (&seq, gimple_try_eval (two));
3058 gimple_try_set_eval (two, seq);
3062 /* Perform EH refactoring optimizations that are simpler to do when code
3063 flow has been lowered but EH structures haven't. */
3065 static void
3066 refactor_eh_r (gimple_seq seq)
3068 gimple_stmt_iterator gsi;
3069 gimple one, two;
3071 one = NULL;
3072 two = NULL;
3073 gsi = gsi_start (seq);
3074 while (1)
3076 one = two;
3077 if (gsi_end_p (gsi))
3078 two = NULL;
3079 else
3080 two = gsi_stmt (gsi);
3081 if (one && two)
3082 if (gtry *try_one = dyn_cast <gtry *> (one))
3083 if (gtry *try_two = dyn_cast <gtry *> (two))
3084 if (gimple_try_kind (try_one) == GIMPLE_TRY_FINALLY
3085 && gimple_try_kind (try_two) == GIMPLE_TRY_FINALLY)
3086 optimize_double_finally (try_one, try_two);
3087 if (one)
3088 switch (gimple_code (one))
3090 case GIMPLE_TRY:
3091 refactor_eh_r (gimple_try_eval (one));
3092 refactor_eh_r (gimple_try_cleanup (one));
3093 break;
3094 case GIMPLE_CATCH:
3095 refactor_eh_r (gimple_catch_handler (as_a <gcatch *> (one)));
3096 break;
3097 case GIMPLE_EH_FILTER:
3098 refactor_eh_r (gimple_eh_filter_failure (one));
3099 break;
3100 case GIMPLE_EH_ELSE:
3102 geh_else *eh_else_stmt = as_a <geh_else *> (one);
3103 refactor_eh_r (gimple_eh_else_n_body (eh_else_stmt));
3104 refactor_eh_r (gimple_eh_else_e_body (eh_else_stmt));
3106 break;
3107 default:
3108 break;
3110 if (two)
3111 gsi_next (&gsi);
3112 else
3113 break;
3117 namespace {
3119 const pass_data pass_data_refactor_eh =
3121 GIMPLE_PASS, /* type */
3122 "ehopt", /* name */
3123 OPTGROUP_NONE, /* optinfo_flags */
3124 TV_TREE_EH, /* tv_id */
3125 PROP_gimple_lcf, /* properties_required */
3126 0, /* properties_provided */
3127 0, /* properties_destroyed */
3128 0, /* todo_flags_start */
3129 0, /* todo_flags_finish */
3132 class pass_refactor_eh : public gimple_opt_pass
3134 public:
3135 pass_refactor_eh (gcc::context *ctxt)
3136 : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3139 /* opt_pass methods: */
3140 virtual bool gate (function *) { return flag_exceptions != 0; }
3141 virtual unsigned int execute (function *)
3143 refactor_eh_r (gimple_body (current_function_decl));
3144 return 0;
3147 }; // class pass_refactor_eh
3149 } // anon namespace
3151 gimple_opt_pass *
3152 make_pass_refactor_eh (gcc::context *ctxt)
3154 return new pass_refactor_eh (ctxt);
3157 /* At the end of gimple optimization, we can lower RESX. */
3159 static bool
3160 lower_resx (basic_block bb, gresx *stmt,
3161 hash_map<eh_region, tree> *mnt_map)
3163 int lp_nr;
3164 eh_region src_r, dst_r;
3165 gimple_stmt_iterator gsi;
3166 gimple x;
3167 tree fn, src_nr;
3168 bool ret = false;
3170 lp_nr = lookup_stmt_eh_lp (stmt);
3171 if (lp_nr != 0)
3172 dst_r = get_eh_region_from_lp_number (lp_nr);
3173 else
3174 dst_r = NULL;
3176 src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3177 gsi = gsi_last_bb (bb);
3179 if (src_r == NULL)
3181 /* We can wind up with no source region when pass_cleanup_eh shows
3182 that there are no entries into an eh region and deletes it, but
3183 then the block that contains the resx isn't removed. This can
3184 happen without optimization when the switch statement created by
3185 lower_try_finally_switch isn't simplified to remove the eh case.
3187 Resolve this by expanding the resx node to an abort. */
3189 fn = builtin_decl_implicit (BUILT_IN_TRAP);
3190 x = gimple_build_call (fn, 0);
3191 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3193 while (EDGE_COUNT (bb->succs) > 0)
3194 remove_edge (EDGE_SUCC (bb, 0));
3196 else if (dst_r)
3198 /* When we have a destination region, we resolve this by copying
3199 the excptr and filter values into place, and changing the edge
3200 to immediately after the landing pad. */
3201 edge e;
3203 if (lp_nr < 0)
3205 basic_block new_bb;
3206 tree lab;
3208 /* We are resuming into a MUST_NOT_CALL region. Expand a call to
3209 the failure decl into a new block, if needed. */
3210 gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3212 tree *slot = mnt_map->get (dst_r);
3213 if (slot == NULL)
3215 gimple_stmt_iterator gsi2;
3217 new_bb = create_empty_bb (bb);
3218 add_bb_to_loop (new_bb, bb->loop_father);
3219 lab = gimple_block_label (new_bb);
3220 gsi2 = gsi_start_bb (new_bb);
3222 fn = dst_r->u.must_not_throw.failure_decl;
3223 x = gimple_build_call (fn, 0);
3224 gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3225 gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3227 mnt_map->put (dst_r, lab);
3229 else
3231 lab = *slot;
3232 new_bb = label_to_block (lab);
3235 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3236 e = make_edge (bb, new_bb, EDGE_FALLTHRU);
3237 e->count = bb->count;
3238 e->probability = REG_BR_PROB_BASE;
3240 else
3242 edge_iterator ei;
3243 tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3245 fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3246 src_nr = build_int_cst (integer_type_node, src_r->index);
3247 x = gimple_build_call (fn, 2, dst_nr, src_nr);
3248 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3250 /* Update the flags for the outgoing edge. */
3251 e = single_succ_edge (bb);
3252 gcc_assert (e->flags & EDGE_EH);
3253 e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3255 /* If there are no more EH users of the landing pad, delete it. */
3256 FOR_EACH_EDGE (e, ei, e->dest->preds)
3257 if (e->flags & EDGE_EH)
3258 break;
3259 if (e == NULL)
3261 eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3262 remove_eh_landing_pad (lp);
3266 ret = true;
3268 else
3270 tree var;
3272 /* When we don't have a destination region, this exception escapes
3273 up the call chain. We resolve this by generating a call to the
3274 _Unwind_Resume library function. */
3276 /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3277 with no arguments for C++ and Java. Check for that. */
3278 if (src_r->use_cxa_end_cleanup)
3280 fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3281 x = gimple_build_call (fn, 0);
3282 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3284 else
3286 fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3287 src_nr = build_int_cst (integer_type_node, src_r->index);
3288 x = gimple_build_call (fn, 1, src_nr);
3289 var = create_tmp_var (ptr_type_node);
3290 var = make_ssa_name (var, x);
3291 gimple_call_set_lhs (x, var);
3292 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3294 fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3295 x = gimple_build_call (fn, 1, var);
3296 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3299 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3302 gsi_remove (&gsi, true);
3304 return ret;
3307 namespace {
3309 const pass_data pass_data_lower_resx =
3311 GIMPLE_PASS, /* type */
3312 "resx", /* name */
3313 OPTGROUP_NONE, /* optinfo_flags */
3314 TV_TREE_EH, /* tv_id */
3315 PROP_gimple_lcf, /* properties_required */
3316 0, /* properties_provided */
3317 0, /* properties_destroyed */
3318 0, /* todo_flags_start */
3319 0, /* todo_flags_finish */
3322 class pass_lower_resx : public gimple_opt_pass
3324 public:
3325 pass_lower_resx (gcc::context *ctxt)
3326 : gimple_opt_pass (pass_data_lower_resx, ctxt)
3329 /* opt_pass methods: */
3330 virtual bool gate (function *) { return flag_exceptions != 0; }
3331 virtual unsigned int execute (function *);
3333 }; // class pass_lower_resx
3335 unsigned
3336 pass_lower_resx::execute (function *fun)
3338 basic_block bb;
3339 bool dominance_invalidated = false;
3340 bool any_rewritten = false;
3342 hash_map<eh_region, tree> mnt_map;
3344 FOR_EACH_BB_FN (bb, fun)
3346 gimple last = last_stmt (bb);
3347 if (last && is_gimple_resx (last))
3349 dominance_invalidated |=
3350 lower_resx (bb, as_a <gresx *> (last), &mnt_map);
3351 any_rewritten = true;
3355 if (dominance_invalidated)
3357 free_dominance_info (CDI_DOMINATORS);
3358 free_dominance_info (CDI_POST_DOMINATORS);
3361 return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3364 } // anon namespace
3366 gimple_opt_pass *
3367 make_pass_lower_resx (gcc::context *ctxt)
3369 return new pass_lower_resx (ctxt);
3372 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3373 external throw. */
3375 static void
3376 optimize_clobbers (basic_block bb)
3378 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3379 bool any_clobbers = false;
3380 bool seen_stack_restore = false;
3381 edge_iterator ei;
3382 edge e;
3384 /* Only optimize anything if the bb contains at least one clobber,
3385 ends with resx (checked by caller), optionally contains some
3386 debug stmts or labels, or at most one __builtin_stack_restore
3387 call, and has an incoming EH edge. */
3388 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3390 gimple stmt = gsi_stmt (gsi);
3391 if (is_gimple_debug (stmt))
3392 continue;
3393 if (gimple_clobber_p (stmt))
3395 any_clobbers = true;
3396 continue;
3398 if (!seen_stack_restore
3399 && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3401 seen_stack_restore = true;
3402 continue;
3404 if (gimple_code (stmt) == GIMPLE_LABEL)
3405 break;
3406 return;
3408 if (!any_clobbers)
3409 return;
3410 FOR_EACH_EDGE (e, ei, bb->preds)
3411 if (e->flags & EDGE_EH)
3412 break;
3413 if (e == NULL)
3414 return;
3415 gsi = gsi_last_bb (bb);
3416 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3418 gimple stmt = gsi_stmt (gsi);
3419 if (!gimple_clobber_p (stmt))
3420 continue;
3421 unlink_stmt_vdef (stmt);
3422 gsi_remove (&gsi, true);
3423 release_defs (stmt);
3427 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3428 internal throw to successor BB. */
3430 static int
3431 sink_clobbers (basic_block bb)
3433 edge e;
3434 edge_iterator ei;
3435 gimple_stmt_iterator gsi, dgsi;
3436 basic_block succbb;
3437 bool any_clobbers = false;
3438 unsigned todo = 0;
3440 /* Only optimize if BB has a single EH successor and
3441 all predecessor edges are EH too. */
3442 if (!single_succ_p (bb)
3443 || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3444 return 0;
3446 FOR_EACH_EDGE (e, ei, bb->preds)
3448 if ((e->flags & EDGE_EH) == 0)
3449 return 0;
3452 /* And BB contains only CLOBBER stmts before the final
3453 RESX. */
3454 gsi = gsi_last_bb (bb);
3455 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3457 gimple stmt = gsi_stmt (gsi);
3458 if (is_gimple_debug (stmt))
3459 continue;
3460 if (gimple_code (stmt) == GIMPLE_LABEL)
3461 break;
3462 if (!gimple_clobber_p (stmt))
3463 return 0;
3464 any_clobbers = true;
3466 if (!any_clobbers)
3467 return 0;
3469 edge succe = single_succ_edge (bb);
3470 succbb = succe->dest;
3472 /* See if there is a virtual PHI node to take an updated virtual
3473 operand from. */
3474 gphi *vphi = NULL;
3475 tree vuse = NULL_TREE;
3476 for (gphi_iterator gpi = gsi_start_phis (succbb);
3477 !gsi_end_p (gpi); gsi_next (&gpi))
3479 tree res = gimple_phi_result (gpi.phi ());
3480 if (virtual_operand_p (res))
3482 vphi = gpi.phi ();
3483 vuse = res;
3484 break;
3488 dgsi = gsi_after_labels (succbb);
3489 gsi = gsi_last_bb (bb);
3490 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3492 gimple stmt = gsi_stmt (gsi);
3493 tree lhs;
3494 if (is_gimple_debug (stmt))
3495 continue;
3496 if (gimple_code (stmt) == GIMPLE_LABEL)
3497 break;
3498 lhs = gimple_assign_lhs (stmt);
3499 /* Unfortunately we don't have dominance info updated at this
3500 point, so checking if
3501 dominated_by_p (CDI_DOMINATORS, succbb,
3502 gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3503 would be too costly. Thus, avoid sinking any clobbers that
3504 refer to non-(D) SSA_NAMEs. */
3505 if (TREE_CODE (lhs) == MEM_REF
3506 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3507 && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3509 unlink_stmt_vdef (stmt);
3510 gsi_remove (&gsi, true);
3511 release_defs (stmt);
3512 continue;
3515 /* As we do not change stmt order when sinking across a
3516 forwarder edge we can keep virtual operands in place. */
3517 gsi_remove (&gsi, false);
3518 gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3520 /* But adjust virtual operands if we sunk across a PHI node. */
3521 if (vuse)
3523 gimple use_stmt;
3524 imm_use_iterator iter;
3525 use_operand_p use_p;
3526 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3527 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3528 SET_USE (use_p, gimple_vdef (stmt));
3529 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3531 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3532 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3534 /* Adjust the incoming virtual operand. */
3535 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3536 SET_USE (gimple_vuse_op (stmt), vuse);
3538 /* If there isn't a single predecessor but no virtual PHI node
3539 arrange for virtual operands to be renamed. */
3540 else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3541 && !single_pred_p (succbb))
3543 /* In this case there will be no use of the VDEF of this stmt.
3544 ??? Unless this is a secondary opportunity and we have not
3545 removed unreachable blocks yet, so we cannot assert this.
3546 Which also means we will end up renaming too many times. */
3547 SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3548 mark_virtual_operands_for_renaming (cfun);
3549 todo |= TODO_update_ssa_only_virtuals;
3553 return todo;
3556 /* At the end of inlining, we can lower EH_DISPATCH. Return true when
3557 we have found some duplicate labels and removed some edges. */
3559 static bool
3560 lower_eh_dispatch (basic_block src, geh_dispatch *stmt)
3562 gimple_stmt_iterator gsi;
3563 int region_nr;
3564 eh_region r;
3565 tree filter, fn;
3566 gimple x;
3567 bool redirected = false;
3569 region_nr = gimple_eh_dispatch_region (stmt);
3570 r = get_eh_region_from_number (region_nr);
3572 gsi = gsi_last_bb (src);
3574 switch (r->type)
3576 case ERT_TRY:
3578 auto_vec<tree> labels;
3579 tree default_label = NULL;
3580 eh_catch c;
3581 edge_iterator ei;
3582 edge e;
3583 hash_set<tree> seen_values;
3585 /* Collect the labels for a switch. Zero the post_landing_pad
3586 field becase we'll no longer have anything keeping these labels
3587 in existence and the optimizer will be free to merge these
3588 blocks at will. */
3589 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3591 tree tp_node, flt_node, lab = c->label;
3592 bool have_label = false;
3594 c->label = NULL;
3595 tp_node = c->type_list;
3596 flt_node = c->filter_list;
3598 if (tp_node == NULL)
3600 default_label = lab;
3601 break;
3605 /* Filter out duplicate labels that arise when this handler
3606 is shadowed by an earlier one. When no labels are
3607 attached to the handler anymore, we remove
3608 the corresponding edge and then we delete unreachable
3609 blocks at the end of this pass. */
3610 if (! seen_values.contains (TREE_VALUE (flt_node)))
3612 tree t = build_case_label (TREE_VALUE (flt_node),
3613 NULL, lab);
3614 labels.safe_push (t);
3615 seen_values.add (TREE_VALUE (flt_node));
3616 have_label = true;
3619 tp_node = TREE_CHAIN (tp_node);
3620 flt_node = TREE_CHAIN (flt_node);
3622 while (tp_node);
3623 if (! have_label)
3625 remove_edge (find_edge (src, label_to_block (lab)));
3626 redirected = true;
3630 /* Clean up the edge flags. */
3631 FOR_EACH_EDGE (e, ei, src->succs)
3633 if (e->flags & EDGE_FALLTHRU)
3635 /* If there was no catch-all, use the fallthru edge. */
3636 if (default_label == NULL)
3637 default_label = gimple_block_label (e->dest);
3638 e->flags &= ~EDGE_FALLTHRU;
3641 gcc_assert (default_label != NULL);
3643 /* Don't generate a switch if there's only a default case.
3644 This is common in the form of try { A; } catch (...) { B; }. */
3645 if (!labels.exists ())
3647 e = single_succ_edge (src);
3648 e->flags |= EDGE_FALLTHRU;
3650 else
3652 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3653 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3654 region_nr));
3655 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3656 filter = make_ssa_name (filter, x);
3657 gimple_call_set_lhs (x, filter);
3658 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3660 /* Turn the default label into a default case. */
3661 default_label = build_case_label (NULL, NULL, default_label);
3662 sort_case_labels (labels);
3664 x = gimple_build_switch (filter, default_label, labels);
3665 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3668 break;
3670 case ERT_ALLOWED_EXCEPTIONS:
3672 edge b_e = BRANCH_EDGE (src);
3673 edge f_e = FALLTHRU_EDGE (src);
3675 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3676 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3677 region_nr));
3678 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3679 filter = make_ssa_name (filter, x);
3680 gimple_call_set_lhs (x, filter);
3681 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3683 r->u.allowed.label = NULL;
3684 x = gimple_build_cond (EQ_EXPR, filter,
3685 build_int_cst (TREE_TYPE (filter),
3686 r->u.allowed.filter),
3687 NULL_TREE, NULL_TREE);
3688 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3690 b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3691 f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3693 break;
3695 default:
3696 gcc_unreachable ();
3699 /* Replace the EH_DISPATCH with the SWITCH or COND generated above. */
3700 gsi_remove (&gsi, true);
3701 return redirected;
3704 namespace {
3706 const pass_data pass_data_lower_eh_dispatch =
3708 GIMPLE_PASS, /* type */
3709 "ehdisp", /* name */
3710 OPTGROUP_NONE, /* optinfo_flags */
3711 TV_TREE_EH, /* tv_id */
3712 PROP_gimple_lcf, /* properties_required */
3713 0, /* properties_provided */
3714 0, /* properties_destroyed */
3715 0, /* todo_flags_start */
3716 0, /* todo_flags_finish */
3719 class pass_lower_eh_dispatch : public gimple_opt_pass
3721 public:
3722 pass_lower_eh_dispatch (gcc::context *ctxt)
3723 : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3726 /* opt_pass methods: */
3727 virtual bool gate (function *fun) { return fun->eh->region_tree != NULL; }
3728 virtual unsigned int execute (function *);
3730 }; // class pass_lower_eh_dispatch
3732 unsigned
3733 pass_lower_eh_dispatch::execute (function *fun)
3735 basic_block bb;
3736 int flags = 0;
3737 bool redirected = false;
3739 assign_filter_values ();
3741 FOR_EACH_BB_FN (bb, fun)
3743 gimple last = last_stmt (bb);
3744 if (last == NULL)
3745 continue;
3746 if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3748 redirected |= lower_eh_dispatch (bb,
3749 as_a <geh_dispatch *> (last));
3750 flags |= TODO_update_ssa_only_virtuals;
3752 else if (gimple_code (last) == GIMPLE_RESX)
3754 if (stmt_can_throw_external (last))
3755 optimize_clobbers (bb);
3756 else
3757 flags |= sink_clobbers (bb);
3761 if (redirected)
3762 delete_unreachable_blocks ();
3763 return flags;
3766 } // anon namespace
3768 gimple_opt_pass *
3769 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3771 return new pass_lower_eh_dispatch (ctxt);
3774 /* Walk statements, see what regions and, optionally, landing pads
3775 are really referenced.
3777 Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3778 and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3780 Passing NULL for LP_REACHABLE is valid, in this case only reachable
3781 regions are marked.
3783 The caller is responsible for freeing the returned sbitmaps. */
3785 static void
3786 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3788 sbitmap r_reachable, lp_reachable;
3789 basic_block bb;
3790 bool mark_landing_pads = (lp_reachablep != NULL);
3791 gcc_checking_assert (r_reachablep != NULL);
3793 r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3794 bitmap_clear (r_reachable);
3795 *r_reachablep = r_reachable;
3797 if (mark_landing_pads)
3799 lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3800 bitmap_clear (lp_reachable);
3801 *lp_reachablep = lp_reachable;
3803 else
3804 lp_reachable = NULL;
3806 FOR_EACH_BB_FN (bb, cfun)
3808 gimple_stmt_iterator gsi;
3810 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3812 gimple stmt = gsi_stmt (gsi);
3814 if (mark_landing_pads)
3816 int lp_nr = lookup_stmt_eh_lp (stmt);
3818 /* Negative LP numbers are MUST_NOT_THROW regions which
3819 are not considered BB enders. */
3820 if (lp_nr < 0)
3821 bitmap_set_bit (r_reachable, -lp_nr);
3823 /* Positive LP numbers are real landing pads, and BB enders. */
3824 else if (lp_nr > 0)
3826 gcc_assert (gsi_one_before_end_p (gsi));
3827 eh_region region = get_eh_region_from_lp_number (lp_nr);
3828 bitmap_set_bit (r_reachable, region->index);
3829 bitmap_set_bit (lp_reachable, lp_nr);
3833 /* Avoid removing regions referenced from RESX/EH_DISPATCH. */
3834 switch (gimple_code (stmt))
3836 case GIMPLE_RESX:
3837 bitmap_set_bit (r_reachable,
3838 gimple_resx_region (as_a <gresx *> (stmt)));
3839 break;
3840 case GIMPLE_EH_DISPATCH:
3841 bitmap_set_bit (r_reachable,
3842 gimple_eh_dispatch_region (
3843 as_a <geh_dispatch *> (stmt)));
3844 break;
3845 default:
3846 break;
3852 /* Remove unreachable handlers and unreachable landing pads. */
3854 static void
3855 remove_unreachable_handlers (void)
3857 sbitmap r_reachable, lp_reachable;
3858 eh_region region;
3859 eh_landing_pad lp;
3860 unsigned i;
3862 mark_reachable_handlers (&r_reachable, &lp_reachable);
3864 if (dump_file)
3866 fprintf (dump_file, "Before removal of unreachable regions:\n");
3867 dump_eh_tree (dump_file, cfun);
3868 fprintf (dump_file, "Reachable regions: ");
3869 dump_bitmap_file (dump_file, r_reachable);
3870 fprintf (dump_file, "Reachable landing pads: ");
3871 dump_bitmap_file (dump_file, lp_reachable);
3874 if (dump_file)
3876 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3877 if (region && !bitmap_bit_p (r_reachable, region->index))
3878 fprintf (dump_file,
3879 "Removing unreachable region %d\n",
3880 region->index);
3883 remove_unreachable_eh_regions (r_reachable);
3885 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3886 if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3888 if (dump_file)
3889 fprintf (dump_file,
3890 "Removing unreachable landing pad %d\n",
3891 lp->index);
3892 remove_eh_landing_pad (lp);
3895 if (dump_file)
3897 fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3898 dump_eh_tree (dump_file, cfun);
3899 fprintf (dump_file, "\n\n");
3902 sbitmap_free (r_reachable);
3903 sbitmap_free (lp_reachable);
3905 #ifdef ENABLE_CHECKING
3906 verify_eh_tree (cfun);
3907 #endif
3910 /* Remove unreachable handlers if any landing pads have been removed after
3911 last ehcleanup pass (due to gimple_purge_dead_eh_edges). */
3913 void
3914 maybe_remove_unreachable_handlers (void)
3916 eh_landing_pad lp;
3917 unsigned i;
3919 if (cfun->eh == NULL)
3920 return;
3922 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3923 if (lp && lp->post_landing_pad)
3925 if (label_to_block (lp->post_landing_pad) == NULL)
3927 remove_unreachable_handlers ();
3928 return;
3933 /* Remove regions that do not have landing pads. This assumes
3934 that remove_unreachable_handlers has already been run, and
3935 that we've just manipulated the landing pads since then.
3937 Preserve regions with landing pads and regions that prevent
3938 exceptions from propagating further, even if these regions
3939 are not reachable. */
3941 static void
3942 remove_unreachable_handlers_no_lp (void)
3944 eh_region region;
3945 sbitmap r_reachable;
3946 unsigned i;
3948 mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3950 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3952 if (! region)
3953 continue;
3955 if (region->landing_pads != NULL
3956 || region->type == ERT_MUST_NOT_THROW)
3957 bitmap_set_bit (r_reachable, region->index);
3959 if (dump_file
3960 && !bitmap_bit_p (r_reachable, region->index))
3961 fprintf (dump_file,
3962 "Removing unreachable region %d\n",
3963 region->index);
3966 remove_unreachable_eh_regions (r_reachable);
3968 sbitmap_free (r_reachable);
3971 /* Undo critical edge splitting on an EH landing pad. Earlier, we
3972 optimisticaly split all sorts of edges, including EH edges. The
3973 optimization passes in between may not have needed them; if not,
3974 we should undo the split.
3976 Recognize this case by having one EH edge incoming to the BB and
3977 one normal edge outgoing; BB should be empty apart from the
3978 post_landing_pad label.
3980 Note that this is slightly different from the empty handler case
3981 handled by cleanup_empty_eh, in that the actual handler may yet
3982 have actual code but the landing pad has been separated from the
3983 handler. As such, cleanup_empty_eh relies on this transformation
3984 having been done first. */
3986 static bool
3987 unsplit_eh (eh_landing_pad lp)
3989 basic_block bb = label_to_block (lp->post_landing_pad);
3990 gimple_stmt_iterator gsi;
3991 edge e_in, e_out;
3993 /* Quickly check the edge counts on BB for singularity. */
3994 if (!single_pred_p (bb) || !single_succ_p (bb))
3995 return false;
3996 e_in = single_pred_edge (bb);
3997 e_out = single_succ_edge (bb);
3999 /* Input edge must be EH and output edge must be normal. */
4000 if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4001 return false;
4003 /* The block must be empty except for the labels and debug insns. */
4004 gsi = gsi_after_labels (bb);
4005 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4006 gsi_next_nondebug (&gsi);
4007 if (!gsi_end_p (gsi))
4008 return false;
4010 /* The destination block must not already have a landing pad
4011 for a different region. */
4012 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4014 glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4015 tree lab;
4016 int lp_nr;
4018 if (!label_stmt)
4019 break;
4020 lab = gimple_label_label (label_stmt);
4021 lp_nr = EH_LANDING_PAD_NR (lab);
4022 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4023 return false;
4026 /* The new destination block must not already be a destination of
4027 the source block, lest we merge fallthru and eh edges and get
4028 all sorts of confused. */
4029 if (find_edge (e_in->src, e_out->dest))
4030 return false;
4032 /* ??? We can get degenerate phis due to cfg cleanups. I would have
4033 thought this should have been cleaned up by a phicprop pass, but
4034 that doesn't appear to handle virtuals. Propagate by hand. */
4035 if (!gimple_seq_empty_p (phi_nodes (bb)))
4037 for (gphi_iterator gpi = gsi_start_phis (bb); !gsi_end_p (gpi); )
4039 gimple use_stmt;
4040 gphi *phi = gpi.phi ();
4041 tree lhs = gimple_phi_result (phi);
4042 tree rhs = gimple_phi_arg_def (phi, 0);
4043 use_operand_p use_p;
4044 imm_use_iterator iter;
4046 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4048 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4049 SET_USE (use_p, rhs);
4052 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4053 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4055 remove_phi_node (&gpi, true);
4059 if (dump_file && (dump_flags & TDF_DETAILS))
4060 fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4061 lp->index, e_out->dest->index);
4063 /* Redirect the edge. Since redirect_eh_edge_1 expects to be moving
4064 a successor edge, humor it. But do the real CFG change with the
4065 predecessor of E_OUT in order to preserve the ordering of arguments
4066 to the PHI nodes in E_OUT->DEST. */
4067 redirect_eh_edge_1 (e_in, e_out->dest, false);
4068 redirect_edge_pred (e_out, e_in->src);
4069 e_out->flags = e_in->flags;
4070 e_out->probability = e_in->probability;
4071 e_out->count = e_in->count;
4072 remove_edge (e_in);
4074 return true;
4077 /* Examine each landing pad block and see if it matches unsplit_eh. */
4079 static bool
4080 unsplit_all_eh (void)
4082 bool changed = false;
4083 eh_landing_pad lp;
4084 int i;
4086 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4087 if (lp)
4088 changed |= unsplit_eh (lp);
4090 return changed;
4093 /* A subroutine of cleanup_empty_eh. Redirect all EH edges incoming
4094 to OLD_BB to NEW_BB; return true on success, false on failure.
4096 OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4097 PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4098 Virtual PHIs may be deleted and marked for renaming. */
4100 static bool
4101 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4102 edge old_bb_out, bool change_region)
4104 gphi_iterator ngsi, ogsi;
4105 edge_iterator ei;
4106 edge e;
4107 bitmap ophi_handled;
4109 /* The destination block must not be a regular successor for any
4110 of the preds of the landing pad. Thus, avoid turning
4111 <..>
4112 | \ EH
4113 | <..>
4115 <..>
4116 into
4117 <..>
4118 | | EH
4119 <..>
4120 which CFG verification would choke on. See PR45172 and PR51089. */
4121 FOR_EACH_EDGE (e, ei, old_bb->preds)
4122 if (find_edge (e->src, new_bb))
4123 return false;
4125 FOR_EACH_EDGE (e, ei, old_bb->preds)
4126 redirect_edge_var_map_clear (e);
4128 ophi_handled = BITMAP_ALLOC (NULL);
4130 /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4131 for the edges we're going to move. */
4132 for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4134 gphi *ophi, *nphi = ngsi.phi ();
4135 tree nresult, nop;
4137 nresult = gimple_phi_result (nphi);
4138 nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4140 /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4141 the source ssa_name. */
4142 ophi = NULL;
4143 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4145 ophi = ogsi.phi ();
4146 if (gimple_phi_result (ophi) == nop)
4147 break;
4148 ophi = NULL;
4151 /* If we did find the corresponding PHI, copy those inputs. */
4152 if (ophi)
4154 /* If NOP is used somewhere else beyond phis in new_bb, give up. */
4155 if (!has_single_use (nop))
4157 imm_use_iterator imm_iter;
4158 use_operand_p use_p;
4160 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4162 if (!gimple_debug_bind_p (USE_STMT (use_p))
4163 && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4164 || gimple_bb (USE_STMT (use_p)) != new_bb))
4165 goto fail;
4168 bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4169 FOR_EACH_EDGE (e, ei, old_bb->preds)
4171 location_t oloc;
4172 tree oop;
4174 if ((e->flags & EDGE_EH) == 0)
4175 continue;
4176 oop = gimple_phi_arg_def (ophi, e->dest_idx);
4177 oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4178 redirect_edge_var_map_add (e, nresult, oop, oloc);
4181 /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4182 from the fact that OLD_BB is tree_empty_eh_handler_p that the
4183 variable is unchanged from input to the block and we can simply
4184 re-use the input to NEW_BB from the OLD_BB_OUT edge. */
4185 else
4187 location_t nloc
4188 = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4189 FOR_EACH_EDGE (e, ei, old_bb->preds)
4190 redirect_edge_var_map_add (e, nresult, nop, nloc);
4194 /* Second, verify that all PHIs from OLD_BB have been handled. If not,
4195 we don't know what values from the other edges into NEW_BB to use. */
4196 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4198 gphi *ophi = ogsi.phi ();
4199 tree oresult = gimple_phi_result (ophi);
4200 if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4201 goto fail;
4204 /* Finally, move the edges and update the PHIs. */
4205 for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4206 if (e->flags & EDGE_EH)
4208 /* ??? CFG manipluation routines do not try to update loop
4209 form on edge redirection. Do so manually here for now. */
4210 /* If we redirect a loop entry or latch edge that will either create
4211 a multiple entry loop or rotate the loop. If the loops merge
4212 we may have created a loop with multiple latches.
4213 All of this isn't easily fixed thus cancel the affected loop
4214 and mark the other loop as possibly having multiple latches. */
4215 if (e->dest == e->dest->loop_father->header)
4217 mark_loop_for_removal (e->dest->loop_father);
4218 new_bb->loop_father->latch = NULL;
4219 loops_state_set (LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4221 redirect_eh_edge_1 (e, new_bb, change_region);
4222 redirect_edge_succ (e, new_bb);
4223 flush_pending_stmts (e);
4225 else
4226 ei_next (&ei);
4228 BITMAP_FREE (ophi_handled);
4229 return true;
4231 fail:
4232 FOR_EACH_EDGE (e, ei, old_bb->preds)
4233 redirect_edge_var_map_clear (e);
4234 BITMAP_FREE (ophi_handled);
4235 return false;
4238 /* A subroutine of cleanup_empty_eh. Move a landing pad LP from its
4239 old region to NEW_REGION at BB. */
4241 static void
4242 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4243 eh_landing_pad lp, eh_region new_region)
4245 gimple_stmt_iterator gsi;
4246 eh_landing_pad *pp;
4248 for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4249 continue;
4250 *pp = lp->next_lp;
4252 lp->region = new_region;
4253 lp->next_lp = new_region->landing_pads;
4254 new_region->landing_pads = lp;
4256 /* Delete the RESX that was matched within the empty handler block. */
4257 gsi = gsi_last_bb (bb);
4258 unlink_stmt_vdef (gsi_stmt (gsi));
4259 gsi_remove (&gsi, true);
4261 /* Clean up E_OUT for the fallthru. */
4262 e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
4263 e_out->probability = REG_BR_PROB_BASE;
4266 /* A subroutine of cleanup_empty_eh. Handle more complex cases of
4267 unsplitting than unsplit_eh was prepared to handle, e.g. when
4268 multiple incoming edges and phis are involved. */
4270 static bool
4271 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4273 gimple_stmt_iterator gsi;
4274 tree lab;
4276 /* We really ought not have totally lost everything following
4277 a landing pad label. Given that BB is empty, there had better
4278 be a successor. */
4279 gcc_assert (e_out != NULL);
4281 /* The destination block must not already have a landing pad
4282 for a different region. */
4283 lab = NULL;
4284 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4286 glabel *stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4287 int lp_nr;
4289 if (!stmt)
4290 break;
4291 lab = gimple_label_label (stmt);
4292 lp_nr = EH_LANDING_PAD_NR (lab);
4293 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4294 return false;
4297 /* Attempt to move the PHIs into the successor block. */
4298 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4300 if (dump_file && (dump_flags & TDF_DETAILS))
4301 fprintf (dump_file,
4302 "Unsplit EH landing pad %d to block %i "
4303 "(via cleanup_empty_eh).\n",
4304 lp->index, e_out->dest->index);
4305 return true;
4308 return false;
4311 /* Return true if edge E_FIRST is part of an empty infinite loop
4312 or leads to such a loop through a series of single successor
4313 empty bbs. */
4315 static bool
4316 infinite_empty_loop_p (edge e_first)
4318 bool inf_loop = false;
4319 edge e;
4321 if (e_first->dest == e_first->src)
4322 return true;
4324 e_first->src->aux = (void *) 1;
4325 for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4327 gimple_stmt_iterator gsi;
4328 if (e->dest->aux)
4330 inf_loop = true;
4331 break;
4333 e->dest->aux = (void *) 1;
4334 gsi = gsi_after_labels (e->dest);
4335 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4336 gsi_next_nondebug (&gsi);
4337 if (!gsi_end_p (gsi))
4338 break;
4340 e_first->src->aux = NULL;
4341 for (e = e_first; e->dest->aux; e = single_succ_edge (e->dest))
4342 e->dest->aux = NULL;
4344 return inf_loop;
4347 /* Examine the block associated with LP to determine if it's an empty
4348 handler for its EH region. If so, attempt to redirect EH edges to
4349 an outer region. Return true the CFG was updated in any way. This
4350 is similar to jump forwarding, just across EH edges. */
4352 static bool
4353 cleanup_empty_eh (eh_landing_pad lp)
4355 basic_block bb = label_to_block (lp->post_landing_pad);
4356 gimple_stmt_iterator gsi;
4357 gimple resx;
4358 eh_region new_region;
4359 edge_iterator ei;
4360 edge e, e_out;
4361 bool has_non_eh_pred;
4362 bool ret = false;
4363 int new_lp_nr;
4365 /* There can be zero or one edges out of BB. This is the quickest test. */
4366 switch (EDGE_COUNT (bb->succs))
4368 case 0:
4369 e_out = NULL;
4370 break;
4371 case 1:
4372 e_out = single_succ_edge (bb);
4373 break;
4374 default:
4375 return false;
4378 resx = last_stmt (bb);
4379 if (resx && is_gimple_resx (resx))
4381 if (stmt_can_throw_external (resx))
4382 optimize_clobbers (bb);
4383 else if (sink_clobbers (bb))
4384 ret = true;
4387 gsi = gsi_after_labels (bb);
4389 /* Make sure to skip debug statements. */
4390 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4391 gsi_next_nondebug (&gsi);
4393 /* If the block is totally empty, look for more unsplitting cases. */
4394 if (gsi_end_p (gsi))
4396 /* For the degenerate case of an infinite loop bail out.
4397 If bb has no successors and is totally empty, which can happen e.g.
4398 because of incorrect noreturn attribute, bail out too. */
4399 if (e_out == NULL
4400 || infinite_empty_loop_p (e_out))
4401 return ret;
4403 return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4406 /* The block should consist only of a single RESX statement, modulo a
4407 preceding call to __builtin_stack_restore if there is no outgoing
4408 edge, since the call can be eliminated in this case. */
4409 resx = gsi_stmt (gsi);
4410 if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4412 gsi_next (&gsi);
4413 resx = gsi_stmt (gsi);
4415 if (!is_gimple_resx (resx))
4416 return ret;
4417 gcc_assert (gsi_one_before_end_p (gsi));
4419 /* Determine if there are non-EH edges, or resx edges into the handler. */
4420 has_non_eh_pred = false;
4421 FOR_EACH_EDGE (e, ei, bb->preds)
4422 if (!(e->flags & EDGE_EH))
4423 has_non_eh_pred = true;
4425 /* Find the handler that's outer of the empty handler by looking at
4426 where the RESX instruction was vectored. */
4427 new_lp_nr = lookup_stmt_eh_lp (resx);
4428 new_region = get_eh_region_from_lp_number (new_lp_nr);
4430 /* If there's no destination region within the current function,
4431 redirection is trivial via removing the throwing statements from
4432 the EH region, removing the EH edges, and allowing the block
4433 to go unreachable. */
4434 if (new_region == NULL)
4436 gcc_assert (e_out == NULL);
4437 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4438 if (e->flags & EDGE_EH)
4440 gimple stmt = last_stmt (e->src);
4441 remove_stmt_from_eh_lp (stmt);
4442 remove_edge (e);
4444 else
4445 ei_next (&ei);
4446 goto succeed;
4449 /* If the destination region is a MUST_NOT_THROW, allow the runtime
4450 to handle the abort and allow the blocks to go unreachable. */
4451 if (new_region->type == ERT_MUST_NOT_THROW)
4453 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4454 if (e->flags & EDGE_EH)
4456 gimple stmt = last_stmt (e->src);
4457 remove_stmt_from_eh_lp (stmt);
4458 add_stmt_to_eh_lp (stmt, new_lp_nr);
4459 remove_edge (e);
4461 else
4462 ei_next (&ei);
4463 goto succeed;
4466 /* Try to redirect the EH edges and merge the PHIs into the destination
4467 landing pad block. If the merge succeeds, we'll already have redirected
4468 all the EH edges. The handler itself will go unreachable if there were
4469 no normal edges. */
4470 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4471 goto succeed;
4473 /* Finally, if all input edges are EH edges, then we can (potentially)
4474 reduce the number of transfers from the runtime by moving the landing
4475 pad from the original region to the new region. This is a win when
4476 we remove the last CLEANUP region along a particular exception
4477 propagation path. Since nothing changes except for the region with
4478 which the landing pad is associated, the PHI nodes do not need to be
4479 adjusted at all. */
4480 if (!has_non_eh_pred)
4482 cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4483 if (dump_file && (dump_flags & TDF_DETAILS))
4484 fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4485 lp->index, new_region->index);
4487 /* ??? The CFG didn't change, but we may have rendered the
4488 old EH region unreachable. Trigger a cleanup there. */
4489 return true;
4492 return ret;
4494 succeed:
4495 if (dump_file && (dump_flags & TDF_DETAILS))
4496 fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4497 remove_eh_landing_pad (lp);
4498 return true;
4501 /* Do a post-order traversal of the EH region tree. Examine each
4502 post_landing_pad block and see if we can eliminate it as empty. */
4504 static bool
4505 cleanup_all_empty_eh (void)
4507 bool changed = false;
4508 eh_landing_pad lp;
4509 int i;
4511 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4512 if (lp)
4513 changed |= cleanup_empty_eh (lp);
4515 return changed;
4518 /* Perform cleanups and lowering of exception handling
4519 1) cleanups regions with handlers doing nothing are optimized out
4520 2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4521 3) Info about regions that are containing instructions, and regions
4522 reachable via local EH edges is collected
4523 4) Eh tree is pruned for regions no longer necessary.
4525 TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4526 Unify those that have the same failure decl and locus.
4529 static unsigned int
4530 execute_cleanup_eh_1 (void)
4532 /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4533 looking up unreachable landing pads. */
4534 remove_unreachable_handlers ();
4536 /* Watch out for the region tree vanishing due to all unreachable. */
4537 if (cfun->eh->region_tree)
4539 bool changed = false;
4541 if (optimize)
4542 changed |= unsplit_all_eh ();
4543 changed |= cleanup_all_empty_eh ();
4545 if (changed)
4547 free_dominance_info (CDI_DOMINATORS);
4548 free_dominance_info (CDI_POST_DOMINATORS);
4550 /* We delayed all basic block deletion, as we may have performed
4551 cleanups on EH edges while non-EH edges were still present. */
4552 delete_unreachable_blocks ();
4554 /* We manipulated the landing pads. Remove any region that no
4555 longer has a landing pad. */
4556 remove_unreachable_handlers_no_lp ();
4558 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4562 return 0;
4565 namespace {
4567 const pass_data pass_data_cleanup_eh =
4569 GIMPLE_PASS, /* type */
4570 "ehcleanup", /* name */
4571 OPTGROUP_NONE, /* optinfo_flags */
4572 TV_TREE_EH, /* tv_id */
4573 PROP_gimple_lcf, /* properties_required */
4574 0, /* properties_provided */
4575 0, /* properties_destroyed */
4576 0, /* todo_flags_start */
4577 0, /* todo_flags_finish */
4580 class pass_cleanup_eh : public gimple_opt_pass
4582 public:
4583 pass_cleanup_eh (gcc::context *ctxt)
4584 : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4587 /* opt_pass methods: */
4588 opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4589 virtual bool gate (function *fun)
4591 return fun->eh != NULL && fun->eh->region_tree != NULL;
4594 virtual unsigned int execute (function *);
4596 }; // class pass_cleanup_eh
4598 unsigned int
4599 pass_cleanup_eh::execute (function *fun)
4601 int ret = execute_cleanup_eh_1 ();
4603 /* If the function no longer needs an EH personality routine
4604 clear it. This exposes cross-language inlining opportunities
4605 and avoids references to a never defined personality routine. */
4606 if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4607 && function_needs_eh_personality (fun) != eh_personality_lang)
4608 DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4610 return ret;
4613 } // anon namespace
4615 gimple_opt_pass *
4616 make_pass_cleanup_eh (gcc::context *ctxt)
4618 return new pass_cleanup_eh (ctxt);
4621 /* Verify that BB containing STMT as the last statement, has precisely the
4622 edge that make_eh_edges would create. */
4624 DEBUG_FUNCTION bool
4625 verify_eh_edges (gimple stmt)
4627 basic_block bb = gimple_bb (stmt);
4628 eh_landing_pad lp = NULL;
4629 int lp_nr;
4630 edge_iterator ei;
4631 edge e, eh_edge;
4633 lp_nr = lookup_stmt_eh_lp (stmt);
4634 if (lp_nr > 0)
4635 lp = get_eh_landing_pad_from_number (lp_nr);
4637 eh_edge = NULL;
4638 FOR_EACH_EDGE (e, ei, bb->succs)
4640 if (e->flags & EDGE_EH)
4642 if (eh_edge)
4644 error ("BB %i has multiple EH edges", bb->index);
4645 return true;
4647 else
4648 eh_edge = e;
4652 if (lp == NULL)
4654 if (eh_edge)
4656 error ("BB %i can not throw but has an EH edge", bb->index);
4657 return true;
4659 return false;
4662 if (!stmt_could_throw_p (stmt))
4664 error ("BB %i last statement has incorrectly set lp", bb->index);
4665 return true;
4668 if (eh_edge == NULL)
4670 error ("BB %i is missing an EH edge", bb->index);
4671 return true;
4674 if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4676 error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4677 return true;
4680 return false;
4683 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically. */
4685 DEBUG_FUNCTION bool
4686 verify_eh_dispatch_edge (geh_dispatch *stmt)
4688 eh_region r;
4689 eh_catch c;
4690 basic_block src, dst;
4691 bool want_fallthru = true;
4692 edge_iterator ei;
4693 edge e, fall_edge;
4695 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4696 src = gimple_bb (stmt);
4698 FOR_EACH_EDGE (e, ei, src->succs)
4699 gcc_assert (e->aux == NULL);
4701 switch (r->type)
4703 case ERT_TRY:
4704 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4706 dst = label_to_block (c->label);
4707 e = find_edge (src, dst);
4708 if (e == NULL)
4710 error ("BB %i is missing an edge", src->index);
4711 return true;
4713 e->aux = (void *)e;
4715 /* A catch-all handler doesn't have a fallthru. */
4716 if (c->type_list == NULL)
4718 want_fallthru = false;
4719 break;
4722 break;
4724 case ERT_ALLOWED_EXCEPTIONS:
4725 dst = label_to_block (r->u.allowed.label);
4726 e = find_edge (src, dst);
4727 if (e == NULL)
4729 error ("BB %i is missing an edge", src->index);
4730 return true;
4732 e->aux = (void *)e;
4733 break;
4735 default:
4736 gcc_unreachable ();
4739 fall_edge = NULL;
4740 FOR_EACH_EDGE (e, ei, src->succs)
4742 if (e->flags & EDGE_FALLTHRU)
4744 if (fall_edge != NULL)
4746 error ("BB %i too many fallthru edges", src->index);
4747 return true;
4749 fall_edge = e;
4751 else if (e->aux)
4752 e->aux = NULL;
4753 else
4755 error ("BB %i has incorrect edge", src->index);
4756 return true;
4759 if ((fall_edge != NULL) ^ want_fallthru)
4761 error ("BB %i has incorrect fallthru edge", src->index);
4762 return true;
4765 return false;