OSDN Git Service

e78341110d9d60226bd7424d60ac0de0603000e3
[pf3gnuchains/gcc-fork.git] / gcc / except.c
1 /* Implements exception handling.
2    Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4    Contributed by Mike Stump <mrs@cygnus.com>.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21 02111-1307, USA.  */
22
23
24 /* An exception is an event that can be signaled from within a
25    function. This event can then be "caught" or "trapped" by the
26    callers of this function. This potentially allows program flow to
27    be transferred to any arbitrary code associated with a function call
28    several levels up the stack.
29
30    The intended use for this mechanism is for signaling "exceptional
31    events" in an out-of-band fashion, hence its name. The C++ language
32    (and many other OO-styled or functional languages) practically
33    requires such a mechanism, as otherwise it becomes very difficult
34    or even impossible to signal failure conditions in complex
35    situations.  The traditional C++ example is when an error occurs in
36    the process of constructing an object; without such a mechanism, it
37    is impossible to signal that the error occurs without adding global
38    state variables and error checks around every object construction.
39
40    The act of causing this event to occur is referred to as "throwing
41    an exception". (Alternate terms include "raising an exception" or
42    "signaling an exception".) The term "throw" is used because control
43    is returned to the callers of the function that is signaling the
44    exception, and thus there is the concept of "throwing" the
45    exception up the call stack.
46
47    [ Add updated documentation on how to use this.  ]  */
48
49
50 #include "config.h"
51 #include "system.h"
52 #include "coretypes.h"
53 #include "tm.h"
54 #include "rtl.h"
55 #include "tree.h"
56 #include "flags.h"
57 #include "function.h"
58 #include "expr.h"
59 #include "libfuncs.h"
60 #include "insn-config.h"
61 #include "except.h"
62 #include "integrate.h"
63 #include "hard-reg-set.h"
64 #include "basic-block.h"
65 #include "output.h"
66 #include "dwarf2asm.h"
67 #include "dwarf2out.h"
68 #include "dwarf2.h"
69 #include "toplev.h"
70 #include "hashtab.h"
71 #include "intl.h"
72 #include "ggc.h"
73 #include "tm_p.h"
74 #include "target.h"
75 #include "langhooks.h"
76 #include "cgraph.h"
77 #include "diagnostic.h"
78
79 /* Provide defaults for stuff that may not be defined when using
80    sjlj exceptions.  */
81 #ifndef EH_RETURN_DATA_REGNO
82 #define EH_RETURN_DATA_REGNO(N) INVALID_REGNUM
83 #endif
84
85
86 /* Protect cleanup actions with must-not-throw regions, with a call
87    to the given failure handler.  */
88 tree (*lang_protect_cleanup_actions) (void);
89
90 /* Return true if type A catches type B.  */
91 int (*lang_eh_type_covers) (tree a, tree b);
92
93 /* Map a type to a runtime object to match type.  */
94 tree (*lang_eh_runtime_type) (tree);
95
96 /* A hash table of label to region number.  */
97
98 struct ehl_map_entry GTY(())
99 {
100   rtx label;
101   struct eh_region *region;
102 };
103
104 static GTY(()) int call_site_base;
105 static GTY ((param_is (union tree_node)))
106   htab_t type_to_runtime_map;
107
108 /* Describe the SjLj_Function_Context structure.  */
109 static GTY(()) tree sjlj_fc_type_node;
110 static int sjlj_fc_call_site_ofs;
111 static int sjlj_fc_data_ofs;
112 static int sjlj_fc_personality_ofs;
113 static int sjlj_fc_lsda_ofs;
114 static int sjlj_fc_jbuf_ofs;
115 \f
116 /* Describes one exception region.  */
117 struct eh_region GTY(())
118 {
119   /* The immediately surrounding region.  */
120   struct eh_region *outer;
121
122   /* The list of immediately contained regions.  */
123   struct eh_region *inner;
124   struct eh_region *next_peer;
125
126   /* An identifier for this region.  */
127   int region_number;
128
129   /* When a region is deleted, its parents inherit the REG_EH_REGION
130      numbers already assigned.  */
131   bitmap aka;
132
133   /* Each region does exactly one thing.  */
134   enum eh_region_type
135   { 
136     ERT_UNKNOWN = 0,
137     ERT_CLEANUP,
138     ERT_TRY,
139     ERT_CATCH,
140     ERT_ALLOWED_EXCEPTIONS,
141     ERT_MUST_NOT_THROW,
142     ERT_THROW
143   } type;
144
145   /* Holds the action to perform based on the preceding type.  */
146   union eh_region_u {
147     /* A list of catch blocks, a surrounding try block,
148        and the label for continuing after a catch.  */
149     struct eh_region_u_try {
150       struct eh_region *catch;
151       struct eh_region *last_catch;
152     } GTY ((tag ("ERT_TRY"))) try;
153
154     /* The list through the catch handlers, the list of type objects
155        matched, and the list of associated filters.  */
156     struct eh_region_u_catch {
157       struct eh_region *next_catch;
158       struct eh_region *prev_catch;
159       tree type_list;
160       tree filter_list;
161     } GTY ((tag ("ERT_CATCH"))) catch;
162
163     /* A tree_list of allowed types.  */
164     struct eh_region_u_allowed {
165       tree type_list;
166       int filter;
167     } GTY ((tag ("ERT_ALLOWED_EXCEPTIONS"))) allowed;
168
169     /* The type given by a call to "throw foo();", or discovered
170        for a throw.  */
171     struct eh_region_u_throw {
172       tree type;
173     } GTY ((tag ("ERT_THROW"))) throw;
174
175     /* Retain the cleanup expression even after expansion so that
176        we can match up fixup regions.  */
177     struct eh_region_u_cleanup {
178       struct eh_region *prev_try;
179     } GTY ((tag ("ERT_CLEANUP"))) cleanup;
180   } GTY ((desc ("%0.type"))) u;
181
182   /* Entry point for this region's handler before landing pads are built.  */
183   rtx label;
184   tree tree_label;
185
186   /* Entry point for this region's handler from the runtime eh library.  */
187   rtx landing_pad;
188
189   /* Entry point for this region's handler from an inner region.  */
190   rtx post_landing_pad;
191
192   /* The RESX insn for handing off control to the next outermost handler,
193      if appropriate.  */
194   rtx resume;
195
196   /* True if something in this region may throw.  */
197   unsigned may_contain_throw : 1;
198 };
199
200 struct call_site_record GTY(())
201 {
202   rtx landing_pad;
203   int action;
204 };
205
206 /* Used to save exception status for each function.  */
207 struct eh_status GTY(())
208 {
209   /* The tree of all regions for this function.  */
210   struct eh_region *region_tree;
211
212   /* The same information as an indexable array.  */
213   struct eh_region ** GTY ((length ("%h.last_region_number"))) region_array;
214
215   /* The most recently open region.  */
216   struct eh_region *cur_region;
217
218   /* This is the region for which we are processing catch blocks.  */
219   struct eh_region *try_region;
220
221   rtx filter;
222   rtx exc_ptr;
223
224   int built_landing_pads;
225   int last_region_number;
226
227   VEC(tree,gc) *ttype_data;
228   varray_type ehspec_data;
229   varray_type action_record_data;
230
231   htab_t GTY ((param_is (struct ehl_map_entry))) exception_handler_label_map;
232
233   struct call_site_record * GTY ((length ("%h.call_site_data_used")))
234     call_site_data;
235   int call_site_data_used;
236   int call_site_data_size;
237
238   rtx ehr_stackadj;
239   rtx ehr_handler;
240   rtx ehr_label;
241
242   rtx sjlj_fc;
243   rtx sjlj_exit_after;
244
245   htab_t GTY((param_is (struct throw_stmt_node))) throw_stmt_table;
246 };
247
248 \f
249 static int t2r_eq (const void *, const void *);
250 static hashval_t t2r_hash (const void *);
251 static void add_type_for_runtime (tree);
252 static tree lookup_type_for_runtime (tree);
253
254 static void remove_unreachable_regions (rtx);
255
256 static int ttypes_filter_eq (const void *, const void *);
257 static hashval_t ttypes_filter_hash (const void *);
258 static int ehspec_filter_eq (const void *, const void *);
259 static hashval_t ehspec_filter_hash (const void *);
260 static int add_ttypes_entry (htab_t, tree);
261 static int add_ehspec_entry (htab_t, htab_t, tree);
262 static void assign_filter_values (void);
263 static void build_post_landing_pads (void);
264 static void connect_post_landing_pads (void);
265 static void dw2_build_landing_pads (void);
266
267 struct sjlj_lp_info;
268 static bool sjlj_find_directly_reachable_regions (struct sjlj_lp_info *);
269 static void sjlj_assign_call_site_values (rtx, struct sjlj_lp_info *);
270 static void sjlj_mark_call_sites (struct sjlj_lp_info *);
271 static void sjlj_emit_function_enter (rtx);
272 static void sjlj_emit_function_exit (void);
273 static void sjlj_emit_dispatch_table (rtx, struct sjlj_lp_info *);
274 static void sjlj_build_landing_pads (void);
275
276 static hashval_t ehl_hash (const void *);
277 static int ehl_eq (const void *, const void *);
278 static void add_ehl_entry (rtx, struct eh_region *);
279 static void remove_exception_handler_label (rtx);
280 static void remove_eh_handler (struct eh_region *);
281 static int for_each_eh_label_1 (void **, void *);
282
283 /* The return value of reachable_next_level.  */
284 enum reachable_code
285 {
286   /* The given exception is not processed by the given region.  */
287   RNL_NOT_CAUGHT,
288   /* The given exception may need processing by the given region.  */
289   RNL_MAYBE_CAUGHT,
290   /* The given exception is completely processed by the given region.  */
291   RNL_CAUGHT,
292   /* The given exception is completely processed by the runtime.  */
293   RNL_BLOCKED
294 };
295
296 struct reachable_info;
297 static enum reachable_code reachable_next_level (struct eh_region *, tree,
298                                                  struct reachable_info *);
299
300 static int action_record_eq (const void *, const void *);
301 static hashval_t action_record_hash (const void *);
302 static int add_action_record (htab_t, int, int);
303 static int collect_one_action_chain (htab_t, struct eh_region *);
304 static int add_call_site (rtx, int);
305
306 static void push_uleb128 (varray_type *, unsigned int);
307 static void push_sleb128 (varray_type *, int);
308 #ifndef HAVE_AS_LEB128
309 static int dw2_size_of_call_site_table (void);
310 static int sjlj_size_of_call_site_table (void);
311 #endif
312 static void dw2_output_call_site_table (void);
313 static void sjlj_output_call_site_table (void);
314
315 \f
316 /* Routine to see if exception handling is turned on.
317    DO_WARN is nonzero if we want to inform the user that exception
318    handling is turned off.
319
320    This is used to ensure that -fexceptions has been specified if the
321    compiler tries to use any exception-specific functions.  */
322
323 int
324 doing_eh (int do_warn)
325 {
326   if (! flag_exceptions)
327     {
328       static int warned = 0;
329       if (! warned && do_warn)
330         {
331           error ("exception handling disabled, use -fexceptions to enable");
332           warned = 1;
333         }
334       return 0;
335     }
336   return 1;
337 }
338
339 \f
340 void
341 init_eh (void)
342 {
343   if (! flag_exceptions)
344     return;
345
346   type_to_runtime_map = htab_create_ggc (31, t2r_hash, t2r_eq, NULL);
347
348   /* Create the SjLj_Function_Context structure.  This should match
349      the definition in unwind-sjlj.c.  */
350   if (USING_SJLJ_EXCEPTIONS)
351     {
352       tree f_jbuf, f_per, f_lsda, f_prev, f_cs, f_data, tmp;
353
354       sjlj_fc_type_node = lang_hooks.types.make_type (RECORD_TYPE);
355
356       f_prev = build_decl (FIELD_DECL, get_identifier ("__prev"),
357                            build_pointer_type (sjlj_fc_type_node));
358       DECL_FIELD_CONTEXT (f_prev) = sjlj_fc_type_node;
359
360       f_cs = build_decl (FIELD_DECL, get_identifier ("__call_site"),
361                          integer_type_node);
362       DECL_FIELD_CONTEXT (f_cs) = sjlj_fc_type_node;
363
364       tmp = build_index_type (build_int_cst (NULL_TREE, 4 - 1));
365       tmp = build_array_type (lang_hooks.types.type_for_mode (word_mode, 1),
366                               tmp);
367       f_data = build_decl (FIELD_DECL, get_identifier ("__data"), tmp);
368       DECL_FIELD_CONTEXT (f_data) = sjlj_fc_type_node;
369
370       f_per = build_decl (FIELD_DECL, get_identifier ("__personality"),
371                           ptr_type_node);
372       DECL_FIELD_CONTEXT (f_per) = sjlj_fc_type_node;
373
374       f_lsda = build_decl (FIELD_DECL, get_identifier ("__lsda"),
375                            ptr_type_node);
376       DECL_FIELD_CONTEXT (f_lsda) = sjlj_fc_type_node;
377
378 #ifdef DONT_USE_BUILTIN_SETJMP
379 #ifdef JMP_BUF_SIZE
380       tmp = build_int_cst (NULL_TREE, JMP_BUF_SIZE - 1);
381 #else
382       /* Should be large enough for most systems, if it is not,
383          JMP_BUF_SIZE should be defined with the proper value.  It will
384          also tend to be larger than necessary for most systems, a more
385          optimal port will define JMP_BUF_SIZE.  */
386       tmp = build_int_cst (NULL_TREE, FIRST_PSEUDO_REGISTER + 2 - 1);
387 #endif
388 #else
389       /* builtin_setjmp takes a pointer to 5 words.  */
390       tmp = build_int_cst (NULL_TREE, 5 * BITS_PER_WORD / POINTER_SIZE - 1);
391 #endif
392       tmp = build_index_type (tmp);
393       tmp = build_array_type (ptr_type_node, tmp);
394       f_jbuf = build_decl (FIELD_DECL, get_identifier ("__jbuf"), tmp);
395 #ifdef DONT_USE_BUILTIN_SETJMP
396       /* We don't know what the alignment requirements of the
397          runtime's jmp_buf has.  Overestimate.  */
398       DECL_ALIGN (f_jbuf) = BIGGEST_ALIGNMENT;
399       DECL_USER_ALIGN (f_jbuf) = 1;
400 #endif
401       DECL_FIELD_CONTEXT (f_jbuf) = sjlj_fc_type_node;
402
403       TYPE_FIELDS (sjlj_fc_type_node) = f_prev;
404       TREE_CHAIN (f_prev) = f_cs;
405       TREE_CHAIN (f_cs) = f_data;
406       TREE_CHAIN (f_data) = f_per;
407       TREE_CHAIN (f_per) = f_lsda;
408       TREE_CHAIN (f_lsda) = f_jbuf;
409
410       layout_type (sjlj_fc_type_node);
411
412       /* Cache the interesting field offsets so that we have
413          easy access from rtl.  */
414       sjlj_fc_call_site_ofs
415         = (tree_low_cst (DECL_FIELD_OFFSET (f_cs), 1)
416            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_cs), 1) / BITS_PER_UNIT);
417       sjlj_fc_data_ofs
418         = (tree_low_cst (DECL_FIELD_OFFSET (f_data), 1)
419            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_data), 1) / BITS_PER_UNIT);
420       sjlj_fc_personality_ofs
421         = (tree_low_cst (DECL_FIELD_OFFSET (f_per), 1)
422            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_per), 1) / BITS_PER_UNIT);
423       sjlj_fc_lsda_ofs
424         = (tree_low_cst (DECL_FIELD_OFFSET (f_lsda), 1)
425            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_lsda), 1) / BITS_PER_UNIT);
426       sjlj_fc_jbuf_ofs
427         = (tree_low_cst (DECL_FIELD_OFFSET (f_jbuf), 1)
428            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_jbuf), 1) / BITS_PER_UNIT);
429     }
430 }
431
432 void
433 init_eh_for_function (void)
434 {
435   cfun->eh = ggc_alloc_cleared (sizeof (struct eh_status));
436 }
437 \f
438 /* Routines to generate the exception tree somewhat directly.  
439    These are used from tree-eh.c when processing exception related
440    nodes during tree optimization.  */
441
442 static struct eh_region *
443 gen_eh_region (enum eh_region_type type, struct eh_region *outer)
444 {
445   struct eh_region *new;
446
447 #ifdef ENABLE_CHECKING
448   gcc_assert (doing_eh (0));
449 #endif
450
451   /* Insert a new blank region as a leaf in the tree.  */
452   new = ggc_alloc_cleared (sizeof (*new));
453   new->type = type;
454   new->outer = outer;
455   if (outer)
456     {
457       new->next_peer = outer->inner;
458       outer->inner = new;
459     }
460   else
461     {
462       new->next_peer = cfun->eh->region_tree;
463       cfun->eh->region_tree = new;
464     }
465
466   new->region_number = ++cfun->eh->last_region_number;
467
468   return new;
469 }
470
471 struct eh_region *
472 gen_eh_region_cleanup (struct eh_region *outer, struct eh_region *prev_try)
473 {
474   struct eh_region *cleanup = gen_eh_region (ERT_CLEANUP, outer);
475   cleanup->u.cleanup.prev_try = prev_try;
476   return cleanup;
477 }
478
479 struct eh_region *
480 gen_eh_region_try (struct eh_region *outer)
481 {
482   return gen_eh_region (ERT_TRY, outer);
483 }
484
485 struct eh_region *
486 gen_eh_region_catch (struct eh_region *t, tree type_or_list)
487 {
488   struct eh_region *c, *l;
489   tree type_list, type_node;
490
491   /* Ensure to always end up with a type list to normalize further
492      processing, then register each type against the runtime types map.  */
493   type_list = type_or_list;
494   if (type_or_list)
495     {
496       if (TREE_CODE (type_or_list) != TREE_LIST)
497         type_list = tree_cons (NULL_TREE, type_or_list, NULL_TREE);
498
499       type_node = type_list;
500       for (; type_node; type_node = TREE_CHAIN (type_node))
501         add_type_for_runtime (TREE_VALUE (type_node));
502     }
503
504   c = gen_eh_region (ERT_CATCH, t->outer);
505   c->u.catch.type_list = type_list;
506   l = t->u.try.last_catch;
507   c->u.catch.prev_catch = l;
508   if (l)
509     l->u.catch.next_catch = c;
510   else
511     t->u.try.catch = c;
512   t->u.try.last_catch = c;
513
514   return c;
515 }
516
517 struct eh_region *
518 gen_eh_region_allowed (struct eh_region *outer, tree allowed)
519 {
520   struct eh_region *region = gen_eh_region (ERT_ALLOWED_EXCEPTIONS, outer);
521   region->u.allowed.type_list = allowed;
522
523   for (; allowed ; allowed = TREE_CHAIN (allowed))
524     add_type_for_runtime (TREE_VALUE (allowed));
525
526   return region;
527 }
528
529 struct eh_region *
530 gen_eh_region_must_not_throw (struct eh_region *outer)
531 {
532   return gen_eh_region (ERT_MUST_NOT_THROW, outer);
533 }
534
535 int
536 get_eh_region_number (struct eh_region *region)
537 {
538   return region->region_number;
539 }
540
541 bool
542 get_eh_region_may_contain_throw (struct eh_region *region)
543 {
544   return region->may_contain_throw;
545 }
546
547 tree
548 get_eh_region_tree_label (struct eh_region *region)
549 {
550   return region->tree_label;
551 }
552
553 void
554 set_eh_region_tree_label (struct eh_region *region, tree lab)
555 {
556   region->tree_label = lab;
557 }
558 \f
559 void
560 expand_resx_expr (tree exp)
561 {
562   int region_nr = TREE_INT_CST_LOW (TREE_OPERAND (exp, 0));
563   struct eh_region *reg = cfun->eh->region_array[region_nr];
564
565   gcc_assert (!reg->resume);
566   reg->resume = emit_jump_insn (gen_rtx_RESX (VOIDmode, region_nr));
567   emit_barrier ();
568 }
569
570 /* Note that the current EH region (if any) may contain a throw, or a
571    call to a function which itself may contain a throw.  */
572
573 void
574 note_eh_region_may_contain_throw (struct eh_region *region)
575 {
576   while (region && !region->may_contain_throw)
577     {
578       region->may_contain_throw = 1;
579       region = region->outer;
580     }
581 }
582
583 void
584 note_current_region_may_contain_throw (void)
585 {
586   note_eh_region_may_contain_throw (cfun->eh->cur_region);
587 }
588
589
590 /* Return an rtl expression for a pointer to the exception object
591    within a handler.  */
592
593 rtx
594 get_exception_pointer (struct function *fun)
595 {
596   rtx exc_ptr = fun->eh->exc_ptr;
597   if (fun == cfun && ! exc_ptr)
598     {
599       exc_ptr = gen_reg_rtx (ptr_mode);
600       fun->eh->exc_ptr = exc_ptr;
601     }
602   return exc_ptr;
603 }
604
605 /* Return an rtl expression for the exception dispatch filter
606    within a handler.  */
607
608 rtx
609 get_exception_filter (struct function *fun)
610 {
611   rtx filter = fun->eh->filter;
612   if (fun == cfun && ! filter)
613     {
614       filter = gen_reg_rtx (targetm.eh_return_filter_mode ());
615       fun->eh->filter = filter;
616     }
617   return filter;
618 }
619 \f
620 /* This section is for the exception handling specific optimization pass.  */
621
622 /* Random access the exception region tree.  */
623
624 void
625 collect_eh_region_array (void)
626 {
627   struct eh_region **array, *i;
628
629   i = cfun->eh->region_tree;
630   if (! i)
631     return;
632
633   array = ggc_alloc_cleared ((cfun->eh->last_region_number + 1)
634                              * sizeof (*array));
635   cfun->eh->region_array = array;
636
637   while (1)
638     {
639       array[i->region_number] = i;
640
641       /* If there are sub-regions, process them.  */
642       if (i->inner)
643         i = i->inner;
644       /* If there are peers, process them.  */
645       else if (i->next_peer)
646         i = i->next_peer;
647       /* Otherwise, step back up the tree to the next peer.  */
648       else
649         {
650           do {
651             i = i->outer;
652             if (i == NULL)
653               return;
654           } while (i->next_peer == NULL);
655           i = i->next_peer;
656         }
657     }
658 }
659
660 /* Remove all regions whose labels are not reachable from insns.  */
661
662 static void
663 remove_unreachable_regions (rtx insns)
664 {
665   int i, *uid_region_num;
666   bool *reachable;
667   struct eh_region *r;
668   rtx insn;
669
670   uid_region_num = xcalloc (get_max_uid (), sizeof(int));
671   reachable = xcalloc (cfun->eh->last_region_number + 1, sizeof(bool));
672
673   for (i = cfun->eh->last_region_number; i > 0; --i)
674     {
675       r = cfun->eh->region_array[i];
676       if (!r || r->region_number != i)
677         continue;
678
679       if (r->resume)
680         {
681           gcc_assert (!uid_region_num[INSN_UID (r->resume)]);
682           uid_region_num[INSN_UID (r->resume)] = i;
683         }
684       if (r->label)
685         {
686           gcc_assert (!uid_region_num[INSN_UID (r->label)]);
687           uid_region_num[INSN_UID (r->label)] = i;
688         }
689     }
690
691   for (insn = insns; insn; insn = NEXT_INSN (insn))
692     reachable[uid_region_num[INSN_UID (insn)]] = true;
693
694   for (i = cfun->eh->last_region_number; i > 0; --i)
695     {
696       r = cfun->eh->region_array[i];
697       if (r && r->region_number == i && !reachable[i])
698         {
699           bool kill_it = true;
700           switch (r->type)
701             {
702             case ERT_THROW:
703               /* Don't remove ERT_THROW regions if their outer region
704                  is reachable.  */
705               if (r->outer && reachable[r->outer->region_number])
706                 kill_it = false;
707               break;
708
709             case ERT_MUST_NOT_THROW:
710               /* MUST_NOT_THROW regions are implementable solely in the
711                  runtime, but their existence continues to affect calls
712                  within that region.  Never delete them here.  */
713               kill_it = false;
714               break;
715
716             case ERT_TRY:
717               {
718                 /* TRY regions are reachable if any of its CATCH regions
719                    are reachable.  */
720                 struct eh_region *c;
721                 for (c = r->u.try.catch; c ; c = c->u.catch.next_catch)
722                   if (reachable[c->region_number])
723                     {
724                       kill_it = false;
725                       break;
726                     }
727                 break;
728               }
729
730             default:
731               break;
732             }
733               
734           if (kill_it)
735             remove_eh_handler (r);
736         }
737     }
738
739   free (reachable);
740   free (uid_region_num);
741 }
742
743 /* Set up EH labels for RTL.  */
744
745 void
746 convert_from_eh_region_ranges (void)
747 {
748   rtx insns = get_insns ();
749   int i, n = cfun->eh->last_region_number;
750
751   /* Most of the work is already done at the tree level.  All we need to
752      do is collect the rtl labels that correspond to the tree labels that
753      collect the rtl labels that correspond to the tree labels
754      we allocated earlier.  */
755   for (i = 1; i <= n; ++i)
756     {
757       struct eh_region *region = cfun->eh->region_array[i];
758       if (region && region->tree_label)
759         region->label = DECL_RTL_IF_SET (region->tree_label);
760     }
761
762   remove_unreachable_regions (insns);
763 }
764
765 static void
766 add_ehl_entry (rtx label, struct eh_region *region)
767 {
768   struct ehl_map_entry **slot, *entry;
769
770   LABEL_PRESERVE_P (label) = 1;
771
772   entry = ggc_alloc (sizeof (*entry));
773   entry->label = label;
774   entry->region = region;
775
776   slot = (struct ehl_map_entry **)
777     htab_find_slot (cfun->eh->exception_handler_label_map, entry, INSERT);
778
779   /* Before landing pad creation, each exception handler has its own
780      label.  After landing pad creation, the exception handlers may
781      share landing pads.  This is ok, since maybe_remove_eh_handler
782      only requires the 1-1 mapping before landing pad creation.  */
783   gcc_assert (!*slot || cfun->eh->built_landing_pads);
784
785   *slot = entry;
786 }
787
788 void
789 find_exception_handler_labels (void)
790 {
791   int i;
792
793   if (cfun->eh->exception_handler_label_map)
794     htab_empty (cfun->eh->exception_handler_label_map);
795   else
796     {
797       /* ??? The expansion factor here (3/2) must be greater than the htab
798          occupancy factor (4/3) to avoid unnecessary resizing.  */
799       cfun->eh->exception_handler_label_map
800         = htab_create_ggc (cfun->eh->last_region_number * 3 / 2,
801                            ehl_hash, ehl_eq, NULL);
802     }
803
804   if (cfun->eh->region_tree == NULL)
805     return;
806
807   for (i = cfun->eh->last_region_number; i > 0; --i)
808     {
809       struct eh_region *region = cfun->eh->region_array[i];
810       rtx lab;
811
812       if (! region || region->region_number != i)
813         continue;
814       if (cfun->eh->built_landing_pads)
815         lab = region->landing_pad;
816       else
817         lab = region->label;
818
819       if (lab)
820         add_ehl_entry (lab, region);
821     }
822
823   /* For sjlj exceptions, need the return label to remain live until
824      after landing pad generation.  */
825   if (USING_SJLJ_EXCEPTIONS && ! cfun->eh->built_landing_pads)
826     add_ehl_entry (return_label, NULL);
827 }
828
829 bool
830 current_function_has_exception_handlers (void)
831 {
832   int i;
833
834   for (i = cfun->eh->last_region_number; i > 0; --i)
835     {
836       struct eh_region *region = cfun->eh->region_array[i];
837
838       if (! region || region->region_number != i)
839         continue;
840       if (region->type != ERT_THROW)
841         return true;
842     }
843
844   return false;
845 }
846 \f
847 static struct eh_region *
848 duplicate_eh_region_1 (struct eh_region *o)
849 {
850   struct eh_region *n = ggc_alloc_cleared (sizeof (struct eh_region));
851
852   *n = *o;
853   
854   n->region_number = o->region_number + cfun->eh->last_region_number;
855   gcc_assert (!o->aka);
856   
857   return n;
858 }
859
860 static void
861 duplicate_eh_region_2 (struct eh_region *o, struct eh_region **n_array,
862                        struct eh_region *prev_try)
863 {
864   struct eh_region *n = n_array[o->region_number];
865   
866   switch (n->type)
867     {
868     case ERT_TRY:
869       if (o->u.try.catch)
870         n->u.try.catch = n_array[o->u.try.catch->region_number];
871       if (o->u.try.last_catch)
872         n->u.try.last_catch = n_array[o->u.try.last_catch->region_number];
873       break;
874       
875     case ERT_CATCH:
876       if (o->u.catch.next_catch)
877         n->u.catch.next_catch = n_array[o->u.catch.next_catch->region_number];
878       if (o->u.catch.prev_catch)
879         n->u.catch.prev_catch = n_array[o->u.catch.prev_catch->region_number];
880       break;
881
882     case ERT_CLEANUP:
883       if (o->u.cleanup.prev_try)
884         n->u.cleanup.prev_try = n_array[o->u.cleanup.prev_try->region_number];
885       else
886         n->u.cleanup.prev_try = prev_try;
887       break;
888       
889     default:
890       break;
891     }
892   
893   if (o->outer)
894     n->outer = n_array[o->outer->region_number];
895   if (o->inner)
896     n->inner = n_array[o->inner->region_number];
897   if (o->next_peer)
898     n->next_peer = n_array[o->next_peer->region_number];
899 }
900
901 /* Duplicate the EH regions of IFUN into current function, root the tree in
902    OUTER_REGION and remap labels using MAP callback.  */
903 int
904 duplicate_eh_regions (struct function *ifun, duplicate_eh_regions_map map,
905                       void *data, int outer_region)
906 {
907   int ifun_last_region_number = ifun->eh->last_region_number;
908   struct eh_region **n_array, *root, *cur, *prev_try;
909   int i;
910   
911   if (ifun_last_region_number == 0 || !ifun->eh->region_tree)
912     return 0;
913   
914   n_array = xcalloc (ifun_last_region_number + 1, sizeof (*n_array));
915   
916   /* Search for the containing ERT_TRY region to fix up
917      the prev_try short-cuts for ERT_CLEANUP regions.  */
918   prev_try = NULL;
919   if (outer_region > 0)
920     for (prev_try = cfun->eh->region_array[outer_region];
921          prev_try && prev_try->type != ERT_TRY;
922          prev_try = prev_try->outer)
923       ;
924
925   for (i = 1; i <= ifun_last_region_number; ++i)
926     {
927       cur = ifun->eh->region_array[i];
928       if (!cur || cur->region_number != i)
929         continue;
930       n_array[i] = duplicate_eh_region_1 (cur);
931       if (cur->tree_label)
932         {
933           tree newlabel = map (cur->tree_label, data);
934           n_array[i]->tree_label = newlabel;
935         }
936       else
937         n_array[i]->tree_label = NULL;
938     }
939   for (i = 1; i <= ifun_last_region_number; ++i)
940     {
941       cur = ifun->eh->region_array[i];
942       if (!cur || cur->region_number != i)
943         continue;
944       duplicate_eh_region_2 (cur, n_array, prev_try);
945     }
946   
947   root = n_array[ifun->eh->region_tree->region_number];
948   gcc_assert (root->outer == NULL);
949   if (outer_region > 0)
950     {
951       struct eh_region *cur = cfun->eh->region_array[outer_region];
952       struct eh_region *p = cur->inner;
953
954       if (p)
955         {
956           while (p->next_peer)
957             p = p->next_peer;
958           p->next_peer = root;
959         }
960       else
961         cur->inner = root;
962       for (i = 1; i <= ifun_last_region_number; ++i)
963         if (n_array[i] && n_array[i]->outer == NULL)
964           n_array[i]->outer = cur;
965     }
966   else
967     {
968       struct eh_region *p = cfun->eh->region_tree;
969       if (p)
970         {
971           while (p->next_peer)
972             p = p->next_peer;
973           p->next_peer = root;
974         }
975       else
976         cfun->eh->region_tree = root;
977     }
978   
979   free (n_array);
980   
981   i = cfun->eh->last_region_number;
982   cfun->eh->last_region_number = i + ifun_last_region_number;
983   
984   collect_eh_region_array ();
985   
986   return i;
987 }
988 \f
989 static int
990 t2r_eq (const void *pentry, const void *pdata)
991 {
992   tree entry = (tree) pentry;
993   tree data = (tree) pdata;
994
995   return TREE_PURPOSE (entry) == data;
996 }
997
998 static hashval_t
999 t2r_hash (const void *pentry)
1000 {
1001   tree entry = (tree) pentry;
1002   return TREE_HASH (TREE_PURPOSE (entry));
1003 }
1004
1005 static void
1006 add_type_for_runtime (tree type)
1007 {
1008   tree *slot;
1009
1010   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1011                                             TREE_HASH (type), INSERT);
1012   if (*slot == NULL)
1013     {
1014       tree runtime = (*lang_eh_runtime_type) (type);
1015       *slot = tree_cons (type, runtime, NULL_TREE);
1016     }
1017 }
1018
1019 static tree
1020 lookup_type_for_runtime (tree type)
1021 {
1022   tree *slot;
1023
1024   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1025                                             TREE_HASH (type), NO_INSERT);
1026
1027   /* We should have always inserted the data earlier.  */
1028   return TREE_VALUE (*slot);
1029 }
1030
1031 \f
1032 /* Represent an entry in @TTypes for either catch actions
1033    or exception filter actions.  */
1034 struct ttypes_filter GTY(())
1035 {
1036   tree t;
1037   int filter;
1038 };
1039
1040 /* Compare ENTRY (a ttypes_filter entry in the hash table) with DATA
1041    (a tree) for a @TTypes type node we are thinking about adding.  */
1042
1043 static int
1044 ttypes_filter_eq (const void *pentry, const void *pdata)
1045 {
1046   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1047   tree data = (tree) pdata;
1048
1049   return entry->t == data;
1050 }
1051
1052 static hashval_t
1053 ttypes_filter_hash (const void *pentry)
1054 {
1055   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1056   return TREE_HASH (entry->t);
1057 }
1058
1059 /* Compare ENTRY with DATA (both struct ttypes_filter) for a @TTypes
1060    exception specification list we are thinking about adding.  */
1061 /* ??? Currently we use the type lists in the order given.  Someone
1062    should put these in some canonical order.  */
1063
1064 static int
1065 ehspec_filter_eq (const void *pentry, const void *pdata)
1066 {
1067   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1068   const struct ttypes_filter *data = (const struct ttypes_filter *) pdata;
1069
1070   return type_list_equal (entry->t, data->t);
1071 }
1072
1073 /* Hash function for exception specification lists.  */
1074
1075 static hashval_t
1076 ehspec_filter_hash (const void *pentry)
1077 {
1078   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1079   hashval_t h = 0;
1080   tree list;
1081
1082   for (list = entry->t; list ; list = TREE_CHAIN (list))
1083     h = (h << 5) + (h >> 27) + TREE_HASH (TREE_VALUE (list));
1084   return h;
1085 }
1086
1087 /* Add TYPE (which may be NULL) to cfun->eh->ttype_data, using TYPES_HASH
1088    to speed up the search.  Return the filter value to be used.  */
1089
1090 static int
1091 add_ttypes_entry (htab_t ttypes_hash, tree type)
1092 {
1093   struct ttypes_filter **slot, *n;
1094
1095   slot = (struct ttypes_filter **)
1096     htab_find_slot_with_hash (ttypes_hash, type, TREE_HASH (type), INSERT);
1097
1098   if ((n = *slot) == NULL)
1099     {
1100       /* Filter value is a 1 based table index.  */
1101
1102       n = xmalloc (sizeof (*n));
1103       n->t = type;
1104       n->filter = VEC_length (tree, cfun->eh->ttype_data) + 1;
1105       *slot = n;
1106
1107       VEC_safe_push (tree, gc, cfun->eh->ttype_data, type);
1108     }
1109
1110   return n->filter;
1111 }
1112
1113 /* Add LIST to cfun->eh->ehspec_data, using EHSPEC_HASH and TYPES_HASH
1114    to speed up the search.  Return the filter value to be used.  */
1115
1116 static int
1117 add_ehspec_entry (htab_t ehspec_hash, htab_t ttypes_hash, tree list)
1118 {
1119   struct ttypes_filter **slot, *n;
1120   struct ttypes_filter dummy;
1121
1122   dummy.t = list;
1123   slot = (struct ttypes_filter **)
1124     htab_find_slot (ehspec_hash, &dummy, INSERT);
1125
1126   if ((n = *slot) == NULL)
1127     {
1128       /* Filter value is a -1 based byte index into a uleb128 buffer.  */
1129
1130       n = xmalloc (sizeof (*n));
1131       n->t = list;
1132       n->filter = -(VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) + 1);
1133       *slot = n;
1134
1135       /* Look up each type in the list and encode its filter
1136          value as a uleb128.  Terminate the list with 0.  */
1137       for (; list ; list = TREE_CHAIN (list))
1138         push_uleb128 (&cfun->eh->ehspec_data,
1139                       add_ttypes_entry (ttypes_hash, TREE_VALUE (list)));
1140       VARRAY_PUSH_UCHAR (cfun->eh->ehspec_data, 0);
1141     }
1142
1143   return n->filter;
1144 }
1145
1146 /* Generate the action filter values to be used for CATCH and
1147    ALLOWED_EXCEPTIONS regions.  When using dwarf2 exception regions,
1148    we use lots of landing pads, and so every type or list can share
1149    the same filter value, which saves table space.  */
1150
1151 static void
1152 assign_filter_values (void)
1153 {
1154   int i;
1155   htab_t ttypes, ehspec;
1156
1157   cfun->eh->ttype_data = VEC_alloc (tree, gc, 16);
1158   VARRAY_UCHAR_INIT (cfun->eh->ehspec_data, 64, "ehspec_data");
1159
1160   ttypes = htab_create (31, ttypes_filter_hash, ttypes_filter_eq, free);
1161   ehspec = htab_create (31, ehspec_filter_hash, ehspec_filter_eq, free);
1162
1163   for (i = cfun->eh->last_region_number; i > 0; --i)
1164     {
1165       struct eh_region *r = cfun->eh->region_array[i];
1166
1167       /* Mind we don't process a region more than once.  */
1168       if (!r || r->region_number != i)
1169         continue;
1170
1171       switch (r->type)
1172         {
1173         case ERT_CATCH:
1174           /* Whatever type_list is (NULL or true list), we build a list
1175              of filters for the region.  */
1176           r->u.catch.filter_list = NULL_TREE;
1177
1178           if (r->u.catch.type_list != NULL)
1179             {
1180               /* Get a filter value for each of the types caught and store
1181                  them in the region's dedicated list.  */
1182               tree tp_node = r->u.catch.type_list;
1183
1184               for (;tp_node; tp_node = TREE_CHAIN (tp_node))
1185                 {
1186                   int flt = add_ttypes_entry (ttypes, TREE_VALUE (tp_node));
1187                   tree flt_node = build_int_cst (NULL_TREE, flt);
1188
1189                   r->u.catch.filter_list
1190                     = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1191                 }
1192             }
1193           else
1194             {
1195               /* Get a filter value for the NULL list also since it will need
1196                  an action record anyway.  */
1197               int flt = add_ttypes_entry (ttypes, NULL);
1198               tree flt_node = build_int_cst (NULL_TREE, flt);
1199
1200               r->u.catch.filter_list
1201                 = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1202             }
1203
1204           break;
1205
1206         case ERT_ALLOWED_EXCEPTIONS:
1207           r->u.allowed.filter
1208             = add_ehspec_entry (ehspec, ttypes, r->u.allowed.type_list);
1209           break;
1210
1211         default:
1212           break;
1213         }
1214     }
1215
1216   htab_delete (ttypes);
1217   htab_delete (ehspec);
1218 }
1219
1220 /* Emit SEQ into basic block just before INSN (that is assumed to be
1221    first instruction of some existing BB and return the newly
1222    produced block.  */
1223 static basic_block
1224 emit_to_new_bb_before (rtx seq, rtx insn)
1225 {
1226   rtx last;
1227   basic_block bb;
1228   edge e;
1229   edge_iterator ei;
1230
1231   /* If there happens to be a fallthru edge (possibly created by cleanup_cfg
1232      call), we don't want it to go into newly created landing pad or other EH 
1233      construct.  */
1234   for (ei = ei_start (BLOCK_FOR_INSN (insn)->preds); (e = ei_safe_edge (ei)); )
1235     if (e->flags & EDGE_FALLTHRU)
1236       force_nonfallthru (e);
1237     else
1238       ei_next (&ei);
1239   last = emit_insn_before (seq, insn);
1240   if (BARRIER_P (last))
1241     last = PREV_INSN (last);
1242   bb = create_basic_block (seq, last, BLOCK_FOR_INSN (insn)->prev_bb);
1243   update_bb_for_insn (bb);
1244   bb->flags |= BB_SUPERBLOCK;
1245   return bb;
1246 }
1247
1248 /* Generate the code to actually handle exceptions, which will follow the
1249    landing pads.  */
1250
1251 static void
1252 build_post_landing_pads (void)
1253 {
1254   int i;
1255
1256   for (i = cfun->eh->last_region_number; i > 0; --i)
1257     {
1258       struct eh_region *region = cfun->eh->region_array[i];
1259       rtx seq;
1260
1261       /* Mind we don't process a region more than once.  */
1262       if (!region || region->region_number != i)
1263         continue;
1264
1265       switch (region->type)
1266         {
1267         case ERT_TRY:
1268           /* ??? Collect the set of all non-overlapping catch handlers
1269                all the way up the chain until blocked by a cleanup.  */
1270           /* ??? Outer try regions can share landing pads with inner
1271              try regions if the types are completely non-overlapping,
1272              and there are no intervening cleanups.  */
1273
1274           region->post_landing_pad = gen_label_rtx ();
1275
1276           start_sequence ();
1277
1278           emit_label (region->post_landing_pad);
1279
1280           /* ??? It is mighty inconvenient to call back into the
1281              switch statement generation code in expand_end_case.
1282              Rapid prototyping sez a sequence of ifs.  */
1283           {
1284             struct eh_region *c;
1285             for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
1286               {
1287                 if (c->u.catch.type_list == NULL)
1288                   emit_jump (c->label);
1289                 else
1290                   {
1291                     /* Need for one cmp/jump per type caught. Each type
1292                        list entry has a matching entry in the filter list
1293                        (see assign_filter_values).  */
1294                     tree tp_node = c->u.catch.type_list;
1295                     tree flt_node = c->u.catch.filter_list;
1296
1297                     for (; tp_node; )
1298                       {
1299                         emit_cmp_and_jump_insns
1300                           (cfun->eh->filter,
1301                            GEN_INT (tree_low_cst (TREE_VALUE (flt_node), 0)),
1302                            EQ, NULL_RTX, 
1303                            targetm.eh_return_filter_mode (), 0, c->label);
1304
1305                         tp_node = TREE_CHAIN (tp_node);
1306                         flt_node = TREE_CHAIN (flt_node);
1307                       }
1308                   }
1309               }
1310           }
1311
1312           /* We delay the generation of the _Unwind_Resume until we generate
1313              landing pads.  We emit a marker here so as to get good control
1314              flow data in the meantime.  */
1315           region->resume
1316             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1317           emit_barrier ();
1318
1319           seq = get_insns ();
1320           end_sequence ();
1321
1322           emit_to_new_bb_before (seq, region->u.try.catch->label);
1323
1324           break;
1325
1326         case ERT_ALLOWED_EXCEPTIONS:
1327           region->post_landing_pad = gen_label_rtx ();
1328
1329           start_sequence ();
1330
1331           emit_label (region->post_landing_pad);
1332
1333           emit_cmp_and_jump_insns (cfun->eh->filter,
1334                                    GEN_INT (region->u.allowed.filter),
1335                                    EQ, NULL_RTX, 
1336                                    targetm.eh_return_filter_mode (), 0, region->label);
1337
1338           /* We delay the generation of the _Unwind_Resume until we generate
1339              landing pads.  We emit a marker here so as to get good control
1340              flow data in the meantime.  */
1341           region->resume
1342             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1343           emit_barrier ();
1344
1345           seq = get_insns ();
1346           end_sequence ();
1347
1348           emit_to_new_bb_before (seq, region->label);
1349           break;
1350
1351         case ERT_CLEANUP:
1352         case ERT_MUST_NOT_THROW:
1353           region->post_landing_pad = region->label;
1354           break;
1355
1356         case ERT_CATCH:
1357         case ERT_THROW:
1358           /* Nothing to do.  */
1359           break;
1360
1361         default:
1362           gcc_unreachable ();
1363         }
1364     }
1365 }
1366
1367 /* Replace RESX patterns with jumps to the next handler if any, or calls to
1368    _Unwind_Resume otherwise.  */
1369
1370 static void
1371 connect_post_landing_pads (void)
1372 {
1373   int i;
1374
1375   for (i = cfun->eh->last_region_number; i > 0; --i)
1376     {
1377       struct eh_region *region = cfun->eh->region_array[i];
1378       struct eh_region *outer;
1379       rtx seq;
1380       rtx barrier;
1381
1382       /* Mind we don't process a region more than once.  */
1383       if (!region || region->region_number != i)
1384         continue;
1385
1386       /* If there is no RESX, or it has been deleted by flow, there's
1387          nothing to fix up.  */
1388       if (! region->resume || INSN_DELETED_P (region->resume))
1389         continue;
1390
1391       /* Search for another landing pad in this function.  */
1392       for (outer = region->outer; outer ; outer = outer->outer)
1393         if (outer->post_landing_pad)
1394           break;
1395
1396       start_sequence ();
1397
1398       if (outer)
1399         {
1400           edge e;
1401           basic_block src, dest;
1402
1403           emit_jump (outer->post_landing_pad);
1404           src = BLOCK_FOR_INSN (region->resume);
1405           dest = BLOCK_FOR_INSN (outer->post_landing_pad);
1406           while (EDGE_COUNT (src->succs) > 0)
1407             remove_edge (EDGE_SUCC (src, 0));
1408           e = make_edge (src, dest, 0);
1409           e->probability = REG_BR_PROB_BASE;
1410           e->count = src->count;
1411         }
1412       else
1413         {
1414           emit_library_call (unwind_resume_libfunc, LCT_THROW,
1415                              VOIDmode, 1, cfun->eh->exc_ptr, ptr_mode);
1416
1417           /* What we just emitted was a throwing libcall, so it got a
1418              barrier automatically added after it.  If the last insn in
1419              the libcall sequence isn't the barrier, it's because the
1420              target emits multiple insns for a call, and there are insns
1421              after the actual call insn (which are redundant and would be
1422              optimized away).  The barrier is inserted exactly after the
1423              call insn, so let's go get that and delete the insns after
1424              it, because below we need the barrier to be the last insn in
1425              the sequence.  */
1426           delete_insns_since (NEXT_INSN (last_call_insn ()));
1427         }
1428
1429       seq = get_insns ();
1430       end_sequence ();
1431       barrier = emit_insn_before (seq, region->resume);
1432       /* Avoid duplicate barrier.  */
1433       gcc_assert (BARRIER_P (barrier));
1434       delete_insn (barrier);
1435       delete_insn (region->resume);
1436
1437       /* ??? From tree-ssa we can wind up with catch regions whose
1438          label is not instantiated, but whose resx is present.  Now
1439          that we've dealt with the resx, kill the region.  */
1440       if (region->label == NULL && region->type == ERT_CLEANUP)
1441         remove_eh_handler (region);
1442     }
1443 }
1444
1445 \f
1446 static void
1447 dw2_build_landing_pads (void)
1448 {
1449   int i;
1450   unsigned int j;
1451
1452   for (i = cfun->eh->last_region_number; i > 0; --i)
1453     {
1454       struct eh_region *region = cfun->eh->region_array[i];
1455       rtx seq;
1456       basic_block bb;
1457       bool clobbers_hard_regs = false;
1458       edge e;
1459
1460       /* Mind we don't process a region more than once.  */
1461       if (!region || region->region_number != i)
1462         continue;
1463
1464       if (region->type != ERT_CLEANUP
1465           && region->type != ERT_TRY
1466           && region->type != ERT_ALLOWED_EXCEPTIONS)
1467         continue;
1468
1469       start_sequence ();
1470
1471       region->landing_pad = gen_label_rtx ();
1472       emit_label (region->landing_pad);
1473
1474 #ifdef HAVE_exception_receiver
1475       if (HAVE_exception_receiver)
1476         emit_insn (gen_exception_receiver ());
1477       else
1478 #endif
1479 #ifdef HAVE_nonlocal_goto_receiver
1480         if (HAVE_nonlocal_goto_receiver)
1481           emit_insn (gen_nonlocal_goto_receiver ());
1482         else
1483 #endif
1484           { /* Nothing */ }
1485
1486       /* If the eh_return data registers are call-saved, then we
1487          won't have considered them clobbered from the call that
1488          threw.  Kill them now.  */
1489       for (j = 0; ; ++j)
1490         {
1491           unsigned r = EH_RETURN_DATA_REGNO (j);
1492           if (r == INVALID_REGNUM)
1493             break;
1494           if (! call_used_regs[r])
1495             {
1496               emit_insn (gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, r)));
1497               clobbers_hard_regs = true;
1498             }
1499         }
1500
1501       if (clobbers_hard_regs)
1502         {
1503           /* @@@ This is a kludge.  Not all machine descriptions define a
1504              blockage insn, but we must not allow the code we just generated
1505              to be reordered by scheduling.  So emit an ASM_INPUT to act as
1506              blockage insn.  */
1507           emit_insn (gen_rtx_ASM_INPUT (VOIDmode, ""));
1508         }
1509
1510       emit_move_insn (cfun->eh->exc_ptr,
1511                       gen_rtx_REG (ptr_mode, EH_RETURN_DATA_REGNO (0)));
1512       emit_move_insn (cfun->eh->filter,
1513                       gen_rtx_REG (targetm.eh_return_filter_mode (), 
1514                                    EH_RETURN_DATA_REGNO (1)));
1515
1516       seq = get_insns ();
1517       end_sequence ();
1518
1519       bb = emit_to_new_bb_before (seq, region->post_landing_pad);
1520       e = make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
1521       e->count = bb->count;
1522       e->probability = REG_BR_PROB_BASE;
1523     }
1524 }
1525
1526 \f
1527 struct sjlj_lp_info
1528 {
1529   int directly_reachable;
1530   int action_index;
1531   int dispatch_index;
1532   int call_site_index;
1533 };
1534
1535 static bool
1536 sjlj_find_directly_reachable_regions (struct sjlj_lp_info *lp_info)
1537 {
1538   rtx insn;
1539   bool found_one = false;
1540
1541   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1542     {
1543       struct eh_region *region;
1544       enum reachable_code rc;
1545       tree type_thrown;
1546       rtx note;
1547
1548       if (! INSN_P (insn))
1549         continue;
1550
1551       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
1552       if (!note || INTVAL (XEXP (note, 0)) <= 0)
1553         continue;
1554
1555       region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
1556
1557       type_thrown = NULL_TREE;
1558       if (region->type == ERT_THROW)
1559         {
1560           type_thrown = region->u.throw.type;
1561           region = region->outer;
1562         }
1563
1564       /* Find the first containing region that might handle the exception.
1565          That's the landing pad to which we will transfer control.  */
1566       rc = RNL_NOT_CAUGHT;
1567       for (; region; region = region->outer)
1568         {
1569           rc = reachable_next_level (region, type_thrown, NULL);
1570           if (rc != RNL_NOT_CAUGHT)
1571             break;
1572         }
1573       if (rc == RNL_MAYBE_CAUGHT || rc == RNL_CAUGHT)
1574         {
1575           lp_info[region->region_number].directly_reachable = 1;
1576           found_one = true;
1577         }
1578     }
1579
1580   return found_one;
1581 }
1582
1583 static void
1584 sjlj_assign_call_site_values (rtx dispatch_label, struct sjlj_lp_info *lp_info)
1585 {
1586   htab_t ar_hash;
1587   int i, index;
1588
1589   /* First task: build the action table.  */
1590
1591   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
1592   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
1593
1594   for (i = cfun->eh->last_region_number; i > 0; --i)
1595     if (lp_info[i].directly_reachable)
1596       {
1597         struct eh_region *r = cfun->eh->region_array[i];
1598         r->landing_pad = dispatch_label;
1599         lp_info[i].action_index = collect_one_action_chain (ar_hash, r);
1600         if (lp_info[i].action_index != -1)
1601           cfun->uses_eh_lsda = 1;
1602       }
1603
1604   htab_delete (ar_hash);
1605
1606   /* Next: assign dispatch values.  In dwarf2 terms, this would be the
1607      landing pad label for the region.  For sjlj though, there is one
1608      common landing pad from which we dispatch to the post-landing pads.
1609
1610      A region receives a dispatch index if it is directly reachable
1611      and requires in-function processing.  Regions that share post-landing
1612      pads may share dispatch indices.  */
1613   /* ??? Post-landing pad sharing doesn't actually happen at the moment
1614      (see build_post_landing_pads) so we don't bother checking for it.  */
1615
1616   index = 0;
1617   for (i = cfun->eh->last_region_number; i > 0; --i)
1618     if (lp_info[i].directly_reachable)
1619       lp_info[i].dispatch_index = index++;
1620
1621   /* Finally: assign call-site values.  If dwarf2 terms, this would be
1622      the region number assigned by convert_to_eh_region_ranges, but
1623      handles no-action and must-not-throw differently.  */
1624
1625   call_site_base = 1;
1626   for (i = cfun->eh->last_region_number; i > 0; --i)
1627     if (lp_info[i].directly_reachable)
1628       {
1629         int action = lp_info[i].action_index;
1630
1631         /* Map must-not-throw to otherwise unused call-site index 0.  */
1632         if (action == -2)
1633           index = 0;
1634         /* Map no-action to otherwise unused call-site index -1.  */
1635         else if (action == -1)
1636           index = -1;
1637         /* Otherwise, look it up in the table.  */
1638         else
1639           index = add_call_site (GEN_INT (lp_info[i].dispatch_index), action);
1640
1641         lp_info[i].call_site_index = index;
1642       }
1643 }
1644
1645 static void
1646 sjlj_mark_call_sites (struct sjlj_lp_info *lp_info)
1647 {
1648   int last_call_site = -2;
1649   rtx insn, mem;
1650
1651   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1652     {
1653       struct eh_region *region;
1654       int this_call_site;
1655       rtx note, before, p;
1656
1657       /* Reset value tracking at extended basic block boundaries.  */
1658       if (LABEL_P (insn))
1659         last_call_site = -2;
1660
1661       if (! INSN_P (insn))
1662         continue;
1663
1664       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
1665       if (!note)
1666         {
1667           /* Calls (and trapping insns) without notes are outside any
1668              exception handling region in this function.  Mark them as
1669              no action.  */
1670           if (CALL_P (insn)
1671               || (flag_non_call_exceptions
1672                   && may_trap_p (PATTERN (insn))))
1673             this_call_site = -1;
1674           else
1675             continue;
1676         }
1677       else
1678         {
1679           /* Calls that are known to not throw need not be marked.  */
1680           if (INTVAL (XEXP (note, 0)) <= 0)
1681             continue;
1682
1683           region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
1684           this_call_site = lp_info[region->region_number].call_site_index;
1685         }
1686
1687       if (this_call_site == last_call_site)
1688         continue;
1689
1690       /* Don't separate a call from it's argument loads.  */
1691       before = insn;
1692       if (CALL_P (insn))
1693         before = find_first_parameter_load (insn, NULL_RTX);
1694
1695       start_sequence ();
1696       mem = adjust_address (cfun->eh->sjlj_fc, TYPE_MODE (integer_type_node),
1697                             sjlj_fc_call_site_ofs);
1698       emit_move_insn (mem, GEN_INT (this_call_site));
1699       p = get_insns ();
1700       end_sequence ();
1701
1702       emit_insn_before (p, before);
1703       last_call_site = this_call_site;
1704     }
1705 }
1706
1707 /* Construct the SjLj_Function_Context.  */
1708
1709 static void
1710 sjlj_emit_function_enter (rtx dispatch_label)
1711 {
1712   rtx fn_begin, fc, mem, seq;
1713
1714   fc = cfun->eh->sjlj_fc;
1715
1716   start_sequence ();
1717
1718   /* We're storing this libcall's address into memory instead of
1719      calling it directly.  Thus, we must call assemble_external_libcall
1720      here, as we can not depend on emit_library_call to do it for us.  */
1721   assemble_external_libcall (eh_personality_libfunc);
1722   mem = adjust_address (fc, Pmode, sjlj_fc_personality_ofs);
1723   emit_move_insn (mem, eh_personality_libfunc);
1724
1725   mem = adjust_address (fc, Pmode, sjlj_fc_lsda_ofs);
1726   if (cfun->uses_eh_lsda)
1727     {
1728       char buf[20];
1729       rtx sym;
1730
1731       ASM_GENERATE_INTERNAL_LABEL (buf, "LLSDA", current_function_funcdef_no);
1732       sym = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
1733       SYMBOL_REF_FLAGS (sym) = SYMBOL_FLAG_LOCAL;
1734       emit_move_insn (mem, sym);
1735     }
1736   else
1737     emit_move_insn (mem, const0_rtx);
1738
1739 #ifdef DONT_USE_BUILTIN_SETJMP
1740   {
1741     rtx x, note;
1742     x = emit_library_call_value (setjmp_libfunc, NULL_RTX, LCT_RETURNS_TWICE,
1743                                  TYPE_MODE (integer_type_node), 1,
1744                                  plus_constant (XEXP (fc, 0),
1745                                                 sjlj_fc_jbuf_ofs), Pmode);
1746
1747     note = emit_note (NOTE_INSN_EXPECTED_VALUE);
1748     NOTE_EXPECTED_VALUE (note) = gen_rtx_EQ (VOIDmode, x, const0_rtx);
1749
1750     emit_cmp_and_jump_insns (x, const0_rtx, NE, 0,
1751                              TYPE_MODE (integer_type_node), 0, dispatch_label);
1752   }
1753 #else
1754   expand_builtin_setjmp_setup (plus_constant (XEXP (fc, 0), sjlj_fc_jbuf_ofs),
1755                                dispatch_label);
1756 #endif
1757
1758   emit_library_call (unwind_sjlj_register_libfunc, LCT_NORMAL, VOIDmode,
1759                      1, XEXP (fc, 0), Pmode);
1760
1761   seq = get_insns ();
1762   end_sequence ();
1763
1764   /* ??? Instead of doing this at the beginning of the function,
1765      do this in a block that is at loop level 0 and dominates all
1766      can_throw_internal instructions.  */
1767
1768   for (fn_begin = get_insns (); ; fn_begin = NEXT_INSN (fn_begin))
1769     if (NOTE_P (fn_begin)
1770         && (NOTE_LINE_NUMBER (fn_begin) == NOTE_INSN_FUNCTION_BEG
1771             || NOTE_LINE_NUMBER (fn_begin) == NOTE_INSN_BASIC_BLOCK))
1772       break;
1773   if (NOTE_LINE_NUMBER (fn_begin) == NOTE_INSN_FUNCTION_BEG)
1774     insert_insn_on_edge (seq, single_succ_edge (ENTRY_BLOCK_PTR));
1775   else
1776     {
1777       rtx last = BB_END (single_succ (ENTRY_BLOCK_PTR));
1778       for (; ; fn_begin = NEXT_INSN (fn_begin))
1779         if ((NOTE_P (fn_begin)
1780              && NOTE_LINE_NUMBER (fn_begin) == NOTE_INSN_FUNCTION_BEG)
1781             || fn_begin == last)
1782           break;
1783       emit_insn_after (seq, fn_begin);
1784     }
1785 }
1786
1787 /* Call back from expand_function_end to know where we should put
1788    the call to unwind_sjlj_unregister_libfunc if needed.  */
1789
1790 void
1791 sjlj_emit_function_exit_after (rtx after)
1792 {
1793   cfun->eh->sjlj_exit_after = after;
1794 }
1795
1796 static void
1797 sjlj_emit_function_exit (void)
1798 {
1799   rtx seq;
1800   edge e;
1801   edge_iterator ei;
1802
1803   start_sequence ();
1804
1805   emit_library_call (unwind_sjlj_unregister_libfunc, LCT_NORMAL, VOIDmode,
1806                      1, XEXP (cfun->eh->sjlj_fc, 0), Pmode);
1807
1808   seq = get_insns ();
1809   end_sequence ();
1810
1811   /* ??? Really this can be done in any block at loop level 0 that
1812      post-dominates all can_throw_internal instructions.  This is
1813      the last possible moment.  */
1814
1815   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1816     if (e->flags & EDGE_FALLTHRU)
1817       break;
1818   if (e)
1819     {
1820       rtx insn;
1821
1822       /* Figure out whether the place we are supposed to insert libcall
1823          is inside the last basic block or after it.  In the other case
1824          we need to emit to edge.  */
1825       gcc_assert (e->src->next_bb == EXIT_BLOCK_PTR);
1826       for (insn = BB_HEAD (e->src); ; insn = NEXT_INSN (insn))
1827         {
1828           if (insn == cfun->eh->sjlj_exit_after)
1829             {
1830               if (LABEL_P (insn))
1831                 insn = NEXT_INSN (insn);
1832               emit_insn_after (seq, insn);
1833               return;
1834             }
1835           if (insn == BB_END (e->src))
1836             break;
1837         }
1838       insert_insn_on_edge (seq, e);
1839     }
1840 }
1841
1842 static void
1843 sjlj_emit_dispatch_table (rtx dispatch_label, struct sjlj_lp_info *lp_info)
1844 {
1845   int i, first_reachable;
1846   rtx mem, dispatch, seq, fc;
1847   rtx before;
1848   basic_block bb;
1849   edge e;
1850
1851   fc = cfun->eh->sjlj_fc;
1852
1853   start_sequence ();
1854
1855   emit_label (dispatch_label);
1856
1857 #ifndef DONT_USE_BUILTIN_SETJMP
1858   expand_builtin_setjmp_receiver (dispatch_label);
1859 #endif
1860
1861   /* Load up dispatch index, exc_ptr and filter values from the
1862      function context.  */
1863   mem = adjust_address (fc, TYPE_MODE (integer_type_node),
1864                         sjlj_fc_call_site_ofs);
1865   dispatch = copy_to_reg (mem);
1866
1867   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs);
1868   if (word_mode != ptr_mode)
1869     {
1870 #ifdef POINTERS_EXTEND_UNSIGNED
1871       mem = convert_memory_address (ptr_mode, mem);
1872 #else
1873       mem = convert_to_mode (ptr_mode, mem, 0);
1874 #endif
1875     }
1876   emit_move_insn (cfun->eh->exc_ptr, mem);
1877
1878   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs + UNITS_PER_WORD);
1879   emit_move_insn (cfun->eh->filter, mem);
1880
1881   /* Jump to one of the directly reachable regions.  */
1882   /* ??? This really ought to be using a switch statement.  */
1883
1884   first_reachable = 0;
1885   for (i = cfun->eh->last_region_number; i > 0; --i)
1886     {
1887       if (! lp_info[i].directly_reachable)
1888         continue;
1889
1890       if (! first_reachable)
1891         {
1892           first_reachable = i;
1893           continue;
1894         }
1895
1896       emit_cmp_and_jump_insns (dispatch, GEN_INT (lp_info[i].dispatch_index),
1897                                EQ, NULL_RTX, TYPE_MODE (integer_type_node), 0,
1898                                cfun->eh->region_array[i]->post_landing_pad);
1899     }
1900
1901   seq = get_insns ();
1902   end_sequence ();
1903
1904   before = cfun->eh->region_array[first_reachable]->post_landing_pad;
1905
1906   bb = emit_to_new_bb_before (seq, before);
1907   e = make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
1908   e->count = bb->count;
1909   e->probability = REG_BR_PROB_BASE;
1910 }
1911
1912 static void
1913 sjlj_build_landing_pads (void)
1914 {
1915   struct sjlj_lp_info *lp_info;
1916
1917   lp_info = xcalloc (cfun->eh->last_region_number + 1,
1918                      sizeof (struct sjlj_lp_info));
1919
1920   if (sjlj_find_directly_reachable_regions (lp_info))
1921     {
1922       rtx dispatch_label = gen_label_rtx ();
1923
1924       cfun->eh->sjlj_fc
1925         = assign_stack_local (TYPE_MODE (sjlj_fc_type_node),
1926                               int_size_in_bytes (sjlj_fc_type_node),
1927                               TYPE_ALIGN (sjlj_fc_type_node));
1928
1929       sjlj_assign_call_site_values (dispatch_label, lp_info);
1930       sjlj_mark_call_sites (lp_info);
1931
1932       sjlj_emit_function_enter (dispatch_label);
1933       sjlj_emit_dispatch_table (dispatch_label, lp_info);
1934       sjlj_emit_function_exit ();
1935     }
1936
1937   free (lp_info);
1938 }
1939
1940 void
1941 finish_eh_generation (void)
1942 {
1943   basic_block bb;
1944
1945   /* Nothing to do if no regions created.  */
1946   if (cfun->eh->region_tree == NULL)
1947     return;
1948
1949   /* The object here is to provide find_basic_blocks with detailed
1950      information (via reachable_handlers) on how exception control
1951      flows within the function.  In this first pass, we can include
1952      type information garnered from ERT_THROW and ERT_ALLOWED_EXCEPTIONS
1953      regions, and hope that it will be useful in deleting unreachable
1954      handlers.  Subsequently, we will generate landing pads which will
1955      connect many of the handlers, and then type information will not
1956      be effective.  Still, this is a win over previous implementations.  */
1957
1958   /* These registers are used by the landing pads.  Make sure they
1959      have been generated.  */
1960   get_exception_pointer (cfun);
1961   get_exception_filter (cfun);
1962
1963   /* Construct the landing pads.  */
1964
1965   assign_filter_values ();
1966   build_post_landing_pads ();
1967   connect_post_landing_pads ();
1968   if (USING_SJLJ_EXCEPTIONS)
1969     sjlj_build_landing_pads ();
1970   else
1971     dw2_build_landing_pads ();
1972
1973   cfun->eh->built_landing_pads = 1;
1974
1975   /* We've totally changed the CFG.  Start over.  */
1976   find_exception_handler_labels ();
1977   break_superblocks ();
1978   if (USING_SJLJ_EXCEPTIONS)
1979     commit_edge_insertions ();
1980   FOR_EACH_BB (bb)
1981     {
1982       edge e;
1983       edge_iterator ei;
1984       bool eh = false;
1985       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
1986         {
1987           if (e->flags & EDGE_EH)
1988             {
1989               remove_edge (e);
1990               eh = true;
1991             }
1992           else
1993             ei_next (&ei);
1994         }
1995       if (eh)
1996         rtl_make_eh_edge (NULL, bb, BB_END (bb));
1997     }
1998 }
1999 \f
2000 static hashval_t
2001 ehl_hash (const void *pentry)
2002 {
2003   struct ehl_map_entry *entry = (struct ehl_map_entry *) pentry;
2004
2005   /* 2^32 * ((sqrt(5) - 1) / 2) */
2006   const hashval_t scaled_golden_ratio = 0x9e3779b9;
2007   return CODE_LABEL_NUMBER (entry->label) * scaled_golden_ratio;
2008 }
2009
2010 static int
2011 ehl_eq (const void *pentry, const void *pdata)
2012 {
2013   struct ehl_map_entry *entry = (struct ehl_map_entry *) pentry;
2014   struct ehl_map_entry *data = (struct ehl_map_entry *) pdata;
2015
2016   return entry->label == data->label;
2017 }
2018
2019 /* This section handles removing dead code for flow.  */
2020
2021 /* Remove LABEL from exception_handler_label_map.  */
2022
2023 static void
2024 remove_exception_handler_label (rtx label)
2025 {
2026   struct ehl_map_entry **slot, tmp;
2027
2028   /* If exception_handler_label_map was not built yet,
2029      there is nothing to do.  */
2030   if (cfun->eh->exception_handler_label_map == NULL)
2031     return;
2032
2033   tmp.label = label;
2034   slot = (struct ehl_map_entry **)
2035     htab_find_slot (cfun->eh->exception_handler_label_map, &tmp, NO_INSERT);
2036   gcc_assert (slot);
2037
2038   htab_clear_slot (cfun->eh->exception_handler_label_map, (void **) slot);
2039 }
2040
2041 /* Splice REGION from the region tree etc.  */
2042
2043 static void
2044 remove_eh_handler (struct eh_region *region)
2045 {
2046   struct eh_region **pp, **pp_start, *p, *outer, *inner;
2047   rtx lab;
2048
2049   /* For the benefit of efficiently handling REG_EH_REGION notes,
2050      replace this region in the region array with its containing
2051      region.  Note that previous region deletions may result in
2052      multiple copies of this region in the array, so we have a
2053      list of alternate numbers by which we are known.  */
2054
2055   outer = region->outer;
2056   cfun->eh->region_array[region->region_number] = outer;
2057   if (region->aka)
2058     {
2059       unsigned i;
2060       bitmap_iterator bi;
2061
2062       EXECUTE_IF_SET_IN_BITMAP (region->aka, 0, i, bi)
2063         {
2064           cfun->eh->region_array[i] = outer;
2065         }
2066     }
2067
2068   if (outer)
2069     {
2070       if (!outer->aka)
2071         outer->aka = BITMAP_GGC_ALLOC ();
2072       if (region->aka)
2073         bitmap_ior_into (outer->aka, region->aka);
2074       bitmap_set_bit (outer->aka, region->region_number);
2075     }
2076
2077   if (cfun->eh->built_landing_pads)
2078     lab = region->landing_pad;
2079   else
2080     lab = region->label;
2081   if (lab)
2082     remove_exception_handler_label (lab);
2083
2084   if (outer)
2085     pp_start = &outer->inner;
2086   else
2087     pp_start = &cfun->eh->region_tree;
2088   for (pp = pp_start, p = *pp; p != region; pp = &p->next_peer, p = *pp)
2089     continue;
2090   *pp = region->next_peer;
2091
2092   inner = region->inner;
2093   if (inner)
2094     {
2095       for (p = inner; p->next_peer ; p = p->next_peer)
2096         p->outer = outer;
2097       p->outer = outer;
2098
2099       p->next_peer = *pp_start;
2100       *pp_start = inner;
2101     }
2102
2103   if (region->type == ERT_CATCH)
2104     {
2105       struct eh_region *try, *next, *prev;
2106
2107       for (try = region->next_peer;
2108            try->type == ERT_CATCH;
2109            try = try->next_peer)
2110         continue;
2111       gcc_assert (try->type == ERT_TRY);
2112
2113       next = region->u.catch.next_catch;
2114       prev = region->u.catch.prev_catch;
2115
2116       if (next)
2117         next->u.catch.prev_catch = prev;
2118       else
2119         try->u.try.last_catch = prev;
2120       if (prev)
2121         prev->u.catch.next_catch = next;
2122       else
2123         {
2124           try->u.try.catch = next;
2125           if (! next)
2126             remove_eh_handler (try);
2127         }
2128     }
2129 }
2130
2131 /* LABEL heads a basic block that is about to be deleted.  If this
2132    label corresponds to an exception region, we may be able to
2133    delete the region.  */
2134
2135 void
2136 maybe_remove_eh_handler (rtx label)
2137 {
2138   struct ehl_map_entry **slot, tmp;
2139   struct eh_region *region;
2140
2141   /* ??? After generating landing pads, it's not so simple to determine
2142      if the region data is completely unused.  One must examine the
2143      landing pad and the post landing pad, and whether an inner try block
2144      is referencing the catch handlers directly.  */
2145   if (cfun->eh->built_landing_pads)
2146     return;
2147
2148   tmp.label = label;
2149   slot = (struct ehl_map_entry **)
2150     htab_find_slot (cfun->eh->exception_handler_label_map, &tmp, NO_INSERT);
2151   if (! slot)
2152     return;
2153   region = (*slot)->region;
2154   if (! region)
2155     return;
2156
2157   /* Flow will want to remove MUST_NOT_THROW regions as unreachable
2158      because there is no path to the fallback call to terminate.
2159      But the region continues to affect call-site data until there
2160      are no more contained calls, which we don't see here.  */
2161   if (region->type == ERT_MUST_NOT_THROW)
2162     {
2163       htab_clear_slot (cfun->eh->exception_handler_label_map, (void **) slot);
2164       region->label = NULL_RTX;
2165     }
2166   else
2167     remove_eh_handler (region);
2168 }
2169
2170 /* Invokes CALLBACK for every exception handler label.  Only used by old
2171    loop hackery; should not be used by new code.  */
2172
2173 void
2174 for_each_eh_label (void (*callback) (rtx))
2175 {
2176   htab_traverse (cfun->eh->exception_handler_label_map, for_each_eh_label_1,
2177                  (void *) &callback);
2178 }
2179
2180 static int
2181 for_each_eh_label_1 (void **pentry, void *data)
2182 {
2183   struct ehl_map_entry *entry = *(struct ehl_map_entry **)pentry;
2184   void (*callback) (rtx) = *(void (**) (rtx)) data;
2185
2186   (*callback) (entry->label);
2187   return 1;
2188 }
2189
2190 /* Invoke CALLBACK for every exception region in the current function.  */
2191
2192 void
2193 for_each_eh_region (void (*callback) (struct eh_region *))
2194 {
2195   int i, n = cfun->eh->last_region_number;
2196   for (i = 1; i <= n; ++i)
2197     {
2198       struct eh_region *region = cfun->eh->region_array[i];
2199       if (region)
2200         (*callback) (region);
2201     }
2202 }
2203 \f
2204 /* This section describes CFG exception edges for flow.  */
2205
2206 /* For communicating between calls to reachable_next_level.  */
2207 struct reachable_info
2208 {
2209   tree types_caught;
2210   tree types_allowed;
2211   void (*callback) (struct eh_region *, void *);
2212   void *callback_data;
2213   bool saw_any_handlers;
2214 };
2215
2216 /* A subroutine of reachable_next_level.  Return true if TYPE, or a
2217    base class of TYPE, is in HANDLED.  */
2218
2219 static int
2220 check_handled (tree handled, tree type)
2221 {
2222   tree t;
2223
2224   /* We can check for exact matches without front-end help.  */
2225   if (! lang_eh_type_covers)
2226     {
2227       for (t = handled; t ; t = TREE_CHAIN (t))
2228         if (TREE_VALUE (t) == type)
2229           return 1;
2230     }
2231   else
2232     {
2233       for (t = handled; t ; t = TREE_CHAIN (t))
2234         if ((*lang_eh_type_covers) (TREE_VALUE (t), type))
2235           return 1;
2236     }
2237
2238   return 0;
2239 }
2240
2241 /* A subroutine of reachable_next_level.  If we are collecting a list
2242    of handlers, add one.  After landing pad generation, reference
2243    it instead of the handlers themselves.  Further, the handlers are
2244    all wired together, so by referencing one, we've got them all.
2245    Before landing pad generation we reference each handler individually.
2246
2247    LP_REGION contains the landing pad; REGION is the handler.  */
2248
2249 static void
2250 add_reachable_handler (struct reachable_info *info,
2251                        struct eh_region *lp_region, struct eh_region *region)
2252 {
2253   if (! info)
2254     return;
2255
2256   info->saw_any_handlers = true;
2257
2258   if (cfun->eh->built_landing_pads)
2259     info->callback (lp_region, info->callback_data);
2260   else
2261     info->callback (region, info->callback_data);
2262 }
2263
2264 /* Process one level of exception regions for reachability.
2265    If TYPE_THROWN is non-null, then it is the *exact* type being
2266    propagated.  If INFO is non-null, then collect handler labels
2267    and caught/allowed type information between invocations.  */
2268
2269 static enum reachable_code
2270 reachable_next_level (struct eh_region *region, tree type_thrown,
2271                       struct reachable_info *info)
2272 {
2273   switch (region->type)
2274     {
2275     case ERT_CLEANUP:
2276       /* Before landing-pad generation, we model control flow
2277          directly to the individual handlers.  In this way we can
2278          see that catch handler types may shadow one another.  */
2279       add_reachable_handler (info, region, region);
2280       return RNL_MAYBE_CAUGHT;
2281
2282     case ERT_TRY:
2283       {
2284         struct eh_region *c;
2285         enum reachable_code ret = RNL_NOT_CAUGHT;
2286
2287         for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
2288           {
2289             /* A catch-all handler ends the search.  */
2290             if (c->u.catch.type_list == NULL)
2291               {
2292                 add_reachable_handler (info, region, c);
2293                 return RNL_CAUGHT;
2294               }
2295
2296             if (type_thrown)
2297               {
2298                 /* If we have at least one type match, end the search.  */
2299                 tree tp_node = c->u.catch.type_list;
2300
2301                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2302                   {
2303                     tree type = TREE_VALUE (tp_node);
2304
2305                     if (type == type_thrown
2306                         || (lang_eh_type_covers
2307                             && (*lang_eh_type_covers) (type, type_thrown)))
2308                       {
2309                         add_reachable_handler (info, region, c);
2310                         return RNL_CAUGHT;
2311                       }
2312                   }
2313
2314                 /* If we have definitive information of a match failure,
2315                    the catch won't trigger.  */
2316                 if (lang_eh_type_covers)
2317                   return RNL_NOT_CAUGHT;
2318               }
2319
2320             /* At this point, we either don't know what type is thrown or
2321                don't have front-end assistance to help deciding if it is
2322                covered by one of the types in the list for this region.
2323
2324                We'd then like to add this region to the list of reachable
2325                handlers since it is indeed potentially reachable based on the
2326                information we have.
2327
2328                Actually, this handler is for sure not reachable if all the
2329                types it matches have already been caught. That is, it is only
2330                potentially reachable if at least one of the types it catches
2331                has not been previously caught.  */
2332
2333             if (! info)
2334               ret = RNL_MAYBE_CAUGHT;
2335             else
2336               {
2337                 tree tp_node = c->u.catch.type_list;
2338                 bool maybe_reachable = false;
2339
2340                 /* Compute the potential reachability of this handler and
2341                    update the list of types caught at the same time.  */
2342                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2343                   {
2344                     tree type = TREE_VALUE (tp_node);
2345
2346                     if (! check_handled (info->types_caught, type))
2347                       {
2348                         info->types_caught
2349                           = tree_cons (NULL, type, info->types_caught);
2350
2351                         maybe_reachable = true;
2352                       }
2353                   }
2354
2355                 if (maybe_reachable)
2356                   {
2357                     add_reachable_handler (info, region, c);
2358
2359                     /* ??? If the catch type is a base class of every allowed
2360                        type, then we know we can stop the search.  */
2361                     ret = RNL_MAYBE_CAUGHT;
2362                   }
2363               }
2364           }
2365
2366         return ret;
2367       }
2368
2369     case ERT_ALLOWED_EXCEPTIONS:
2370       /* An empty list of types definitely ends the search.  */
2371       if (region->u.allowed.type_list == NULL_TREE)
2372         {
2373           add_reachable_handler (info, region, region);
2374           return RNL_CAUGHT;
2375         }
2376
2377       /* Collect a list of lists of allowed types for use in detecting
2378          when a catch may be transformed into a catch-all.  */
2379       if (info)
2380         info->types_allowed = tree_cons (NULL_TREE,
2381                                          region->u.allowed.type_list,
2382                                          info->types_allowed);
2383
2384       /* If we have definitive information about the type hierarchy,
2385          then we can tell if the thrown type will pass through the
2386          filter.  */
2387       if (type_thrown && lang_eh_type_covers)
2388         {
2389           if (check_handled (region->u.allowed.type_list, type_thrown))
2390             return RNL_NOT_CAUGHT;
2391           else
2392             {
2393               add_reachable_handler (info, region, region);
2394               return RNL_CAUGHT;
2395             }
2396         }
2397
2398       add_reachable_handler (info, region, region);
2399       return RNL_MAYBE_CAUGHT;
2400
2401     case ERT_CATCH:
2402       /* Catch regions are handled by their controlling try region.  */
2403       return RNL_NOT_CAUGHT;
2404
2405     case ERT_MUST_NOT_THROW:
2406       /* Here we end our search, since no exceptions may propagate.
2407          If we've touched down at some landing pad previous, then the
2408          explicit function call we generated may be used.  Otherwise
2409          the call is made by the runtime. 
2410
2411          Before inlining, do not perform this optimization.  We may
2412          inline a subroutine that contains handlers, and that will
2413          change the value of saw_any_handlers.  */
2414
2415       if ((info && info->saw_any_handlers) || !cfun->after_inlining)
2416         {
2417           add_reachable_handler (info, region, region);
2418           return RNL_CAUGHT;
2419         }
2420       else
2421         return RNL_BLOCKED;
2422
2423     case ERT_THROW:
2424     case ERT_UNKNOWN:
2425       /* Shouldn't see these here.  */
2426       gcc_unreachable ();
2427       break;
2428     default:
2429       gcc_unreachable ();
2430     }
2431 }
2432
2433 /* Invoke CALLBACK on each region reachable from REGION_NUMBER.  */
2434
2435 void
2436 foreach_reachable_handler (int region_number, bool is_resx,
2437                            void (*callback) (struct eh_region *, void *),
2438                            void *callback_data)
2439 {
2440   struct reachable_info info;
2441   struct eh_region *region;
2442   tree type_thrown;
2443
2444   memset (&info, 0, sizeof (info));
2445   info.callback = callback;
2446   info.callback_data = callback_data;
2447
2448   region = cfun->eh->region_array[region_number];
2449
2450   type_thrown = NULL_TREE;
2451   if (is_resx)
2452     {
2453       /* A RESX leaves a region instead of entering it.  Thus the
2454          region itself may have been deleted out from under us.  */
2455       if (region == NULL)
2456         return;
2457       region = region->outer;
2458     }
2459   else if (region->type == ERT_THROW)
2460     {
2461       type_thrown = region->u.throw.type;
2462       region = region->outer;
2463     }
2464
2465   while (region)
2466     {
2467       if (reachable_next_level (region, type_thrown, &info) >= RNL_CAUGHT)
2468         break;
2469       /* If we have processed one cleanup, there is no point in
2470          processing any more of them.  Each cleanup will have an edge
2471          to the next outer cleanup region, so the flow graph will be
2472          accurate.  */
2473       if (region->type == ERT_CLEANUP)
2474         region = region->u.cleanup.prev_try;
2475       else
2476         region = region->outer;
2477     }
2478 }
2479
2480 /* Retrieve a list of labels of exception handlers which can be
2481    reached by a given insn.  */
2482
2483 static void
2484 arh_to_landing_pad (struct eh_region *region, void *data)
2485 {
2486   rtx *p_handlers = data;
2487   if (! *p_handlers)
2488     *p_handlers = alloc_INSN_LIST (region->landing_pad, NULL_RTX);
2489 }
2490
2491 static void
2492 arh_to_label (struct eh_region *region, void *data)
2493 {
2494   rtx *p_handlers = data;
2495   *p_handlers = alloc_INSN_LIST (region->label, *p_handlers);
2496 }
2497
2498 rtx
2499 reachable_handlers (rtx insn)
2500 {
2501   bool is_resx = false;
2502   rtx handlers = NULL;
2503   int region_number;
2504
2505   if (JUMP_P (insn)
2506       && GET_CODE (PATTERN (insn)) == RESX)
2507     {
2508       region_number = XINT (PATTERN (insn), 0);
2509       is_resx = true;
2510     }
2511   else
2512     {
2513       rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2514       if (!note || INTVAL (XEXP (note, 0)) <= 0)
2515         return NULL;
2516       region_number = INTVAL (XEXP (note, 0));
2517     }
2518
2519   foreach_reachable_handler (region_number, is_resx,
2520                              (cfun->eh->built_landing_pads
2521                               ? arh_to_landing_pad
2522                               : arh_to_label),
2523                              &handlers);
2524
2525   return handlers;
2526 }
2527
2528 /* Determine if the given INSN can throw an exception that is caught
2529    within the function.  */
2530
2531 bool
2532 can_throw_internal_1 (int region_number, bool is_resx)
2533 {
2534   struct eh_region *region;
2535   tree type_thrown;
2536
2537   region = cfun->eh->region_array[region_number];
2538
2539   type_thrown = NULL_TREE;
2540   if (is_resx)
2541     region = region->outer;
2542   else if (region->type == ERT_THROW)
2543     {
2544       type_thrown = region->u.throw.type;
2545       region = region->outer;
2546     }
2547
2548   /* If this exception is ignored by each and every containing region,
2549      then control passes straight out.  The runtime may handle some
2550      regions, which also do not require processing internally.  */
2551   for (; region; region = region->outer)
2552     {
2553       enum reachable_code how = reachable_next_level (region, type_thrown, 0);
2554       if (how == RNL_BLOCKED)
2555         return false;
2556       if (how != RNL_NOT_CAUGHT)
2557         return true;
2558     }
2559
2560   return false;
2561 }
2562
2563 bool
2564 can_throw_internal (rtx insn)
2565 {
2566   rtx note;
2567
2568   if (! INSN_P (insn))
2569     return false;
2570
2571   if (JUMP_P (insn)
2572       && GET_CODE (PATTERN (insn)) == RESX
2573       && XINT (PATTERN (insn), 0) > 0)
2574     return can_throw_internal_1 (XINT (PATTERN (insn), 0), true);
2575
2576   if (NONJUMP_INSN_P (insn)
2577       && GET_CODE (PATTERN (insn)) == SEQUENCE)
2578     insn = XVECEXP (PATTERN (insn), 0, 0);
2579
2580   /* Every insn that might throw has an EH_REGION note.  */
2581   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2582   if (!note || INTVAL (XEXP (note, 0)) <= 0)
2583     return false;
2584
2585   return can_throw_internal_1 (INTVAL (XEXP (note, 0)), false);
2586 }
2587
2588 /* Determine if the given INSN can throw an exception that is
2589    visible outside the function.  */
2590
2591 bool
2592 can_throw_external_1 (int region_number, bool is_resx)
2593 {
2594   struct eh_region *region;
2595   tree type_thrown;
2596
2597   region = cfun->eh->region_array[region_number];
2598
2599   type_thrown = NULL_TREE;
2600   if (is_resx)
2601     region = region->outer;
2602   else if (region->type == ERT_THROW)
2603     {
2604       type_thrown = region->u.throw.type;
2605       region = region->outer;
2606     }
2607
2608   /* If the exception is caught or blocked by any containing region,
2609      then it is not seen by any calling function.  */
2610   for (; region ; region = region->outer)
2611     if (reachable_next_level (region, type_thrown, NULL) >= RNL_CAUGHT)
2612       return false;
2613
2614   return true;
2615 }
2616
2617 bool
2618 can_throw_external (rtx insn)
2619 {
2620   rtx note;
2621
2622   if (! INSN_P (insn))
2623     return false;
2624
2625   if (JUMP_P (insn)
2626       && GET_CODE (PATTERN (insn)) == RESX
2627       && XINT (PATTERN (insn), 0) > 0)
2628     return can_throw_external_1 (XINT (PATTERN (insn), 0), true);
2629
2630   if (NONJUMP_INSN_P (insn)
2631       && GET_CODE (PATTERN (insn)) == SEQUENCE)
2632     insn = XVECEXP (PATTERN (insn), 0, 0);
2633
2634   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2635   if (!note)
2636     {
2637       /* Calls (and trapping insns) without notes are outside any
2638          exception handling region in this function.  We have to
2639          assume it might throw.  Given that the front end and middle
2640          ends mark known NOTHROW functions, this isn't so wildly
2641          inaccurate.  */
2642       return (CALL_P (insn)
2643               || (flag_non_call_exceptions
2644                   && may_trap_p (PATTERN (insn))));
2645     }
2646   if (INTVAL (XEXP (note, 0)) <= 0)
2647     return false;
2648
2649   return can_throw_external_1 (INTVAL (XEXP (note, 0)), false);
2650 }
2651
2652 /* Set TREE_NOTHROW and cfun->all_throwers_are_sibcalls.  */
2653
2654 void
2655 set_nothrow_function_flags (void)
2656 {
2657   rtx insn;
2658
2659   TREE_NOTHROW (current_function_decl) = 1;
2660
2661   /* Assume cfun->all_throwers_are_sibcalls until we encounter
2662      something that can throw an exception.  We specifically exempt
2663      CALL_INSNs that are SIBLING_CALL_P, as these are really jumps,
2664      and can't throw.  Most CALL_INSNs are not SIBLING_CALL_P, so this
2665      is optimistic.  */
2666
2667   cfun->all_throwers_are_sibcalls = 1;
2668
2669   if (! flag_exceptions)
2670     return;
2671
2672   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2673     if (can_throw_external (insn))
2674       {
2675         TREE_NOTHROW (current_function_decl) = 0;
2676
2677         if (!CALL_P (insn) || !SIBLING_CALL_P (insn))
2678           {
2679             cfun->all_throwers_are_sibcalls = 0;
2680             return;
2681           }
2682       }
2683
2684   for (insn = current_function_epilogue_delay_list; insn;
2685        insn = XEXP (insn, 1))
2686     if (can_throw_external (insn))
2687       {
2688         TREE_NOTHROW (current_function_decl) = 0;
2689
2690         if (!CALL_P (insn) || !SIBLING_CALL_P (insn))
2691           {
2692             cfun->all_throwers_are_sibcalls = 0;
2693             return;
2694           }
2695       }
2696 }
2697
2698 \f
2699 /* Various hooks for unwind library.  */
2700
2701 /* Do any necessary initialization to access arbitrary stack frames.
2702    On the SPARC, this means flushing the register windows.  */
2703
2704 void
2705 expand_builtin_unwind_init (void)
2706 {
2707   /* Set this so all the registers get saved in our frame; we need to be
2708      able to copy the saved values for any registers from frames we unwind.  */
2709   current_function_has_nonlocal_label = 1;
2710
2711 #ifdef SETUP_FRAME_ADDRESSES
2712   SETUP_FRAME_ADDRESSES ();
2713 #endif
2714 }
2715
2716 rtx
2717 expand_builtin_eh_return_data_regno (tree arglist)
2718 {
2719   tree which = TREE_VALUE (arglist);
2720   unsigned HOST_WIDE_INT iwhich;
2721
2722   if (TREE_CODE (which) != INTEGER_CST)
2723     {
2724       error ("argument of %<__builtin_eh_return_regno%> must be constant");
2725       return constm1_rtx;
2726     }
2727
2728   iwhich = tree_low_cst (which, 1);
2729   iwhich = EH_RETURN_DATA_REGNO (iwhich);
2730   if (iwhich == INVALID_REGNUM)
2731     return constm1_rtx;
2732
2733 #ifdef DWARF_FRAME_REGNUM
2734   iwhich = DWARF_FRAME_REGNUM (iwhich);
2735 #else
2736   iwhich = DBX_REGISTER_NUMBER (iwhich);
2737 #endif
2738
2739   return GEN_INT (iwhich);
2740 }
2741
2742 /* Given a value extracted from the return address register or stack slot,
2743    return the actual address encoded in that value.  */
2744
2745 rtx
2746 expand_builtin_extract_return_addr (tree addr_tree)
2747 {
2748   rtx addr = expand_expr (addr_tree, NULL_RTX, Pmode, 0);
2749
2750   if (GET_MODE (addr) != Pmode
2751       && GET_MODE (addr) != VOIDmode)
2752     {
2753 #ifdef POINTERS_EXTEND_UNSIGNED
2754       addr = convert_memory_address (Pmode, addr);
2755 #else
2756       addr = convert_to_mode (Pmode, addr, 0);
2757 #endif
2758     }
2759
2760   /* First mask out any unwanted bits.  */
2761 #ifdef MASK_RETURN_ADDR
2762   expand_and (Pmode, addr, MASK_RETURN_ADDR, addr);
2763 #endif
2764
2765   /* Then adjust to find the real return address.  */
2766 #if defined (RETURN_ADDR_OFFSET)
2767   addr = plus_constant (addr, RETURN_ADDR_OFFSET);
2768 #endif
2769
2770   return addr;
2771 }
2772
2773 /* Given an actual address in addr_tree, do any necessary encoding
2774    and return the value to be stored in the return address register or
2775    stack slot so the epilogue will return to that address.  */
2776
2777 rtx
2778 expand_builtin_frob_return_addr (tree addr_tree)
2779 {
2780   rtx addr = expand_expr (addr_tree, NULL_RTX, ptr_mode, 0);
2781
2782   addr = convert_memory_address (Pmode, addr);
2783
2784 #ifdef RETURN_ADDR_OFFSET
2785   addr = force_reg (Pmode, addr);
2786   addr = plus_constant (addr, -RETURN_ADDR_OFFSET);
2787 #endif
2788
2789   return addr;
2790 }
2791
2792 /* Set up the epilogue with the magic bits we'll need to return to the
2793    exception handler.  */
2794
2795 void
2796 expand_builtin_eh_return (tree stackadj_tree ATTRIBUTE_UNUSED,
2797                           tree handler_tree)
2798 {
2799   rtx tmp;
2800
2801 #ifdef EH_RETURN_STACKADJ_RTX
2802   tmp = expand_expr (stackadj_tree, cfun->eh->ehr_stackadj, VOIDmode, 0);
2803   tmp = convert_memory_address (Pmode, tmp);
2804   if (!cfun->eh->ehr_stackadj)
2805     cfun->eh->ehr_stackadj = copy_to_reg (tmp);
2806   else if (tmp != cfun->eh->ehr_stackadj)
2807     emit_move_insn (cfun->eh->ehr_stackadj, tmp);
2808 #endif
2809
2810   tmp = expand_expr (handler_tree, cfun->eh->ehr_handler, VOIDmode, 0);
2811   tmp = convert_memory_address (Pmode, tmp);
2812   if (!cfun->eh->ehr_handler)
2813     cfun->eh->ehr_handler = copy_to_reg (tmp);
2814   else if (tmp != cfun->eh->ehr_handler)
2815     emit_move_insn (cfun->eh->ehr_handler, tmp);
2816
2817   if (!cfun->eh->ehr_label)
2818     cfun->eh->ehr_label = gen_label_rtx ();
2819   emit_jump (cfun->eh->ehr_label);
2820 }
2821
2822 void
2823 expand_eh_return (void)
2824 {
2825   rtx around_label;
2826
2827   if (! cfun->eh->ehr_label)
2828     return;
2829
2830   current_function_calls_eh_return = 1;
2831
2832 #ifdef EH_RETURN_STACKADJ_RTX
2833   emit_move_insn (EH_RETURN_STACKADJ_RTX, const0_rtx);
2834 #endif
2835
2836   around_label = gen_label_rtx ();
2837   emit_jump (around_label);
2838
2839   emit_label (cfun->eh->ehr_label);
2840   clobber_return_register ();
2841
2842 #ifdef EH_RETURN_STACKADJ_RTX
2843   emit_move_insn (EH_RETURN_STACKADJ_RTX, cfun->eh->ehr_stackadj);
2844 #endif
2845
2846 #ifdef HAVE_eh_return
2847   if (HAVE_eh_return)
2848     emit_insn (gen_eh_return (cfun->eh->ehr_handler));
2849   else
2850 #endif
2851     {
2852 #ifdef EH_RETURN_HANDLER_RTX
2853       emit_move_insn (EH_RETURN_HANDLER_RTX, cfun->eh->ehr_handler);
2854 #else
2855       error ("__builtin_eh_return not supported on this target");
2856 #endif
2857     }
2858
2859   emit_label (around_label);
2860 }
2861
2862 /* Convert a ptr_mode address ADDR_TREE to a Pmode address controlled by
2863    POINTERS_EXTEND_UNSIGNED and return it.  */
2864
2865 rtx
2866 expand_builtin_extend_pointer (tree addr_tree)
2867 {
2868   rtx addr = expand_expr (addr_tree, NULL_RTX, ptr_mode, 0);
2869   int extend;
2870
2871 #ifdef POINTERS_EXTEND_UNSIGNED
2872   extend = POINTERS_EXTEND_UNSIGNED;
2873 #else
2874   /* The previous EH code did an unsigned extend by default, so we do this also
2875      for consistency.  */
2876   extend = 1;
2877 #endif
2878
2879   return convert_modes (word_mode, ptr_mode, addr, extend);
2880 }
2881 \f
2882 /* In the following functions, we represent entries in the action table
2883    as 1-based indices.  Special cases are:
2884
2885          0:     null action record, non-null landing pad; implies cleanups
2886         -1:     null action record, null landing pad; implies no action
2887         -2:     no call-site entry; implies must_not_throw
2888         -3:     we have yet to process outer regions
2889
2890    Further, no special cases apply to the "next" field of the record.
2891    For next, 0 means end of list.  */
2892
2893 struct action_record
2894 {
2895   int offset;
2896   int filter;
2897   int next;
2898 };
2899
2900 static int
2901 action_record_eq (const void *pentry, const void *pdata)
2902 {
2903   const struct action_record *entry = (const struct action_record *) pentry;
2904   const struct action_record *data = (const struct action_record *) pdata;
2905   return entry->filter == data->filter && entry->next == data->next;
2906 }
2907
2908 static hashval_t
2909 action_record_hash (const void *pentry)
2910 {
2911   const struct action_record *entry = (const struct action_record *) pentry;
2912   return entry->next * 1009 + entry->filter;
2913 }
2914
2915 static int
2916 add_action_record (htab_t ar_hash, int filter, int next)
2917 {
2918   struct action_record **slot, *new, tmp;
2919
2920   tmp.filter = filter;
2921   tmp.next = next;
2922   slot = (struct action_record **) htab_find_slot (ar_hash, &tmp, INSERT);
2923
2924   if ((new = *slot) == NULL)
2925     {
2926       new = xmalloc (sizeof (*new));
2927       new->offset = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
2928       new->filter = filter;
2929       new->next = next;
2930       *slot = new;
2931
2932       /* The filter value goes in untouched.  The link to the next
2933          record is a "self-relative" byte offset, or zero to indicate
2934          that there is no next record.  So convert the absolute 1 based
2935          indices we've been carrying around into a displacement.  */
2936
2937       push_sleb128 (&cfun->eh->action_record_data, filter);
2938       if (next)
2939         next -= VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
2940       push_sleb128 (&cfun->eh->action_record_data, next);
2941     }
2942
2943   return new->offset;
2944 }
2945
2946 static int
2947 collect_one_action_chain (htab_t ar_hash, struct eh_region *region)
2948 {
2949   struct eh_region *c;
2950   int next;
2951
2952   /* If we've reached the top of the region chain, then we have
2953      no actions, and require no landing pad.  */
2954   if (region == NULL)
2955     return -1;
2956
2957   switch (region->type)
2958     {
2959     case ERT_CLEANUP:
2960       /* A cleanup adds a zero filter to the beginning of the chain, but
2961          there are special cases to look out for.  If there are *only*
2962          cleanups along a path, then it compresses to a zero action.
2963          Further, if there are multiple cleanups along a path, we only
2964          need to represent one of them, as that is enough to trigger
2965          entry to the landing pad at runtime.  */
2966       next = collect_one_action_chain (ar_hash, region->outer);
2967       if (next <= 0)
2968         return 0;
2969       for (c = region->outer; c ; c = c->outer)
2970         if (c->type == ERT_CLEANUP)
2971           return next;
2972       return add_action_record (ar_hash, 0, next);
2973
2974     case ERT_TRY:
2975       /* Process the associated catch regions in reverse order.
2976          If there's a catch-all handler, then we don't need to
2977          search outer regions.  Use a magic -3 value to record
2978          that we haven't done the outer search.  */
2979       next = -3;
2980       for (c = region->u.try.last_catch; c ; c = c->u.catch.prev_catch)
2981         {
2982           if (c->u.catch.type_list == NULL)
2983             {
2984               /* Retrieve the filter from the head of the filter list
2985                  where we have stored it (see assign_filter_values).  */
2986               int filter
2987                 = TREE_INT_CST_LOW (TREE_VALUE (c->u.catch.filter_list));
2988
2989               next = add_action_record (ar_hash, filter, 0);
2990             }
2991           else
2992             {
2993               /* Once the outer search is done, trigger an action record for
2994                  each filter we have.  */
2995               tree flt_node;
2996
2997               if (next == -3)
2998                 {
2999                   next = collect_one_action_chain (ar_hash, region->outer);
3000
3001                   /* If there is no next action, terminate the chain.  */
3002                   if (next == -1)
3003                     next = 0;
3004                   /* If all outer actions are cleanups or must_not_throw,
3005                      we'll have no action record for it, since we had wanted
3006                      to encode these states in the call-site record directly.
3007                      Add a cleanup action to the chain to catch these.  */
3008                   else if (next <= 0)
3009                     next = add_action_record (ar_hash, 0, 0);
3010                 }
3011
3012               flt_node = c->u.catch.filter_list;
3013               for (; flt_node; flt_node = TREE_CHAIN (flt_node))
3014                 {
3015                   int filter = TREE_INT_CST_LOW (TREE_VALUE (flt_node));
3016                   next = add_action_record (ar_hash, filter, next);
3017                 }
3018             }
3019         }
3020       return next;
3021
3022     case ERT_ALLOWED_EXCEPTIONS:
3023       /* An exception specification adds its filter to the
3024          beginning of the chain.  */
3025       next = collect_one_action_chain (ar_hash, region->outer);
3026
3027       /* If there is no next action, terminate the chain.  */
3028       if (next == -1)
3029         next = 0;
3030       /* If all outer actions are cleanups or must_not_throw,
3031          we'll have no action record for it, since we had wanted
3032          to encode these states in the call-site record directly.
3033          Add a cleanup action to the chain to catch these.  */
3034       else if (next <= 0)
3035         next = add_action_record (ar_hash, 0, 0);
3036       
3037       return add_action_record (ar_hash, region->u.allowed.filter, next);
3038
3039     case ERT_MUST_NOT_THROW:
3040       /* A must-not-throw region with no inner handlers or cleanups
3041          requires no call-site entry.  Note that this differs from
3042          the no handler or cleanup case in that we do require an lsda
3043          to be generated.  Return a magic -2 value to record this.  */
3044       return -2;
3045
3046     case ERT_CATCH:
3047     case ERT_THROW:
3048       /* CATCH regions are handled in TRY above.  THROW regions are
3049          for optimization information only and produce no output.  */
3050       return collect_one_action_chain (ar_hash, region->outer);
3051
3052     default:
3053       gcc_unreachable ();
3054     }
3055 }
3056
3057 static int
3058 add_call_site (rtx landing_pad, int action)
3059 {
3060   struct call_site_record *data = cfun->eh->call_site_data;
3061   int used = cfun->eh->call_site_data_used;
3062   int size = cfun->eh->call_site_data_size;
3063
3064   if (used >= size)
3065     {
3066       size = (size ? size * 2 : 64);
3067       data = ggc_realloc (data, sizeof (*data) * size);
3068       cfun->eh->call_site_data = data;
3069       cfun->eh->call_site_data_size = size;
3070     }
3071
3072   data[used].landing_pad = landing_pad;
3073   data[used].action = action;
3074
3075   cfun->eh->call_site_data_used = used + 1;
3076
3077   return used + call_site_base;
3078 }
3079
3080 /* Turn REG_EH_REGION notes back into NOTE_INSN_EH_REGION notes.
3081    The new note numbers will not refer to region numbers, but
3082    instead to call site entries.  */
3083
3084 void
3085 convert_to_eh_region_ranges (void)
3086 {
3087   rtx insn, iter, note;
3088   htab_t ar_hash;
3089   int last_action = -3;
3090   rtx last_action_insn = NULL_RTX;
3091   rtx last_landing_pad = NULL_RTX;
3092   rtx first_no_action_insn = NULL_RTX;
3093   int call_site = 0;
3094
3095   if (USING_SJLJ_EXCEPTIONS || cfun->eh->region_tree == NULL)
3096     return;
3097
3098   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
3099
3100   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
3101
3102   for (iter = get_insns (); iter ; iter = NEXT_INSN (iter))
3103     if (INSN_P (iter))
3104       {
3105         struct eh_region *region;
3106         int this_action;
3107         rtx this_landing_pad;
3108
3109         insn = iter;
3110         if (NONJUMP_INSN_P (insn)
3111             && GET_CODE (PATTERN (insn)) == SEQUENCE)
3112           insn = XVECEXP (PATTERN (insn), 0, 0);
3113
3114         note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
3115         if (!note)
3116           {
3117             if (! (CALL_P (insn)
3118                    || (flag_non_call_exceptions
3119                        && may_trap_p (PATTERN (insn)))))
3120               continue;
3121             this_action = -1;
3122             region = NULL;
3123           }
3124         else
3125           {
3126             if (INTVAL (XEXP (note, 0)) <= 0)
3127               continue;
3128             region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
3129             this_action = collect_one_action_chain (ar_hash, region);
3130           }
3131
3132         /* Existence of catch handlers, or must-not-throw regions
3133            implies that an lsda is needed (even if empty).  */
3134         if (this_action != -1)
3135           cfun->uses_eh_lsda = 1;
3136
3137         /* Delay creation of region notes for no-action regions
3138            until we're sure that an lsda will be required.  */
3139         else if (last_action == -3)
3140           {
3141             first_no_action_insn = iter;
3142             last_action = -1;
3143           }
3144
3145         /* Cleanups and handlers may share action chains but not
3146            landing pads.  Collect the landing pad for this region.  */
3147         if (this_action >= 0)
3148           {
3149             struct eh_region *o;
3150             for (o = region; ! o->landing_pad ; o = o->outer)
3151               continue;
3152             this_landing_pad = o->landing_pad;
3153           }
3154         else
3155           this_landing_pad = NULL_RTX;
3156
3157         /* Differing actions or landing pads implies a change in call-site
3158            info, which implies some EH_REGION note should be emitted.  */
3159         if (last_action != this_action
3160             || last_landing_pad != this_landing_pad)
3161           {
3162             /* If we'd not seen a previous action (-3) or the previous
3163                action was must-not-throw (-2), then we do not need an
3164                end note.  */
3165             if (last_action >= -1)
3166               {
3167                 /* If we delayed the creation of the begin, do it now.  */
3168                 if (first_no_action_insn)
3169                   {
3170                     call_site = add_call_site (NULL_RTX, 0);
3171                     note = emit_note_before (NOTE_INSN_EH_REGION_BEG,
3172                                              first_no_action_insn);
3173                     NOTE_EH_HANDLER (note) = call_site;
3174                     first_no_action_insn = NULL_RTX;
3175                   }
3176
3177                 note = emit_note_after (NOTE_INSN_EH_REGION_END,
3178                                         last_action_insn);
3179                 NOTE_EH_HANDLER (note) = call_site;
3180               }
3181
3182             /* If the new action is must-not-throw, then no region notes
3183                are created.  */
3184             if (this_action >= -1)
3185               {
3186                 call_site = add_call_site (this_landing_pad,
3187                                            this_action < 0 ? 0 : this_action);
3188                 note = emit_note_before (NOTE_INSN_EH_REGION_BEG, iter);
3189                 NOTE_EH_HANDLER (note) = call_site;
3190               }
3191
3192             last_action = this_action;
3193             last_landing_pad = this_landing_pad;
3194           }
3195         last_action_insn = iter;
3196       }
3197
3198   if (last_action >= -1 && ! first_no_action_insn)
3199     {
3200       note = emit_note_after (NOTE_INSN_EH_REGION_END, last_action_insn);
3201       NOTE_EH_HANDLER (note) = call_site;
3202     }
3203
3204   htab_delete (ar_hash);
3205 }
3206
3207 \f
3208 static void
3209 push_uleb128 (varray_type *data_area, unsigned int value)
3210 {
3211   do
3212     {
3213       unsigned char byte = value & 0x7f;
3214       value >>= 7;
3215       if (value)
3216         byte |= 0x80;
3217       VARRAY_PUSH_UCHAR (*data_area, byte);
3218     }
3219   while (value);
3220 }
3221
3222 static void
3223 push_sleb128 (varray_type *data_area, int value)
3224 {
3225   unsigned char byte;
3226   int more;
3227
3228   do
3229     {
3230       byte = value & 0x7f;
3231       value >>= 7;
3232       more = ! ((value == 0 && (byte & 0x40) == 0)
3233                 || (value == -1 && (byte & 0x40) != 0));
3234       if (more)
3235         byte |= 0x80;
3236       VARRAY_PUSH_UCHAR (*data_area, byte);
3237     }
3238   while (more);
3239 }
3240
3241 \f
3242 #ifndef HAVE_AS_LEB128
3243 static int
3244 dw2_size_of_call_site_table (void)
3245 {
3246   int n = cfun->eh->call_site_data_used;
3247   int size = n * (4 + 4 + 4);
3248   int i;
3249
3250   for (i = 0; i < n; ++i)
3251     {
3252       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3253       size += size_of_uleb128 (cs->action);
3254     }
3255
3256   return size;
3257 }
3258
3259 static int
3260 sjlj_size_of_call_site_table (void)
3261 {
3262   int n = cfun->eh->call_site_data_used;
3263   int size = 0;
3264   int i;
3265
3266   for (i = 0; i < n; ++i)
3267     {
3268       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3269       size += size_of_uleb128 (INTVAL (cs->landing_pad));
3270       size += size_of_uleb128 (cs->action);
3271     }
3272
3273   return size;
3274 }
3275 #endif
3276
3277 static void
3278 dw2_output_call_site_table (void)
3279 {
3280   int n = cfun->eh->call_site_data_used;
3281   int i;
3282
3283   for (i = 0; i < n; ++i)
3284     {
3285       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3286       char reg_start_lab[32];
3287       char reg_end_lab[32];
3288       char landing_pad_lab[32];
3289
3290       ASM_GENERATE_INTERNAL_LABEL (reg_start_lab, "LEHB", call_site_base + i);
3291       ASM_GENERATE_INTERNAL_LABEL (reg_end_lab, "LEHE", call_site_base + i);
3292
3293       if (cs->landing_pad)
3294         ASM_GENERATE_INTERNAL_LABEL (landing_pad_lab, "L",
3295                                      CODE_LABEL_NUMBER (cs->landing_pad));
3296
3297       /* ??? Perhaps use insn length scaling if the assembler supports
3298          generic arithmetic.  */
3299       /* ??? Perhaps use attr_length to choose data1 or data2 instead of
3300          data4 if the function is small enough.  */
3301 #ifdef HAVE_AS_LEB128
3302       dw2_asm_output_delta_uleb128 (reg_start_lab,
3303                                     current_function_func_begin_label,
3304                                     "region %d start", i);
3305       dw2_asm_output_delta_uleb128 (reg_end_lab, reg_start_lab,
3306                                     "length");
3307       if (cs->landing_pad)
3308         dw2_asm_output_delta_uleb128 (landing_pad_lab,
3309                                       current_function_func_begin_label,
3310                                       "landing pad");
3311       else
3312         dw2_asm_output_data_uleb128 (0, "landing pad");
3313 #else
3314       dw2_asm_output_delta (4, reg_start_lab,
3315                             current_function_func_begin_label,
3316                             "region %d start", i);
3317       dw2_asm_output_delta (4, reg_end_lab, reg_start_lab, "length");
3318       if (cs->landing_pad)
3319         dw2_asm_output_delta (4, landing_pad_lab,
3320                               current_function_func_begin_label,
3321                               "landing pad");
3322       else
3323         dw2_asm_output_data (4, 0, "landing pad");
3324 #endif
3325       dw2_asm_output_data_uleb128 (cs->action, "action");
3326     }
3327
3328   call_site_base += n;
3329 }
3330
3331 static void
3332 sjlj_output_call_site_table (void)
3333 {
3334   int n = cfun->eh->call_site_data_used;
3335   int i;
3336
3337   for (i = 0; i < n; ++i)
3338     {
3339       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3340
3341       dw2_asm_output_data_uleb128 (INTVAL (cs->landing_pad),
3342                                    "region %d landing pad", i);
3343       dw2_asm_output_data_uleb128 (cs->action, "action");
3344     }
3345
3346   call_site_base += n;
3347 }
3348
3349 /* Tell assembler to switch to the section for the exception handling
3350    table.  */
3351
3352 void
3353 default_exception_section (void)
3354 {
3355   if (targetm.have_named_sections)
3356     {
3357       int flags;
3358
3359       if (EH_TABLES_CAN_BE_READ_ONLY)
3360         {
3361           int tt_format = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/1);
3362           
3363           flags = (! flag_pic
3364                    || ((tt_format & 0x70) != DW_EH_PE_absptr
3365                        && (tt_format & 0x70) != DW_EH_PE_aligned))
3366             ? 0 : SECTION_WRITE;
3367         }
3368       else
3369         flags = SECTION_WRITE;
3370       named_section_flags (".gcc_except_table", flags);
3371     }
3372   else if (flag_pic)
3373     data_section ();
3374   else
3375     readonly_data_section ();
3376 }
3377
3378 void
3379 output_function_exception_table (void)
3380 {
3381   int tt_format, cs_format, lp_format, i, n;
3382 #ifdef HAVE_AS_LEB128
3383   char ttype_label[32];
3384   char cs_after_size_label[32];
3385   char cs_end_label[32];
3386 #else
3387   int call_site_len;
3388 #endif
3389   int have_tt_data;
3390   int tt_format_size = 0;
3391
3392   /* Not all functions need anything.  */
3393   if (! cfun->uses_eh_lsda)
3394     return;
3395
3396 #ifdef TARGET_UNWIND_INFO
3397   /* TODO: Move this into target file.  */
3398   assemble_external_libcall (eh_personality_libfunc);
3399   fputs ("\t.personality\t", asm_out_file);
3400   output_addr_const (asm_out_file, eh_personality_libfunc);
3401   fputs ("\n\t.handlerdata\n", asm_out_file);
3402   /* Note that varasm still thinks we're in the function's code section.
3403      The ".endp" directive that will immediately follow will take us back.  */
3404 #else
3405   targetm.asm_out.exception_section ();
3406 #endif
3407
3408   have_tt_data = (VEC_length (tree, cfun->eh->ttype_data) > 0
3409                   || VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) > 0);
3410
3411   /* Indicate the format of the @TType entries.  */
3412   if (! have_tt_data)
3413     tt_format = DW_EH_PE_omit;
3414   else
3415     {
3416       tt_format = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/1);
3417 #ifdef HAVE_AS_LEB128
3418       ASM_GENERATE_INTERNAL_LABEL (ttype_label, "LLSDATT",
3419                                    current_function_funcdef_no);
3420 #endif
3421       tt_format_size = size_of_encoded_value (tt_format);
3422
3423       assemble_align (tt_format_size * BITS_PER_UNIT);
3424     }
3425
3426   targetm.asm_out.internal_label (asm_out_file, "LLSDA",
3427                              current_function_funcdef_no);
3428
3429   /* The LSDA header.  */
3430
3431   /* Indicate the format of the landing pad start pointer.  An omitted
3432      field implies @LPStart == @Start.  */
3433   /* Currently we always put @LPStart == @Start.  This field would
3434      be most useful in moving the landing pads completely out of
3435      line to another section, but it could also be used to minimize
3436      the size of uleb128 landing pad offsets.  */
3437   lp_format = DW_EH_PE_omit;
3438   dw2_asm_output_data (1, lp_format, "@LPStart format (%s)",
3439                        eh_data_format_name (lp_format));
3440
3441   /* @LPStart pointer would go here.  */
3442
3443   dw2_asm_output_data (1, tt_format, "@TType format (%s)",
3444                        eh_data_format_name (tt_format));
3445
3446 #ifndef HAVE_AS_LEB128
3447   if (USING_SJLJ_EXCEPTIONS)
3448     call_site_len = sjlj_size_of_call_site_table ();
3449   else
3450     call_site_len = dw2_size_of_call_site_table ();
3451 #endif
3452
3453   /* A pc-relative 4-byte displacement to the @TType data.  */
3454   if (have_tt_data)
3455     {
3456 #ifdef HAVE_AS_LEB128
3457       char ttype_after_disp_label[32];
3458       ASM_GENERATE_INTERNAL_LABEL (ttype_after_disp_label, "LLSDATTD",
3459                                    current_function_funcdef_no);
3460       dw2_asm_output_delta_uleb128 (ttype_label, ttype_after_disp_label,
3461                                     "@TType base offset");
3462       ASM_OUTPUT_LABEL (asm_out_file, ttype_after_disp_label);
3463 #else
3464       /* Ug.  Alignment queers things.  */
3465       unsigned int before_disp, after_disp, last_disp, disp;
3466
3467       before_disp = 1 + 1;
3468       after_disp = (1 + size_of_uleb128 (call_site_len)
3469                     + call_site_len
3470                     + VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data)
3471                     + (VEC_length (tree, cfun->eh->ttype_data)
3472                        * tt_format_size));
3473
3474       disp = after_disp;
3475       do
3476         {
3477           unsigned int disp_size, pad;
3478
3479           last_disp = disp;
3480           disp_size = size_of_uleb128 (disp);
3481           pad = before_disp + disp_size + after_disp;
3482           if (pad % tt_format_size)
3483             pad = tt_format_size - (pad % tt_format_size);
3484           else
3485             pad = 0;
3486           disp = after_disp + pad;
3487         }
3488       while (disp != last_disp);
3489
3490       dw2_asm_output_data_uleb128 (disp, "@TType base offset");
3491 #endif
3492     }
3493
3494   /* Indicate the format of the call-site offsets.  */
3495 #ifdef HAVE_AS_LEB128
3496   cs_format = DW_EH_PE_uleb128;
3497 #else
3498   cs_format = DW_EH_PE_udata4;
3499 #endif
3500   dw2_asm_output_data (1, cs_format, "call-site format (%s)",
3501                        eh_data_format_name (cs_format));
3502
3503 #ifdef HAVE_AS_LEB128
3504   ASM_GENERATE_INTERNAL_LABEL (cs_after_size_label, "LLSDACSB",
3505                                current_function_funcdef_no);
3506   ASM_GENERATE_INTERNAL_LABEL (cs_end_label, "LLSDACSE",
3507                                current_function_funcdef_no);
3508   dw2_asm_output_delta_uleb128 (cs_end_label, cs_after_size_label,
3509                                 "Call-site table length");
3510   ASM_OUTPUT_LABEL (asm_out_file, cs_after_size_label);
3511   if (USING_SJLJ_EXCEPTIONS)
3512     sjlj_output_call_site_table ();
3513   else
3514     dw2_output_call_site_table ();
3515   ASM_OUTPUT_LABEL (asm_out_file, cs_end_label);
3516 #else
3517   dw2_asm_output_data_uleb128 (call_site_len,"Call-site table length");
3518   if (USING_SJLJ_EXCEPTIONS)
3519     sjlj_output_call_site_table ();
3520   else
3521     dw2_output_call_site_table ();
3522 #endif
3523
3524   /* ??? Decode and interpret the data for flag_debug_asm.  */
3525   n = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data);
3526   for (i = 0; i < n; ++i)
3527     dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->action_record_data, i),
3528                          (i ? NULL : "Action record table"));
3529
3530   if (have_tt_data)
3531     assemble_align (tt_format_size * BITS_PER_UNIT);
3532
3533   i = VEC_length (tree, cfun->eh->ttype_data);
3534   while (i-- > 0)
3535     {
3536       tree type = VEC_index (tree, cfun->eh->ttype_data, i);
3537       rtx value;
3538
3539       if (type == NULL_TREE)
3540         value = const0_rtx;
3541       else
3542         {
3543           struct cgraph_varpool_node *node;
3544
3545           type = lookup_type_for_runtime (type);
3546           value = expand_expr (type, NULL_RTX, VOIDmode, EXPAND_INITIALIZER);
3547
3548           /* Let cgraph know that the rtti decl is used.  Not all of the
3549              paths below go through assemble_integer, which would take
3550              care of this for us.  */
3551           STRIP_NOPS (type);
3552           if (TREE_CODE (type) == ADDR_EXPR)
3553             {
3554               type = TREE_OPERAND (type, 0);
3555               if (TREE_CODE (type) == VAR_DECL)
3556                 {
3557                   node = cgraph_varpool_node (type);
3558                   if (node)
3559                     cgraph_varpool_mark_needed_node (node);
3560                 }
3561             }
3562           else
3563             gcc_assert (TREE_CODE (type) == INTEGER_CST);
3564         }
3565
3566       if (tt_format == DW_EH_PE_absptr || tt_format == DW_EH_PE_aligned)
3567         assemble_integer (value, tt_format_size,
3568                           tt_format_size * BITS_PER_UNIT, 1);
3569       else
3570         dw2_asm_output_encoded_addr_rtx (tt_format, value, NULL);
3571     }
3572
3573 #ifdef HAVE_AS_LEB128
3574   if (have_tt_data)
3575       ASM_OUTPUT_LABEL (asm_out_file, ttype_label);
3576 #endif
3577
3578   /* ??? Decode and interpret the data for flag_debug_asm.  */
3579   n = VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data);
3580   for (i = 0; i < n; ++i)
3581     dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->ehspec_data, i),
3582                          (i ? NULL : "Exception specification table"));
3583
3584   current_function_section (current_function_decl);
3585 }
3586
3587 void
3588 set_eh_throw_stmt_table (struct function *fun, struct htab *table)
3589 {
3590   fun->eh->throw_stmt_table = table;
3591 }
3592
3593 htab_t
3594 get_eh_throw_stmt_table (struct function *fun)
3595 {
3596   return fun->eh->throw_stmt_table;
3597 }
3598
3599 /* Dump EH information to OUT.  */
3600 void 
3601 dump_eh_tree (FILE *out, struct function *fun)
3602 {
3603   struct eh_region *i;
3604   int depth = 0;
3605   static const char * const type_name[] = {"unknown", "cleanup", "try", "catch",
3606                                            "allowed_exceptions", "must_not_throw",
3607                                            "throw"};
3608
3609   i = fun->eh->region_tree;
3610   if (! i)
3611     return;
3612
3613   fprintf (out, "Eh tree:\n");
3614   while (1)
3615     {
3616       fprintf (out, "  %*s %i %s", depth * 2, "",
3617                i->region_number, type_name [(int)i->type]);
3618       if (i->tree_label)
3619         {
3620           fprintf (out, " tree_label:");
3621           print_generic_expr (out, i->tree_label, 0);
3622         }
3623       fprintf (out, "\n");
3624       /* If there are sub-regions, process them.  */
3625       if (i->inner)
3626         i = i->inner, depth++;
3627       /* If there are peers, process them.  */
3628       else if (i->next_peer)
3629         i = i->next_peer;
3630       /* Otherwise, step back up the tree to the next peer.  */
3631       else
3632         {
3633           do {
3634             i = i->outer;
3635             depth--;
3636             if (i == NULL)
3637               return;
3638           } while (i->next_peer == NULL);
3639           i = i->next_peer;
3640         }
3641     }
3642 }
3643
3644 /* Verify some basic invariants on EH datastructures.  Could be extended to
3645    catch more.  */
3646 void 
3647 verify_eh_tree (struct function *fun)
3648 {
3649   struct eh_region *i, *outer = NULL;
3650   bool err = false;
3651   int nvisited = 0;
3652   int count = 0;
3653   int j;
3654   int depth = 0;
3655
3656   i = fun->eh->region_tree;
3657   if (! i)
3658     return;
3659   for (j = fun->eh->last_region_number; j > 0; --j)
3660     if (fun->eh->region_array[j])
3661       {
3662         count++;
3663         if (fun->eh->region_array[j]->region_number != j)
3664           {
3665             error ("region_array is corrupted for region %i", i->region_number);
3666             err = true;
3667           }
3668       }
3669
3670   while (1)
3671     {
3672       if (fun->eh->region_array[i->region_number] != i)
3673         {
3674           error ("region_array is corrupted for region %i", i->region_number);
3675           err = true;
3676         }
3677       if (i->outer != outer)
3678         {
3679           error ("outer block of region %i is wrong", i->region_number);
3680           err = true;
3681         }
3682       if (i->may_contain_throw && outer && !outer->may_contain_throw)
3683         {
3684           error ("region %i may contain throw and is contained in region that may not",
3685                  i->region_number);
3686           err = true;
3687         }
3688       if (depth < 0)
3689         {
3690           error ("negative nesting depth of region %i", i->region_number);
3691           err = true;
3692         }
3693       nvisited ++;
3694       /* If there are sub-regions, process them.  */
3695       if (i->inner)
3696         outer = i, i = i->inner, depth++;
3697       /* If there are peers, process them.  */
3698       else if (i->next_peer)
3699         i = i->next_peer;
3700       /* Otherwise, step back up the tree to the next peer.  */
3701       else
3702         {
3703           do {
3704             i = i->outer;
3705             depth--;
3706             if (i == NULL)
3707               {
3708                 if (depth != -1)
3709                   {
3710                     error ("Tree list ends on depth %i", depth + 1);
3711                     err = true;
3712                   }
3713                 if (count != nvisited)
3714                   {
3715                     error ("array does not match the region tree");
3716                     err = true;
3717                   }
3718                 if (err)
3719                   {
3720                     dump_eh_tree (stderr, fun);
3721                     internal_error ("verify_eh_tree failed.");
3722                   }
3723                 return;
3724               }
3725             outer = i->outer;
3726           } while (i->next_peer == NULL);
3727           i = i->next_peer;
3728         }
3729     }
3730 }
3731 #include "gt-except.h"