OSDN Git Service

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