add auto_vec
[platform/upstream/gcc.git] / gcc / tree-eh.c
1 /* Exception handling semantics and decomposition for trees.
2    Copyright (C) 2003-2013 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>.  */
19
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 "function.h"
30 #include "except.h"
31 #include "pointer-set.h"
32 #include "gimple.h"
33 #include "gimple-iterator.h"
34 #include "gimple-ssa.h"
35 #include "cgraph.h"
36 #include "tree-cfg.h"
37 #include "tree-phinodes.h"
38 #include "ssa-iterators.h"
39 #include "stringpool.h"
40 #include "tree-ssanames.h"
41 #include "tree-into-ssa.h"
42 #include "tree-ssa.h"
43 #include "tree-inline.h"
44 #include "tree-pass.h"
45 #include "langhooks.h"
46 #include "ggc.h"
47 #include "diagnostic-core.h"
48 #include "target.h"
49 #include "cfgloop.h"
50 #include "gimple-low.h"
51
52 /* In some instances a tree and a gimple need to be stored in a same table,
53    i.e. in hash tables. This is a structure to do this. */
54 typedef union {tree *tp; tree t; gimple g;} treemple;
55
56 /* Misc functions used in this file.  */
57
58 /* Remember and lookup EH landing pad data for arbitrary statements.
59    Really this means any statement that could_throw_p.  We could
60    stuff this information into the stmt_ann data structure, but:
61
62    (1) We absolutely rely on this information being kept until
63    we get to rtl.  Once we're done with lowering here, if we lose
64    the information there's no way to recover it!
65
66    (2) There are many more statements that *cannot* throw as
67    compared to those that can.  We should be saving some amount
68    of space by only allocating memory for those that can throw.  */
69
70 /* Add statement T in function IFUN to landing pad NUM.  */
71
72 static void
73 add_stmt_to_eh_lp_fn (struct function *ifun, gimple t, int num)
74 {
75   struct throw_stmt_node *n;
76   void **slot;
77
78   gcc_assert (num != 0);
79
80   n = ggc_alloc_throw_stmt_node ();
81   n->stmt = t;
82   n->lp_nr = num;
83
84   if (!get_eh_throw_stmt_table (ifun))
85     set_eh_throw_stmt_table (ifun, htab_create_ggc (31, struct_ptr_hash,
86                                                     struct_ptr_eq,
87                                                     ggc_free));
88
89   slot = htab_find_slot (get_eh_throw_stmt_table (ifun), n, INSERT);
90   gcc_assert (!*slot);
91   *slot = n;
92 }
93
94 /* Add statement T in the current function (cfun) to EH landing pad NUM.  */
95
96 void
97 add_stmt_to_eh_lp (gimple t, int num)
98 {
99   add_stmt_to_eh_lp_fn (cfun, t, num);
100 }
101
102 /* Add statement T to the single EH landing pad in REGION.  */
103
104 static void
105 record_stmt_eh_region (eh_region region, gimple t)
106 {
107   if (region == NULL)
108     return;
109   if (region->type == ERT_MUST_NOT_THROW)
110     add_stmt_to_eh_lp_fn (cfun, t, -region->index);
111   else
112     {
113       eh_landing_pad lp = region->landing_pads;
114       if (lp == NULL)
115         lp = gen_eh_landing_pad (region);
116       else
117         gcc_assert (lp->next_lp == NULL);
118       add_stmt_to_eh_lp_fn (cfun, t, lp->index);
119     }
120 }
121
122
123 /* Remove statement T in function IFUN from its EH landing pad.  */
124
125 bool
126 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple t)
127 {
128   struct throw_stmt_node dummy;
129   void **slot;
130
131   if (!get_eh_throw_stmt_table (ifun))
132     return false;
133
134   dummy.stmt = t;
135   slot = htab_find_slot (get_eh_throw_stmt_table (ifun), &dummy,
136                         NO_INSERT);
137   if (slot)
138     {
139       htab_clear_slot (get_eh_throw_stmt_table (ifun), slot);
140       return true;
141     }
142   else
143     return false;
144 }
145
146
147 /* Remove statement T in the current function (cfun) from its
148    EH landing pad.  */
149
150 bool
151 remove_stmt_from_eh_lp (gimple t)
152 {
153   return remove_stmt_from_eh_lp_fn (cfun, t);
154 }
155
156 /* Determine if statement T is inside an EH region in function IFUN.
157    Positive numbers indicate a landing pad index; negative numbers
158    indicate a MUST_NOT_THROW region index; zero indicates that the
159    statement is not recorded in the region table.  */
160
161 int
162 lookup_stmt_eh_lp_fn (struct function *ifun, gimple t)
163 {
164   struct throw_stmt_node *p, n;
165
166   if (ifun->eh->throw_stmt_table == NULL)
167     return 0;
168
169   n.stmt = t;
170   p = (struct throw_stmt_node *) htab_find (ifun->eh->throw_stmt_table, &n);
171   return p ? p->lp_nr : 0;
172 }
173
174 /* Likewise, but always use the current function.  */
175
176 int
177 lookup_stmt_eh_lp (gimple t)
178 {
179   /* We can get called from initialized data when -fnon-call-exceptions
180      is on; prevent crash.  */
181   if (!cfun)
182     return 0;
183   return lookup_stmt_eh_lp_fn (cfun, t);
184 }
185
186 /* First pass of EH node decomposition.  Build up a tree of GIMPLE_TRY_FINALLY
187    nodes and LABEL_DECL nodes.  We will use this during the second phase to
188    determine if a goto leaves the body of a TRY_FINALLY_EXPR node.  */
189
190 struct finally_tree_node
191 {
192   /* When storing a GIMPLE_TRY, we have to record a gimple.  However
193      when deciding whether a GOTO to a certain LABEL_DECL (which is a
194      tree) leaves the TRY block, its necessary to record a tree in
195      this field.  Thus a treemple is used. */
196   treemple child;
197   gimple parent;
198 };
199
200 /* Hashtable helpers.  */
201
202 struct finally_tree_hasher : typed_free_remove <finally_tree_node>
203 {
204   typedef finally_tree_node value_type;
205   typedef finally_tree_node compare_type;
206   static inline hashval_t hash (const value_type *);
207   static inline bool equal (const value_type *, const compare_type *);
208 };
209
210 inline hashval_t
211 finally_tree_hasher::hash (const value_type *v)
212 {
213   return (intptr_t)v->child.t >> 4;
214 }
215
216 inline bool
217 finally_tree_hasher::equal (const value_type *v, const compare_type *c)
218 {
219   return v->child.t == c->child.t;
220 }
221
222 /* Note that this table is *not* marked GTY.  It is short-lived.  */
223 static hash_table <finally_tree_hasher> finally_tree;
224
225 static void
226 record_in_finally_tree (treemple child, gimple parent)
227 {
228   struct finally_tree_node *n;
229   finally_tree_node **slot;
230
231   n = XNEW (struct finally_tree_node);
232   n->child = child;
233   n->parent = parent;
234
235   slot = finally_tree.find_slot (n, INSERT);
236   gcc_assert (!*slot);
237   *slot = n;
238 }
239
240 static void
241 collect_finally_tree (gimple stmt, gimple region);
242
243 /* Go through the gimple sequence.  Works with collect_finally_tree to
244    record all GIMPLE_LABEL and GIMPLE_TRY statements. */
245
246 static void
247 collect_finally_tree_1 (gimple_seq seq, gimple region)
248 {
249   gimple_stmt_iterator gsi;
250
251   for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
252     collect_finally_tree (gsi_stmt (gsi), region);
253 }
254
255 static void
256 collect_finally_tree (gimple stmt, gimple region)
257 {
258   treemple temp;
259
260   switch (gimple_code (stmt))
261     {
262     case GIMPLE_LABEL:
263       temp.t = gimple_label_label (stmt);
264       record_in_finally_tree (temp, region);
265       break;
266
267     case GIMPLE_TRY:
268       if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
269         {
270           temp.g = stmt;
271           record_in_finally_tree (temp, region);
272           collect_finally_tree_1 (gimple_try_eval (stmt), stmt);
273           collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
274         }
275       else if (gimple_try_kind (stmt) == GIMPLE_TRY_CATCH)
276         {
277           collect_finally_tree_1 (gimple_try_eval (stmt), region);
278           collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
279         }
280       break;
281
282     case GIMPLE_CATCH:
283       collect_finally_tree_1 (gimple_catch_handler (stmt), region);
284       break;
285
286     case GIMPLE_EH_FILTER:
287       collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
288       break;
289
290     case GIMPLE_EH_ELSE:
291       collect_finally_tree_1 (gimple_eh_else_n_body (stmt), region);
292       collect_finally_tree_1 (gimple_eh_else_e_body (stmt), region);
293       break;
294
295     default:
296       /* A type, a decl, or some kind of statement that we're not
297          interested in.  Don't walk them.  */
298       break;
299     }
300 }
301
302
303 /* Use the finally tree to determine if a jump from START to TARGET
304    would leave the try_finally node that START lives in.  */
305
306 static bool
307 outside_finally_tree (treemple start, gimple target)
308 {
309   struct finally_tree_node n, *p;
310
311   do
312     {
313       n.child = start;
314       p = finally_tree.find (&n);
315       if (!p)
316         return true;
317       start.g = p->parent;
318     }
319   while (start.g != target);
320
321   return false;
322 }
323
324 /* Second pass of EH node decomposition.  Actually transform the GIMPLE_TRY
325    nodes into a set of gotos, magic labels, and eh regions.
326    The eh region creation is straight-forward, but frobbing all the gotos
327    and such into shape isn't.  */
328
329 /* The sequence into which we record all EH stuff.  This will be
330    placed at the end of the function when we're all done.  */
331 static gimple_seq eh_seq;
332
333 /* Record whether an EH region contains something that can throw,
334    indexed by EH region number.  */
335 static bitmap eh_region_may_contain_throw_map;
336
337 /* The GOTO_QUEUE is is an array of GIMPLE_GOTO and GIMPLE_RETURN
338    statements that are seen to escape this GIMPLE_TRY_FINALLY node.
339    The idea is to record a gimple statement for everything except for
340    the conditionals, which get their labels recorded. Since labels are
341    of type 'tree', we need this node to store both gimple and tree
342    objects.  REPL_STMT is the sequence used to replace the goto/return
343    statement.  CONT_STMT is used to store the statement that allows
344    the return/goto to jump to the original destination. */
345
346 struct goto_queue_node
347 {
348   treemple stmt;
349   location_t location;
350   gimple_seq repl_stmt;
351   gimple cont_stmt;
352   int index;
353   /* This is used when index >= 0 to indicate that stmt is a label (as
354      opposed to a goto stmt).  */
355   int is_label;
356 };
357
358 /* State of the world while lowering.  */
359
360 struct leh_state
361 {
362   /* What's "current" while constructing the eh region tree.  These
363      correspond to variables of the same name in cfun->eh, which we
364      don't have easy access to.  */
365   eh_region cur_region;
366
367   /* What's "current" for the purposes of __builtin_eh_pointer.  For
368      a CATCH, this is the associated TRY.  For an EH_FILTER, this is
369      the associated ALLOWED_EXCEPTIONS, etc.  */
370   eh_region ehp_region;
371
372   /* Processing of TRY_FINALLY requires a bit more state.  This is
373      split out into a separate structure so that we don't have to
374      copy so much when processing other nodes.  */
375   struct leh_tf_state *tf;
376 };
377
378 struct leh_tf_state
379 {
380   /* Pointer to the GIMPLE_TRY_FINALLY node under discussion.  The
381      try_finally_expr is the original GIMPLE_TRY_FINALLY.  We need to retain
382      this so that outside_finally_tree can reliably reference the tree used
383      in the collect_finally_tree data structures.  */
384   gimple try_finally_expr;
385   gimple top_p;
386
387   /* While lowering a top_p usually it is expanded into multiple statements,
388      thus we need the following field to store them. */
389   gimple_seq top_p_seq;
390
391   /* The state outside this try_finally node.  */
392   struct leh_state *outer;
393
394   /* The exception region created for it.  */
395   eh_region region;
396
397   /* The goto queue.  */
398   struct goto_queue_node *goto_queue;
399   size_t goto_queue_size;
400   size_t goto_queue_active;
401
402   /* Pointer map to help in searching goto_queue when it is large.  */
403   struct pointer_map_t *goto_queue_map;
404
405   /* The set of unique labels seen as entries in the goto queue.  */
406   vec<tree> dest_array;
407
408   /* A label to be added at the end of the completed transformed
409      sequence.  It will be set if may_fallthru was true *at one time*,
410      though subsequent transformations may have cleared that flag.  */
411   tree fallthru_label;
412
413   /* True if it is possible to fall out the bottom of the try block.
414      Cleared if the fallthru is converted to a goto.  */
415   bool may_fallthru;
416
417   /* True if any entry in goto_queue is a GIMPLE_RETURN.  */
418   bool may_return;
419
420   /* True if the finally block can receive an exception edge.
421      Cleared if the exception case is handled by code duplication.  */
422   bool may_throw;
423 };
424
425 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gimple);
426
427 /* Search for STMT in the goto queue.  Return the replacement,
428    or null if the statement isn't in the queue.  */
429
430 #define LARGE_GOTO_QUEUE 20
431
432 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq *seq);
433
434 static gimple_seq
435 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
436 {
437   unsigned int i;
438   void **slot;
439
440   if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
441     {
442       for (i = 0; i < tf->goto_queue_active; i++)
443         if ( tf->goto_queue[i].stmt.g == stmt.g)
444           return tf->goto_queue[i].repl_stmt;
445       return NULL;
446     }
447
448   /* If we have a large number of entries in the goto_queue, create a
449      pointer map and use that for searching.  */
450
451   if (!tf->goto_queue_map)
452     {
453       tf->goto_queue_map = pointer_map_create ();
454       for (i = 0; i < tf->goto_queue_active; i++)
455         {
456           slot = pointer_map_insert (tf->goto_queue_map,
457                                      tf->goto_queue[i].stmt.g);
458           gcc_assert (*slot == NULL);
459           *slot = &tf->goto_queue[i];
460         }
461     }
462
463   slot = pointer_map_contains (tf->goto_queue_map, stmt.g);
464   if (slot != NULL)
465     return (((struct goto_queue_node *) *slot)->repl_stmt);
466
467   return NULL;
468 }
469
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.  */
474
475 static void
476 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
477                                 gimple_stmt_iterator *gsi)
478 {
479   tree label;
480   gimple_seq new_seq;
481   treemple temp;
482   location_t loc = gimple_location (gsi_stmt (*gsi));
483
484   temp.tp = tp;
485   new_seq = find_goto_replacement (tf, temp);
486   if (!new_seq)
487     return;
488
489   if (gimple_seq_singleton_p (new_seq)
490       && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
491     {
492       *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
493       return;
494     }
495
496   label = create_artificial_label (loc);
497   /* Set the new label for the GIMPLE_COND */
498   *tp = label;
499
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);
502 }
503
504 /* The real work of replace_goto_queue.  Returns with TSI updated to
505    point to the next statement.  */
506
507 static void replace_goto_queue_stmt_list (gimple_seq *, struct leh_tf_state *);
508
509 static void
510 replace_goto_queue_1 (gimple stmt, struct leh_tf_state *tf,
511                       gimple_stmt_iterator *gsi)
512 {
513   gimple_seq seq;
514   treemple temp;
515   temp.g = NULL;
516
517   switch (gimple_code (stmt))
518     {
519     case GIMPLE_GOTO:
520     case GIMPLE_RETURN:
521       temp.g = stmt;
522       seq = find_goto_replacement (tf, temp);
523       if (seq)
524         {
525           gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
526           gsi_remove (gsi, false);
527           return;
528         }
529       break;
530
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;
535
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 (stmt), tf);
542       break;
543     case GIMPLE_EH_FILTER:
544       replace_goto_queue_stmt_list (gimple_eh_filter_failure_ptr (stmt), tf);
545       break;
546     case GIMPLE_EH_ELSE:
547       replace_goto_queue_stmt_list (gimple_eh_else_n_body_ptr (stmt), tf);
548       replace_goto_queue_stmt_list (gimple_eh_else_e_body_ptr (stmt), tf);
549       break;
550
551     default:
552       /* These won't have gotos in them.  */
553       break;
554     }
555
556   gsi_next (gsi);
557 }
558
559 /* A subroutine of replace_goto_queue.  Handles GIMPLE_SEQ.  */
560
561 static void
562 replace_goto_queue_stmt_list (gimple_seq *seq, struct leh_tf_state *tf)
563 {
564   gimple_stmt_iterator gsi = gsi_start (*seq);
565
566   while (!gsi_end_p (gsi))
567     replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
568 }
569
570 /* Replace all goto queue members.  */
571
572 static void
573 replace_goto_queue (struct leh_tf_state *tf)
574 {
575   if (tf->goto_queue_active == 0)
576     return;
577   replace_goto_queue_stmt_list (&tf->top_p_seq, tf);
578   replace_goto_queue_stmt_list (&eh_seq, tf);
579 }
580
581 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
582    data to be added, IS_LABEL indicates whether NEW_STMT is a label or
583    a gimple return. */
584
585 static void
586 record_in_goto_queue (struct leh_tf_state *tf,
587                       treemple new_stmt,
588                       int index,
589                       bool is_label,
590                       location_t location)
591 {
592   size_t active, size;
593   struct goto_queue_node *q;
594
595   gcc_assert (!tf->goto_queue_map);
596
597   active = tf->goto_queue_active;
598   size = tf->goto_queue_size;
599   if (active >= size)
600     {
601       size = (size ? size * 2 : 32);
602       tf->goto_queue_size = size;
603       tf->goto_queue
604          = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
605     }
606
607   q = &tf->goto_queue[active];
608   tf->goto_queue_active = active + 1;
609
610   memset (q, 0, sizeof (*q));
611   q->stmt = new_stmt;
612   q->index = index;
613   q->location = location;
614   q->is_label = is_label;
615 }
616
617 /* Record the LABEL label in the goto queue contained in TF.
618    TF is not null.  */
619
620 static void
621 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label,
622                             location_t location)
623 {
624   int index;
625   treemple temp, new_stmt;
626
627   if (!label)
628     return;
629
630   /* Computed and non-local gotos do not get processed.  Given
631      their nature we can neither tell whether we've escaped the
632      finally block nor redirect them if we knew.  */
633   if (TREE_CODE (label) != LABEL_DECL)
634     return;
635
636   /* No need to record gotos that don't leave the try block.  */
637   temp.t = label;
638   if (!outside_finally_tree (temp, tf->try_finally_expr))
639     return;
640
641   if (! tf->dest_array.exists ())
642     {
643       tf->dest_array.create (10);
644       tf->dest_array.quick_push (label);
645       index = 0;
646     }
647   else
648     {
649       int n = tf->dest_array.length ();
650       for (index = 0; index < n; ++index)
651         if (tf->dest_array[index] == label)
652           break;
653       if (index == n)
654         tf->dest_array.safe_push (label);
655     }
656
657   /* In the case of a GOTO we want to record the destination label,
658      since with a GIMPLE_COND we have an easy access to the then/else
659      labels. */
660   new_stmt = stmt;
661   record_in_goto_queue (tf, new_stmt, index, true, location);
662 }
663
664 /* For any GIMPLE_GOTO or GIMPLE_RETURN, decide whether it leaves a try_finally
665    node, and if so record that fact in the goto queue associated with that
666    try_finally node.  */
667
668 static void
669 maybe_record_in_goto_queue (struct leh_state *state, gimple stmt)
670 {
671   struct leh_tf_state *tf = state->tf;
672   treemple new_stmt;
673
674   if (!tf)
675     return;
676
677   switch (gimple_code (stmt))
678     {
679     case GIMPLE_COND:
680       new_stmt.tp = gimple_op_ptr (stmt, 2);
681       record_in_goto_queue_label (tf, new_stmt, gimple_cond_true_label (stmt),
682                                   EXPR_LOCATION (*new_stmt.tp));
683       new_stmt.tp = gimple_op_ptr (stmt, 3);
684       record_in_goto_queue_label (tf, new_stmt, gimple_cond_false_label (stmt),
685                                   EXPR_LOCATION (*new_stmt.tp));
686       break;
687     case GIMPLE_GOTO:
688       new_stmt.g = stmt;
689       record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt),
690                                   gimple_location (stmt));
691       break;
692
693     case GIMPLE_RETURN:
694       tf->may_return = true;
695       new_stmt.g = stmt;
696       record_in_goto_queue (tf, new_stmt, -1, false, gimple_location (stmt));
697       break;
698
699     default:
700       gcc_unreachable ();
701     }
702 }
703
704
705 #ifdef ENABLE_CHECKING
706 /* We do not process GIMPLE_SWITCHes for now.  As long as the original source
707    was in fact structured, and we've not yet done jump threading, then none
708    of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this.  */
709
710 static void
711 verify_norecord_switch_expr (struct leh_state *state, gimple switch_expr)
712 {
713   struct leh_tf_state *tf = state->tf;
714   size_t i, n;
715
716   if (!tf)
717     return;
718
719   n = gimple_switch_num_labels (switch_expr);
720
721   for (i = 0; i < n; ++i)
722     {
723       treemple temp;
724       tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
725       temp.t = lab;
726       gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
727     }
728 }
729 #else
730 #define verify_norecord_switch_expr(state, switch_expr)
731 #endif
732
733 /* Redirect a RETURN_EXPR pointed to by Q to FINLAB.  If MOD is
734    non-null, insert it before the new branch.  */
735
736 static void
737 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod)
738 {
739   gimple x;
740
741   /* In the case of a return, the queue node must be a gimple statement.  */
742   gcc_assert (!q->is_label);
743
744   /* Note that the return value may have already been computed, e.g.,
745
746         int x;
747         int foo (void)
748         {
749           x = 0;
750           try {
751             return x;
752           } finally {
753             x++;
754           }
755         }
756
757      should return 0, not 1.  We don't have to do anything to make
758      this happens because the return value has been placed in the
759      RESULT_DECL already.  */
760
761   q->cont_stmt = q->stmt.g;
762
763   if (mod)
764     gimple_seq_add_seq (&q->repl_stmt, mod);
765
766   x = gimple_build_goto (finlab);
767   gimple_set_location (x, q->location);
768   gimple_seq_add_stmt (&q->repl_stmt, x);
769 }
770
771 /* Similar, but easier, for GIMPLE_GOTO.  */
772
773 static void
774 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
775                      struct leh_tf_state *tf)
776 {
777   gimple x;
778
779   gcc_assert (q->is_label);
780
781   q->cont_stmt = gimple_build_goto (tf->dest_array[q->index]);
782
783   if (mod)
784     gimple_seq_add_seq (&q->repl_stmt, mod);
785
786   x = gimple_build_goto (finlab);
787   gimple_set_location (x, q->location);
788   gimple_seq_add_stmt (&q->repl_stmt, x);
789 }
790
791 /* Emit a standard landing pad sequence into SEQ for REGION.  */
792
793 static void
794 emit_post_landing_pad (gimple_seq *seq, eh_region region)
795 {
796   eh_landing_pad lp = region->landing_pads;
797   gimple x;
798
799   if (lp == NULL)
800     lp = gen_eh_landing_pad (region);
801
802   lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
803   EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
804
805   x = gimple_build_label (lp->post_landing_pad);
806   gimple_seq_add_stmt (seq, x);
807 }
808
809 /* Emit a RESX statement into SEQ for REGION.  */
810
811 static void
812 emit_resx (gimple_seq *seq, eh_region region)
813 {
814   gimple x = gimple_build_resx (region->index);
815   gimple_seq_add_stmt (seq, x);
816   if (region->outer)
817     record_stmt_eh_region (region->outer, x);
818 }
819
820 /* Emit an EH_DISPATCH statement into SEQ for REGION.  */
821
822 static void
823 emit_eh_dispatch (gimple_seq *seq, eh_region region)
824 {
825   gimple x = gimple_build_eh_dispatch (region->index);
826   gimple_seq_add_stmt (seq, x);
827 }
828
829 /* Note that the current EH region may contain a throw, or a
830    call to a function which itself may contain a throw.  */
831
832 static void
833 note_eh_region_may_contain_throw (eh_region region)
834 {
835   while (bitmap_set_bit (eh_region_may_contain_throw_map, region->index))
836     {
837       if (region->type == ERT_MUST_NOT_THROW)
838         break;
839       region = region->outer;
840       if (region == NULL)
841         break;
842     }
843 }
844
845 /* Check if REGION has been marked as containing a throw.  If REGION is
846    NULL, this predicate is false.  */
847
848 static inline bool
849 eh_region_may_contain_throw (eh_region r)
850 {
851   return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
852 }
853
854 /* We want to transform
855         try { body; } catch { stuff; }
856    to
857         normal_seqence:
858           body;
859           over:
860         eh_seqence:
861           landing_pad:
862           stuff;
863           goto over;
864
865    TP is a GIMPLE_TRY node.  REGION is the region whose post_landing_pad
866    should be placed before the second operand, or NULL.  OVER is
867    an existing label that should be put at the exit, or NULL.  */
868
869 static gimple_seq
870 frob_into_branch_around (gimple tp, eh_region region, tree over)
871 {
872   gimple x;
873   gimple_seq cleanup, result;
874   location_t loc = gimple_location (tp);
875
876   cleanup = gimple_try_cleanup (tp);
877   result = gimple_try_eval (tp);
878
879   if (region)
880     emit_post_landing_pad (&eh_seq, region);
881
882   if (gimple_seq_may_fallthru (cleanup))
883     {
884       if (!over)
885         over = create_artificial_label (loc);
886       x = gimple_build_goto (over);
887       gimple_set_location (x, loc);
888       gimple_seq_add_stmt (&cleanup, x);
889     }
890   gimple_seq_add_seq (&eh_seq, cleanup);
891
892   if (over)
893     {
894       x = gimple_build_label (over);
895       gimple_seq_add_stmt (&result, x);
896     }
897   return result;
898 }
899
900 /* A subroutine of lower_try_finally.  Duplicate the tree rooted at T.
901    Make sure to record all new labels found.  */
902
903 static gimple_seq
904 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state,
905                              location_t loc)
906 {
907   gimple region = NULL;
908   gimple_seq new_seq;
909   gimple_stmt_iterator gsi;
910
911   new_seq = copy_gimple_seq_and_replace_locals (seq);
912
913   for (gsi = gsi_start (new_seq); !gsi_end_p (gsi); gsi_next (&gsi))
914     {
915       gimple stmt = gsi_stmt (gsi);
916       if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
917         {
918           tree block = gimple_block (stmt);
919           gimple_set_location (stmt, loc);
920           gimple_set_block (stmt, block);
921         }
922     }
923
924   if (outer_state->tf)
925     region = outer_state->tf->try_finally_expr;
926   collect_finally_tree_1 (new_seq, region);
927
928   return new_seq;
929 }
930
931 /* A subroutine of lower_try_finally.  Create a fallthru label for
932    the given try_finally state.  The only tricky bit here is that
933    we have to make sure to record the label in our outer context.  */
934
935 static tree
936 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
937 {
938   tree label = tf->fallthru_label;
939   treemple temp;
940
941   if (!label)
942     {
943       label = create_artificial_label (gimple_location (tf->try_finally_expr));
944       tf->fallthru_label = label;
945       if (tf->outer->tf)
946         {
947           temp.t = label;
948           record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
949         }
950     }
951   return label;
952 }
953
954 /* A subroutine of lower_try_finally.  If FINALLY consits of a
955    GIMPLE_EH_ELSE node, return it.  */
956
957 static inline gimple
958 get_eh_else (gimple_seq finally)
959 {
960   gimple x = gimple_seq_first_stmt (finally);
961   if (gimple_code (x) == GIMPLE_EH_ELSE)
962     {
963       gcc_assert (gimple_seq_singleton_p (finally));
964       return x;
965     }
966   return NULL;
967 }
968
969 /* A subroutine of lower_try_finally.  If the eh_protect_cleanup_actions
970    langhook returns non-null, then the language requires that the exception
971    path out of a try_finally be treated specially.  To wit: the code within
972    the finally block may not itself throw an exception.  We have two choices
973    here. First we can duplicate the finally block and wrap it in a
974    must_not_throw region.  Second, we can generate code like
975
976         try {
977           finally_block;
978         } catch {
979           if (fintmp == eh_edge)
980             protect_cleanup_actions;
981         }
982
983    where "fintmp" is the temporary used in the switch statement generation
984    alternative considered below.  For the nonce, we always choose the first
985    option.
986
987    THIS_STATE may be null if this is a try-cleanup, not a try-finally.  */
988
989 static void
990 honor_protect_cleanup_actions (struct leh_state *outer_state,
991                                struct leh_state *this_state,
992                                struct leh_tf_state *tf)
993 {
994   tree protect_cleanup_actions;
995   gimple_stmt_iterator gsi;
996   bool finally_may_fallthru;
997   gimple_seq finally;
998   gimple x, eh_else;
999
1000   /* First check for nothing to do.  */
1001   if (lang_hooks.eh_protect_cleanup_actions == NULL)
1002     return;
1003   protect_cleanup_actions = lang_hooks.eh_protect_cleanup_actions ();
1004   if (protect_cleanup_actions == NULL)
1005     return;
1006
1007   finally = gimple_try_cleanup (tf->top_p);
1008   eh_else = get_eh_else (finally);
1009
1010   /* Duplicate the FINALLY block.  Only need to do this for try-finally,
1011      and not for cleanups.  If we've got an EH_ELSE, extract it now.  */
1012   if (eh_else)
1013     {
1014       finally = gimple_eh_else_e_body (eh_else);
1015       gimple_try_set_cleanup (tf->top_p, gimple_eh_else_n_body (eh_else));
1016     }
1017   else if (this_state)
1018     finally = lower_try_finally_dup_block (finally, outer_state,
1019         gimple_location (tf->try_finally_expr));
1020   finally_may_fallthru = gimple_seq_may_fallthru (finally);
1021
1022   /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1023      set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1024      to be in an enclosing scope, but needs to be implemented at this level
1025      to avoid a nesting violation (see wrap_temporary_cleanups in
1026      cp/decl.c).  Since it's logically at an outer level, we should call
1027      terminate before we get to it, so strip it away before adding the
1028      MUST_NOT_THROW filter.  */
1029   gsi = gsi_start (finally);
1030   x = gsi_stmt (gsi);
1031   if (gimple_code (x) == GIMPLE_TRY
1032       && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1033       && gimple_try_catch_is_cleanup (x))
1034     {
1035       gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1036       gsi_remove (&gsi, false);
1037     }
1038
1039   /* Wrap the block with protect_cleanup_actions as the action.  */
1040   x = gimple_build_eh_must_not_throw (protect_cleanup_actions);
1041   x = gimple_build_try (finally, gimple_seq_alloc_with_stmt (x),
1042                         GIMPLE_TRY_CATCH);
1043   finally = lower_eh_must_not_throw (outer_state, x);
1044
1045   /* Drop all of this into the exception sequence.  */
1046   emit_post_landing_pad (&eh_seq, tf->region);
1047   gimple_seq_add_seq (&eh_seq, finally);
1048   if (finally_may_fallthru)
1049     emit_resx (&eh_seq, tf->region);
1050
1051   /* Having now been handled, EH isn't to be considered with
1052      the rest of the outgoing edges.  */
1053   tf->may_throw = false;
1054 }
1055
1056 /* A subroutine of lower_try_finally.  We have determined that there is
1057    no fallthru edge out of the finally block.  This means that there is
1058    no outgoing edge corresponding to any incoming edge.  Restructure the
1059    try_finally node for this special case.  */
1060
1061 static void
1062 lower_try_finally_nofallthru (struct leh_state *state,
1063                               struct leh_tf_state *tf)
1064 {
1065   tree lab;
1066   gimple x, eh_else;
1067   gimple_seq finally;
1068   struct goto_queue_node *q, *qe;
1069
1070   lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1071
1072   /* We expect that tf->top_p is a GIMPLE_TRY. */
1073   finally = gimple_try_cleanup (tf->top_p);
1074   tf->top_p_seq = gimple_try_eval (tf->top_p);
1075
1076   x = gimple_build_label (lab);
1077   gimple_seq_add_stmt (&tf->top_p_seq, x);
1078
1079   q = tf->goto_queue;
1080   qe = q + tf->goto_queue_active;
1081   for (; q < qe; ++q)
1082     if (q->index < 0)
1083       do_return_redirection (q, lab, NULL);
1084     else
1085       do_goto_redirection (q, lab, NULL, tf);
1086
1087   replace_goto_queue (tf);
1088
1089   /* Emit the finally block into the stream.  Lower EH_ELSE at this time.  */
1090   eh_else = get_eh_else (finally);
1091   if (eh_else)
1092     {
1093       finally = gimple_eh_else_n_body (eh_else);
1094       lower_eh_constructs_1 (state, &finally);
1095       gimple_seq_add_seq (&tf->top_p_seq, finally);
1096
1097       if (tf->may_throw)
1098         {
1099           finally = gimple_eh_else_e_body (eh_else);
1100           lower_eh_constructs_1 (state, &finally);
1101
1102           emit_post_landing_pad (&eh_seq, tf->region);
1103           gimple_seq_add_seq (&eh_seq, finally);
1104         }
1105     }
1106   else
1107     {
1108       lower_eh_constructs_1 (state, &finally);
1109       gimple_seq_add_seq (&tf->top_p_seq, finally);
1110
1111       if (tf->may_throw)
1112         {
1113           emit_post_landing_pad (&eh_seq, tf->region);
1114
1115           x = gimple_build_goto (lab);
1116           gimple_set_location (x, gimple_location (tf->try_finally_expr));
1117           gimple_seq_add_stmt (&eh_seq, x);
1118         }
1119     }
1120 }
1121
1122 /* A subroutine of lower_try_finally.  We have determined that there is
1123    exactly one destination of the finally block.  Restructure the
1124    try_finally node for this special case.  */
1125
1126 static void
1127 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1128 {
1129   struct goto_queue_node *q, *qe;
1130   gimple x;
1131   gimple_seq finally;
1132   gimple_stmt_iterator gsi;
1133   tree finally_label;
1134   location_t loc = gimple_location (tf->try_finally_expr);
1135
1136   finally = gimple_try_cleanup (tf->top_p);
1137   tf->top_p_seq = gimple_try_eval (tf->top_p);
1138
1139   /* Since there's only one destination, and the destination edge can only
1140      either be EH or non-EH, that implies that all of our incoming edges
1141      are of the same type.  Therefore we can lower EH_ELSE immediately.  */
1142   x = get_eh_else (finally);
1143   if (x)
1144     {
1145       if (tf->may_throw)
1146         finally = gimple_eh_else_e_body (x);
1147       else
1148         finally = gimple_eh_else_n_body (x);
1149     }
1150
1151   lower_eh_constructs_1 (state, &finally);
1152
1153   for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1154     {
1155       gimple stmt = gsi_stmt (gsi);
1156       if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
1157         {
1158           tree block = gimple_block (stmt);
1159           gimple_set_location (stmt, gimple_location (tf->try_finally_expr));
1160           gimple_set_block (stmt, block);
1161         }
1162     }
1163
1164   if (tf->may_throw)
1165     {
1166       /* Only reachable via the exception edge.  Add the given label to
1167          the head of the FINALLY block.  Append a RESX at the end.  */
1168       emit_post_landing_pad (&eh_seq, tf->region);
1169       gimple_seq_add_seq (&eh_seq, finally);
1170       emit_resx (&eh_seq, tf->region);
1171       return;
1172     }
1173
1174   if (tf->may_fallthru)
1175     {
1176       /* Only reachable via the fallthru edge.  Do nothing but let
1177          the two blocks run together; we'll fall out the bottom.  */
1178       gimple_seq_add_seq (&tf->top_p_seq, finally);
1179       return;
1180     }
1181
1182   finally_label = create_artificial_label (loc);
1183   x = gimple_build_label (finally_label);
1184   gimple_seq_add_stmt (&tf->top_p_seq, x);
1185
1186   gimple_seq_add_seq (&tf->top_p_seq, finally);
1187
1188   q = tf->goto_queue;
1189   qe = q + tf->goto_queue_active;
1190
1191   if (tf->may_return)
1192     {
1193       /* Reachable by return expressions only.  Redirect them.  */
1194       for (; q < qe; ++q)
1195         do_return_redirection (q, finally_label, NULL);
1196       replace_goto_queue (tf);
1197     }
1198   else
1199     {
1200       /* Reachable by goto expressions only.  Redirect them.  */
1201       for (; q < qe; ++q)
1202         do_goto_redirection (q, finally_label, NULL, tf);
1203       replace_goto_queue (tf);
1204
1205       if (tf->dest_array[0] == tf->fallthru_label)
1206         {
1207           /* Reachable by goto to fallthru label only.  Redirect it
1208              to the new label (already created, sadly), and do not
1209              emit the final branch out, or the fallthru label.  */
1210           tf->fallthru_label = NULL;
1211           return;
1212         }
1213     }
1214
1215   /* Place the original return/goto to the original destination
1216      immediately after the finally block. */
1217   x = tf->goto_queue[0].cont_stmt;
1218   gimple_seq_add_stmt (&tf->top_p_seq, x);
1219   maybe_record_in_goto_queue (state, x);
1220 }
1221
1222 /* A subroutine of lower_try_finally.  There are multiple edges incoming
1223    and outgoing from the finally block.  Implement this by duplicating the
1224    finally block for every destination.  */
1225
1226 static void
1227 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1228 {
1229   gimple_seq finally;
1230   gimple_seq new_stmt;
1231   gimple_seq seq;
1232   gimple x, eh_else;
1233   tree tmp;
1234   location_t tf_loc = gimple_location (tf->try_finally_expr);
1235
1236   finally = gimple_try_cleanup (tf->top_p);
1237
1238   /* Notice EH_ELSE, and simplify some of the remaining code
1239      by considering FINALLY to be the normal return path only.  */
1240   eh_else = get_eh_else (finally);
1241   if (eh_else)
1242     finally = gimple_eh_else_n_body (eh_else);
1243
1244   tf->top_p_seq = gimple_try_eval (tf->top_p);
1245   new_stmt = NULL;
1246
1247   if (tf->may_fallthru)
1248     {
1249       seq = lower_try_finally_dup_block (finally, state, tf_loc);
1250       lower_eh_constructs_1 (state, &seq);
1251       gimple_seq_add_seq (&new_stmt, seq);
1252
1253       tmp = lower_try_finally_fallthru_label (tf);
1254       x = gimple_build_goto (tmp);
1255       gimple_set_location (x, tf_loc);
1256       gimple_seq_add_stmt (&new_stmt, x);
1257     }
1258
1259   if (tf->may_throw)
1260     {
1261       /* We don't need to copy the EH path of EH_ELSE,
1262          since it is only emitted once.  */
1263       if (eh_else)
1264         seq = gimple_eh_else_e_body (eh_else);
1265       else
1266         seq = lower_try_finally_dup_block (finally, state, tf_loc);
1267       lower_eh_constructs_1 (state, &seq);
1268
1269       emit_post_landing_pad (&eh_seq, tf->region);
1270       gimple_seq_add_seq (&eh_seq, seq);
1271       emit_resx (&eh_seq, tf->region);
1272     }
1273
1274   if (tf->goto_queue)
1275     {
1276       struct goto_queue_node *q, *qe;
1277       int return_index, index;
1278       struct labels_s
1279       {
1280         struct goto_queue_node *q;
1281         tree label;
1282       } *labels;
1283
1284       return_index = tf->dest_array.length ();
1285       labels = XCNEWVEC (struct labels_s, return_index + 1);
1286
1287       q = tf->goto_queue;
1288       qe = q + tf->goto_queue_active;
1289       for (; q < qe; q++)
1290         {
1291           index = q->index < 0 ? return_index : q->index;
1292
1293           if (!labels[index].q)
1294             labels[index].q = q;
1295         }
1296
1297       for (index = 0; index < return_index + 1; index++)
1298         {
1299           tree lab;
1300
1301           q = labels[index].q;
1302           if (! q)
1303             continue;
1304
1305           lab = labels[index].label
1306             = create_artificial_label (tf_loc);
1307
1308           if (index == return_index)
1309             do_return_redirection (q, lab, NULL);
1310           else
1311             do_goto_redirection (q, lab, NULL, tf);
1312
1313           x = gimple_build_label (lab);
1314           gimple_seq_add_stmt (&new_stmt, x);
1315
1316           seq = lower_try_finally_dup_block (finally, state, q->location);
1317           lower_eh_constructs_1 (state, &seq);
1318           gimple_seq_add_seq (&new_stmt, seq);
1319
1320           gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1321           maybe_record_in_goto_queue (state, q->cont_stmt);
1322         }
1323
1324       for (q = tf->goto_queue; q < qe; q++)
1325         {
1326           tree lab;
1327
1328           index = q->index < 0 ? return_index : q->index;
1329
1330           if (labels[index].q == q)
1331             continue;
1332
1333           lab = labels[index].label;
1334
1335           if (index == return_index)
1336             do_return_redirection (q, lab, NULL);
1337           else
1338             do_goto_redirection (q, lab, NULL, tf);
1339         }
1340
1341       replace_goto_queue (tf);
1342       free (labels);
1343     }
1344
1345   /* Need to link new stmts after running replace_goto_queue due
1346      to not wanting to process the same goto stmts twice.  */
1347   gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1348 }
1349
1350 /* A subroutine of lower_try_finally.  There are multiple edges incoming
1351    and outgoing from the finally block.  Implement this by instrumenting
1352    each incoming edge and creating a switch statement at the end of the
1353    finally block that branches to the appropriate destination.  */
1354
1355 static void
1356 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1357 {
1358   struct goto_queue_node *q, *qe;
1359   tree finally_tmp, finally_label;
1360   int return_index, eh_index, fallthru_index;
1361   int nlabels, ndests, j, last_case_index;
1362   tree last_case;
1363   vec<tree> case_label_vec;
1364   gimple_seq switch_body = NULL;
1365   gimple x, eh_else;
1366   tree tmp;
1367   gimple switch_stmt;
1368   gimple_seq finally;
1369   struct pointer_map_t *cont_map = NULL;
1370   /* The location of the TRY_FINALLY stmt.  */
1371   location_t tf_loc = gimple_location (tf->try_finally_expr);
1372   /* The location of the finally block.  */
1373   location_t finally_loc;
1374
1375   finally = gimple_try_cleanup (tf->top_p);
1376   eh_else = get_eh_else (finally);
1377
1378   /* Mash the TRY block to the head of the chain.  */
1379   tf->top_p_seq = gimple_try_eval (tf->top_p);
1380
1381   /* The location of the finally is either the last stmt in the finally
1382      block or the location of the TRY_FINALLY itself.  */
1383   x = gimple_seq_last_stmt (finally);
1384   finally_loc = x ? gimple_location (x) : tf_loc;
1385
1386   /* Lower the finally block itself.  */
1387   lower_eh_constructs_1 (state, &finally);
1388
1389   /* Prepare for switch statement generation.  */
1390   nlabels = tf->dest_array.length ();
1391   return_index = nlabels;
1392   eh_index = return_index + tf->may_return;
1393   fallthru_index = eh_index + (tf->may_throw && !eh_else);
1394   ndests = fallthru_index + tf->may_fallthru;
1395
1396   finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1397   finally_label = create_artificial_label (finally_loc);
1398
1399   /* We use vec::quick_push on case_label_vec throughout this function,
1400      since we know the size in advance and allocate precisely as muce
1401      space as needed.  */
1402   case_label_vec.create (ndests);
1403   last_case = NULL;
1404   last_case_index = 0;
1405
1406   /* Begin inserting code for getting to the finally block.  Things
1407      are done in this order to correspond to the sequence the code is
1408      laid out.  */
1409
1410   if (tf->may_fallthru)
1411     {
1412       x = gimple_build_assign (finally_tmp,
1413                                build_int_cst (integer_type_node,
1414                                               fallthru_index));
1415       gimple_seq_add_stmt (&tf->top_p_seq, x);
1416
1417       tmp = build_int_cst (integer_type_node, fallthru_index);
1418       last_case = build_case_label (tmp, NULL,
1419                                     create_artificial_label (tf_loc));
1420       case_label_vec.quick_push (last_case);
1421       last_case_index++;
1422
1423       x = gimple_build_label (CASE_LABEL (last_case));
1424       gimple_seq_add_stmt (&switch_body, x);
1425
1426       tmp = lower_try_finally_fallthru_label (tf);
1427       x = gimple_build_goto (tmp);
1428       gimple_set_location (x, tf_loc);
1429       gimple_seq_add_stmt (&switch_body, x);
1430     }
1431
1432   /* For EH_ELSE, emit the exception path (plus resx) now, then
1433      subsequently we only need consider the normal path.  */
1434   if (eh_else)
1435     {
1436       if (tf->may_throw)
1437         {
1438           finally = gimple_eh_else_e_body (eh_else);
1439           lower_eh_constructs_1 (state, &finally);
1440
1441           emit_post_landing_pad (&eh_seq, tf->region);
1442           gimple_seq_add_seq (&eh_seq, finally);
1443           emit_resx (&eh_seq, tf->region);
1444         }
1445
1446       finally = gimple_eh_else_n_body (eh_else);
1447     }
1448   else if (tf->may_throw)
1449     {
1450       emit_post_landing_pad (&eh_seq, tf->region);
1451
1452       x = gimple_build_assign (finally_tmp,
1453                                build_int_cst (integer_type_node, eh_index));
1454       gimple_seq_add_stmt (&eh_seq, x);
1455
1456       x = gimple_build_goto (finally_label);
1457       gimple_set_location (x, tf_loc);
1458       gimple_seq_add_stmt (&eh_seq, x);
1459
1460       tmp = build_int_cst (integer_type_node, eh_index);
1461       last_case = build_case_label (tmp, NULL,
1462                                     create_artificial_label (tf_loc));
1463       case_label_vec.quick_push (last_case);
1464       last_case_index++;
1465
1466       x = gimple_build_label (CASE_LABEL (last_case));
1467       gimple_seq_add_stmt (&eh_seq, x);
1468       emit_resx (&eh_seq, tf->region);
1469     }
1470
1471   x = gimple_build_label (finally_label);
1472   gimple_seq_add_stmt (&tf->top_p_seq, x);
1473
1474   gimple_seq_add_seq (&tf->top_p_seq, finally);
1475
1476   /* Redirect each incoming goto edge.  */
1477   q = tf->goto_queue;
1478   qe = q + tf->goto_queue_active;
1479   j = last_case_index + tf->may_return;
1480   /* Prepare the assignments to finally_tmp that are executed upon the
1481      entrance through a particular edge. */
1482   for (; q < qe; ++q)
1483     {
1484       gimple_seq mod = NULL;
1485       int switch_id;
1486       unsigned int case_index;
1487
1488       if (q->index < 0)
1489         {
1490           x = gimple_build_assign (finally_tmp,
1491                                    build_int_cst (integer_type_node,
1492                                                   return_index));
1493           gimple_seq_add_stmt (&mod, x);
1494           do_return_redirection (q, finally_label, mod);
1495           switch_id = return_index;
1496         }
1497       else
1498         {
1499           x = gimple_build_assign (finally_tmp,
1500                                    build_int_cst (integer_type_node, q->index));
1501           gimple_seq_add_stmt (&mod, x);
1502           do_goto_redirection (q, finally_label, mod, tf);
1503           switch_id = q->index;
1504         }
1505
1506       case_index = j + q->index;
1507       if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1508         {
1509           tree case_lab;
1510           void **slot;
1511           tmp = build_int_cst (integer_type_node, switch_id);
1512           case_lab = build_case_label (tmp, NULL,
1513                                        create_artificial_label (tf_loc));
1514           /* We store the cont_stmt in the pointer map, so that we can recover
1515              it in the loop below.  */
1516           if (!cont_map)
1517             cont_map = pointer_map_create ();
1518           slot = pointer_map_insert (cont_map, case_lab);
1519           *slot = q->cont_stmt;
1520           case_label_vec.quick_push (case_lab);
1521         }
1522     }
1523   for (j = last_case_index; j < last_case_index + nlabels; j++)
1524     {
1525       gimple cont_stmt;
1526       void **slot;
1527
1528       last_case = case_label_vec[j];
1529
1530       gcc_assert (last_case);
1531       gcc_assert (cont_map);
1532
1533       slot = pointer_map_contains (cont_map, last_case);
1534       gcc_assert (slot);
1535       cont_stmt = *(gimple *) slot;
1536
1537       x = gimple_build_label (CASE_LABEL (last_case));
1538       gimple_seq_add_stmt (&switch_body, x);
1539       gimple_seq_add_stmt (&switch_body, cont_stmt);
1540       maybe_record_in_goto_queue (state, cont_stmt);
1541     }
1542   if (cont_map)
1543     pointer_map_destroy (cont_map);
1544
1545   replace_goto_queue (tf);
1546
1547   /* Make sure that the last case is the default label, as one is required.
1548      Then sort the labels, which is also required in GIMPLE.  */
1549   CASE_LOW (last_case) = NULL;
1550   sort_case_labels (case_label_vec);
1551
1552   /* Build the switch statement, setting last_case to be the default
1553      label.  */
1554   switch_stmt = gimple_build_switch (finally_tmp, last_case,
1555                                      case_label_vec);
1556   gimple_set_location (switch_stmt, finally_loc);
1557
1558   /* Need to link SWITCH_STMT after running replace_goto_queue
1559      due to not wanting to process the same goto stmts twice.  */
1560   gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1561   gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1562 }
1563
1564 /* Decide whether or not we are going to duplicate the finally block.
1565    There are several considerations.
1566
1567    First, if this is Java, then the finally block contains code
1568    written by the user.  It has line numbers associated with it,
1569    so duplicating the block means it's difficult to set a breakpoint.
1570    Since controlling code generation via -g is verboten, we simply
1571    never duplicate code without optimization.
1572
1573    Second, we'd like to prevent egregious code growth.  One way to
1574    do this is to estimate the size of the finally block, multiply
1575    that by the number of copies we'd need to make, and compare against
1576    the estimate of the size of the switch machinery we'd have to add.  */
1577
1578 static bool
1579 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1580 {
1581   int f_estimate, sw_estimate;
1582   gimple eh_else;
1583
1584   /* If there's an EH_ELSE involved, the exception path is separate
1585      and really doesn't come into play for this computation.  */
1586   eh_else = get_eh_else (finally);
1587   if (eh_else)
1588     {
1589       ndests -= may_throw;
1590       finally = gimple_eh_else_n_body (eh_else);
1591     }
1592
1593   if (!optimize)
1594     {
1595       gimple_stmt_iterator gsi;
1596
1597       if (ndests == 1)
1598         return true;
1599
1600       for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1601         {
1602           gimple stmt = gsi_stmt (gsi);
1603           if (!is_gimple_debug (stmt) && !gimple_clobber_p (stmt))
1604             return false;
1605         }
1606       return true;
1607     }
1608
1609   /* Finally estimate N times, plus N gotos.  */
1610   f_estimate = count_insns_seq (finally, &eni_size_weights);
1611   f_estimate = (f_estimate + 1) * ndests;
1612
1613   /* Switch statement (cost 10), N variable assignments, N gotos.  */
1614   sw_estimate = 10 + 2 * ndests;
1615
1616   /* Optimize for size clearly wants our best guess.  */
1617   if (optimize_function_for_size_p (cfun))
1618     return f_estimate < sw_estimate;
1619
1620   /* ??? These numbers are completely made up so far.  */
1621   if (optimize > 1)
1622     return f_estimate < 100 || f_estimate < sw_estimate * 2;
1623   else
1624     return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1625 }
1626
1627 /* REG is the enclosing region for a possible cleanup region, or the region
1628    itself.  Returns TRUE if such a region would be unreachable.
1629
1630    Cleanup regions within a must-not-throw region aren't actually reachable
1631    even if there are throwing stmts within them, because the personality
1632    routine will call terminate before unwinding.  */
1633
1634 static bool
1635 cleanup_is_dead_in (eh_region reg)
1636 {
1637   while (reg && reg->type == ERT_CLEANUP)
1638     reg = reg->outer;
1639   return (reg && reg->type == ERT_MUST_NOT_THROW);
1640 }
1641
1642 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY_FINALLY nodes
1643    to a sequence of labels and blocks, plus the exception region trees
1644    that record all the magic.  This is complicated by the need to
1645    arrange for the FINALLY block to be executed on all exits.  */
1646
1647 static gimple_seq
1648 lower_try_finally (struct leh_state *state, gimple tp)
1649 {
1650   struct leh_tf_state this_tf;
1651   struct leh_state this_state;
1652   int ndests;
1653   gimple_seq old_eh_seq;
1654
1655   /* Process the try block.  */
1656
1657   memset (&this_tf, 0, sizeof (this_tf));
1658   this_tf.try_finally_expr = tp;
1659   this_tf.top_p = tp;
1660   this_tf.outer = state;
1661   if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1662     {
1663       this_tf.region = gen_eh_region_cleanup (state->cur_region);
1664       this_state.cur_region = this_tf.region;
1665     }
1666   else
1667     {
1668       this_tf.region = NULL;
1669       this_state.cur_region = state->cur_region;
1670     }
1671
1672   this_state.ehp_region = state->ehp_region;
1673   this_state.tf = &this_tf;
1674
1675   old_eh_seq = eh_seq;
1676   eh_seq = NULL;
1677
1678   lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1679
1680   /* Determine if the try block is escaped through the bottom.  */
1681   this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1682
1683   /* Determine if any exceptions are possible within the try block.  */
1684   if (this_tf.region)
1685     this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1686   if (this_tf.may_throw)
1687     honor_protect_cleanup_actions (state, &this_state, &this_tf);
1688
1689   /* Determine how many edges (still) reach the finally block.  Or rather,
1690      how many destinations are reached by the finally block.  Use this to
1691      determine how we process the finally block itself.  */
1692
1693   ndests = this_tf.dest_array.length ();
1694   ndests += this_tf.may_fallthru;
1695   ndests += this_tf.may_return;
1696   ndests += this_tf.may_throw;
1697
1698   /* If the FINALLY block is not reachable, dike it out.  */
1699   if (ndests == 0)
1700     {
1701       gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1702       gimple_try_set_cleanup (tp, NULL);
1703     }
1704   /* If the finally block doesn't fall through, then any destination
1705      we might try to impose there isn't reached either.  There may be
1706      some minor amount of cleanup and redirection still needed.  */
1707   else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1708     lower_try_finally_nofallthru (state, &this_tf);
1709
1710   /* We can easily special-case redirection to a single destination.  */
1711   else if (ndests == 1)
1712     lower_try_finally_onedest (state, &this_tf);
1713   else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1714                                     gimple_try_cleanup (tp)))
1715     lower_try_finally_copy (state, &this_tf);
1716   else
1717     lower_try_finally_switch (state, &this_tf);
1718
1719   /* If someone requested we add a label at the end of the transformed
1720      block, do so.  */
1721   if (this_tf.fallthru_label)
1722     {
1723       /* This must be reached only if ndests == 0. */
1724       gimple x = gimple_build_label (this_tf.fallthru_label);
1725       gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1726     }
1727
1728   this_tf.dest_array.release ();
1729   free (this_tf.goto_queue);
1730   if (this_tf.goto_queue_map)
1731     pointer_map_destroy (this_tf.goto_queue_map);
1732
1733   /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1734      If there was no old eh_seq, then the append is trivially already done.  */
1735   if (old_eh_seq)
1736     {
1737       if (eh_seq == NULL)
1738         eh_seq = old_eh_seq;
1739       else
1740         {
1741           gimple_seq new_eh_seq = eh_seq;
1742           eh_seq = old_eh_seq;
1743           gimple_seq_add_seq (&eh_seq, new_eh_seq);
1744         }
1745     }
1746
1747   return this_tf.top_p_seq;
1748 }
1749
1750 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY_CATCH with a
1751    list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1752    exception region trees that records all the magic.  */
1753
1754 static gimple_seq
1755 lower_catch (struct leh_state *state, gimple tp)
1756 {
1757   eh_region try_region = NULL;
1758   struct leh_state this_state = *state;
1759   gimple_stmt_iterator gsi;
1760   tree out_label;
1761   gimple_seq new_seq, cleanup;
1762   gimple x;
1763   location_t try_catch_loc = gimple_location (tp);
1764
1765   if (flag_exceptions)
1766     {
1767       try_region = gen_eh_region_try (state->cur_region);
1768       this_state.cur_region = try_region;
1769     }
1770
1771   lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1772
1773   if (!eh_region_may_contain_throw (try_region))
1774     return gimple_try_eval (tp);
1775
1776   new_seq = NULL;
1777   emit_eh_dispatch (&new_seq, try_region);
1778   emit_resx (&new_seq, try_region);
1779
1780   this_state.cur_region = state->cur_region;
1781   this_state.ehp_region = try_region;
1782
1783   out_label = NULL;
1784   cleanup = gimple_try_cleanup (tp);
1785   for (gsi = gsi_start (cleanup);
1786        !gsi_end_p (gsi);
1787        gsi_next (&gsi))
1788     {
1789       eh_catch c;
1790       gimple gcatch;
1791       gimple_seq handler;
1792
1793       gcatch = gsi_stmt (gsi);
1794       c = gen_eh_region_catch (try_region, gimple_catch_types (gcatch));
1795
1796       handler = gimple_catch_handler (gcatch);
1797       lower_eh_constructs_1 (&this_state, &handler);
1798
1799       c->label = create_artificial_label (UNKNOWN_LOCATION);
1800       x = gimple_build_label (c->label);
1801       gimple_seq_add_stmt (&new_seq, x);
1802
1803       gimple_seq_add_seq (&new_seq, handler);
1804
1805       if (gimple_seq_may_fallthru (new_seq))
1806         {
1807           if (!out_label)
1808             out_label = create_artificial_label (try_catch_loc);
1809
1810           x = gimple_build_goto (out_label);
1811           gimple_seq_add_stmt (&new_seq, x);
1812         }
1813       if (!c->type_list)
1814         break;
1815     }
1816
1817   gimple_try_set_cleanup (tp, new_seq);
1818
1819   return frob_into_branch_around (tp, try_region, out_label);
1820 }
1821
1822 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY with a
1823    GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1824    region trees that record all the magic.  */
1825
1826 static gimple_seq
1827 lower_eh_filter (struct leh_state *state, gimple tp)
1828 {
1829   struct leh_state this_state = *state;
1830   eh_region this_region = NULL;
1831   gimple inner, x;
1832   gimple_seq new_seq;
1833
1834   inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1835
1836   if (flag_exceptions)
1837     {
1838       this_region = gen_eh_region_allowed (state->cur_region,
1839                                            gimple_eh_filter_types (inner));
1840       this_state.cur_region = this_region;
1841     }
1842
1843   lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1844
1845   if (!eh_region_may_contain_throw (this_region))
1846     return gimple_try_eval (tp);
1847
1848   new_seq = NULL;
1849   this_state.cur_region = state->cur_region;
1850   this_state.ehp_region = this_region;
1851
1852   emit_eh_dispatch (&new_seq, this_region);
1853   emit_resx (&new_seq, this_region);
1854
1855   this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1856   x = gimple_build_label (this_region->u.allowed.label);
1857   gimple_seq_add_stmt (&new_seq, x);
1858
1859   lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1860   gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1861
1862   gimple_try_set_cleanup (tp, new_seq);
1863
1864   return frob_into_branch_around (tp, this_region, NULL);
1865 }
1866
1867 /* A subroutine of lower_eh_constructs_1.  Lower a GIMPLE_TRY with
1868    an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1869    plus the exception region trees that record all the magic.  */
1870
1871 static gimple_seq
1872 lower_eh_must_not_throw (struct leh_state *state, gimple tp)
1873 {
1874   struct leh_state this_state = *state;
1875
1876   if (flag_exceptions)
1877     {
1878       gimple inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1879       eh_region this_region;
1880
1881       this_region = gen_eh_region_must_not_throw (state->cur_region);
1882       this_region->u.must_not_throw.failure_decl
1883         = gimple_eh_must_not_throw_fndecl (inner);
1884       this_region->u.must_not_throw.failure_loc
1885         = LOCATION_LOCUS (gimple_location (tp));
1886
1887       /* In order to get mangling applied to this decl, we must mark it
1888          used now.  Otherwise, pass_ipa_free_lang_data won't think it
1889          needs to happen.  */
1890       TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1891
1892       this_state.cur_region = this_region;
1893     }
1894
1895   lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1896
1897   return gimple_try_eval (tp);
1898 }
1899
1900 /* Implement a cleanup expression.  This is similar to try-finally,
1901    except that we only execute the cleanup block for exception edges.  */
1902
1903 static gimple_seq
1904 lower_cleanup (struct leh_state *state, gimple tp)
1905 {
1906   struct leh_state this_state = *state;
1907   eh_region this_region = NULL;
1908   struct leh_tf_state fake_tf;
1909   gimple_seq result;
1910   bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1911
1912   if (flag_exceptions && !cleanup_dead)
1913     {
1914       this_region = gen_eh_region_cleanup (state->cur_region);
1915       this_state.cur_region = this_region;
1916     }
1917
1918   lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1919
1920   if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1921     return gimple_try_eval (tp);
1922
1923   /* Build enough of a try-finally state so that we can reuse
1924      honor_protect_cleanup_actions.  */
1925   memset (&fake_tf, 0, sizeof (fake_tf));
1926   fake_tf.top_p = fake_tf.try_finally_expr = tp;
1927   fake_tf.outer = state;
1928   fake_tf.region = this_region;
1929   fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1930   fake_tf.may_throw = true;
1931
1932   honor_protect_cleanup_actions (state, NULL, &fake_tf);
1933
1934   if (fake_tf.may_throw)
1935     {
1936       /* In this case honor_protect_cleanup_actions had nothing to do,
1937          and we should process this normally.  */
1938       lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1939       result = frob_into_branch_around (tp, this_region,
1940                                         fake_tf.fallthru_label);
1941     }
1942   else
1943     {
1944       /* In this case honor_protect_cleanup_actions did nearly all of
1945          the work.  All we have left is to append the fallthru_label.  */
1946
1947       result = gimple_try_eval (tp);
1948       if (fake_tf.fallthru_label)
1949         {
1950           gimple x = gimple_build_label (fake_tf.fallthru_label);
1951           gimple_seq_add_stmt (&result, x);
1952         }
1953     }
1954   return result;
1955 }
1956
1957 /* Main loop for lowering eh constructs. Also moves gsi to the next
1958    statement. */
1959
1960 static void
1961 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1962 {
1963   gimple_seq replace;
1964   gimple x;
1965   gimple stmt = gsi_stmt (*gsi);
1966
1967   switch (gimple_code (stmt))
1968     {
1969     case GIMPLE_CALL:
1970       {
1971         tree fndecl = gimple_call_fndecl (stmt);
1972         tree rhs, lhs;
1973
1974         if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1975           switch (DECL_FUNCTION_CODE (fndecl))
1976             {
1977             case BUILT_IN_EH_POINTER:
1978               /* The front end may have generated a call to
1979                  __builtin_eh_pointer (0) within a catch region.  Replace
1980                  this zero argument with the current catch region number.  */
1981               if (state->ehp_region)
1982                 {
1983                   tree nr = build_int_cst (integer_type_node,
1984                                            state->ehp_region->index);
1985                   gimple_call_set_arg (stmt, 0, nr);
1986                 }
1987               else
1988                 {
1989                   /* The user has dome something silly.  Remove it.  */
1990                   rhs = null_pointer_node;
1991                   goto do_replace;
1992                 }
1993               break;
1994
1995             case BUILT_IN_EH_FILTER:
1996               /* ??? This should never appear, but since it's a builtin it
1997                  is accessible to abuse by users.  Just remove it and
1998                  replace the use with the arbitrary value zero.  */
1999               rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2000             do_replace:
2001               lhs = gimple_call_lhs (stmt);
2002               x = gimple_build_assign (lhs, rhs);
2003               gsi_insert_before (gsi, x, GSI_SAME_STMT);
2004               /* FALLTHRU */
2005
2006             case BUILT_IN_EH_COPY_VALUES:
2007               /* Likewise this should not appear.  Remove it.  */
2008               gsi_remove (gsi, true);
2009               return;
2010
2011             default:
2012               break;
2013             }
2014       }
2015       /* FALLTHRU */
2016
2017     case GIMPLE_ASSIGN:
2018       /* If the stmt can throw use a new temporary for the assignment
2019          to a LHS.  This makes sure the old value of the LHS is
2020          available on the EH edge.  Only do so for statements that
2021          potentially fall through (no noreturn calls e.g.), otherwise
2022          this new assignment might create fake fallthru regions.  */
2023       if (stmt_could_throw_p (stmt)
2024           && gimple_has_lhs (stmt)
2025           && gimple_stmt_may_fallthru (stmt)
2026           && !tree_could_throw_p (gimple_get_lhs (stmt))
2027           && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2028         {
2029           tree lhs = gimple_get_lhs (stmt);
2030           tree tmp = create_tmp_var (TREE_TYPE (lhs), NULL);
2031           gimple s = gimple_build_assign (lhs, tmp);
2032           gimple_set_location (s, gimple_location (stmt));
2033           gimple_set_block (s, gimple_block (stmt));
2034           gimple_set_lhs (stmt, tmp);
2035           if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2036               || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2037             DECL_GIMPLE_REG_P (tmp) = 1;
2038           gsi_insert_after (gsi, s, GSI_SAME_STMT);
2039         }
2040       /* Look for things that can throw exceptions, and record them.  */
2041       if (state->cur_region && stmt_could_throw_p (stmt))
2042         {
2043           record_stmt_eh_region (state->cur_region, stmt);
2044           note_eh_region_may_contain_throw (state->cur_region);
2045         }
2046       break;
2047
2048     case GIMPLE_COND:
2049     case GIMPLE_GOTO:
2050     case GIMPLE_RETURN:
2051       maybe_record_in_goto_queue (state, stmt);
2052       break;
2053
2054     case GIMPLE_SWITCH:
2055       verify_norecord_switch_expr (state, stmt);
2056       break;
2057
2058     case GIMPLE_TRY:
2059       if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
2060         replace = lower_try_finally (state, stmt);
2061       else
2062         {
2063           x = gimple_seq_first_stmt (gimple_try_cleanup (stmt));
2064           if (!x)
2065             {
2066               replace = gimple_try_eval (stmt);
2067               lower_eh_constructs_1 (state, &replace);
2068             }
2069           else
2070             switch (gimple_code (x))
2071               {
2072                 case GIMPLE_CATCH:
2073                     replace = lower_catch (state, stmt);
2074                     break;
2075                 case GIMPLE_EH_FILTER:
2076                     replace = lower_eh_filter (state, stmt);
2077                     break;
2078                 case GIMPLE_EH_MUST_NOT_THROW:
2079                     replace = lower_eh_must_not_throw (state, stmt);
2080                     break;
2081                 case GIMPLE_EH_ELSE:
2082                     /* This code is only valid with GIMPLE_TRY_FINALLY.  */
2083                     gcc_unreachable ();
2084                 default:
2085                     replace = lower_cleanup (state, stmt);
2086                     break;
2087               }
2088         }
2089
2090       /* Remove the old stmt and insert the transformed sequence
2091          instead. */
2092       gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2093       gsi_remove (gsi, true);
2094
2095       /* Return since we don't want gsi_next () */
2096       return;
2097
2098     case GIMPLE_EH_ELSE:
2099       /* We should be eliminating this in lower_try_finally et al.  */
2100       gcc_unreachable ();
2101
2102     default:
2103       /* A type, a decl, or some kind of statement that we're not
2104          interested in.  Don't walk them.  */
2105       break;
2106     }
2107
2108   gsi_next (gsi);
2109 }
2110
2111 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2112
2113 static void
2114 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2115 {
2116   gimple_stmt_iterator gsi;
2117   for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2118     lower_eh_constructs_2 (state, &gsi);
2119 }
2120
2121 static unsigned int
2122 lower_eh_constructs (void)
2123 {
2124   struct leh_state null_state;
2125   gimple_seq bodyp;
2126
2127   bodyp = gimple_body (current_function_decl);
2128   if (bodyp == NULL)
2129     return 0;
2130
2131   finally_tree.create (31);
2132   eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2133   memset (&null_state, 0, sizeof (null_state));
2134
2135   collect_finally_tree_1 (bodyp, NULL);
2136   lower_eh_constructs_1 (&null_state, &bodyp);
2137   gimple_set_body (current_function_decl, bodyp);
2138
2139   /* We assume there's a return statement, or something, at the end of
2140      the function, and thus ploping the EH sequence afterward won't
2141      change anything.  */
2142   gcc_assert (!gimple_seq_may_fallthru (bodyp));
2143   gimple_seq_add_seq (&bodyp, eh_seq);
2144
2145   /* We assume that since BODYP already existed, adding EH_SEQ to it
2146      didn't change its value, and we don't have to re-set the function.  */
2147   gcc_assert (bodyp == gimple_body (current_function_decl));
2148
2149   finally_tree.dispose ();
2150   BITMAP_FREE (eh_region_may_contain_throw_map);
2151   eh_seq = NULL;
2152
2153   /* If this function needs a language specific EH personality routine
2154      and the frontend didn't already set one do so now.  */
2155   if (function_needs_eh_personality (cfun) == eh_personality_lang
2156       && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2157     DECL_FUNCTION_PERSONALITY (current_function_decl)
2158       = lang_hooks.eh_personality ();
2159
2160   return 0;
2161 }
2162
2163 namespace {
2164
2165 const pass_data pass_data_lower_eh =
2166 {
2167   GIMPLE_PASS, /* type */
2168   "eh", /* name */
2169   OPTGROUP_NONE, /* optinfo_flags */
2170   false, /* has_gate */
2171   true, /* has_execute */
2172   TV_TREE_EH, /* tv_id */
2173   PROP_gimple_lcf, /* properties_required */
2174   PROP_gimple_leh, /* properties_provided */
2175   0, /* properties_destroyed */
2176   0, /* todo_flags_start */
2177   0, /* todo_flags_finish */
2178 };
2179
2180 class pass_lower_eh : public gimple_opt_pass
2181 {
2182 public:
2183   pass_lower_eh (gcc::context *ctxt)
2184     : gimple_opt_pass (pass_data_lower_eh, ctxt)
2185   {}
2186
2187   /* opt_pass methods: */
2188   unsigned int execute () { return lower_eh_constructs (); }
2189
2190 }; // class pass_lower_eh
2191
2192 } // anon namespace
2193
2194 gimple_opt_pass *
2195 make_pass_lower_eh (gcc::context *ctxt)
2196 {
2197   return new pass_lower_eh (ctxt);
2198 }
2199 \f
2200 /* Create the multiple edges from an EH_DISPATCH statement to all of
2201    the possible handlers for its EH region.  Return true if there's
2202    no fallthru edge; false if there is.  */
2203
2204 bool
2205 make_eh_dispatch_edges (gimple stmt)
2206 {
2207   eh_region r;
2208   eh_catch c;
2209   basic_block src, dst;
2210
2211   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2212   src = gimple_bb (stmt);
2213
2214   switch (r->type)
2215     {
2216     case ERT_TRY:
2217       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2218         {
2219           dst = label_to_block (c->label);
2220           make_edge (src, dst, 0);
2221
2222           /* A catch-all handler doesn't have a fallthru.  */
2223           if (c->type_list == NULL)
2224             return false;
2225         }
2226       break;
2227
2228     case ERT_ALLOWED_EXCEPTIONS:
2229       dst = label_to_block (r->u.allowed.label);
2230       make_edge (src, dst, 0);
2231       break;
2232
2233     default:
2234       gcc_unreachable ();
2235     }
2236
2237   return true;
2238 }
2239
2240 /* Create the single EH edge from STMT to its nearest landing pad,
2241    if there is such a landing pad within the current function.  */
2242
2243 void
2244 make_eh_edges (gimple stmt)
2245 {
2246   basic_block src, dst;
2247   eh_landing_pad lp;
2248   int lp_nr;
2249
2250   lp_nr = lookup_stmt_eh_lp (stmt);
2251   if (lp_nr <= 0)
2252     return;
2253
2254   lp = get_eh_landing_pad_from_number (lp_nr);
2255   gcc_assert (lp != NULL);
2256
2257   src = gimple_bb (stmt);
2258   dst = label_to_block (lp->post_landing_pad);
2259   make_edge (src, dst, EDGE_EH);
2260 }
2261
2262 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2263    do not actually perform the final edge redirection.
2264
2265    CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2266    we intend to change the destination EH region as well; this means
2267    EH_LANDING_PAD_NR must already be set on the destination block label.
2268    If false, we're being called from generic cfg manipulation code and we
2269    should preserve our place within the region tree.  */
2270
2271 static void
2272 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2273 {
2274   eh_landing_pad old_lp, new_lp;
2275   basic_block old_bb;
2276   gimple throw_stmt;
2277   int old_lp_nr, new_lp_nr;
2278   tree old_label, new_label;
2279   edge_iterator ei;
2280   edge e;
2281
2282   old_bb = edge_in->dest;
2283   old_label = gimple_block_label (old_bb);
2284   old_lp_nr = EH_LANDING_PAD_NR (old_label);
2285   gcc_assert (old_lp_nr > 0);
2286   old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2287
2288   throw_stmt = last_stmt (edge_in->src);
2289   gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2290
2291   new_label = gimple_block_label (new_bb);
2292
2293   /* Look for an existing region that might be using NEW_BB already.  */
2294   new_lp_nr = EH_LANDING_PAD_NR (new_label);
2295   if (new_lp_nr)
2296     {
2297       new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2298       gcc_assert (new_lp);
2299
2300       /* Unless CHANGE_REGION is true, the new and old landing pad
2301          had better be associated with the same EH region.  */
2302       gcc_assert (change_region || new_lp->region == old_lp->region);
2303     }
2304   else
2305     {
2306       new_lp = NULL;
2307       gcc_assert (!change_region);
2308     }
2309
2310   /* Notice when we redirect the last EH edge away from OLD_BB.  */
2311   FOR_EACH_EDGE (e, ei, old_bb->preds)
2312     if (e != edge_in && (e->flags & EDGE_EH))
2313       break;
2314
2315   if (new_lp)
2316     {
2317       /* NEW_LP already exists.  If there are still edges into OLD_LP,
2318          there's nothing to do with the EH tree.  If there are no more
2319          edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2320          If CHANGE_REGION is true, then our caller is expecting to remove
2321          the landing pad.  */
2322       if (e == NULL && !change_region)
2323         remove_eh_landing_pad (old_lp);
2324     }
2325   else
2326     {
2327       /* No correct landing pad exists.  If there are no more edges
2328          into OLD_LP, then we can simply re-use the existing landing pad.
2329          Otherwise, we have to create a new landing pad.  */
2330       if (e == NULL)
2331         {
2332           EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2333           new_lp = old_lp;
2334         }
2335       else
2336         new_lp = gen_eh_landing_pad (old_lp->region);
2337       new_lp->post_landing_pad = new_label;
2338       EH_LANDING_PAD_NR (new_label) = new_lp->index;
2339     }
2340
2341   /* Maybe move the throwing statement to the new region.  */
2342   if (old_lp != new_lp)
2343     {
2344       remove_stmt_from_eh_lp (throw_stmt);
2345       add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2346     }
2347 }
2348
2349 /* Redirect EH edge E to NEW_BB.  */
2350
2351 edge
2352 redirect_eh_edge (edge edge_in, basic_block new_bb)
2353 {
2354   redirect_eh_edge_1 (edge_in, new_bb, false);
2355   return ssa_redirect_edge (edge_in, new_bb);
2356 }
2357
2358 /* This is a subroutine of gimple_redirect_edge_and_branch.  Update the
2359    labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2360    The actual edge update will happen in the caller.  */
2361
2362 void
2363 redirect_eh_dispatch_edge (gimple stmt, edge e, basic_block new_bb)
2364 {
2365   tree new_lab = gimple_block_label (new_bb);
2366   bool any_changed = false;
2367   basic_block old_bb;
2368   eh_region r;
2369   eh_catch c;
2370
2371   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2372   switch (r->type)
2373     {
2374     case ERT_TRY:
2375       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2376         {
2377           old_bb = label_to_block (c->label);
2378           if (old_bb == e->dest)
2379             {
2380               c->label = new_lab;
2381               any_changed = true;
2382             }
2383         }
2384       break;
2385
2386     case ERT_ALLOWED_EXCEPTIONS:
2387       old_bb = label_to_block (r->u.allowed.label);
2388       gcc_assert (old_bb == e->dest);
2389       r->u.allowed.label = new_lab;
2390       any_changed = true;
2391       break;
2392
2393     default:
2394       gcc_unreachable ();
2395     }
2396
2397   gcc_assert (any_changed);
2398 }
2399 \f
2400 /* Helper function for operation_could_trap_p and stmt_could_throw_p.  */
2401
2402 bool
2403 operation_could_trap_helper_p (enum tree_code op,
2404                                bool fp_operation,
2405                                bool honor_trapv,
2406                                bool honor_nans,
2407                                bool honor_snans,
2408                                tree divisor,
2409                                bool *handled)
2410 {
2411   *handled = true;
2412   switch (op)
2413     {
2414     case TRUNC_DIV_EXPR:
2415     case CEIL_DIV_EXPR:
2416     case FLOOR_DIV_EXPR:
2417     case ROUND_DIV_EXPR:
2418     case EXACT_DIV_EXPR:
2419     case CEIL_MOD_EXPR:
2420     case FLOOR_MOD_EXPR:
2421     case ROUND_MOD_EXPR:
2422     case TRUNC_MOD_EXPR:
2423     case RDIV_EXPR:
2424       if (honor_snans || honor_trapv)
2425         return true;
2426       if (fp_operation)
2427         return flag_trapping_math;
2428       if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2429         return true;
2430       return false;
2431
2432     case LT_EXPR:
2433     case LE_EXPR:
2434     case GT_EXPR:
2435     case GE_EXPR:
2436     case LTGT_EXPR:
2437       /* Some floating point comparisons may trap.  */
2438       return honor_nans;
2439
2440     case EQ_EXPR:
2441     case NE_EXPR:
2442     case UNORDERED_EXPR:
2443     case ORDERED_EXPR:
2444     case UNLT_EXPR:
2445     case UNLE_EXPR:
2446     case UNGT_EXPR:
2447     case UNGE_EXPR:
2448     case UNEQ_EXPR:
2449       return honor_snans;
2450
2451     case CONVERT_EXPR:
2452     case FIX_TRUNC_EXPR:
2453       /* Conversion of floating point might trap.  */
2454       return honor_nans;
2455
2456     case NEGATE_EXPR:
2457     case ABS_EXPR:
2458     case CONJ_EXPR:
2459       /* These operations don't trap with floating point.  */
2460       if (honor_trapv)
2461         return true;
2462       return false;
2463
2464     case PLUS_EXPR:
2465     case MINUS_EXPR:
2466     case MULT_EXPR:
2467       /* Any floating arithmetic may trap.  */
2468       if (fp_operation && flag_trapping_math)
2469         return true;
2470       if (honor_trapv)
2471         return true;
2472       return false;
2473
2474     case COMPLEX_EXPR:
2475     case CONSTRUCTOR:
2476       /* Constructing an object cannot trap.  */
2477       return false;
2478
2479     default:
2480       /* Any floating arithmetic may trap.  */
2481       if (fp_operation && flag_trapping_math)
2482         return true;
2483
2484       *handled = false;
2485       return false;
2486     }
2487 }
2488
2489 /* Return true if operation OP may trap.  FP_OPERATION is true if OP is applied
2490    on floating-point values.  HONOR_TRAPV is true if OP is applied on integer
2491    type operands that may trap.  If OP is a division operator, DIVISOR contains
2492    the value of the divisor.  */
2493
2494 bool
2495 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2496                         tree divisor)
2497 {
2498   bool honor_nans = (fp_operation && flag_trapping_math
2499                      && !flag_finite_math_only);
2500   bool honor_snans = fp_operation && flag_signaling_nans != 0;
2501   bool handled;
2502
2503   if (TREE_CODE_CLASS (op) != tcc_comparison
2504       && TREE_CODE_CLASS (op) != tcc_unary
2505       && TREE_CODE_CLASS (op) != tcc_binary)
2506     return false;
2507
2508   return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2509                                         honor_nans, honor_snans, divisor,
2510                                         &handled);
2511 }
2512
2513
2514 /* Returns true if it is possible to prove that the index of
2515    an array access REF (an ARRAY_REF expression) falls into the
2516    array bounds.  */
2517
2518 static bool
2519 in_array_bounds_p (tree ref)
2520 {
2521   tree idx = TREE_OPERAND (ref, 1);
2522   tree min, max;
2523
2524   if (TREE_CODE (idx) != INTEGER_CST)
2525     return false;
2526
2527   min = array_ref_low_bound (ref);
2528   max = array_ref_up_bound (ref);
2529   if (!min
2530       || !max
2531       || TREE_CODE (min) != INTEGER_CST
2532       || TREE_CODE (max) != INTEGER_CST)
2533     return false;
2534
2535   if (tree_int_cst_lt (idx, min)
2536       || tree_int_cst_lt (max, idx))
2537     return false;
2538
2539   return true;
2540 }
2541
2542 /* Returns true if it is possible to prove that the range of
2543    an array access REF (an ARRAY_RANGE_REF expression) falls
2544    into the array bounds.  */
2545
2546 static bool
2547 range_in_array_bounds_p (tree ref)
2548 {
2549   tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2550   tree range_min, range_max, min, max;
2551
2552   range_min = TYPE_MIN_VALUE (domain_type);
2553   range_max = TYPE_MAX_VALUE (domain_type);
2554   if (!range_min
2555       || !range_max
2556       || TREE_CODE (range_min) != INTEGER_CST
2557       || TREE_CODE (range_max) != INTEGER_CST)
2558     return false;
2559
2560   min = array_ref_low_bound (ref);
2561   max = array_ref_up_bound (ref);
2562   if (!min
2563       || !max
2564       || TREE_CODE (min) != INTEGER_CST
2565       || TREE_CODE (max) != INTEGER_CST)
2566     return false;
2567
2568   if (tree_int_cst_lt (range_min, min)
2569       || tree_int_cst_lt (max, range_max))
2570     return false;
2571
2572   return true;
2573 }
2574
2575 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2576    location or floating point arithmetic.  C.f. the rtl version, may_trap_p.
2577    This routine expects only GIMPLE lhs or rhs input.  */
2578
2579 bool
2580 tree_could_trap_p (tree expr)
2581 {
2582   enum tree_code code;
2583   bool fp_operation = false;
2584   bool honor_trapv = false;
2585   tree t, base, div = NULL_TREE;
2586
2587   if (!expr)
2588     return false;
2589
2590   code = TREE_CODE (expr);
2591   t = TREE_TYPE (expr);
2592
2593   if (t)
2594     {
2595       if (COMPARISON_CLASS_P (expr))
2596         fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2597       else
2598         fp_operation = FLOAT_TYPE_P (t);
2599       honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2600     }
2601
2602   if (TREE_CODE_CLASS (code) == tcc_binary)
2603     div = TREE_OPERAND (expr, 1);
2604   if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2605     return true;
2606
2607  restart:
2608   switch (code)
2609     {
2610     case TARGET_MEM_REF:
2611       if (TREE_CODE (TMR_BASE (expr)) == ADDR_EXPR
2612           && !TMR_INDEX (expr) && !TMR_INDEX2 (expr))
2613         return false;
2614       return !TREE_THIS_NOTRAP (expr);
2615
2616     case COMPONENT_REF:
2617     case REALPART_EXPR:
2618     case IMAGPART_EXPR:
2619     case BIT_FIELD_REF:
2620     case VIEW_CONVERT_EXPR:
2621     case WITH_SIZE_EXPR:
2622       expr = TREE_OPERAND (expr, 0);
2623       code = TREE_CODE (expr);
2624       goto restart;
2625
2626     case ARRAY_RANGE_REF:
2627       base = TREE_OPERAND (expr, 0);
2628       if (tree_could_trap_p (base))
2629         return true;
2630       if (TREE_THIS_NOTRAP (expr))
2631         return false;
2632       return !range_in_array_bounds_p (expr);
2633
2634     case ARRAY_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 !in_array_bounds_p (expr);
2641
2642     case MEM_REF:
2643       if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2644         return false;
2645       /* Fallthru.  */
2646     case INDIRECT_REF:
2647       return !TREE_THIS_NOTRAP (expr);
2648
2649     case ASM_EXPR:
2650       return TREE_THIS_VOLATILE (expr);
2651
2652     case CALL_EXPR:
2653       t = get_callee_fndecl (expr);
2654       /* Assume that calls to weak functions may trap.  */
2655       if (!t || !DECL_P (t))
2656         return true;
2657       if (DECL_WEAK (t))
2658         return tree_could_trap_p (t);
2659       return false;
2660
2661     case FUNCTION_DECL:
2662       /* Assume that accesses to weak functions may trap, unless we know
2663          they are certainly defined in current TU or in some other
2664          LTO partition.  */
2665       if (DECL_WEAK (expr) && !DECL_COMDAT (expr))
2666         {
2667           struct cgraph_node *node;
2668           if (!DECL_EXTERNAL (expr))
2669             return false;
2670           node = cgraph_function_node (cgraph_get_node (expr), NULL);
2671           if (node && node->in_other_partition)
2672             return false;
2673           return true;
2674         }
2675       return false;
2676
2677     case VAR_DECL:
2678       /* Assume that accesses to weak vars may trap, unless we know
2679          they are certainly defined in current TU or in some other
2680          LTO partition.  */
2681       if (DECL_WEAK (expr) && !DECL_COMDAT (expr))
2682         {
2683           struct varpool_node *node;
2684           if (!DECL_EXTERNAL (expr))
2685             return false;
2686           node = varpool_variable_node (varpool_get_node (expr), NULL);
2687           if (node && node->in_other_partition)
2688             return false;
2689           return true;
2690         }
2691       return false;
2692
2693     default:
2694       return false;
2695     }
2696 }
2697
2698
2699 /* Helper for stmt_could_throw_p.  Return true if STMT (assumed to be a
2700    an assignment or a conditional) may throw.  */
2701
2702 static bool
2703 stmt_could_throw_1_p (gimple stmt)
2704 {
2705   enum tree_code code = gimple_expr_code (stmt);
2706   bool honor_nans = false;
2707   bool honor_snans = false;
2708   bool fp_operation = false;
2709   bool honor_trapv = false;
2710   tree t;
2711   size_t i;
2712   bool handled, ret;
2713
2714   if (TREE_CODE_CLASS (code) == tcc_comparison
2715       || TREE_CODE_CLASS (code) == tcc_unary
2716       || TREE_CODE_CLASS (code) == tcc_binary)
2717     {
2718       if (is_gimple_assign (stmt)
2719           && TREE_CODE_CLASS (code) == tcc_comparison)
2720         t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2721       else if (gimple_code (stmt) == GIMPLE_COND)
2722         t = TREE_TYPE (gimple_cond_lhs (stmt));
2723       else
2724         t = gimple_expr_type (stmt);
2725       fp_operation = FLOAT_TYPE_P (t);
2726       if (fp_operation)
2727         {
2728           honor_nans = flag_trapping_math && !flag_finite_math_only;
2729           honor_snans = flag_signaling_nans != 0;
2730         }
2731       else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2732         honor_trapv = true;
2733     }
2734
2735   /* Check if the main expression may trap.  */
2736   t = is_gimple_assign (stmt) ? gimple_assign_rhs2 (stmt) : NULL;
2737   ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2738                                        honor_nans, honor_snans, t,
2739                                        &handled);
2740   if (handled)
2741     return ret;
2742
2743   /* If the expression does not trap, see if any of the individual operands may
2744      trap.  */
2745   for (i = 0; i < gimple_num_ops (stmt); i++)
2746     if (tree_could_trap_p (gimple_op (stmt, i)))
2747       return true;
2748
2749   return false;
2750 }
2751
2752
2753 /* Return true if statement STMT could throw an exception.  */
2754
2755 bool
2756 stmt_could_throw_p (gimple stmt)
2757 {
2758   if (!flag_exceptions)
2759     return false;
2760
2761   /* The only statements that can throw an exception are assignments,
2762      conditionals, calls, resx, and asms.  */
2763   switch (gimple_code (stmt))
2764     {
2765     case GIMPLE_RESX:
2766       return true;
2767
2768     case GIMPLE_CALL:
2769       return !gimple_call_nothrow_p (stmt);
2770
2771     case GIMPLE_ASSIGN:
2772     case GIMPLE_COND:
2773       if (!cfun->can_throw_non_call_exceptions)
2774         return false;
2775       return stmt_could_throw_1_p (stmt);
2776
2777     case GIMPLE_ASM:
2778       if (!cfun->can_throw_non_call_exceptions)
2779         return false;
2780       return gimple_asm_volatile_p (stmt);
2781
2782     default:
2783       return false;
2784     }
2785 }
2786
2787
2788 /* Return true if expression T could throw an exception.  */
2789
2790 bool
2791 tree_could_throw_p (tree t)
2792 {
2793   if (!flag_exceptions)
2794     return false;
2795   if (TREE_CODE (t) == MODIFY_EXPR)
2796     {
2797       if (cfun->can_throw_non_call_exceptions
2798           && tree_could_trap_p (TREE_OPERAND (t, 0)))
2799         return true;
2800       t = TREE_OPERAND (t, 1);
2801     }
2802
2803   if (TREE_CODE (t) == WITH_SIZE_EXPR)
2804     t = TREE_OPERAND (t, 0);
2805   if (TREE_CODE (t) == CALL_EXPR)
2806     return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2807   if (cfun->can_throw_non_call_exceptions)
2808     return tree_could_trap_p (t);
2809   return false;
2810 }
2811
2812 /* Return true if STMT can throw an exception that is not caught within
2813    the current function (CFUN).  */
2814
2815 bool
2816 stmt_can_throw_external (gimple stmt)
2817 {
2818   int lp_nr;
2819
2820   if (!stmt_could_throw_p (stmt))
2821     return false;
2822
2823   lp_nr = lookup_stmt_eh_lp (stmt);
2824   return lp_nr == 0;
2825 }
2826
2827 /* Return true if STMT can throw an exception that is caught within
2828    the current function (CFUN).  */
2829
2830 bool
2831 stmt_can_throw_internal (gimple stmt)
2832 {
2833   int lp_nr;
2834
2835   if (!stmt_could_throw_p (stmt))
2836     return false;
2837
2838   lp_nr = lookup_stmt_eh_lp (stmt);
2839   return lp_nr > 0;
2840 }
2841
2842 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2843    remove any entry it might have from the EH table.  Return true if
2844    any change was made.  */
2845
2846 bool
2847 maybe_clean_eh_stmt_fn (struct function *ifun, gimple stmt)
2848 {
2849   if (stmt_could_throw_p (stmt))
2850     return false;
2851   return remove_stmt_from_eh_lp_fn (ifun, stmt);
2852 }
2853
2854 /* Likewise, but always use the current function.  */
2855
2856 bool
2857 maybe_clean_eh_stmt (gimple stmt)
2858 {
2859   return maybe_clean_eh_stmt_fn (cfun, stmt);
2860 }
2861
2862 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2863    OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2864    in the table if it should be in there.  Return TRUE if a replacement was
2865    done that my require an EH edge purge.  */
2866
2867 bool
2868 maybe_clean_or_replace_eh_stmt (gimple old_stmt, gimple new_stmt)
2869 {
2870   int lp_nr = lookup_stmt_eh_lp (old_stmt);
2871
2872   if (lp_nr != 0)
2873     {
2874       bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2875
2876       if (new_stmt == old_stmt && new_stmt_could_throw)
2877         return false;
2878
2879       remove_stmt_from_eh_lp (old_stmt);
2880       if (new_stmt_could_throw)
2881         {
2882           add_stmt_to_eh_lp (new_stmt, lp_nr);
2883           return false;
2884         }
2885       else
2886         return true;
2887     }
2888
2889   return false;
2890 }
2891
2892 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2893    in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT.  The MAP
2894    operand is the return value of duplicate_eh_regions.  */
2895
2896 bool
2897 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple new_stmt,
2898                             struct function *old_fun, gimple old_stmt,
2899                             struct pointer_map_t *map, int default_lp_nr)
2900 {
2901   int old_lp_nr, new_lp_nr;
2902   void **slot;
2903
2904   if (!stmt_could_throw_p (new_stmt))
2905     return false;
2906
2907   old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2908   if (old_lp_nr == 0)
2909     {
2910       if (default_lp_nr == 0)
2911         return false;
2912       new_lp_nr = default_lp_nr;
2913     }
2914   else if (old_lp_nr > 0)
2915     {
2916       eh_landing_pad old_lp, new_lp;
2917
2918       old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2919       slot = pointer_map_contains (map, old_lp);
2920       new_lp = (eh_landing_pad) *slot;
2921       new_lp_nr = new_lp->index;
2922     }
2923   else
2924     {
2925       eh_region old_r, new_r;
2926
2927       old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2928       slot = pointer_map_contains (map, old_r);
2929       new_r = (eh_region) *slot;
2930       new_lp_nr = -new_r->index;
2931     }
2932
2933   add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2934   return true;
2935 }
2936
2937 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2938    and thus no remapping is required.  */
2939
2940 bool
2941 maybe_duplicate_eh_stmt (gimple new_stmt, gimple old_stmt)
2942 {
2943   int lp_nr;
2944
2945   if (!stmt_could_throw_p (new_stmt))
2946     return false;
2947
2948   lp_nr = lookup_stmt_eh_lp (old_stmt);
2949   if (lp_nr == 0)
2950     return false;
2951
2952   add_stmt_to_eh_lp (new_stmt, lp_nr);
2953   return true;
2954 }
2955 \f
2956 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2957    GIMPLE_TRY) that are similar enough to be considered the same.  Currently
2958    this only handles handlers consisting of a single call, as that's the
2959    important case for C++: a destructor call for a particular object showing
2960    up in multiple handlers.  */
2961
2962 static bool
2963 same_handler_p (gimple_seq oneh, gimple_seq twoh)
2964 {
2965   gimple_stmt_iterator gsi;
2966   gimple ones, twos;
2967   unsigned int ai;
2968
2969   gsi = gsi_start (oneh);
2970   if (!gsi_one_before_end_p (gsi))
2971     return false;
2972   ones = gsi_stmt (gsi);
2973
2974   gsi = gsi_start (twoh);
2975   if (!gsi_one_before_end_p (gsi))
2976     return false;
2977   twos = gsi_stmt (gsi);
2978
2979   if (!is_gimple_call (ones)
2980       || !is_gimple_call (twos)
2981       || gimple_call_lhs (ones)
2982       || gimple_call_lhs (twos)
2983       || gimple_call_chain (ones)
2984       || gimple_call_chain (twos)
2985       || !gimple_call_same_target_p (ones, twos)
2986       || gimple_call_num_args (ones) != gimple_call_num_args (twos))
2987     return false;
2988
2989   for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
2990     if (!operand_equal_p (gimple_call_arg (ones, ai),
2991                           gimple_call_arg (twos, ai), 0))
2992       return false;
2993
2994   return true;
2995 }
2996
2997 /* Optimize
2998     try { A() } finally { try { ~B() } catch { ~A() } }
2999     try { ... } finally { ~A() }
3000    into
3001     try { A() } catch { ~B() }
3002     try { ~B() ... } finally { ~A() }
3003
3004    This occurs frequently in C++, where A is a local variable and B is a
3005    temporary used in the initializer for A.  */
3006
3007 static void
3008 optimize_double_finally (gimple one, gimple two)
3009 {
3010   gimple oneh;
3011   gimple_stmt_iterator gsi;
3012   gimple_seq cleanup;
3013
3014   cleanup = gimple_try_cleanup (one);
3015   gsi = gsi_start (cleanup);
3016   if (!gsi_one_before_end_p (gsi))
3017     return;
3018
3019   oneh = gsi_stmt (gsi);
3020   if (gimple_code (oneh) != GIMPLE_TRY
3021       || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3022     return;
3023
3024   if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3025     {
3026       gimple_seq seq = gimple_try_eval (oneh);
3027
3028       gimple_try_set_cleanup (one, seq);
3029       gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3030       seq = copy_gimple_seq_and_replace_locals (seq);
3031       gimple_seq_add_seq (&seq, gimple_try_eval (two));
3032       gimple_try_set_eval (two, seq);
3033     }
3034 }
3035
3036 /* Perform EH refactoring optimizations that are simpler to do when code
3037    flow has been lowered but EH structures haven't.  */
3038
3039 static void
3040 refactor_eh_r (gimple_seq seq)
3041 {
3042   gimple_stmt_iterator gsi;
3043   gimple one, two;
3044
3045   one = NULL;
3046   two = NULL;
3047   gsi = gsi_start (seq);
3048   while (1)
3049     {
3050       one = two;
3051       if (gsi_end_p (gsi))
3052         two = NULL;
3053       else
3054         two = gsi_stmt (gsi);
3055       if (one
3056           && two
3057           && gimple_code (one) == GIMPLE_TRY
3058           && gimple_code (two) == GIMPLE_TRY
3059           && gimple_try_kind (one) == GIMPLE_TRY_FINALLY
3060           && gimple_try_kind (two) == GIMPLE_TRY_FINALLY)
3061         optimize_double_finally (one, two);
3062       if (one)
3063         switch (gimple_code (one))
3064           {
3065           case GIMPLE_TRY:
3066             refactor_eh_r (gimple_try_eval (one));
3067             refactor_eh_r (gimple_try_cleanup (one));
3068             break;
3069           case GIMPLE_CATCH:
3070             refactor_eh_r (gimple_catch_handler (one));
3071             break;
3072           case GIMPLE_EH_FILTER:
3073             refactor_eh_r (gimple_eh_filter_failure (one));
3074             break;
3075           case GIMPLE_EH_ELSE:
3076             refactor_eh_r (gimple_eh_else_n_body (one));
3077             refactor_eh_r (gimple_eh_else_e_body (one));
3078             break;
3079           default:
3080             break;
3081           }
3082       if (two)
3083         gsi_next (&gsi);
3084       else
3085         break;
3086     }
3087 }
3088
3089 static unsigned
3090 refactor_eh (void)
3091 {
3092   refactor_eh_r (gimple_body (current_function_decl));
3093   return 0;
3094 }
3095
3096 static bool
3097 gate_refactor_eh (void)
3098 {
3099   return flag_exceptions != 0;
3100 }
3101
3102 namespace {
3103
3104 const pass_data pass_data_refactor_eh =
3105 {
3106   GIMPLE_PASS, /* type */
3107   "ehopt", /* name */
3108   OPTGROUP_NONE, /* optinfo_flags */
3109   true, /* has_gate */
3110   true, /* has_execute */
3111   TV_TREE_EH, /* tv_id */
3112   PROP_gimple_lcf, /* properties_required */
3113   0, /* properties_provided */
3114   0, /* properties_destroyed */
3115   0, /* todo_flags_start */
3116   0, /* todo_flags_finish */
3117 };
3118
3119 class pass_refactor_eh : public gimple_opt_pass
3120 {
3121 public:
3122   pass_refactor_eh (gcc::context *ctxt)
3123     : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3124   {}
3125
3126   /* opt_pass methods: */
3127   bool gate () { return gate_refactor_eh (); }
3128   unsigned int execute () { return refactor_eh (); }
3129
3130 }; // class pass_refactor_eh
3131
3132 } // anon namespace
3133
3134 gimple_opt_pass *
3135 make_pass_refactor_eh (gcc::context *ctxt)
3136 {
3137   return new pass_refactor_eh (ctxt);
3138 }
3139 \f
3140 /* At the end of gimple optimization, we can lower RESX.  */
3141
3142 static bool
3143 lower_resx (basic_block bb, gimple stmt, struct pointer_map_t *mnt_map)
3144 {
3145   int lp_nr;
3146   eh_region src_r, dst_r;
3147   gimple_stmt_iterator gsi;
3148   gimple x;
3149   tree fn, src_nr;
3150   bool ret = false;
3151
3152   lp_nr = lookup_stmt_eh_lp (stmt);
3153   if (lp_nr != 0)
3154     dst_r = get_eh_region_from_lp_number (lp_nr);
3155   else
3156     dst_r = NULL;
3157
3158   src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3159   gsi = gsi_last_bb (bb);
3160
3161   if (src_r == NULL)
3162     {
3163       /* We can wind up with no source region when pass_cleanup_eh shows
3164          that there are no entries into an eh region and deletes it, but
3165          then the block that contains the resx isn't removed.  This can
3166          happen without optimization when the switch statement created by
3167          lower_try_finally_switch isn't simplified to remove the eh case.
3168
3169          Resolve this by expanding the resx node to an abort.  */
3170
3171       fn = builtin_decl_implicit (BUILT_IN_TRAP);
3172       x = gimple_build_call (fn, 0);
3173       gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3174
3175       while (EDGE_COUNT (bb->succs) > 0)
3176         remove_edge (EDGE_SUCC (bb, 0));
3177     }
3178   else if (dst_r)
3179     {
3180       /* When we have a destination region, we resolve this by copying
3181          the excptr and filter values into place, and changing the edge
3182          to immediately after the landing pad.  */
3183       edge e;
3184
3185       if (lp_nr < 0)
3186         {
3187           basic_block new_bb;
3188           void **slot;
3189           tree lab;
3190
3191           /* We are resuming into a MUST_NOT_CALL region.  Expand a call to
3192              the failure decl into a new block, if needed.  */
3193           gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3194
3195           slot = pointer_map_contains (mnt_map, dst_r);
3196           if (slot == NULL)
3197             {
3198               gimple_stmt_iterator gsi2;
3199
3200               new_bb = create_empty_bb (bb);
3201               if (current_loops)
3202                 add_bb_to_loop (new_bb, bb->loop_father);
3203               lab = gimple_block_label (new_bb);
3204               gsi2 = gsi_start_bb (new_bb);
3205
3206               fn = dst_r->u.must_not_throw.failure_decl;
3207               x = gimple_build_call (fn, 0);
3208               gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3209               gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3210
3211               slot = pointer_map_insert (mnt_map, dst_r);
3212               *slot = lab;
3213             }
3214           else
3215             {
3216               lab = (tree) *slot;
3217               new_bb = label_to_block (lab);
3218             }
3219
3220           gcc_assert (EDGE_COUNT (bb->succs) == 0);
3221           e = make_edge (bb, new_bb, EDGE_FALLTHRU);
3222           e->count = bb->count;
3223           e->probability = REG_BR_PROB_BASE;
3224         }
3225       else
3226         {
3227           edge_iterator ei;
3228           tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3229
3230           fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3231           src_nr = build_int_cst (integer_type_node, src_r->index);
3232           x = gimple_build_call (fn, 2, dst_nr, src_nr);
3233           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3234
3235           /* Update the flags for the outgoing edge.  */
3236           e = single_succ_edge (bb);
3237           gcc_assert (e->flags & EDGE_EH);
3238           e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3239
3240           /* If there are no more EH users of the landing pad, delete it.  */
3241           FOR_EACH_EDGE (e, ei, e->dest->preds)
3242             if (e->flags & EDGE_EH)
3243               break;
3244           if (e == NULL)
3245             {
3246               eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3247               remove_eh_landing_pad (lp);
3248             }
3249         }
3250
3251       ret = true;
3252     }
3253   else
3254     {
3255       tree var;
3256
3257       /* When we don't have a destination region, this exception escapes
3258          up the call chain.  We resolve this by generating a call to the
3259          _Unwind_Resume library function.  */
3260
3261       /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3262          with no arguments for C++ and Java.  Check for that.  */
3263       if (src_r->use_cxa_end_cleanup)
3264         {
3265           fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3266           x = gimple_build_call (fn, 0);
3267           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3268         }
3269       else
3270         {
3271           fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3272           src_nr = build_int_cst (integer_type_node, src_r->index);
3273           x = gimple_build_call (fn, 1, src_nr);
3274           var = create_tmp_var (ptr_type_node, NULL);
3275           var = make_ssa_name (var, x);
3276           gimple_call_set_lhs (x, var);
3277           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3278
3279           fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3280           x = gimple_build_call (fn, 1, var);
3281           gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3282         }
3283
3284       gcc_assert (EDGE_COUNT (bb->succs) == 0);
3285     }
3286
3287   gsi_remove (&gsi, true);
3288
3289   return ret;
3290 }
3291
3292 static unsigned
3293 execute_lower_resx (void)
3294 {
3295   basic_block bb;
3296   struct pointer_map_t *mnt_map;
3297   bool dominance_invalidated = false;
3298   bool any_rewritten = false;
3299
3300   mnt_map = pointer_map_create ();
3301
3302   FOR_EACH_BB (bb)
3303     {
3304       gimple last = last_stmt (bb);
3305       if (last && is_gimple_resx (last))
3306         {
3307           dominance_invalidated |= lower_resx (bb, last, mnt_map);
3308           any_rewritten = true;
3309         }
3310     }
3311
3312   pointer_map_destroy (mnt_map);
3313
3314   if (dominance_invalidated)
3315     {
3316       free_dominance_info (CDI_DOMINATORS);
3317       free_dominance_info (CDI_POST_DOMINATORS);
3318     }
3319
3320   return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3321 }
3322
3323 static bool
3324 gate_lower_resx (void)
3325 {
3326   return flag_exceptions != 0;
3327 }
3328
3329 namespace {
3330
3331 const pass_data pass_data_lower_resx =
3332 {
3333   GIMPLE_PASS, /* type */
3334   "resx", /* name */
3335   OPTGROUP_NONE, /* optinfo_flags */
3336   true, /* has_gate */
3337   true, /* has_execute */
3338   TV_TREE_EH, /* tv_id */
3339   PROP_gimple_lcf, /* properties_required */
3340   0, /* properties_provided */
3341   0, /* properties_destroyed */
3342   0, /* todo_flags_start */
3343   TODO_verify_flow, /* todo_flags_finish */
3344 };
3345
3346 class pass_lower_resx : public gimple_opt_pass
3347 {
3348 public:
3349   pass_lower_resx (gcc::context *ctxt)
3350     : gimple_opt_pass (pass_data_lower_resx, ctxt)
3351   {}
3352
3353   /* opt_pass methods: */
3354   bool gate () { return gate_lower_resx (); }
3355   unsigned int execute () { return execute_lower_resx (); }
3356
3357 }; // class pass_lower_resx
3358
3359 } // anon namespace
3360
3361 gimple_opt_pass *
3362 make_pass_lower_resx (gcc::context *ctxt)
3363 {
3364   return new pass_lower_resx (ctxt);
3365 }
3366
3367 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3368    external throw.  */
3369
3370 static void
3371 optimize_clobbers (basic_block bb)
3372 {
3373   gimple_stmt_iterator gsi = gsi_last_bb (bb);
3374   bool any_clobbers = false;
3375   bool seen_stack_restore = false;
3376   edge_iterator ei;
3377   edge e;
3378
3379   /* Only optimize anything if the bb contains at least one clobber,
3380      ends with resx (checked by caller), optionally contains some
3381      debug stmts or labels, or at most one __builtin_stack_restore
3382      call, and has an incoming EH edge.  */
3383   for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3384     {
3385       gimple stmt = gsi_stmt (gsi);
3386       if (is_gimple_debug (stmt))
3387         continue;
3388       if (gimple_clobber_p (stmt))
3389         {
3390           any_clobbers = true;
3391           continue;
3392         }
3393       if (!seen_stack_restore
3394           && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3395         {
3396           seen_stack_restore = true;
3397           continue;
3398         }
3399       if (gimple_code (stmt) == GIMPLE_LABEL)
3400         break;
3401       return;
3402     }
3403   if (!any_clobbers)
3404     return;
3405   FOR_EACH_EDGE (e, ei, bb->preds)
3406     if (e->flags & EDGE_EH)
3407       break;
3408   if (e == NULL)
3409     return;
3410   gsi = gsi_last_bb (bb);
3411   for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3412     {
3413       gimple stmt = gsi_stmt (gsi);
3414       if (!gimple_clobber_p (stmt))
3415         continue;
3416       unlink_stmt_vdef (stmt);
3417       gsi_remove (&gsi, true);
3418       release_defs (stmt);
3419     }
3420 }
3421
3422 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3423    internal throw to successor BB.  */
3424
3425 static int
3426 sink_clobbers (basic_block bb)
3427 {
3428   edge e;
3429   edge_iterator ei;
3430   gimple_stmt_iterator gsi, dgsi;
3431   basic_block succbb;
3432   bool any_clobbers = false;
3433   unsigned todo = 0;
3434
3435   /* Only optimize if BB has a single EH successor and
3436      all predecessor edges are EH too.  */
3437   if (!single_succ_p (bb)
3438       || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3439     return 0;
3440
3441   FOR_EACH_EDGE (e, ei, bb->preds)
3442     {
3443       if ((e->flags & EDGE_EH) == 0)
3444         return 0;
3445     }
3446
3447   /* And BB contains only CLOBBER stmts before the final
3448      RESX.  */
3449   gsi = gsi_last_bb (bb);
3450   for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3451     {
3452       gimple stmt = gsi_stmt (gsi);
3453       if (is_gimple_debug (stmt))
3454         continue;
3455       if (gimple_code (stmt) == GIMPLE_LABEL)
3456         break;
3457       if (!gimple_clobber_p (stmt))
3458         return 0;
3459       any_clobbers = true;
3460     }
3461   if (!any_clobbers)
3462     return 0;
3463
3464   edge succe = single_succ_edge (bb);
3465   succbb = succe->dest;
3466
3467   /* See if there is a virtual PHI node to take an updated virtual
3468      operand from.  */
3469   gimple vphi = NULL;
3470   tree vuse = NULL_TREE;
3471   for (gsi = gsi_start_phis (succbb); !gsi_end_p (gsi); gsi_next (&gsi))
3472     {
3473       tree res = gimple_phi_result (gsi_stmt (gsi));
3474       if (virtual_operand_p (res))
3475         {
3476           vphi = gsi_stmt (gsi);
3477           vuse = res;
3478           break;
3479         }
3480     }
3481
3482   dgsi = gsi_after_labels (succbb);
3483   gsi = gsi_last_bb (bb);
3484   for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3485     {
3486       gimple stmt = gsi_stmt (gsi);
3487       tree lhs;
3488       if (is_gimple_debug (stmt))
3489         continue;
3490       if (gimple_code (stmt) == GIMPLE_LABEL)
3491         break;
3492       lhs = gimple_assign_lhs (stmt);
3493       /* Unfortunately we don't have dominance info updated at this
3494          point, so checking if
3495          dominated_by_p (CDI_DOMINATORS, succbb,
3496                          gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3497          would be too costly.  Thus, avoid sinking any clobbers that
3498          refer to non-(D) SSA_NAMEs.  */
3499       if (TREE_CODE (lhs) == MEM_REF
3500           && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3501           && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3502         {
3503           unlink_stmt_vdef (stmt);
3504           gsi_remove (&gsi, true);
3505           release_defs (stmt);
3506           continue;
3507         }
3508
3509       /* As we do not change stmt order when sinking across a
3510          forwarder edge we can keep virtual operands in place.  */
3511       gsi_remove (&gsi, false);
3512       gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3513
3514       /* But adjust virtual operands if we sunk across a PHI node.  */
3515       if (vuse)
3516         {
3517           gimple use_stmt;
3518           imm_use_iterator iter;
3519           use_operand_p use_p;
3520           FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3521             FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3522               SET_USE (use_p, gimple_vdef (stmt));
3523           if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3524             {
3525               SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3526               SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3527             }
3528           /* Adjust the incoming virtual operand.  */
3529           SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3530           SET_USE (gimple_vuse_op (stmt), vuse);
3531         }
3532       /* If there isn't a single predecessor but no virtual PHI node
3533          arrange for virtual operands to be renamed.  */
3534       else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3535                && !single_pred_p (succbb))
3536         {
3537           /* In this case there will be no use of the VDEF of this stmt. 
3538              ???  Unless this is a secondary opportunity and we have not
3539              removed unreachable blocks yet, so we cannot assert this.  
3540              Which also means we will end up renaming too many times.  */
3541           SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3542           mark_virtual_operands_for_renaming (cfun);
3543           todo |= TODO_update_ssa_only_virtuals;
3544         }
3545     }
3546
3547   return todo;
3548 }
3549
3550 /* At the end of inlining, we can lower EH_DISPATCH.  Return true when 
3551    we have found some duplicate labels and removed some edges.  */
3552
3553 static bool
3554 lower_eh_dispatch (basic_block src, gimple stmt)
3555 {
3556   gimple_stmt_iterator gsi;
3557   int region_nr;
3558   eh_region r;
3559   tree filter, fn;
3560   gimple x;
3561   bool redirected = false;
3562
3563   region_nr = gimple_eh_dispatch_region (stmt);
3564   r = get_eh_region_from_number (region_nr);
3565
3566   gsi = gsi_last_bb (src);
3567
3568   switch (r->type)
3569     {
3570     case ERT_TRY:
3571       {
3572         auto_vec<tree> labels;
3573         tree default_label = NULL;
3574         eh_catch c;
3575         edge_iterator ei;
3576         edge e;
3577         struct pointer_set_t *seen_values = pointer_set_create ();
3578
3579         /* Collect the labels for a switch.  Zero the post_landing_pad
3580            field becase we'll no longer have anything keeping these labels
3581            in existence and the optimizer will be free to merge these
3582            blocks at will.  */
3583         for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3584           {
3585             tree tp_node, flt_node, lab = c->label;
3586             bool have_label = false;
3587
3588             c->label = NULL;
3589             tp_node = c->type_list;
3590             flt_node = c->filter_list;
3591
3592             if (tp_node == NULL)
3593               {
3594                 default_label = lab;
3595                 break;
3596               }
3597             do
3598               {
3599                 /* Filter out duplicate labels that arise when this handler 
3600                    is shadowed by an earlier one.  When no labels are 
3601                    attached to the handler anymore, we remove 
3602                    the corresponding edge and then we delete unreachable 
3603                    blocks at the end of this pass.  */
3604                 if (! pointer_set_contains (seen_values, TREE_VALUE (flt_node)))
3605                   {
3606                     tree t = build_case_label (TREE_VALUE (flt_node),
3607                                                NULL, lab);
3608                     labels.safe_push (t);
3609                     pointer_set_insert (seen_values, TREE_VALUE (flt_node));
3610                     have_label = true;
3611                   }
3612
3613                 tp_node = TREE_CHAIN (tp_node);
3614                 flt_node = TREE_CHAIN (flt_node);
3615               }
3616             while (tp_node);
3617             if (! have_label)
3618               {
3619                 remove_edge (find_edge (src, label_to_block (lab)));
3620                 redirected = true;
3621               }
3622           }
3623
3624         /* Clean up the edge flags.  */
3625         FOR_EACH_EDGE (e, ei, src->succs)
3626           {
3627             if (e->flags & EDGE_FALLTHRU)
3628               {
3629                 /* If there was no catch-all, use the fallthru edge.  */
3630                 if (default_label == NULL)
3631                   default_label = gimple_block_label (e->dest);
3632                 e->flags &= ~EDGE_FALLTHRU;
3633               }
3634           }
3635         gcc_assert (default_label != NULL);
3636
3637         /* Don't generate a switch if there's only a default case.
3638            This is common in the form of try { A; } catch (...) { B; }.  */
3639         if (!labels.exists ())
3640           {
3641             e = single_succ_edge (src);
3642             e->flags |= EDGE_FALLTHRU;
3643           }
3644         else
3645           {
3646             fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3647             x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3648                                                          region_nr));
3649             filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3650             filter = make_ssa_name (filter, x);
3651             gimple_call_set_lhs (x, filter);
3652             gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3653
3654             /* Turn the default label into a default case.  */
3655             default_label = build_case_label (NULL, NULL, default_label);
3656             sort_case_labels (labels);
3657
3658             x = gimple_build_switch (filter, default_label, labels);
3659             gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3660           }
3661         pointer_set_destroy (seen_values);
3662       }
3663       break;
3664
3665     case ERT_ALLOWED_EXCEPTIONS:
3666       {
3667         edge b_e = BRANCH_EDGE (src);
3668         edge f_e = FALLTHRU_EDGE (src);
3669
3670         fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3671         x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3672                                                      region_nr));
3673         filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)), NULL);
3674         filter = make_ssa_name (filter, x);
3675         gimple_call_set_lhs (x, filter);
3676         gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3677
3678         r->u.allowed.label = NULL;
3679         x = gimple_build_cond (EQ_EXPR, filter,
3680                                build_int_cst (TREE_TYPE (filter),
3681                                               r->u.allowed.filter),
3682                                NULL_TREE, NULL_TREE);
3683         gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3684
3685         b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3686         f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3687       }
3688       break;
3689
3690     default:
3691       gcc_unreachable ();
3692     }
3693
3694   /* Replace the EH_DISPATCH with the SWITCH or COND generated above.  */
3695   gsi_remove (&gsi, true);
3696   return redirected;
3697 }
3698
3699 static unsigned
3700 execute_lower_eh_dispatch (void)
3701 {
3702   basic_block bb;
3703   int flags = 0;
3704   bool redirected = false;
3705
3706   assign_filter_values ();
3707
3708   FOR_EACH_BB (bb)
3709     {
3710       gimple last = last_stmt (bb);
3711       if (last == NULL)
3712         continue;
3713       if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3714         {
3715           redirected |= lower_eh_dispatch (bb, last);
3716           flags |= TODO_update_ssa_only_virtuals;
3717         }
3718       else if (gimple_code (last) == GIMPLE_RESX)
3719         {
3720           if (stmt_can_throw_external (last))
3721             optimize_clobbers (bb);
3722           else
3723             flags |= sink_clobbers (bb);
3724         }
3725     }
3726
3727   if (redirected)
3728     delete_unreachable_blocks ();
3729   return flags;
3730 }
3731
3732 static bool
3733 gate_lower_eh_dispatch (void)
3734 {
3735   return cfun->eh->region_tree != NULL;
3736 }
3737
3738 namespace {
3739
3740 const pass_data pass_data_lower_eh_dispatch =
3741 {
3742   GIMPLE_PASS, /* type */
3743   "ehdisp", /* name */
3744   OPTGROUP_NONE, /* optinfo_flags */
3745   true, /* has_gate */
3746   true, /* has_execute */
3747   TV_TREE_EH, /* tv_id */
3748   PROP_gimple_lcf, /* properties_required */
3749   0, /* properties_provided */
3750   0, /* properties_destroyed */
3751   0, /* todo_flags_start */
3752   TODO_verify_flow, /* todo_flags_finish */
3753 };
3754
3755 class pass_lower_eh_dispatch : public gimple_opt_pass
3756 {
3757 public:
3758   pass_lower_eh_dispatch (gcc::context *ctxt)
3759     : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3760   {}
3761
3762   /* opt_pass methods: */
3763   bool gate () { return gate_lower_eh_dispatch (); }
3764   unsigned int execute () { return execute_lower_eh_dispatch (); }
3765
3766 }; // class pass_lower_eh_dispatch
3767
3768 } // anon namespace
3769
3770 gimple_opt_pass *
3771 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3772 {
3773   return new pass_lower_eh_dispatch (ctxt);
3774 }
3775 \f
3776 /* Walk statements, see what regions and, optionally, landing pads
3777    are really referenced.
3778    
3779    Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3780    and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3781
3782    Passing NULL for LP_REACHABLE is valid, in this case only reachable
3783    regions are marked.
3784
3785    The caller is responsible for freeing the returned sbitmaps.  */
3786
3787 static void
3788 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3789 {
3790   sbitmap r_reachable, lp_reachable;
3791   basic_block bb;
3792   bool mark_landing_pads = (lp_reachablep != NULL);
3793   gcc_checking_assert (r_reachablep != NULL);
3794
3795   r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3796   bitmap_clear (r_reachable);
3797   *r_reachablep = r_reachable;
3798
3799   if (mark_landing_pads)
3800     {
3801       lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3802       bitmap_clear (lp_reachable);
3803       *lp_reachablep = lp_reachable;
3804     }
3805   else
3806     lp_reachable = NULL;
3807
3808   FOR_EACH_BB (bb)
3809     {
3810       gimple_stmt_iterator gsi;
3811
3812       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3813         {
3814           gimple stmt = gsi_stmt (gsi);
3815
3816           if (mark_landing_pads)
3817             {
3818               int lp_nr = lookup_stmt_eh_lp (stmt);
3819
3820               /* Negative LP numbers are MUST_NOT_THROW regions which
3821                  are not considered BB enders.  */
3822               if (lp_nr < 0)
3823                 bitmap_set_bit (r_reachable, -lp_nr);
3824
3825               /* Positive LP numbers are real landing pads, and BB enders.  */
3826               else if (lp_nr > 0)
3827                 {
3828                   gcc_assert (gsi_one_before_end_p (gsi));
3829                   eh_region region = get_eh_region_from_lp_number (lp_nr);
3830                   bitmap_set_bit (r_reachable, region->index);
3831                   bitmap_set_bit (lp_reachable, lp_nr);
3832                 }
3833             }
3834
3835           /* Avoid removing regions referenced from RESX/EH_DISPATCH.  */
3836           switch (gimple_code (stmt))
3837             {
3838             case GIMPLE_RESX:
3839               bitmap_set_bit (r_reachable, gimple_resx_region (stmt));
3840               break;
3841             case GIMPLE_EH_DISPATCH:
3842               bitmap_set_bit (r_reachable, gimple_eh_dispatch_region (stmt));
3843               break;
3844             default:
3845               break;
3846             }
3847         }
3848     }
3849 }
3850
3851 /* Remove unreachable handlers and unreachable landing pads.  */
3852
3853 static void
3854 remove_unreachable_handlers (void)
3855 {
3856   sbitmap r_reachable, lp_reachable;
3857   eh_region region;
3858   eh_landing_pad lp;
3859   unsigned i;
3860
3861   mark_reachable_handlers (&r_reachable, &lp_reachable);
3862
3863   if (dump_file)
3864     {
3865       fprintf (dump_file, "Before removal of unreachable regions:\n");
3866       dump_eh_tree (dump_file, cfun);
3867       fprintf (dump_file, "Reachable regions: ");
3868       dump_bitmap_file (dump_file, r_reachable);
3869       fprintf (dump_file, "Reachable landing pads: ");
3870       dump_bitmap_file (dump_file, lp_reachable);
3871     }
3872
3873   if (dump_file)
3874     {
3875       FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3876         if (region && !bitmap_bit_p (r_reachable, region->index))
3877           fprintf (dump_file,
3878                    "Removing unreachable region %d\n",
3879                    region->index);
3880     }
3881
3882   remove_unreachable_eh_regions (r_reachable);
3883
3884   FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3885     if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3886       {
3887         if (dump_file)
3888           fprintf (dump_file,
3889                    "Removing unreachable landing pad %d\n",
3890                    lp->index);
3891         remove_eh_landing_pad (lp);
3892       }
3893
3894   if (dump_file)
3895     {
3896       fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3897       dump_eh_tree (dump_file, cfun);
3898       fprintf (dump_file, "\n\n");
3899     }
3900
3901   sbitmap_free (r_reachable);
3902   sbitmap_free (lp_reachable);
3903
3904 #ifdef ENABLE_CHECKING
3905   verify_eh_tree (cfun);
3906 #endif
3907 }
3908
3909 /* Remove unreachable handlers if any landing pads have been removed after
3910    last ehcleanup pass (due to gimple_purge_dead_eh_edges).  */
3911
3912 void
3913 maybe_remove_unreachable_handlers (void)
3914 {
3915   eh_landing_pad lp;
3916   unsigned i;
3917
3918   if (cfun->eh == NULL)
3919     return;
3920            
3921   FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3922     if (lp && lp->post_landing_pad)
3923       {
3924         if (label_to_block (lp->post_landing_pad) == NULL)
3925           {
3926             remove_unreachable_handlers ();
3927             return;
3928           }
3929       }
3930 }
3931
3932 /* Remove regions that do not have landing pads.  This assumes
3933    that remove_unreachable_handlers has already been run, and
3934    that we've just manipulated the landing pads since then.
3935
3936    Preserve regions with landing pads and regions that prevent
3937    exceptions from propagating further, even if these regions
3938    are not reachable.  */
3939
3940 static void
3941 remove_unreachable_handlers_no_lp (void)
3942 {
3943   eh_region region;
3944   sbitmap r_reachable;
3945   unsigned i;
3946
3947   mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3948
3949   FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3950     {
3951       if (! region)
3952         continue;
3953
3954       if (region->landing_pads != NULL
3955           || region->type == ERT_MUST_NOT_THROW)
3956         bitmap_set_bit (r_reachable, region->index);
3957
3958       if (dump_file
3959           && !bitmap_bit_p (r_reachable, region->index))
3960         fprintf (dump_file,
3961                  "Removing unreachable region %d\n",
3962                  region->index);
3963     }
3964
3965   remove_unreachable_eh_regions (r_reachable);
3966
3967   sbitmap_free (r_reachable);
3968 }
3969
3970 /* Undo critical edge splitting on an EH landing pad.  Earlier, we
3971    optimisticaly split all sorts of edges, including EH edges.  The
3972    optimization passes in between may not have needed them; if not,
3973    we should undo the split.
3974
3975    Recognize this case by having one EH edge incoming to the BB and
3976    one normal edge outgoing; BB should be empty apart from the
3977    post_landing_pad label.
3978
3979    Note that this is slightly different from the empty handler case
3980    handled by cleanup_empty_eh, in that the actual handler may yet
3981    have actual code but the landing pad has been separated from the
3982    handler.  As such, cleanup_empty_eh relies on this transformation
3983    having been done first.  */
3984
3985 static bool
3986 unsplit_eh (eh_landing_pad lp)
3987 {
3988   basic_block bb = label_to_block (lp->post_landing_pad);
3989   gimple_stmt_iterator gsi;
3990   edge e_in, e_out;
3991
3992   /* Quickly check the edge counts on BB for singularity.  */
3993   if (!single_pred_p (bb) || !single_succ_p (bb))
3994     return false;
3995   e_in = single_pred_edge (bb);
3996   e_out = single_succ_edge (bb);
3997
3998   /* Input edge must be EH and output edge must be normal.  */
3999   if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4000     return false;
4001
4002   /* The block must be empty except for the labels and debug insns.  */
4003   gsi = gsi_after_labels (bb);
4004   if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4005     gsi_next_nondebug (&gsi);
4006   if (!gsi_end_p (gsi))
4007     return false;
4008
4009   /* The destination block must not already have a landing pad
4010      for a different region.  */
4011   for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4012     {
4013       gimple stmt = gsi_stmt (gsi);
4014       tree lab;
4015       int lp_nr;
4016
4017       if (gimple_code (stmt) != GIMPLE_LABEL)
4018         break;
4019       lab = gimple_label_label (stmt);
4020       lp_nr = EH_LANDING_PAD_NR (lab);
4021       if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4022         return false;
4023     }
4024
4025   /* The new destination block must not already be a destination of
4026      the source block, lest we merge fallthru and eh edges and get
4027      all sorts of confused.  */
4028   if (find_edge (e_in->src, e_out->dest))
4029     return false;
4030
4031   /* ??? We can get degenerate phis due to cfg cleanups.  I would have
4032      thought this should have been cleaned up by a phicprop pass, but
4033      that doesn't appear to handle virtuals.  Propagate by hand.  */
4034   if (!gimple_seq_empty_p (phi_nodes (bb)))
4035     {
4036       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); )
4037         {
4038           gimple use_stmt, phi = gsi_stmt (gsi);
4039           tree lhs = gimple_phi_result (phi);
4040           tree rhs = gimple_phi_arg_def (phi, 0);
4041           use_operand_p use_p;
4042           imm_use_iterator iter;
4043
4044           FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4045             {
4046               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4047                 SET_USE (use_p, rhs);
4048             }
4049
4050           if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4051             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4052
4053           remove_phi_node (&gsi, true);
4054         }
4055     }
4056
4057   if (dump_file && (dump_flags & TDF_DETAILS))
4058     fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4059              lp->index, e_out->dest->index);
4060
4061   /* Redirect the edge.  Since redirect_eh_edge_1 expects to be moving
4062      a successor edge, humor it.  But do the real CFG change with the
4063      predecessor of E_OUT in order to preserve the ordering of arguments
4064      to the PHI nodes in E_OUT->DEST.  */
4065   redirect_eh_edge_1 (e_in, e_out->dest, false);
4066   redirect_edge_pred (e_out, e_in->src);
4067   e_out->flags = e_in->flags;
4068   e_out->probability = e_in->probability;
4069   e_out->count = e_in->count;
4070   remove_edge (e_in);
4071
4072   return true;
4073 }
4074
4075 /* Examine each landing pad block and see if it matches unsplit_eh.  */
4076
4077 static bool
4078 unsplit_all_eh (void)
4079 {
4080   bool changed = false;
4081   eh_landing_pad lp;
4082   int i;
4083
4084   for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4085     if (lp)
4086       changed |= unsplit_eh (lp);
4087
4088   return changed;
4089 }
4090
4091 /* A subroutine of cleanup_empty_eh.  Redirect all EH edges incoming
4092    to OLD_BB to NEW_BB; return true on success, false on failure.
4093
4094    OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4095    PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4096    Virtual PHIs may be deleted and marked for renaming.  */
4097
4098 static bool
4099 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4100                              edge old_bb_out, bool change_region)
4101 {
4102   gimple_stmt_iterator ngsi, ogsi;
4103   edge_iterator ei;
4104   edge e;
4105   bitmap ophi_handled;
4106
4107   /* The destination block must not be a regular successor for any
4108      of the preds of the landing pad.  Thus, avoid turning
4109         <..>
4110          |  \ EH
4111          |  <..>
4112          |  /
4113         <..>
4114      into
4115         <..>
4116         |  | EH
4117         <..>
4118      which CFG verification would choke on.  See PR45172 and PR51089.  */
4119   FOR_EACH_EDGE (e, ei, old_bb->preds)
4120     if (find_edge (e->src, new_bb))
4121       return false;
4122
4123   FOR_EACH_EDGE (e, ei, old_bb->preds)
4124     redirect_edge_var_map_clear (e);
4125
4126   ophi_handled = BITMAP_ALLOC (NULL);
4127
4128   /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4129      for the edges we're going to move.  */
4130   for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4131     {
4132       gimple ophi, nphi = gsi_stmt (ngsi);
4133       tree nresult, nop;
4134
4135       nresult = gimple_phi_result (nphi);
4136       nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4137
4138       /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4139          the source ssa_name.  */
4140       ophi = NULL;
4141       for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4142         {
4143           ophi = gsi_stmt (ogsi);
4144           if (gimple_phi_result (ophi) == nop)
4145             break;
4146           ophi = NULL;
4147         }
4148
4149       /* If we did find the corresponding PHI, copy those inputs.  */
4150       if (ophi)
4151         {
4152           /* If NOP is used somewhere else beyond phis in new_bb, give up.  */
4153           if (!has_single_use (nop))
4154             {
4155               imm_use_iterator imm_iter;
4156               use_operand_p use_p;
4157
4158               FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4159                 {
4160                   if (!gimple_debug_bind_p (USE_STMT (use_p))
4161                       && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4162                           || gimple_bb (USE_STMT (use_p)) != new_bb))
4163                     goto fail;
4164                 }
4165             }
4166           bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4167           FOR_EACH_EDGE (e, ei, old_bb->preds)
4168             {
4169               location_t oloc;
4170               tree oop;
4171
4172               if ((e->flags & EDGE_EH) == 0)
4173                 continue;
4174               oop = gimple_phi_arg_def (ophi, e->dest_idx);
4175               oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4176               redirect_edge_var_map_add (e, nresult, oop, oloc);
4177             }
4178         }
4179       /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4180          from the fact that OLD_BB is tree_empty_eh_handler_p that the
4181          variable is unchanged from input to the block and we can simply
4182          re-use the input to NEW_BB from the OLD_BB_OUT edge.  */
4183       else
4184         {
4185           location_t nloc
4186             = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4187           FOR_EACH_EDGE (e, ei, old_bb->preds)
4188             redirect_edge_var_map_add (e, nresult, nop, nloc);
4189         }
4190     }
4191
4192   /* Second, verify that all PHIs from OLD_BB have been handled.  If not,
4193      we don't know what values from the other edges into NEW_BB to use.  */
4194   for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4195     {
4196       gimple ophi = gsi_stmt (ogsi);
4197       tree oresult = gimple_phi_result (ophi);
4198       if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4199         goto fail;
4200     }
4201
4202   /* Finally, move the edges and update the PHIs.  */
4203   for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4204     if (e->flags & EDGE_EH)
4205       {
4206         /* ???  CFG manipluation routines do not try to update loop
4207            form on edge redirection.  Do so manually here for now.  */
4208         /* If we redirect a loop entry or latch edge that will either create
4209            a multiple entry loop or rotate the loop.  If the loops merge
4210            we may have created a loop with multiple latches.
4211            All of this isn't easily fixed thus cancel the affected loop
4212            and mark the other loop as possibly having multiple latches.  */
4213         if (current_loops
4214             && e->dest == e->dest->loop_father->header)
4215           {
4216             e->dest->loop_father->header = NULL;
4217             e->dest->loop_father->latch = NULL;
4218             new_bb->loop_father->latch = NULL;
4219             loops_state_set (LOOPS_NEED_FIXUP|LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4220           }
4221         redirect_eh_edge_1 (e, new_bb, change_region);
4222         redirect_edge_succ (e, new_bb);
4223         flush_pending_stmts (e);
4224       }
4225     else
4226       ei_next (&ei);
4227
4228   BITMAP_FREE (ophi_handled);
4229   return true;
4230
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;
4236 }
4237
4238 /* A subroutine of cleanup_empty_eh.  Move a landing pad LP from its
4239    old region to NEW_REGION at BB.  */
4240
4241 static void
4242 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4243                           eh_landing_pad lp, eh_region new_region)
4244 {
4245   gimple_stmt_iterator gsi;
4246   eh_landing_pad *pp;
4247
4248   for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4249     continue;
4250   *pp = lp->next_lp;
4251
4252   lp->region = new_region;
4253   lp->next_lp = new_region->landing_pads;
4254   new_region->landing_pads = lp;
4255
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);
4260
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;
4264 }
4265
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.  */
4269
4270 static bool
4271 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4272 {
4273   gimple_stmt_iterator gsi;
4274   tree lab;
4275
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);
4280
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))
4285     {
4286       gimple stmt = gsi_stmt (gsi);
4287       int lp_nr;
4288
4289       if (gimple_code (stmt) != GIMPLE_LABEL)
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;
4295     }
4296
4297   /* Attempt to move the PHIs into the successor block.  */
4298   if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4299     {
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;
4306     }
4307
4308   return false;
4309 }
4310
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.  */
4314
4315 static bool
4316 infinite_empty_loop_p (edge e_first)
4317 {
4318   bool inf_loop = false;
4319   edge e;
4320
4321   if (e_first->dest == e_first->src)
4322     return true;
4323
4324   e_first->src->aux = (void *) 1;
4325   for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4326     {
4327       gimple_stmt_iterator gsi;
4328       if (e->dest->aux)
4329         {
4330           inf_loop = true;
4331           break;
4332         }
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;
4339     }
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;
4343
4344   return inf_loop;
4345 }
4346
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.  */
4351
4352 static bool
4353 cleanup_empty_eh (eh_landing_pad lp)
4354 {
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;
4364
4365   /* There can be zero or one edges out of BB.  This is the quickest test.  */
4366   switch (EDGE_COUNT (bb->succs))
4367     {
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;
4376     }
4377
4378   resx = last_stmt (bb);
4379   if (resx && is_gimple_resx (resx))
4380     {
4381       if (stmt_can_throw_external (resx))
4382         optimize_clobbers (bb);
4383       else if (sink_clobbers (bb))
4384         ret = true;
4385     }
4386
4387   gsi = gsi_after_labels (bb);
4388
4389   /* Make sure to skip debug statements.  */
4390   if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4391     gsi_next_nondebug (&gsi);
4392
4393   /* If the block is totally empty, look for more unsplitting cases.  */
4394   if (gsi_end_p (gsi))
4395     {
4396       /* For the degenerate case of an infinite loop bail out.  */
4397       if (infinite_empty_loop_p (e_out))
4398         return ret;
4399
4400       return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4401     }
4402
4403   /* The block should consist only of a single RESX statement, modulo a
4404      preceding call to __builtin_stack_restore if there is no outgoing
4405      edge, since the call can be eliminated in this case.  */
4406   resx = gsi_stmt (gsi);
4407   if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4408     {
4409       gsi_next (&gsi);
4410       resx = gsi_stmt (gsi);
4411     }
4412   if (!is_gimple_resx (resx))
4413     return ret;
4414   gcc_assert (gsi_one_before_end_p (gsi));
4415
4416   /* Determine if there are non-EH edges, or resx edges into the handler.  */
4417   has_non_eh_pred = false;
4418   FOR_EACH_EDGE (e, ei, bb->preds)
4419     if (!(e->flags & EDGE_EH))
4420       has_non_eh_pred = true;
4421
4422   /* Find the handler that's outer of the empty handler by looking at
4423      where the RESX instruction was vectored.  */
4424   new_lp_nr = lookup_stmt_eh_lp (resx);
4425   new_region = get_eh_region_from_lp_number (new_lp_nr);
4426
4427   /* If there's no destination region within the current function,
4428      redirection is trivial via removing the throwing statements from
4429      the EH region, removing the EH edges, and allowing the block
4430      to go unreachable.  */
4431   if (new_region == NULL)
4432     {
4433       gcc_assert (e_out == NULL);
4434       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4435         if (e->flags & EDGE_EH)
4436           {
4437             gimple stmt = last_stmt (e->src);
4438             remove_stmt_from_eh_lp (stmt);
4439             remove_edge (e);
4440           }
4441         else
4442           ei_next (&ei);
4443       goto succeed;
4444     }
4445
4446   /* If the destination region is a MUST_NOT_THROW, allow the runtime
4447      to handle the abort and allow the blocks to go unreachable.  */
4448   if (new_region->type == ERT_MUST_NOT_THROW)
4449     {
4450       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4451         if (e->flags & EDGE_EH)
4452           {
4453             gimple stmt = last_stmt (e->src);
4454             remove_stmt_from_eh_lp (stmt);
4455             add_stmt_to_eh_lp (stmt, new_lp_nr);
4456             remove_edge (e);
4457           }
4458         else
4459           ei_next (&ei);
4460       goto succeed;
4461     }
4462
4463   /* Try to redirect the EH edges and merge the PHIs into the destination
4464      landing pad block.  If the merge succeeds, we'll already have redirected
4465      all the EH edges.  The handler itself will go unreachable if there were
4466      no normal edges.  */
4467   if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4468     goto succeed;
4469
4470   /* Finally, if all input edges are EH edges, then we can (potentially)
4471      reduce the number of transfers from the runtime by moving the landing
4472      pad from the original region to the new region.  This is a win when
4473      we remove the last CLEANUP region along a particular exception
4474      propagation path.  Since nothing changes except for the region with
4475      which the landing pad is associated, the PHI nodes do not need to be
4476      adjusted at all.  */
4477   if (!has_non_eh_pred)
4478     {
4479       cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4480       if (dump_file && (dump_flags & TDF_DETAILS))
4481         fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4482                  lp->index, new_region->index);
4483
4484       /* ??? The CFG didn't change, but we may have rendered the
4485          old EH region unreachable.  Trigger a cleanup there.  */
4486       return true;
4487     }
4488
4489   return ret;
4490
4491  succeed:
4492   if (dump_file && (dump_flags & TDF_DETAILS))
4493     fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4494   remove_eh_landing_pad (lp);
4495   return true;
4496 }
4497
4498 /* Do a post-order traversal of the EH region tree.  Examine each
4499    post_landing_pad block and see if we can eliminate it as empty.  */
4500
4501 static bool
4502 cleanup_all_empty_eh (void)
4503 {
4504   bool changed = false;
4505   eh_landing_pad lp;
4506   int i;
4507
4508   for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4509     if (lp)
4510       changed |= cleanup_empty_eh (lp);
4511
4512   return changed;
4513 }
4514
4515 /* Perform cleanups and lowering of exception handling
4516     1) cleanups regions with handlers doing nothing are optimized out
4517     2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4518     3) Info about regions that are containing instructions, and regions
4519        reachable via local EH edges is collected
4520     4) Eh tree is pruned for regions no longer necessary.
4521
4522    TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4523          Unify those that have the same failure decl and locus.
4524 */
4525
4526 static unsigned int
4527 execute_cleanup_eh_1 (void)
4528 {
4529   /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4530      looking up unreachable landing pads.  */
4531   remove_unreachable_handlers ();
4532
4533   /* Watch out for the region tree vanishing due to all unreachable.  */
4534   if (cfun->eh->region_tree && optimize)
4535     {
4536       bool changed = false;
4537
4538       changed |= unsplit_all_eh ();
4539       changed |= cleanup_all_empty_eh ();
4540
4541       if (changed)
4542         {
4543           free_dominance_info (CDI_DOMINATORS);
4544           free_dominance_info (CDI_POST_DOMINATORS);
4545
4546           /* We delayed all basic block deletion, as we may have performed
4547              cleanups on EH edges while non-EH edges were still present.  */
4548           delete_unreachable_blocks ();
4549
4550           /* We manipulated the landing pads.  Remove any region that no
4551              longer has a landing pad.  */
4552           remove_unreachable_handlers_no_lp ();
4553
4554           return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4555         }
4556     }
4557
4558   return 0;
4559 }
4560
4561 static unsigned int
4562 execute_cleanup_eh (void)
4563 {
4564   int ret = execute_cleanup_eh_1 ();
4565
4566   /* If the function no longer needs an EH personality routine
4567      clear it.  This exposes cross-language inlining opportunities
4568      and avoids references to a never defined personality routine.  */
4569   if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4570       && function_needs_eh_personality (cfun) != eh_personality_lang)
4571     DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4572
4573   return ret;
4574 }
4575
4576 static bool
4577 gate_cleanup_eh (void)
4578 {
4579   return cfun->eh != NULL && cfun->eh->region_tree != NULL;
4580 }
4581
4582 namespace {
4583
4584 const pass_data pass_data_cleanup_eh =
4585 {
4586   GIMPLE_PASS, /* type */
4587   "ehcleanup", /* name */
4588   OPTGROUP_NONE, /* optinfo_flags */
4589   true, /* has_gate */
4590   true, /* has_execute */
4591   TV_TREE_EH, /* tv_id */
4592   PROP_gimple_lcf, /* properties_required */
4593   0, /* properties_provided */
4594   0, /* properties_destroyed */
4595   0, /* todo_flags_start */
4596   TODO_verify_ssa, /* todo_flags_finish */
4597 };
4598
4599 class pass_cleanup_eh : public gimple_opt_pass
4600 {
4601 public:
4602   pass_cleanup_eh (gcc::context *ctxt)
4603     : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4604   {}
4605
4606   /* opt_pass methods: */
4607   opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4608   bool gate () { return gate_cleanup_eh (); }
4609   unsigned int execute () { return execute_cleanup_eh (); }
4610
4611 }; // class pass_cleanup_eh
4612
4613 } // anon namespace
4614
4615 gimple_opt_pass *
4616 make_pass_cleanup_eh (gcc::context *ctxt)
4617 {
4618   return new pass_cleanup_eh (ctxt);
4619 }
4620 \f
4621 /* Verify that BB containing STMT as the last statement, has precisely the
4622    edge that make_eh_edges would create.  */
4623
4624 DEBUG_FUNCTION bool
4625 verify_eh_edges (gimple stmt)
4626 {
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;
4632
4633   lp_nr = lookup_stmt_eh_lp (stmt);
4634   if (lp_nr > 0)
4635     lp = get_eh_landing_pad_from_number (lp_nr);
4636
4637   eh_edge = NULL;
4638   FOR_EACH_EDGE (e, ei, bb->succs)
4639     {
4640       if (e->flags & EDGE_EH)
4641         {
4642           if (eh_edge)
4643             {
4644               error ("BB %i has multiple EH edges", bb->index);
4645               return true;
4646             }
4647           else
4648             eh_edge = e;
4649         }
4650     }
4651
4652   if (lp == NULL)
4653     {
4654       if (eh_edge)
4655         {
4656           error ("BB %i can not throw but has an EH edge", bb->index);
4657           return true;
4658         }
4659       return false;
4660     }
4661
4662   if (!stmt_could_throw_p (stmt))
4663     {
4664       error ("BB %i last statement has incorrectly set lp", bb->index);
4665       return true;
4666     }
4667
4668   if (eh_edge == NULL)
4669     {
4670       error ("BB %i is missing an EH edge", bb->index);
4671       return true;
4672     }
4673
4674   if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4675     {
4676       error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4677       return true;
4678     }
4679
4680   return false;
4681 }
4682
4683 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically.  */
4684
4685 DEBUG_FUNCTION bool
4686 verify_eh_dispatch_edge (gimple stmt)
4687 {
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;
4694
4695   r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4696   src = gimple_bb (stmt);
4697
4698   FOR_EACH_EDGE (e, ei, src->succs)
4699     gcc_assert (e->aux == NULL);
4700
4701   switch (r->type)
4702     {
4703     case ERT_TRY:
4704       for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4705         {
4706           dst = label_to_block (c->label);
4707           e = find_edge (src, dst);
4708           if (e == NULL)
4709             {
4710               error ("BB %i is missing an edge", src->index);
4711               return true;
4712             }
4713           e->aux = (void *)e;
4714
4715           /* A catch-all handler doesn't have a fallthru.  */
4716           if (c->type_list == NULL)
4717             {
4718               want_fallthru = false;
4719               break;
4720             }
4721         }
4722       break;
4723
4724     case ERT_ALLOWED_EXCEPTIONS:
4725       dst = label_to_block (r->u.allowed.label);
4726       e = find_edge (src, dst);
4727       if (e == NULL)
4728         {
4729           error ("BB %i is missing an edge", src->index);
4730           return true;
4731         }
4732       e->aux = (void *)e;
4733       break;
4734
4735     default:
4736       gcc_unreachable ();
4737     }
4738
4739   fall_edge = NULL;
4740   FOR_EACH_EDGE (e, ei, src->succs)
4741     {
4742       if (e->flags & EDGE_FALLTHRU)
4743         {
4744           if (fall_edge != NULL)
4745             {
4746               error ("BB %i too many fallthru edges", src->index);
4747               return true;
4748             }
4749           fall_edge = e;
4750         }
4751       else if (e->aux)
4752         e->aux = NULL;
4753       else
4754         {
4755           error ("BB %i has incorrect edge", src->index);
4756           return true;
4757         }
4758     }
4759   if ((fall_edge != NULL) ^ want_fallthru)
4760     {
4761       error ("BB %i has incorrect fallthru edge", src->index);
4762       return true;
4763     }
4764
4765   return false;
4766 }