OSDN Git Service

Thu Oct 29 14:10:22 EST 1998 Andrew MacLeod <amacleod@cygnus.com>
[pf3gnuchains/gcc-fork.git] / gcc / except.c
1 /* Implements exception handling.
2    Copyright (C) 1989, 92-97, 1998 Free Software Foundation, Inc.
3    Contributed by Mike Stump <mrs@cygnus.com>.
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22
23 /* An exception is an event that can be signaled from within a
24    function. This event can then be "caught" or "trapped" by the
25    callers of this function. This potentially allows program flow to
26    be transferred to any arbitrary code associated with a function call
27    several levels up the stack.
28
29    The intended use for this mechanism is for signaling "exceptional
30    events" in an out-of-band fashion, hence its name. The C++ language
31    (and many other OO-styled or functional languages) practically
32    requires such a mechanism, as otherwise it becomes very difficult
33    or even impossible to signal failure conditions in complex
34    situations.  The traditional C++ example is when an error occurs in
35    the process of constructing an object; without such a mechanism, it
36    is impossible to signal that the error occurs without adding global
37    state variables and error checks around every object construction.
38
39    The act of causing this event to occur is referred to as "throwing
40    an exception". (Alternate terms include "raising an exception" or
41    "signaling an exception".) The term "throw" is used because control
42    is returned to the callers of the function that is signaling the
43    exception, and thus there is the concept of "throwing" the
44    exception up the call stack.
45
46    There are two major codegen options for exception handling.  The
47    flag -fsjlj-exceptions can be used to select the setjmp/longjmp
48    approach, which is the default.  -fno-sjlj-exceptions can be used to
49    get the PC range table approach.  While this is a compile time
50    flag, an entire application must be compiled with the same codegen
51    option.  The first is a PC range table approach, the second is a
52    setjmp/longjmp based scheme.  We will first discuss the PC range
53    table approach, after that, we will discuss the setjmp/longjmp
54    based approach.
55
56    It is appropriate to speak of the "context of a throw". This
57    context refers to the address where the exception is thrown from,
58    and is used to determine which exception region will handle the
59    exception.
60
61    Regions of code within a function can be marked such that if it
62    contains the context of a throw, control will be passed to a
63    designated "exception handler". These areas are known as "exception
64    regions".  Exception regions cannot overlap, but they can be nested
65    to any arbitrary depth. Also, exception regions cannot cross
66    function boundaries.
67
68    Exception handlers can either be specified by the user (which we
69    will call a "user-defined handler") or generated by the compiler
70    (which we will designate as a "cleanup"). Cleanups are used to
71    perform tasks such as destruction of objects allocated on the
72    stack.
73
74    In the current implementation, cleanups are handled by allocating an
75    exception region for the area that the cleanup is designated for,
76    and the handler for the region performs the cleanup and then
77    rethrows the exception to the outer exception region. From the
78    standpoint of the current implementation, there is little
79    distinction made between a cleanup and a user-defined handler, and
80    the phrase "exception handler" can be used to refer to either one
81    equally well. (The section "Future Directions" below discusses how
82    this will change).
83
84    Each object file that is compiled with exception handling contains
85    a static array of exception handlers named __EXCEPTION_TABLE__.
86    Each entry contains the starting and ending addresses of the
87    exception region, and the address of the handler designated for
88    that region.
89
90    If the target does not use the DWARF 2 frame unwind information, at
91    program startup each object file invokes a function named
92    __register_exceptions with the address of its local
93    __EXCEPTION_TABLE__. __register_exceptions is defined in libgcc2.c, and
94    is responsible for recording all of the exception regions into one list
95    (which is kept in a static variable named exception_table_list).
96
97    On targets that support crtstuff.c, the unwind information
98    is stored in a section named .eh_frame and the information for the
99    entire shared object or program is registered with a call to
100    __register_frame_info.  On other targets, the information for each
101    translation unit is registered from the file generated by collect2.
102    __register_frame_info is defined in frame.c, and is responsible for
103    recording all of the unwind regions into one list (which is kept in a
104    static variable named unwind_table_list).
105
106    The function __throw is actually responsible for doing the
107    throw. On machines that have unwind info support, __throw is generated
108    by code in libgcc2.c, otherwise __throw is generated on a
109    per-object-file basis for each source file compiled with
110    -fexceptions by the C++ frontend.  Before __throw is invoked,
111    the current context of the throw needs to be placed in the global
112    variable __eh_pc.
113
114    __throw attempts to find the appropriate exception handler for the 
115    PC value stored in __eh_pc by calling __find_first_exception_table_match
116    (which is defined in libgcc2.c). If __find_first_exception_table_match
117    finds a relevant handler, __throw transfers control directly to it.
118
119    If a handler for the context being thrown from can't be found, __throw
120    walks (see Walking the stack below) the stack up the dynamic call chain to
121    continue searching for an appropriate exception handler based upon the
122    caller of the function it last sought a exception handler for.  It stops
123    then either an exception handler is found, or when the top of the
124    call chain is reached.
125
126    If no handler is found, an external library function named
127    __terminate is called.  If a handler is found, then we restart
128    our search for a handler at the end of the call chain, and repeat
129    the search process, but instead of just walking up the call chain,
130    we unwind the call chain as we walk up it.
131
132    Internal implementation details:
133
134    To associate a user-defined handler with a block of statements, the
135    function expand_start_try_stmts is used to mark the start of the
136    block of statements with which the handler is to be associated
137    (which is known as a "try block"). All statements that appear
138    afterwards will be associated with the try block.
139
140    A call to expand_start_all_catch marks the end of the try block,
141    and also marks the start of the "catch block" (the user-defined
142    handler) associated with the try block.
143
144    This user-defined handler will be invoked for *every* exception
145    thrown with the context of the try block. It is up to the handler
146    to decide whether or not it wishes to handle any given exception,
147    as there is currently no mechanism in this implementation for doing
148    this. (There are plans for conditionally processing an exception
149    based on its "type", which will provide a language-independent
150    mechanism).
151
152    If the handler chooses not to process the exception (perhaps by
153    looking at an "exception type" or some other additional data
154    supplied with the exception), it can fall through to the end of the
155    handler. expand_end_all_catch and expand_leftover_cleanups
156    add additional code to the end of each handler to take care of
157    rethrowing to the outer exception handler.
158
159    The handler also has the option to continue with "normal flow of
160    code", or in other words to resume executing at the statement
161    immediately after the end of the exception region. The variable
162    caught_return_label_stack contains a stack of labels, and jumping
163    to the topmost entry's label via expand_goto will resume normal
164    flow to the statement immediately after the end of the exception
165    region. If the handler falls through to the end, the exception will
166    be rethrown to the outer exception region.
167
168    The instructions for the catch block are kept as a separate
169    sequence, and will be emitted at the end of the function along with
170    the handlers specified via expand_eh_region_end. The end of the
171    catch block is marked with expand_end_all_catch.
172
173    Any data associated with the exception must currently be handled by
174    some external mechanism maintained in the frontend.  For example,
175    the C++ exception mechanism passes an arbitrary value along with
176    the exception, and this is handled in the C++ frontend by using a
177    global variable to hold the value. (This will be changing in the
178    future.)
179
180    The mechanism in C++ for handling data associated with the
181    exception is clearly not thread-safe. For a thread-based
182    environment, another mechanism must be used (possibly using a
183    per-thread allocation mechanism if the size of the area that needs
184    to be allocated isn't known at compile time.)
185
186    Internally-generated exception regions (cleanups) are marked by
187    calling expand_eh_region_start to mark the start of the region,
188    and expand_eh_region_end (handler) is used to both designate the
189    end of the region and to associate a specified handler/cleanup with
190    the region. The rtl code in HANDLER will be invoked whenever an
191    exception occurs in the region between the calls to
192    expand_eh_region_start and expand_eh_region_end. After HANDLER is
193    executed, additional code is emitted to handle rethrowing the
194    exception to the outer exception handler. The code for HANDLER will
195    be emitted at the end of the function.
196
197    TARGET_EXPRs can also be used to designate exception regions. A
198    TARGET_EXPR gives an unwind-protect style interface commonly used
199    in functional languages such as LISP. The associated expression is
200    evaluated, and whether or not it (or any of the functions that it
201    calls) throws an exception, the protect expression is always
202    invoked. This implementation takes care of the details of
203    associating an exception table entry with the expression and
204    generating the necessary code (it actually emits the protect
205    expression twice, once for normal flow and once for the exception
206    case). As for the other handlers, the code for the exception case
207    will be emitted at the end of the function.
208
209    Cleanups can also be specified by using add_partial_entry (handler)
210    and end_protect_partials. add_partial_entry creates the start of
211    a new exception region; HANDLER will be invoked if an exception is
212    thrown with the context of the region between the calls to
213    add_partial_entry and end_protect_partials. end_protect_partials is
214    used to mark the end of these regions. add_partial_entry can be
215    called as many times as needed before calling end_protect_partials.
216    However, end_protect_partials should only be invoked once for each
217    group of calls to add_partial_entry as the entries are queued
218    and all of the outstanding entries are processed simultaneously
219    when end_protect_partials is invoked. Similarly to the other
220    handlers, the code for HANDLER will be emitted at the end of the
221    function.
222
223    The generated RTL for an exception region includes
224    NOTE_INSN_EH_REGION_BEG and NOTE_INSN_EH_REGION_END notes that mark
225    the start and end of the exception region. A unique label is also
226    generated at the start of the exception region, which is available
227    by looking at the ehstack variable. The topmost entry corresponds
228    to the current region.
229
230    In the current implementation, an exception can only be thrown from
231    a function call (since the mechanism used to actually throw an
232    exception involves calling __throw).  If an exception region is
233    created but no function calls occur within that region, the region
234    can be safely optimized away (along with its exception handlers)
235    since no exceptions can ever be caught in that region.  This
236    optimization is performed unless -fasynchronous-exceptions is
237    given.  If the user wishes to throw from a signal handler, or other
238    asynchronous place, -fasynchronous-exceptions should be used when
239    compiling for maximally correct code, at the cost of additional
240    exception regions.  Using -fasynchronous-exceptions only produces
241    code that is reasonably safe in such situations, but a correct
242    program cannot rely upon this working.  It can be used in failsafe
243    code, where trying to continue on, and proceeding with potentially
244    incorrect results is better than halting the program.
245
246
247    Walking the stack:
248
249    The stack is walked by starting with a pointer to the current
250    frame, and finding the pointer to the callers frame.  The unwind info
251    tells __throw how to find it.
252
253    Unwinding the stack:
254
255    When we use the term unwinding the stack, we mean undoing the
256    effects of the function prologue in a controlled fashion so that we
257    still have the flow of control.  Otherwise, we could just return
258    (jump to the normal end of function epilogue).
259
260    This is done in __throw in libgcc2.c when we know that a handler exists
261    in a frame higher up the call stack than its immediate caller.
262
263    To unwind, we find the unwind data associated with the frame, if any.
264    If we don't find any, we call the library routine __terminate.  If we do
265    find it, we use the information to copy the saved register values from
266    that frame into the register save area in the frame for __throw, return
267    into a stub which updates the stack pointer, and jump to the handler.
268    The normal function epilogue for __throw handles restoring the saved
269    values into registers.
270
271    When unwinding, we use this method if we know it will
272    work (if DWARF2_UNWIND_INFO is defined).  Otherwise, we know that
273    an inline unwinder will have been emitted for any function that
274    __unwind_function cannot unwind.  The inline unwinder appears as a
275    normal exception handler for the entire function, for any function
276    that we know cannot be unwound by __unwind_function.  We inform the
277    compiler of whether a function can be unwound with
278    __unwind_function by having DOESNT_NEED_UNWINDER evaluate to true
279    when the unwinder isn't needed.  __unwind_function is used as an
280    action of last resort.  If no other method can be used for
281    unwinding, __unwind_function is used.  If it cannot unwind, it
282    should call __terminate.
283
284    By default, if the target-specific backend doesn't supply a definition
285    for __unwind_function and doesn't support DWARF2_UNWIND_INFO, inlined
286    unwinders will be used instead. The main tradeoff here is in text space
287    utilization.  Obviously, if inline unwinders have to be generated
288    repeatedly, this uses much more space than if a single routine is used.
289
290    However, it is simply not possible on some platforms to write a
291    generalized routine for doing stack unwinding without having some
292    form of additional data associated with each function.  The current
293    implementation can encode this data in the form of additional
294    machine instructions or as static data in tabular form.  The later
295    is called the unwind data.
296
297    The backend macro DOESNT_NEED_UNWINDER is used to conditionalize whether
298    or not per-function unwinders are needed. If DOESNT_NEED_UNWINDER is
299    defined and has a non-zero value, a per-function unwinder is not emitted
300    for the current function.  If the static unwind data is supported, then
301    a per-function unwinder is not emitted.
302
303    On some platforms it is possible that neither __unwind_function
304    nor inlined unwinders are available. For these platforms it is not
305    possible to throw through a function call, and abort will be
306    invoked instead of performing the throw. 
307
308    The reason the unwind data may be needed is that on some platforms
309    the order and types of data stored on the stack can vary depending
310    on the type of function, its arguments and returned values, and the
311    compilation options used (optimization versus non-optimization,
312    -fomit-frame-pointer, processor variations, etc).
313
314    Unfortunately, this also means that throwing through functions that
315    aren't compiled with exception handling support will still not be
316    possible on some platforms. This problem is currently being
317    investigated, but no solutions have been found that do not imply
318    some unacceptable performance penalties.
319
320    Future directions:
321
322    Currently __throw makes no differentiation between cleanups and
323    user-defined exception regions. While this makes the implementation
324    simple, it also implies that it is impossible to determine if a
325    user-defined exception handler exists for a given exception without
326    completely unwinding the stack in the process. This is undesirable
327    from the standpoint of debugging, as ideally it would be possible
328    to trap unhandled exceptions in the debugger before the process of
329    unwinding has even started.
330
331    This problem can be solved by marking user-defined handlers in a
332    special way (probably by adding additional bits to exception_table_list).
333    A two-pass scheme could then be used by __throw to iterate
334    through the table. The first pass would search for a relevant
335    user-defined handler for the current context of the throw, and if
336    one is found, the second pass would then invoke all needed cleanups
337    before jumping to the user-defined handler.
338
339    Many languages (including C++ and Ada) make execution of a
340    user-defined handler conditional on the "type" of the exception
341    thrown. (The type of the exception is actually the type of the data
342    that is thrown with the exception.) It will thus be necessary for
343    __throw to be able to determine if a given user-defined
344    exception handler will actually be executed, given the type of
345    exception.
346
347    One scheme is to add additional information to exception_table_list
348    as to the types of exceptions accepted by each handler. __throw
349    can do the type comparisons and then determine if the handler is
350    actually going to be executed.
351
352    There is currently no significant level of debugging support
353    available, other than to place a breakpoint on __throw. While
354    this is sufficient in most cases, it would be helpful to be able to
355    know where a given exception was going to be thrown to before it is
356    actually thrown, and to be able to choose between stopping before
357    every exception region (including cleanups), or just user-defined
358    exception regions. This should be possible to do in the two-pass
359    scheme by adding additional labels to __throw for appropriate
360    breakpoints, and additional debugger commands could be added to
361    query various state variables to determine what actions are to be
362    performed next.
363
364    Another major problem that is being worked on is the issue with stack
365    unwinding on various platforms. Currently the only platforms that have
366    support for the generation of a generic unwinder are the SPARC and MIPS.
367    All other ports require per-function unwinders, which produce large
368    amounts of code bloat.
369
370    For setjmp/longjmp based exception handling, some of the details
371    are as above, but there are some additional details.  This section
372    discusses the details.
373
374    We don't use NOTE_INSN_EH_REGION_{BEG,END} pairs.  We don't
375    optimize EH regions yet.  We don't have to worry about machine
376    specific issues with unwinding the stack, as we rely upon longjmp
377    for all the machine specific details.  There is no variable context
378    of a throw, just the one implied by the dynamic handler stack
379    pointed to by the dynamic handler chain.  There is no exception
380    table, and no calls to __register_exceptions.  __sjthrow is used
381    instead of __throw, and it works by using the dynamic handler
382    chain, and longjmp.  -fasynchronous-exceptions has no effect, as
383    the elimination of trivial exception regions is not yet performed.
384
385    A frontend can set protect_cleanup_actions_with_terminate when all
386    the cleanup actions should be protected with an EH region that
387    calls terminate when an unhandled exception is throw.  C++ does
388    this, Ada does not.  */
389
390
391 #include "config.h"
392 #include "defaults.h"
393 #include "eh-common.h"
394 #include "system.h"
395 #include "rtl.h"
396 #include "tree.h"
397 #include "flags.h"
398 #include "except.h"
399 #include "function.h"
400 #include "insn-flags.h"
401 #include "expr.h"
402 #include "insn-codes.h"
403 #include "regs.h"
404 #include "hard-reg-set.h"
405 #include "insn-config.h"
406 #include "recog.h"
407 #include "output.h"
408 #include "toplev.h"
409
410 /* One to use setjmp/longjmp method of generating code for exception
411    handling.  */
412
413 int exceptions_via_longjmp = 2;
414
415 /* One to enable asynchronous exception support.  */
416
417 int asynchronous_exceptions = 0;
418
419 /* One to protect cleanup actions with a handler that calls
420    __terminate, zero otherwise.  */
421
422 int protect_cleanup_actions_with_terminate;
423
424 /* A list of labels used for exception handlers.  Created by
425    find_exception_handler_labels for the optimization passes.  */
426
427 rtx exception_handler_labels;
428
429 /* The EH context.  Nonzero if the function has already
430    fetched a pointer to the EH context  for exception handling.  */
431
432 rtx current_function_ehc;
433
434 /* A stack used for keeping track of the currently active exception
435    handling region.  As each exception region is started, an entry
436    describing the region is pushed onto this stack.  The current
437    region can be found by looking at the top of the stack, and as we
438    exit regions, the corresponding entries are popped. 
439
440    Entries cannot overlap; they can be nested. So there is only one
441    entry at most that corresponds to the current instruction, and that
442    is the entry on the top of the stack.  */
443
444 static struct eh_stack ehstack;
445
446
447 /* This stack is used to represent what the current eh region is
448    for the catch blocks beings processed */
449
450 static struct eh_stack catchstack;
451
452 /* A queue used for tracking which exception regions have closed but
453    whose handlers have not yet been expanded. Regions are emitted in
454    groups in an attempt to improve paging performance.
455
456    As we exit a region, we enqueue a new entry. The entries are then
457    dequeued during expand_leftover_cleanups and expand_start_all_catch,
458
459    We should redo things so that we either take RTL for the handler,
460    or we expand the handler expressed as a tree immediately at region
461    end time.  */
462
463 static struct eh_queue ehqueue;
464
465 /* Insns for all of the exception handlers for the current function.
466    They are currently emitted by the frontend code.  */
467
468 rtx catch_clauses;
469
470 /* A TREE_CHAINed list of handlers for regions that are not yet
471    closed. The TREE_VALUE of each entry contains the handler for the
472    corresponding entry on the ehstack.  */
473
474 static tree protect_list;
475
476 /* Stacks to keep track of various labels.  */
477
478 /* Keeps track of the label to resume to should one want to resume
479    normal control flow out of a handler (instead of, say, returning to
480    the caller of the current function or exiting the program).  */
481
482 struct label_node *caught_return_label_stack = NULL;
483
484 /* Keeps track of the label used as the context of a throw to rethrow an
485    exception to the outer exception region.  */
486
487 struct label_node *outer_context_label_stack = NULL;
488
489 /* A random data area for the front end's own use.  */
490
491 struct label_node *false_label_stack = NULL;
492
493 /* Pseudos used to hold exception return data in the interim between
494    __builtin_eh_return and the end of the function.  */
495
496 static rtx eh_return_context;
497 static rtx eh_return_stack_adjust;
498 static rtx eh_return_handler;
499
500 /* Used to mark the eh return stub for flow, so that the Right Thing
501    happens with the values for the hardregs therin.  */
502
503 rtx eh_return_stub_label;
504
505 /* Prototypes for local functions.  */
506
507 static void push_eh_entry       PROTO((struct eh_stack *));
508 static struct eh_entry * pop_eh_entry           PROTO((struct eh_stack *));
509 static void enqueue_eh_entry    PROTO((struct eh_queue *, struct eh_entry *));
510 static struct eh_entry * dequeue_eh_entry       PROTO((struct eh_queue *));
511 static rtx call_get_eh_context  PROTO((void));
512 static void start_dynamic_cleanup               PROTO((tree, tree));
513 static void start_dynamic_handler               PROTO((void));
514 static void expand_rethrow      PROTO((rtx));
515 static void output_exception_table_entry        PROTO((FILE *, int));
516 static int can_throw            PROTO((rtx));
517 static rtx scan_region          PROTO((rtx, int, int *));
518 static void eh_regs             PROTO((rtx *, rtx *, rtx *, int));
519 static void set_insn_eh_region  PROTO((rtx *, int));
520 #ifdef DONT_USE_BUILTIN_SETJMP
521 static void jumpif_rtx          PROTO((rtx, rtx));
522 #endif
523
524 rtx expand_builtin_return_addr  PROTO((enum built_in_function, int, rtx));
525 \f
526 /* Various support routines to manipulate the various data structures
527    used by the exception handling code.  */
528
529 /* Push a label entry onto the given STACK.  */
530
531 void
532 push_label_entry (stack, rlabel, tlabel)
533      struct label_node **stack;
534      rtx rlabel;
535      tree tlabel;
536 {
537   struct label_node *newnode
538     = (struct label_node *) xmalloc (sizeof (struct label_node));
539
540   if (rlabel)
541     newnode->u.rlabel = rlabel;
542   else
543     newnode->u.tlabel = tlabel;
544   newnode->chain = *stack;
545   *stack = newnode;
546 }
547
548 /* Pop a label entry from the given STACK.  */
549
550 rtx
551 pop_label_entry (stack)
552      struct label_node **stack;
553 {
554   rtx label;
555   struct label_node *tempnode;
556
557   if (! *stack)
558     return NULL_RTX;
559
560   tempnode = *stack;
561   label = tempnode->u.rlabel;
562   *stack = (*stack)->chain;
563   free (tempnode);
564
565   return label;
566 }
567
568 /* Return the top element of the given STACK.  */
569
570 tree
571 top_label_entry (stack)
572      struct label_node **stack;
573 {
574   if (! *stack)
575     return NULL_TREE;
576
577   return (*stack)->u.tlabel;
578 }
579
580 /* get an exception label. These must be on the permanent obstack */
581
582 rtx
583 gen_exception_label ()
584 {
585   rtx lab;
586
587   push_obstacks_nochange ();
588   end_temporary_allocation ();
589   lab = gen_label_rtx ();
590   pop_obstacks ();
591   return lab;
592 }
593
594 /* Push a new eh_node entry onto STACK.  */
595
596 static void
597 push_eh_entry (stack)
598      struct eh_stack *stack;
599 {
600   struct eh_node *node = (struct eh_node *) xmalloc (sizeof (struct eh_node));
601   struct eh_entry *entry = (struct eh_entry *) xmalloc (sizeof (struct eh_entry));
602
603   entry->outer_context = gen_label_rtx ();
604   entry->finalization = NULL_TREE;
605   entry->label_used = 0;
606   entry->exception_handler_label = gen_exception_label ();
607   entry->false_label = NULL_RTX;
608
609   node->entry = entry;
610   node->chain = stack->top;
611   stack->top = node;
612 }
613
614 /* push an existing entry onto a stack. */
615 static void
616 push_entry (stack, entry)
617      struct eh_stack *stack;
618      struct eh_entry *entry;
619 {
620   struct eh_node *node = (struct eh_node *) xmalloc (sizeof (struct eh_node));
621   node->entry = entry;
622   node->chain = stack->top;
623   stack->top = node;
624 }
625
626 /* Pop an entry from the given STACK.  */
627
628 static struct eh_entry *
629 pop_eh_entry (stack)
630      struct eh_stack *stack;
631 {
632   struct eh_node *tempnode;
633   struct eh_entry *tempentry;
634   
635   tempnode = stack->top;
636   tempentry = tempnode->entry;
637   stack->top = stack->top->chain;
638   free (tempnode);
639
640   return tempentry;
641 }
642
643 /* Enqueue an ENTRY onto the given QUEUE.  */
644
645 static void
646 enqueue_eh_entry (queue, entry)
647      struct eh_queue *queue;
648      struct eh_entry *entry;
649 {
650   struct eh_node *node = (struct eh_node *) xmalloc (sizeof (struct eh_node));
651
652   node->entry = entry;
653   node->chain = NULL;
654
655   if (queue->head == NULL)
656     {
657       queue->head = node;
658     }
659   else
660     {
661       queue->tail->chain = node;
662     }
663   queue->tail = node;
664 }
665
666 /* Dequeue an entry from the given QUEUE.  */
667
668 static struct eh_entry *
669 dequeue_eh_entry (queue)
670      struct eh_queue *queue;
671 {
672   struct eh_node *tempnode;
673   struct eh_entry *tempentry;
674
675   if (queue->head == NULL)
676     return NULL;
677
678   tempnode = queue->head;
679   queue->head = queue->head->chain;
680
681   tempentry = tempnode->entry;
682   free (tempnode);
683
684   return tempentry;
685 }
686
687 static void
688 receive_exception_label (handler_label)
689      rtx handler_label;
690 {
691   emit_label (handler_label);
692   
693 #ifdef HAVE_exception_receiver
694   if (! exceptions_via_longjmp)
695     if (HAVE_exception_receiver)
696       emit_insn (gen_exception_receiver ());
697 #endif
698
699 #ifdef HAVE_nonlocal_goto_receiver
700   if (! exceptions_via_longjmp)
701     if (HAVE_nonlocal_goto_receiver)
702       emit_insn (gen_nonlocal_goto_receiver ());
703 #endif
704 }
705
706
707 struct func_eh_entry 
708 {
709   int range_number;   /* EH region number from EH NOTE insn's */
710   struct handler_info *handlers;
711 };
712
713
714 /* table of function eh regions */
715 static struct func_eh_entry *function_eh_regions = NULL;
716 static int num_func_eh_entries = 0;
717 static int current_func_eh_entry = 0;
718
719 #define SIZE_FUNC_EH(X)   (sizeof (struct func_eh_entry) * X)
720
721 /* Add a new eh_entry for this function, and base it off of the information
722    in the EH_ENTRY parameter. A NULL parameter is invalid. The number
723    returned is an number which uniquely identifies this exception range. */
724
725 int 
726 new_eh_region_entry (note_eh_region) 
727      int note_eh_region;
728 {
729   if (current_func_eh_entry == num_func_eh_entries) 
730     {
731       if (num_func_eh_entries == 0)
732         {
733           function_eh_regions = 
734                         (struct func_eh_entry *) malloc (SIZE_FUNC_EH (50));
735           num_func_eh_entries = 50;
736         }
737       else
738         {
739           num_func_eh_entries  = num_func_eh_entries * 3 / 2;
740           function_eh_regions = (struct func_eh_entry *) 
741             realloc (function_eh_regions, SIZE_FUNC_EH (num_func_eh_entries));
742         }
743     }
744   function_eh_regions[current_func_eh_entry].range_number = note_eh_region;
745   function_eh_regions[current_func_eh_entry].handlers = NULL;
746
747   return current_func_eh_entry++;
748 }
749
750 /* Add new handler information to an exception range. The  first parameter
751    specifies the range number (returned from new_eh_entry()). The second
752    parameter specifies the handler.  By default the handler is inserted at
753    the end of the list. A handler list may contain only ONE NULL_TREE
754    typeinfo entry. Regardless where it is positioned, a NULL_TREE entry
755    is always output as the LAST handler in the exception table for a region. */
756
757 void 
758 add_new_handler (region, newhandler)
759      int region;
760      struct handler_info *newhandler;
761 {
762   struct handler_info *last;
763
764   newhandler->next = NULL;
765   last = function_eh_regions[region].handlers;
766   if (last == NULL)
767     function_eh_regions[region].handlers = newhandler;
768   else 
769     {
770       for ( ; last->next != NULL; last = last->next)
771         ;
772       last->next = newhandler;
773     }
774 }
775
776 /* Remove a handler label. The handler label is being deleted, so all
777    regions which reference this handler should have it removed from their
778    list of possible handlers. Any region which has the final handler
779    removed can be deleted. */
780
781 void remove_handler (removing_label)
782      rtx removing_label;
783 {
784   struct handler_info *handler, *last;
785   int x;
786   for (x = 0 ; x < current_func_eh_entry; ++x)
787     {
788       last = NULL;
789       handler = function_eh_regions[x].handlers;
790       for ( ; handler; last = handler, handler = handler->next)
791         if (handler->handler_label == removing_label)
792           {
793             if (last)
794               {
795                 last->next = handler->next;
796                 handler = last;
797               }
798             else
799               function_eh_regions[x].handlers = handler->next;
800           }
801     }
802 }
803
804 /* This function will return a malloc'd pointer to an array of 
805    void pointer representing the runtime match values that 
806    currently exist in all regions. */
807
808 int 
809 find_all_handler_type_matches (array)
810   void ***array;
811 {
812   struct handler_info *handler, *last;
813   int x,y;
814   void *val;
815   void **ptr;
816   int max_ptr;
817   int n_ptr = 0;
818
819   *array = NULL;
820
821   if (!doing_eh (0) || ! flag_new_exceptions)
822     return 0;
823
824   max_ptr = 100;
825   ptr = (void **)malloc (max_ptr * sizeof (void *));
826
827   if (ptr == NULL)
828     return 0;
829
830   for (x = 0 ; x < current_func_eh_entry; x++)
831     {
832       last = NULL;
833       handler = function_eh_regions[x].handlers;
834       for ( ; handler; last = handler, handler = handler->next)
835         {
836           val = handler->type_info;
837           if (val != NULL && val != CATCH_ALL_TYPE)
838             {
839               /* See if this match value has already been found. */
840               for (y = 0; y < n_ptr; y++)
841                 if (ptr[y] == val)
842                   break;
843
844               /* If we break early, we already found this value. */
845               if (y < n_ptr)
846                 continue;
847
848               /* Do we need to allocate more space? */
849               if (n_ptr >= max_ptr) 
850                 {
851                   max_ptr += max_ptr / 2;
852                   ptr = (void **)realloc (ptr, max_ptr * sizeof (void *));
853                   if (ptr == NULL)
854                     return 0;
855                 }
856               ptr[n_ptr] = val;
857               n_ptr++;
858             }
859         }
860     }
861   *array = ptr;
862   return n_ptr;
863 }
864
865 /* Create a new handler structure initialized with the handler label and
866    typeinfo fields passed in. */
867
868 struct handler_info *
869 get_new_handler (handler, typeinfo)
870      rtx handler;
871      void *typeinfo;
872 {
873   struct handler_info* ptr;
874   ptr = (struct handler_info *) malloc (sizeof (struct handler_info));
875   ptr->handler_label = handler;
876   ptr->type_info = typeinfo;
877   ptr->next = NULL;
878
879   return ptr;
880 }
881
882
883
884 /* Find the index in function_eh_regions associated with a NOTE region. If
885    the region cannot be found, a -1 is returned. This should never happen! */
886
887 int 
888 find_func_region (insn_region)
889      int insn_region;
890 {
891   int x;
892   for (x = 0; x < current_func_eh_entry; x++)
893     if (function_eh_regions[x].range_number == insn_region)
894       return x;
895
896   return -1;
897 }
898
899 /* Get a pointer to the first handler in an exception region's list. */
900
901 struct handler_info *
902 get_first_handler (region)
903      int region;
904 {
905   return function_eh_regions[find_func_region (region)].handlers;
906 }
907
908 /* Clean out the function_eh_region table and free all memory */
909
910 static void
911 clear_function_eh_region ()
912 {
913   int x;
914   struct handler_info *ptr, *next;
915   for (x = 0; x < current_func_eh_entry; x++)
916     for (ptr = function_eh_regions[x].handlers; ptr != NULL; ptr = next)
917       {
918         next = ptr->next;
919         free (ptr);
920       }
921   free (function_eh_regions);
922   num_func_eh_entries  = 0;
923   current_func_eh_entry = 0;
924 }
925
926 /* Make a duplicate of an exception region by copying all the handlers
927    for an exception region. Return the new handler index. */
928
929 int 
930 duplicate_handlers (old_note_eh_region, new_note_eh_region)
931      int old_note_eh_region, new_note_eh_region;
932 {
933   struct handler_info *ptr, *new_ptr;
934   int new_region, region;
935
936   region = find_func_region (old_note_eh_region);
937   if (region == -1)
938     error ("Cannot duplicate non-existant exception region.");
939
940   if (find_func_region (new_note_eh_region) != -1)
941     error ("Cannot duplicate EH region because new note region already exists");
942
943   new_region = new_eh_region_entry (new_note_eh_region);
944   ptr = function_eh_regions[region].handlers;
945
946   for ( ; ptr; ptr = ptr->next) 
947     {
948       new_ptr = get_new_handler (ptr->handler_label, ptr->type_info);
949       add_new_handler (new_region, new_ptr);
950     }
951
952   return new_region;
953 }
954
955 \f
956 /* Routine to see if exception handling is turned on.
957    DO_WARN is non-zero if we want to inform the user that exception
958    handling is turned off. 
959
960    This is used to ensure that -fexceptions has been specified if the
961    compiler tries to use any exception-specific functions.  */
962
963 int
964 doing_eh (do_warn)
965      int do_warn;
966 {
967   if (! flag_exceptions)
968     {
969       static int warned = 0;
970       if (! warned && do_warn)
971         {
972           error ("exception handling disabled, use -fexceptions to enable");
973           warned = 1;
974         }
975       return 0;
976     }
977   return 1;
978 }
979
980 /* Given a return address in ADDR, determine the address we should use
981    to find the corresponding EH region.  */
982
983 rtx
984 eh_outer_context (addr)
985      rtx addr;
986 {
987   /* First mask out any unwanted bits.  */
988 #ifdef MASK_RETURN_ADDR
989   expand_and (addr, MASK_RETURN_ADDR, addr);
990 #endif
991
992   /* Then adjust to find the real return address.  */
993 #if defined (RETURN_ADDR_OFFSET)
994   addr = plus_constant (addr, RETURN_ADDR_OFFSET);
995 #endif
996
997   return addr;
998 }
999
1000 /* Start a new exception region for a region of code that has a
1001    cleanup action and push the HANDLER for the region onto
1002    protect_list. All of the regions created with add_partial_entry
1003    will be ended when end_protect_partials is invoked.  */
1004
1005 void
1006 add_partial_entry (handler)
1007      tree handler;
1008 {
1009   expand_eh_region_start ();
1010
1011   /* Make sure the entry is on the correct obstack.  */
1012   push_obstacks_nochange ();
1013   resume_temporary_allocation ();
1014
1015   /* Because this is a cleanup action, we may have to protect the handler
1016      with __terminate.  */
1017   handler = protect_with_terminate (handler);
1018
1019   protect_list = tree_cons (NULL_TREE, handler, protect_list);
1020   pop_obstacks ();
1021 }
1022
1023 /* Emit code to get EH context to current function.  */
1024
1025 static rtx
1026 call_get_eh_context ()
1027 {
1028   static tree fn;
1029   tree expr;
1030
1031   if (fn == NULL_TREE)
1032     {
1033       tree fntype;
1034       fn = get_identifier ("__get_eh_context");
1035       push_obstacks_nochange ();
1036       end_temporary_allocation ();
1037       fntype = build_pointer_type (build_pointer_type
1038                                    (build_pointer_type (void_type_node)));
1039       fntype = build_function_type (fntype, NULL_TREE);
1040       fn = build_decl (FUNCTION_DECL, fn, fntype);
1041       DECL_EXTERNAL (fn) = 1;
1042       TREE_PUBLIC (fn) = 1;
1043       DECL_ARTIFICIAL (fn) = 1;
1044       TREE_READONLY (fn) = 1;
1045       make_decl_rtl (fn, NULL_PTR, 1);
1046       assemble_external (fn);
1047       pop_obstacks ();
1048     }
1049
1050   expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
1051   expr = build (CALL_EXPR, TREE_TYPE (TREE_TYPE (fn)),
1052                 expr, NULL_TREE, NULL_TREE);
1053   TREE_SIDE_EFFECTS (expr) = 1;
1054
1055   return copy_to_reg (expand_expr (expr, NULL_RTX, VOIDmode, 0));
1056 }
1057
1058 /* Get a reference to the EH context.
1059    We will only generate a register for the current function EH context here,
1060    and emit a USE insn to mark that this is a EH context register.
1061
1062    Later, emit_eh_context will emit needed call to __get_eh_context
1063    in libgcc2, and copy the value to the register we have generated. */
1064
1065 rtx
1066 get_eh_context ()
1067 {
1068   if (current_function_ehc == 0)
1069     {
1070       rtx insn;
1071
1072       current_function_ehc = gen_reg_rtx (Pmode);
1073       
1074       insn = gen_rtx_USE (GET_MODE (current_function_ehc),
1075                           current_function_ehc);
1076       insn = emit_insn_before (insn, get_first_nonparm_insn ());
1077
1078       REG_NOTES (insn)
1079         = gen_rtx_EXPR_LIST (REG_EH_CONTEXT, current_function_ehc,
1080                              REG_NOTES (insn));
1081     }
1082   return current_function_ehc;
1083 }
1084      
1085 /* Get a reference to the dynamic handler chain.  It points to the
1086    pointer to the next element in the dynamic handler chain.  It ends
1087    when there are no more elements in the dynamic handler chain, when
1088    the value is &top_elt from libgcc2.c.  Immediately after the
1089    pointer, is an area suitable for setjmp/longjmp when
1090    DONT_USE_BUILTIN_SETJMP is defined, and an area suitable for
1091    __builtin_setjmp/__builtin_longjmp when DONT_USE_BUILTIN_SETJMP
1092    isn't defined. */
1093
1094 rtx
1095 get_dynamic_handler_chain ()
1096 {
1097   rtx ehc, dhc, result;
1098
1099   ehc = get_eh_context ();
1100
1101   /* This is the offset of dynamic_handler_chain in the eh_context struct
1102      declared in eh-common.h. If its location is change, change this offset */
1103   dhc = plus_constant (ehc, POINTER_SIZE / BITS_PER_UNIT);
1104
1105   result = copy_to_reg (dhc);
1106
1107   /* We don't want a copy of the dcc, but rather, the single dcc.  */
1108   return gen_rtx_MEM (Pmode, result);
1109 }
1110
1111 /* Get a reference to the dynamic cleanup chain.  It points to the
1112    pointer to the next element in the dynamic cleanup chain.
1113    Immediately after the pointer, are two Pmode variables, one for a
1114    pointer to a function that performs the cleanup action, and the
1115    second, the argument to pass to that function.  */
1116
1117 rtx
1118 get_dynamic_cleanup_chain ()
1119 {
1120   rtx dhc, dcc, result;
1121
1122   dhc = get_dynamic_handler_chain ();
1123   dcc = plus_constant (dhc, POINTER_SIZE / BITS_PER_UNIT);
1124
1125   result = copy_to_reg (dcc);
1126
1127   /* We don't want a copy of the dcc, but rather, the single dcc.  */
1128   return gen_rtx_MEM (Pmode, result);
1129 }
1130
1131 #ifdef DONT_USE_BUILTIN_SETJMP
1132 /* Generate code to evaluate X and jump to LABEL if the value is nonzero.
1133    LABEL is an rtx of code CODE_LABEL, in this function.  */
1134
1135 static void
1136 jumpif_rtx (x, label)
1137      rtx x;
1138      rtx label;
1139 {
1140   jumpif (make_tree (type_for_mode (GET_MODE (x), 0), x), label);
1141 }
1142 #endif
1143
1144 /* Start a dynamic cleanup on the EH runtime dynamic cleanup stack.
1145    We just need to create an element for the cleanup list, and push it
1146    into the chain.
1147
1148    A dynamic cleanup is a cleanup action implied by the presence of an
1149    element on the EH runtime dynamic cleanup stack that is to be
1150    performed when an exception is thrown.  The cleanup action is
1151    performed by __sjthrow when an exception is thrown.  Only certain
1152    actions can be optimized into dynamic cleanup actions.  For the
1153    restrictions on what actions can be performed using this routine,
1154    see expand_eh_region_start_tree.  */
1155
1156 static void
1157 start_dynamic_cleanup (func, arg)
1158      tree func;
1159      tree arg;
1160 {
1161   rtx dcc;
1162   rtx new_func, new_arg;
1163   rtx x, buf;
1164   int size;
1165
1166   /* We allocate enough room for a pointer to the function, and
1167      one argument.  */
1168   size = 2;
1169
1170   /* XXX, FIXME: The stack space allocated this way is too long lived,
1171      but there is no allocation routine that allocates at the level of
1172      the last binding contour.  */
1173   buf = assign_stack_local (BLKmode,
1174                             GET_MODE_SIZE (Pmode)*(size+1),
1175                             0);
1176
1177   buf = change_address (buf, Pmode, NULL_RTX);
1178
1179   /* Store dcc into the first word of the newly allocated buffer.  */
1180
1181   dcc = get_dynamic_cleanup_chain ();
1182   emit_move_insn (buf, dcc);
1183
1184   /* Store func and arg into the cleanup list element.  */
1185
1186   new_func = gen_rtx_MEM (Pmode, plus_constant (XEXP (buf, 0),
1187                                                 GET_MODE_SIZE (Pmode)));
1188   new_arg = gen_rtx_MEM (Pmode, plus_constant (XEXP (buf, 0),
1189                                                GET_MODE_SIZE (Pmode)*2));
1190   x = expand_expr (func, new_func, Pmode, 0);
1191   if (x != new_func)
1192     emit_move_insn (new_func, x);
1193
1194   x = expand_expr (arg, new_arg, Pmode, 0);
1195   if (x != new_arg)
1196     emit_move_insn (new_arg, x);
1197
1198   /* Update the cleanup chain.  */
1199
1200   emit_move_insn (dcc, XEXP (buf, 0));
1201 }
1202
1203 /* Emit RTL to start a dynamic handler on the EH runtime dynamic
1204    handler stack.  This should only be used by expand_eh_region_start
1205    or expand_eh_region_start_tree.  */
1206
1207 static void
1208 start_dynamic_handler ()
1209 {
1210   rtx dhc, dcc;
1211   rtx x, arg, buf;
1212   int size;
1213
1214 #ifndef DONT_USE_BUILTIN_SETJMP
1215   /* The number of Pmode words for the setjmp buffer, when using the
1216      builtin setjmp/longjmp, see expand_builtin, case
1217      BUILT_IN_LONGJMP.  */
1218   size = 5;
1219 #else
1220 #ifdef JMP_BUF_SIZE
1221   size = JMP_BUF_SIZE;
1222 #else
1223   /* Should be large enough for most systems, if it is not,
1224      JMP_BUF_SIZE should be defined with the proper value.  It will
1225      also tend to be larger than necessary for most systems, a more
1226      optimal port will define JMP_BUF_SIZE.  */
1227   size = FIRST_PSEUDO_REGISTER+2;
1228 #endif
1229 #endif
1230   /* XXX, FIXME: The stack space allocated this way is too long lived,
1231      but there is no allocation routine that allocates at the level of
1232      the last binding contour.  */
1233   arg = assign_stack_local (BLKmode,
1234                             GET_MODE_SIZE (Pmode)*(size+1),
1235                             0);
1236
1237   arg = change_address (arg, Pmode, NULL_RTX);
1238
1239   /* Store dhc into the first word of the newly allocated buffer.  */
1240
1241   dhc = get_dynamic_handler_chain ();
1242   dcc = gen_rtx_MEM (Pmode, plus_constant (XEXP (arg, 0),
1243                                            GET_MODE_SIZE (Pmode)));
1244   emit_move_insn (arg, dhc);
1245
1246   /* Zero out the start of the cleanup chain.  */
1247   emit_move_insn (dcc, const0_rtx);
1248
1249   /* The jmpbuf starts two words into the area allocated.  */
1250   buf = plus_constant (XEXP (arg, 0), GET_MODE_SIZE (Pmode)*2);
1251
1252 #ifdef DONT_USE_BUILTIN_SETJMP
1253   x = emit_library_call_value (setjmp_libfunc, NULL_RTX, 1, SImode, 1,
1254                                buf, Pmode);
1255   /* If we come back here for a catch, transfer control to the handler.  */
1256   jumpif_rtx (x, ehstack.top->entry->exception_handler_label);
1257 #else
1258   {
1259     /* A label to continue execution for the no exception case.  */
1260     rtx noex = gen_label_rtx();
1261     x = expand_builtin_setjmp (buf, NULL_RTX, noex,
1262                                ehstack.top->entry->exception_handler_label);
1263     emit_label (noex);
1264   }
1265 #endif
1266
1267   /* We are committed to this, so update the handler chain.  */
1268
1269   emit_move_insn (dhc, XEXP (arg, 0));
1270 }
1271
1272 /* Start an exception handling region for the given cleanup action.
1273    All instructions emitted after this point are considered to be part
1274    of the region until expand_eh_region_end is invoked.  CLEANUP is
1275    the cleanup action to perform.  The return value is true if the
1276    exception region was optimized away.  If that case,
1277    expand_eh_region_end does not need to be called for this cleanup,
1278    nor should it be.
1279
1280    This routine notices one particular common case in C++ code
1281    generation, and optimizes it so as to not need the exception
1282    region.  It works by creating a dynamic cleanup action, instead of
1283    a using an exception region.  */
1284
1285 int
1286 expand_eh_region_start_tree (decl, cleanup)
1287      tree decl;
1288      tree cleanup;
1289 {
1290   /* This is the old code.  */
1291   if (! doing_eh (0))
1292     return 0;
1293
1294   /* The optimization only applies to actions protected with
1295      terminate, and only applies if we are using the setjmp/longjmp
1296      codegen method.  */
1297   if (exceptions_via_longjmp
1298       && protect_cleanup_actions_with_terminate)
1299     {
1300       tree func, arg;
1301       tree args;
1302
1303       /* Ignore any UNSAVE_EXPR.  */
1304       if (TREE_CODE (cleanup) == UNSAVE_EXPR)
1305         cleanup = TREE_OPERAND (cleanup, 0);
1306       
1307       /* Further, it only applies if the action is a call, if there
1308          are 2 arguments, and if the second argument is 2.  */
1309
1310       if (TREE_CODE (cleanup) == CALL_EXPR
1311           && (args = TREE_OPERAND (cleanup, 1))
1312           && (func = TREE_OPERAND (cleanup, 0))
1313           && (arg = TREE_VALUE (args))
1314           && (args = TREE_CHAIN (args))
1315
1316           /* is the second argument 2?  */
1317           && TREE_CODE (TREE_VALUE (args)) == INTEGER_CST
1318           && TREE_INT_CST_LOW (TREE_VALUE (args)) == 2
1319           && TREE_INT_CST_HIGH (TREE_VALUE (args)) == 0
1320
1321           /* Make sure there are no other arguments.  */
1322           && TREE_CHAIN (args) == NULL_TREE)
1323         {
1324           /* Arrange for returns and gotos to pop the entry we make on the
1325              dynamic cleanup stack.  */
1326           expand_dcc_cleanup (decl);
1327           start_dynamic_cleanup (func, arg);
1328           return 1;
1329         }
1330     }
1331
1332   expand_eh_region_start_for_decl (decl);
1333   ehstack.top->entry->finalization = cleanup;
1334
1335   return 0;
1336 }
1337
1338 /* Just like expand_eh_region_start, except if a cleanup action is
1339    entered on the cleanup chain, the TREE_PURPOSE of the element put
1340    on the chain is DECL.  DECL should be the associated VAR_DECL, if
1341    any, otherwise it should be NULL_TREE.  */
1342
1343 void
1344 expand_eh_region_start_for_decl (decl)
1345      tree decl;
1346 {
1347   rtx note;
1348
1349   /* This is the old code.  */
1350   if (! doing_eh (0))
1351     return;
1352
1353   if (exceptions_via_longjmp)
1354     {
1355       /* We need a new block to record the start and end of the
1356          dynamic handler chain.  We could always do this, but we
1357          really want to permit jumping into such a block, and we want
1358          to avoid any errors or performance impact in the SJ EH code
1359          for now.  */
1360       expand_start_bindings (0);
1361
1362       /* But we don't need or want a new temporary level.  */
1363       pop_temp_slots ();
1364
1365       /* Mark this block as created by expand_eh_region_start.  This
1366          is so that we can pop the block with expand_end_bindings
1367          automatically.  */
1368       mark_block_as_eh_region ();
1369
1370       /* Arrange for returns and gotos to pop the entry we make on the
1371          dynamic handler stack.  */
1372       expand_dhc_cleanup (decl);
1373     }
1374
1375   push_eh_entry (&ehstack);
1376   note = emit_note (NULL_PTR, NOTE_INSN_EH_REGION_BEG);
1377   NOTE_BLOCK_NUMBER (note)
1378     = CODE_LABEL_NUMBER (ehstack.top->entry->exception_handler_label);
1379   if (exceptions_via_longjmp)
1380     start_dynamic_handler ();
1381 }
1382
1383 /* Start an exception handling region.  All instructions emitted after
1384    this point are considered to be part of the region until
1385    expand_eh_region_end is invoked.  */
1386
1387 void
1388 expand_eh_region_start ()
1389 {
1390   expand_eh_region_start_for_decl (NULL_TREE);
1391 }
1392
1393 /* End an exception handling region.  The information about the region
1394    is found on the top of ehstack.
1395
1396    HANDLER is either the cleanup for the exception region, or if we're
1397    marking the end of a try block, HANDLER is integer_zero_node.
1398
1399    HANDLER will be transformed to rtl when expand_leftover_cleanups
1400    is invoked.  */
1401
1402 void
1403 expand_eh_region_end (handler)
1404      tree handler;
1405 {
1406   struct eh_entry *entry;
1407   rtx note;
1408
1409   if (! doing_eh (0))
1410     return;
1411
1412   entry = pop_eh_entry (&ehstack);
1413
1414   note = emit_note (NULL_PTR, NOTE_INSN_EH_REGION_END);
1415   NOTE_BLOCK_NUMBER (note)
1416     = CODE_LABEL_NUMBER (entry->exception_handler_label);
1417   if (exceptions_via_longjmp == 0
1418       /* We share outer_context between regions; only emit it once.  */
1419       && INSN_UID (entry->outer_context) == 0)
1420     {
1421       rtx label;
1422
1423       label = gen_label_rtx ();
1424       emit_jump (label);
1425
1426       /* Emit a label marking the end of this exception region that
1427          is used for rethrowing into the outer context.  */
1428       emit_label (entry->outer_context);
1429       expand_internal_throw ();
1430
1431       emit_label (label);
1432     }
1433
1434   entry->finalization = handler;
1435
1436   /* create region entry in final exception table */
1437   new_eh_region_entry (NOTE_BLOCK_NUMBER (note));
1438
1439   enqueue_eh_entry (&ehqueue, entry);
1440
1441   /* If we have already started ending the bindings, don't recurse.
1442      This only happens when exceptions_via_longjmp is true.  */
1443   if (is_eh_region ())
1444     {
1445       /* Because we don't need or want a new temporary level and
1446          because we didn't create one in expand_eh_region_start,
1447          create a fake one now to avoid removing one in
1448          expand_end_bindings.  */
1449       push_temp_slots ();
1450
1451       mark_block_as_not_eh_region ();
1452
1453       /* Maybe do this to prevent jumping in and so on...  */
1454       expand_end_bindings (NULL_TREE, 0, 0);
1455     }
1456 }
1457
1458 /* End the EH region for a goto fixup.  We only need them in the region-based
1459    EH scheme.  */
1460
1461 void
1462 expand_fixup_region_start ()
1463 {
1464   if (! doing_eh (0) || exceptions_via_longjmp)
1465     return;
1466
1467   expand_eh_region_start ();
1468 }
1469
1470 /* End the EH region for a goto fixup.  CLEANUP is the cleanup we just
1471    expanded; to avoid running it twice if it throws, we look through the
1472    ehqueue for a matching region and rethrow from its outer_context.  */
1473
1474 void
1475 expand_fixup_region_end (cleanup)
1476      tree cleanup;
1477 {
1478   struct eh_node *node;
1479
1480   if (! doing_eh (0) || exceptions_via_longjmp)
1481     return;
1482
1483   for (node = ehstack.top; node && node->entry->finalization != cleanup; )
1484     node = node->chain;
1485   if (node == 0)
1486     for (node = ehqueue.head; node && node->entry->finalization != cleanup; )
1487       node = node->chain;
1488   if (node == 0)
1489     abort ();
1490
1491   ehstack.top->entry->outer_context = node->entry->outer_context;
1492
1493   /* Just rethrow.  size_zero_node is just a NOP.  */
1494   expand_eh_region_end (size_zero_node);
1495 }
1496
1497 /* If we are using the setjmp/longjmp EH codegen method, we emit a
1498    call to __sjthrow.
1499
1500    Otherwise, we emit a call to __throw and note that we threw
1501    something, so we know we need to generate the necessary code for
1502    __throw.
1503
1504    Before invoking throw, the __eh_pc variable must have been set up
1505    to contain the PC being thrown from. This address is used by
1506    __throw to determine which exception region (if any) is
1507    responsible for handling the exception.  */
1508
1509 void
1510 emit_throw ()
1511 {
1512   if (exceptions_via_longjmp)
1513     {
1514       emit_library_call (sjthrow_libfunc, 0, VOIDmode, 0);
1515     }
1516   else
1517     {
1518 #ifdef JUMP_TO_THROW
1519       emit_indirect_jump (throw_libfunc);
1520 #else
1521       emit_library_call (throw_libfunc, 0, VOIDmode, 0);
1522 #endif
1523     }
1524   emit_barrier ();
1525 }
1526
1527 /* Throw the current exception.  If appropriate, this is done by jumping
1528    to the next handler.  */
1529
1530 void
1531 expand_internal_throw ()
1532 {
1533   emit_throw ();
1534 }
1535
1536 /* Called from expand_exception_blocks and expand_end_catch_block to
1537    emit any pending handlers/cleanups queued from expand_eh_region_end.  */
1538
1539 void
1540 expand_leftover_cleanups ()
1541 {
1542   struct eh_entry *entry;
1543
1544   while ((entry = dequeue_eh_entry (&ehqueue)) != 0)
1545     {
1546       rtx prev;
1547
1548       /* A leftover try block. Shouldn't be one here.  */
1549       if (entry->finalization == integer_zero_node)
1550         abort ();
1551
1552       /* Output the label for the start of the exception handler.  */
1553
1554       receive_exception_label (entry->exception_handler_label);
1555
1556       /* register a handler for this cleanup region */
1557       add_new_handler (
1558         find_func_region (CODE_LABEL_NUMBER (entry->exception_handler_label)), 
1559         get_new_handler (entry->exception_handler_label, NULL));
1560
1561       /* And now generate the insns for the handler.  */
1562       expand_expr (entry->finalization, const0_rtx, VOIDmode, 0);
1563
1564       prev = get_last_insn ();
1565       if (prev == NULL || GET_CODE (prev) != BARRIER)
1566         /* Emit code to throw to the outer context if we fall off
1567            the end of the handler.  */
1568         expand_rethrow (entry->outer_context);
1569
1570       do_pending_stack_adjust ();
1571       free (entry);
1572     }
1573 }
1574
1575 /* Called at the start of a block of try statements.  */
1576 void
1577 expand_start_try_stmts ()
1578 {
1579   if (! doing_eh (1))
1580     return;
1581
1582   expand_eh_region_start ();
1583 }
1584
1585 /* Called to begin a catch clause. The parameter is the object which
1586    will be passed to the runtime type check routine. */
1587 void 
1588 start_catch_handler (rtime)
1589      tree rtime;
1590 {
1591   rtx handler_label;
1592   int insn_region_num;
1593   int eh_region_entry;
1594
1595   if (! doing_eh (1))
1596     return;
1597
1598   handler_label = catchstack.top->entry->exception_handler_label;
1599   insn_region_num = CODE_LABEL_NUMBER (handler_label);
1600   eh_region_entry = find_func_region (insn_region_num);
1601
1602   /* If we've already issued this label, pick a new one */
1603   if (catchstack.top->entry->label_used)
1604     handler_label = gen_exception_label ();
1605   else
1606     catchstack.top->entry->label_used = 1;
1607
1608   receive_exception_label (handler_label);
1609
1610   add_new_handler (eh_region_entry, get_new_handler (handler_label, rtime));
1611
1612   if (flag_new_exceptions && ! exceptions_via_longjmp)
1613     return;
1614
1615   /* Under the old mechanism, as well as setjmp/longjmp, we need to
1616      issue code to compare 'rtime' to the value in eh_info, via the
1617      matching function in eh_info. If its is false, we branch around
1618      the handler we are about to issue. */
1619
1620   if (rtime != NULL_TREE && rtime != CATCH_ALL_TYPE)
1621     {
1622       rtx call_rtx, rtime_address;
1623
1624       if (catchstack.top->entry->false_label != NULL_RTX)
1625         fatal ("Compiler Bug: Never issued previous false_label");
1626       catchstack.top->entry->false_label = gen_exception_label ();
1627
1628       rtime_address = expand_expr (rtime, NULL_RTX, Pmode, EXPAND_INITIALIZER);
1629       rtime_address = force_reg (Pmode, rtime_address);
1630
1631       /* Now issue the call, and branch around handler if needed */
1632       call_rtx = emit_library_call_value (eh_rtime_match_libfunc, NULL_RTX, 
1633                                           0, SImode, 1, rtime_address, Pmode);
1634
1635       /* Did the function return true? */
1636       emit_cmp_insn (call_rtx, const0_rtx, EQ, NULL_RTX,
1637                                                 GET_MODE (call_rtx), 0 ,0);
1638       emit_jump_insn (gen_beq (catchstack.top->entry->false_label));
1639     }
1640 }
1641
1642 /* Called to end a catch clause. If we aren't using the new exception
1643    model tabel mechanism, we need to issue the branch-around label
1644    for the end of the catch block. */
1645
1646 void 
1647 end_catch_handler ()
1648 {
1649   if (! doing_eh (1) || (flag_new_exceptions && ! exceptions_via_longjmp))
1650     return;
1651   
1652   /* A NULL label implies the catch clause was a catch all or cleanup */
1653   if (catchstack.top->entry->false_label == NULL_RTX)
1654     return;
1655
1656   emit_label (catchstack.top->entry->false_label);
1657   catchstack.top->entry->false_label = NULL_RTX;
1658 }
1659
1660 /* Generate RTL for the start of a group of catch clauses. 
1661
1662    It is responsible for starting a new instruction sequence for the
1663    instructions in the catch block, and expanding the handlers for the
1664    internally-generated exception regions nested within the try block
1665    corresponding to this catch block.  */
1666
1667 void
1668 expand_start_all_catch ()
1669 {
1670   struct eh_entry *entry;
1671   tree label;
1672   rtx outer_context;
1673
1674   if (! doing_eh (1))
1675     return;
1676
1677   outer_context = ehstack.top->entry->outer_context;
1678
1679   /* End the try block.  */
1680   expand_eh_region_end (integer_zero_node);
1681
1682   emit_line_note (input_filename, lineno);
1683   label = build_decl (LABEL_DECL, NULL_TREE, NULL_TREE);
1684
1685   /* The label for the exception handling block that we will save.
1686      This is Lresume in the documentation.  */
1687   expand_label (label);
1688   
1689   /* Push the label that points to where normal flow is resumed onto
1690      the top of the label stack.  */
1691   push_label_entry (&caught_return_label_stack, NULL_RTX, label);
1692
1693   /* Start a new sequence for all the catch blocks.  We will add this
1694      to the global sequence catch_clauses when we have completed all
1695      the handlers in this handler-seq.  */
1696   start_sequence ();
1697
1698   entry = dequeue_eh_entry (&ehqueue);
1699   for ( ; entry->finalization != integer_zero_node;
1700                                  entry = dequeue_eh_entry (&ehqueue))
1701     {
1702       rtx prev;
1703
1704       /* Emit the label for the cleanup handler for this region, and
1705          expand the code for the handler. 
1706
1707          Note that a catch region is handled as a side-effect here;
1708          for a try block, entry->finalization will contain
1709          integer_zero_node, so no code will be generated in the
1710          expand_expr call below. But, the label for the handler will
1711          still be emitted, so any code emitted after this point will
1712          end up being the handler.  */
1713       
1714       receive_exception_label (entry->exception_handler_label);
1715
1716       /* register a handler for this cleanup region */
1717       add_new_handler (
1718         find_func_region (CODE_LABEL_NUMBER (entry->exception_handler_label)), 
1719         get_new_handler (entry->exception_handler_label, NULL));
1720
1721       /* And now generate the insns for the cleanup handler.  */
1722       expand_expr (entry->finalization, const0_rtx, VOIDmode, 0);
1723
1724       prev = get_last_insn ();
1725       if (prev == NULL || GET_CODE (prev) != BARRIER)
1726         /* Code to throw out to outer context when we fall off end
1727            of the handler. We can't do this here for catch blocks,
1728            so it's done in expand_end_all_catch instead.  */
1729         expand_rethrow (entry->outer_context);
1730
1731       do_pending_stack_adjust ();
1732       free (entry);
1733     }
1734
1735   /* At this point, all the cleanups are done, and the ehqueue now has
1736      the current exception region at its head. We dequeue it, and put it
1737      on the catch stack. */
1738
1739     push_entry (&catchstack, entry);
1740
1741   /* If we are not doing setjmp/longjmp EH, because we are reordered
1742      out of line, we arrange to rethrow in the outer context.  We need to
1743      do this because we are not physically within the region, if any, that
1744      logically contains this catch block.  */
1745   if (! exceptions_via_longjmp)
1746     {
1747       expand_eh_region_start ();
1748       ehstack.top->entry->outer_context = outer_context;
1749     }
1750
1751 }
1752
1753 /* Finish up the catch block.  At this point all the insns for the
1754    catch clauses have already been generated, so we only have to add
1755    them to the catch_clauses list. We also want to make sure that if
1756    we fall off the end of the catch clauses that we rethrow to the
1757    outer EH region.  */
1758
1759 void
1760 expand_end_all_catch ()
1761 {
1762   rtx new_catch_clause, outer_context = NULL_RTX;
1763   struct eh_entry *entry;
1764
1765   if (! doing_eh (1))
1766     return;
1767
1768   /* Dequeue the current catch clause region. */
1769   entry = pop_eh_entry (&catchstack);
1770   free (entry);
1771
1772   if (! exceptions_via_longjmp)
1773     {
1774       outer_context = ehstack.top->entry->outer_context;
1775
1776       /* Finish the rethrow region.  size_zero_node is just a NOP.  */
1777       expand_eh_region_end (size_zero_node);
1778     }
1779
1780   /* Code to throw out to outer context, if we fall off end of catch
1781      handlers.  This is rethrow (Lresume, same id, same obj) in the
1782      documentation. We use Lresume because we know that it will throw
1783      to the correct context.
1784
1785      In other words, if the catch handler doesn't exit or return, we
1786      do a "throw" (using the address of Lresume as the point being
1787      thrown from) so that the outer EH region can then try to process
1788      the exception.  */
1789   expand_rethrow (outer_context);
1790
1791   /* Now we have the complete catch sequence.  */
1792   new_catch_clause = get_insns ();
1793   end_sequence ();
1794   
1795   /* This level of catch blocks is done, so set up the successful
1796      catch jump label for the next layer of catch blocks.  */
1797   pop_label_entry (&caught_return_label_stack);
1798   pop_label_entry (&outer_context_label_stack);
1799
1800   /* Add the new sequence of catches to the main one for this function.  */
1801   push_to_sequence (catch_clauses);
1802   emit_insns (new_catch_clause);
1803   catch_clauses = get_insns ();
1804   end_sequence ();
1805   
1806   /* Here we fall through into the continuation code.  */
1807 }
1808
1809 /* Rethrow from the outer context LABEL.  */
1810
1811 static void
1812 expand_rethrow (label)
1813      rtx label;
1814 {
1815   if (exceptions_via_longjmp)
1816     emit_throw ();
1817   else
1818     emit_jump (label);
1819 }
1820
1821 /* End all the pending exception regions on protect_list. The handlers
1822    will be emitted when expand_leftover_cleanups is invoked.  */
1823
1824 void
1825 end_protect_partials ()
1826 {
1827   while (protect_list)
1828     {
1829       expand_eh_region_end (TREE_VALUE (protect_list));
1830       protect_list = TREE_CHAIN (protect_list);
1831     }
1832 }
1833
1834 /* Arrange for __terminate to be called if there is an unhandled throw
1835    from within E.  */
1836
1837 tree
1838 protect_with_terminate (e)
1839      tree e;
1840 {
1841   /* We only need to do this when using setjmp/longjmp EH and the
1842      language requires it, as otherwise we protect all of the handlers
1843      at once, if we need to.  */
1844   if (exceptions_via_longjmp && protect_cleanup_actions_with_terminate)
1845     {
1846       tree handler, result;
1847
1848       /* All cleanups must be on the function_obstack.  */
1849       push_obstacks_nochange ();
1850       resume_temporary_allocation ();
1851
1852       handler = make_node (RTL_EXPR);
1853       TREE_TYPE (handler) = void_type_node;
1854       RTL_EXPR_RTL (handler) = const0_rtx;
1855       TREE_SIDE_EFFECTS (handler) = 1;
1856       start_sequence_for_rtl_expr (handler);
1857
1858       emit_library_call (terminate_libfunc, 0, VOIDmode, 0);
1859       emit_barrier ();
1860
1861       RTL_EXPR_SEQUENCE (handler) = get_insns ();
1862       end_sequence ();
1863         
1864       result = build (TRY_CATCH_EXPR, TREE_TYPE (e), e, handler);
1865       TREE_SIDE_EFFECTS (result) = TREE_SIDE_EFFECTS (e);
1866       TREE_THIS_VOLATILE (result) = TREE_THIS_VOLATILE (e);
1867       TREE_READONLY (result) = TREE_READONLY (e);
1868
1869       pop_obstacks ();
1870
1871       e = result;
1872     }
1873
1874   return e;
1875 }
1876 \f
1877 /* The exception table that we build that is used for looking up and
1878    dispatching exceptions, the current number of entries, and its
1879    maximum size before we have to extend it. 
1880
1881    The number in eh_table is the code label number of the exception
1882    handler for the region. This is added by add_eh_table_entry and
1883    used by output_exception_table_entry.  */
1884
1885 static int *eh_table = NULL;
1886 static int eh_table_size = 0;
1887 static int eh_table_max_size = 0;
1888
1889 /* Note the need for an exception table entry for region N.  If we
1890    don't need to output an explicit exception table, avoid all of the
1891    extra work.
1892
1893    Called from final_scan_insn when a NOTE_INSN_EH_REGION_BEG is seen.
1894    (Or NOTE_INSN_EH_REGION_END sometimes)
1895    N is the NOTE_BLOCK_NUMBER of the note, which comes from the code
1896    label number of the exception handler for the region.  */
1897
1898 void
1899 add_eh_table_entry (n)
1900      int n;
1901 {
1902 #ifndef OMIT_EH_TABLE
1903   if (eh_table_size >= eh_table_max_size)
1904     {
1905       if (eh_table)
1906         {
1907           eh_table_max_size += eh_table_max_size>>1;
1908
1909           if (eh_table_max_size < 0)
1910             abort ();
1911
1912           eh_table = (int *) xrealloc (eh_table,
1913                                        eh_table_max_size * sizeof (int));
1914         }
1915       else
1916         {
1917           eh_table_max_size = 252;
1918           eh_table = (int *) xmalloc (eh_table_max_size * sizeof (int));
1919         }
1920     }
1921   eh_table[eh_table_size++] = n;
1922 #endif
1923 }
1924
1925 /* Return a non-zero value if we need to output an exception table.
1926
1927    On some platforms, we don't have to output a table explicitly.
1928    This routine doesn't mean we don't have one.  */
1929
1930 int
1931 exception_table_p ()
1932 {
1933   if (eh_table)
1934     return 1;
1935
1936   return 0;
1937 }
1938
1939 /* Output the entry of the exception table corresponding to the
1940    exception region numbered N to file FILE. 
1941
1942    N is the code label number corresponding to the handler of the
1943    region.  */
1944
1945 static void
1946 output_exception_table_entry (file, n)
1947      FILE *file;
1948      int n;
1949 {
1950   char buf[256];
1951   rtx sym;
1952   struct handler_info *handler;
1953
1954   handler = get_first_handler (n);
1955
1956   for ( ; handler != NULL; handler = handler->next)
1957     {
1958       ASM_GENERATE_INTERNAL_LABEL (buf, "LEHB", n);
1959       sym = gen_rtx_SYMBOL_REF (Pmode, buf);
1960       assemble_integer (sym, POINTER_SIZE / BITS_PER_UNIT, 1);
1961
1962       ASM_GENERATE_INTERNAL_LABEL (buf, "LEHE", n);
1963       sym = gen_rtx_SYMBOL_REF (Pmode, buf);
1964       assemble_integer (sym, POINTER_SIZE / BITS_PER_UNIT, 1);
1965       
1966       assemble_integer (handler->handler_label, 
1967                                          POINTER_SIZE / BITS_PER_UNIT, 1);
1968
1969       if (flag_new_exceptions)
1970         {
1971           if (handler->type_info == NULL)
1972             assemble_integer (const0_rtx, POINTER_SIZE / BITS_PER_UNIT, 1);
1973           else
1974             if (handler->type_info == CATCH_ALL_TYPE)
1975               assemble_integer (GEN_INT (CATCH_ALL_TYPE), 
1976                                              POINTER_SIZE / BITS_PER_UNIT, 1);
1977             else
1978               output_constant ((tree)(handler->type_info), 
1979                                                 POINTER_SIZE / BITS_PER_UNIT);
1980         }
1981       putc ('\n', file);                /* blank line */
1982       /* We only output the first label under the old scheme */
1983       if (! flag_new_exceptions)
1984         break;
1985     }
1986 }
1987
1988 /* Output the exception table if we have and need one.  */
1989
1990 static short language_code = 0;
1991 static short version_code = 0; 
1992
1993 /* This routine will set the language code for exceptions. */
1994 void
1995 set_exception_lang_code (code)
1996      int code;
1997 {
1998   language_code = code;
1999 }
2000
2001 /* This routine will set the language version code for exceptions. */
2002 void
2003 set_exception_version_code (code)
2004      short code;
2005 {
2006   version_code = code;
2007 }
2008
2009
2010 void
2011 output_exception_table ()
2012 {
2013   int i;
2014   extern FILE *asm_out_file;
2015
2016   if (! doing_eh (0) || ! eh_table)
2017     return;
2018
2019   exception_section ();
2020
2021   /* Beginning marker for table.  */
2022   assemble_align (GET_MODE_ALIGNMENT (ptr_mode));
2023   assemble_label ("__EXCEPTION_TABLE__");
2024
2025   if (flag_new_exceptions)
2026     {
2027       assemble_integer (GEN_INT (NEW_EH_RUNTIME), 
2028                                         POINTER_SIZE / BITS_PER_UNIT, 1);
2029       assemble_integer (GEN_INT (language_code), 2 , 1); 
2030       assemble_integer (GEN_INT (version_code), 2 , 1);
2031
2032       /* Add enough padding to make sure table aligns on a pointer boundry. */
2033       i = GET_MODE_ALIGNMENT (ptr_mode) / BITS_PER_UNIT - 4;
2034       for ( ; i < 0; i = i + GET_MODE_ALIGNMENT (ptr_mode) / BITS_PER_UNIT)
2035         ;
2036       if (i != 0)
2037         assemble_integer (const0_rtx, i , 1);
2038     }
2039
2040   for (i = 0; i < eh_table_size; ++i)
2041     output_exception_table_entry (asm_out_file, eh_table[i]);
2042
2043   free (eh_table);
2044   clear_function_eh_region ();
2045
2046   /* Ending marker for table.  */
2047   assemble_integer (constm1_rtx, POINTER_SIZE / BITS_PER_UNIT, 1);
2048
2049   /* for binary compatability, the old __throw checked the second
2050      position for a -1, so we should output at least 2 -1's */
2051   if (! flag_new_exceptions)
2052     assemble_integer (constm1_rtx, POINTER_SIZE / BITS_PER_UNIT, 1);
2053
2054   putc ('\n', asm_out_file);            /* blank line */
2055 }
2056 \f
2057 /* Emit code to get EH context.
2058    
2059    We have to scan thru the code to find possible EH context registers.
2060    Inlined functions may use it too, and thus we'll have to be able
2061    to change them too.
2062
2063    This is done only if using exceptions_via_longjmp. */
2064
2065 void
2066 emit_eh_context ()
2067 {
2068   rtx insn;
2069   rtx ehc = 0;
2070
2071   if (! doing_eh (0))
2072     return;
2073
2074   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2075     if (GET_CODE (insn) == INSN
2076         && GET_CODE (PATTERN (insn)) == USE)
2077       {
2078         rtx reg = find_reg_note (insn, REG_EH_CONTEXT, 0);
2079         if (reg)
2080           {
2081             rtx insns;
2082             
2083             start_sequence ();
2084
2085             /* If this is the first use insn, emit the call here.  This
2086                will always be at the top of our function, because if
2087                expand_inline_function notices a REG_EH_CONTEXT note, it
2088                adds a use insn to this function as well.  */
2089             if (ehc == 0)
2090               ehc = call_get_eh_context ();
2091
2092             emit_move_insn (XEXP (reg, 0), ehc);
2093             insns = get_insns ();
2094             end_sequence ();
2095
2096             emit_insns_before (insns, insn);
2097
2098             /* At -O0, we must make the context register stay alive so
2099                that the stupid.c register allocator doesn't get confused. */
2100             if (obey_regdecls != 0)
2101               {
2102                 insns = gen_rtx_USE (GET_MODE (XEXP (reg,0)), XEXP (reg,0));
2103                 emit_insn_before (insns, get_last_insn ());
2104               }
2105           }
2106       }
2107 }
2108
2109 /* Scan the current insns and build a list of handler labels. The
2110    resulting list is placed in the global variable exception_handler_labels.
2111
2112    It is called after the last exception handling region is added to
2113    the current function (when the rtl is almost all built for the
2114    current function) and before the jump optimization pass.  */
2115
2116 void
2117 find_exception_handler_labels ()
2118 {
2119   rtx insn;
2120
2121   exception_handler_labels = NULL_RTX;
2122
2123   /* If we aren't doing exception handling, there isn't much to check.  */
2124   if (! doing_eh (0))
2125     return;
2126
2127   /* For each start of a region, add its label to the list.  */
2128
2129   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2130     {
2131       struct handler_info* ptr;
2132       if (GET_CODE (insn) == NOTE
2133           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG)
2134         {
2135           ptr = get_first_handler (NOTE_BLOCK_NUMBER (insn));
2136           for ( ; ptr; ptr = ptr->next) 
2137             {
2138               /* make sure label isn't in the list already */
2139               rtx x;
2140               for (x = exception_handler_labels; x; x = XEXP (x, 1))
2141                 if (XEXP (x, 0) == ptr->handler_label)
2142                   break;
2143               if (! x)
2144                 exception_handler_labels = gen_rtx_EXPR_LIST (VOIDmode,
2145                                ptr->handler_label, exception_handler_labels);
2146             }
2147         }
2148     }
2149 }
2150
2151 /* Return a value of 1 if the parameter label number is an exception handler
2152    label. Return 0 otherwise. */
2153
2154 int
2155 is_exception_handler_label (lab)
2156      int lab;
2157 {
2158   rtx x;
2159   for (x = exception_handler_labels ; x ; x = XEXP (x, 1))
2160     if (lab == CODE_LABEL_NUMBER (XEXP (x, 0)))
2161       return 1;
2162   return 0;
2163 }
2164
2165 /* Perform sanity checking on the exception_handler_labels list.
2166
2167    Can be called after find_exception_handler_labels is called to
2168    build the list of exception handlers for the current function and
2169    before we finish processing the current function.  */
2170
2171 void
2172 check_exception_handler_labels ()
2173 {
2174   rtx insn, insn2;
2175
2176   /* If we aren't doing exception handling, there isn't much to check.  */
2177   if (! doing_eh (0))
2178     return;
2179
2180   /* Make sure there is no more than 1 copy of a label */
2181   for (insn = exception_handler_labels; insn; insn = XEXP (insn, 1))
2182     {
2183       int count = 0;
2184       for (insn2 = exception_handler_labels; insn2; insn2 = XEXP (insn2, 1))
2185         if (XEXP (insn, 0) == XEXP (insn2, 0))
2186           count++;
2187       if (count != 1)
2188        warning ("Counted %d copies of EH region %d in list.\n", count, 
2189                                         CODE_LABEL_NUMBER (insn));
2190     }
2191
2192 }
2193 \f
2194 /* This group of functions initializes the exception handling data
2195    structures at the start of the compilation, initializes the data
2196    structures at the start of a function, and saves and restores the
2197    exception handling data structures for the start/end of a nested
2198    function.  */
2199
2200 /* Toplevel initialization for EH things.  */ 
2201
2202 void
2203 init_eh ()
2204 {
2205 }
2206
2207 /* Initialize the per-function EH information.  */
2208
2209 void
2210 init_eh_for_function ()
2211 {
2212   ehstack.top = 0;
2213   catchstack.top = 0;
2214   ehqueue.head = ehqueue.tail = 0;
2215   catch_clauses = NULL_RTX;
2216   false_label_stack = 0;
2217   caught_return_label_stack = 0;
2218   protect_list = NULL_TREE;
2219   current_function_ehc = NULL_RTX;
2220   eh_return_context = NULL_RTX;
2221   eh_return_stack_adjust = NULL_RTX;
2222   eh_return_handler = NULL_RTX;
2223   eh_return_stub_label = NULL_RTX;
2224 }
2225
2226 /* Save some of the per-function EH info into the save area denoted by
2227    P. 
2228
2229    This is currently called from save_stmt_status.  */
2230
2231 void
2232 save_eh_status (p)
2233      struct function *p;
2234 {
2235   if (p == NULL)
2236     abort ();
2237
2238   p->ehstack = ehstack;
2239   p->catchstack = catchstack;
2240   p->ehqueue = ehqueue;
2241   p->catch_clauses = catch_clauses;
2242   p->false_label_stack = false_label_stack;
2243   p->caught_return_label_stack = caught_return_label_stack;
2244   p->protect_list = protect_list;
2245   p->ehc = current_function_ehc;
2246
2247   init_eh_for_function ();
2248 }
2249
2250 /* Restore the per-function EH info saved into the area denoted by P.  
2251
2252    This is currently called from restore_stmt_status.  */
2253
2254 void
2255 restore_eh_status (p)
2256      struct function *p;
2257 {
2258   if (p == NULL)
2259     abort ();
2260
2261   protect_list = p->protect_list;
2262   caught_return_label_stack = p->caught_return_label_stack;
2263   false_label_stack = p->false_label_stack;
2264   catch_clauses = p->catch_clauses;
2265   ehqueue = p->ehqueue;
2266   ehstack = p->ehstack;
2267   catchstack = p->catchstack;
2268   current_function_ehc = p->ehc;
2269 }
2270 \f
2271 /* This section is for the exception handling specific optimization
2272    pass.  First are the internal routines, and then the main
2273    optimization pass.  */
2274
2275 /* Determine if the given INSN can throw an exception.  */
2276
2277 static int
2278 can_throw (insn)
2279      rtx insn;
2280 {
2281   /* Calls can always potentially throw exceptions.  */
2282   if (GET_CODE (insn) == CALL_INSN)
2283     return 1;
2284
2285   if (asynchronous_exceptions)
2286     {
2287       /* If we wanted asynchronous exceptions, then everything but NOTEs
2288          and CODE_LABELs could throw.  */
2289       if (GET_CODE (insn) != NOTE && GET_CODE (insn) != CODE_LABEL)
2290         return 1;
2291     }
2292
2293   return 0;
2294 }
2295
2296 /* Scan a exception region looking for the matching end and then
2297    remove it if possible. INSN is the start of the region, N is the
2298    region number, and DELETE_OUTER is to note if anything in this
2299    region can throw.
2300
2301    Regions are removed if they cannot possibly catch an exception.
2302    This is determined by invoking can_throw on each insn within the
2303    region; if can_throw returns true for any of the instructions, the
2304    region can catch an exception, since there is an insn within the
2305    region that is capable of throwing an exception.
2306
2307    Returns the NOTE_INSN_EH_REGION_END corresponding to this region, or
2308    calls abort if it can't find one.
2309
2310    Can abort if INSN is not a NOTE_INSN_EH_REGION_BEGIN, or if N doesn't
2311    correspond to the region number, or if DELETE_OUTER is NULL.  */
2312
2313 static rtx
2314 scan_region (insn, n, delete_outer)
2315      rtx insn;
2316      int n;
2317      int *delete_outer;
2318 {
2319   rtx start = insn;
2320
2321   /* Assume we can delete the region.  */
2322   int delete = 1;
2323
2324   if (insn == NULL_RTX
2325       || GET_CODE (insn) != NOTE
2326       || NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_BEG
2327       || NOTE_BLOCK_NUMBER (insn) != n
2328       || delete_outer == NULL)
2329     abort ();
2330
2331   insn = NEXT_INSN (insn);
2332
2333   /* Look for the matching end.  */
2334   while (! (GET_CODE (insn) == NOTE
2335             && NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END))
2336     {
2337       /* If anything can throw, we can't remove the region.  */
2338       if (delete && can_throw (insn))
2339         {
2340           delete = 0;
2341         }
2342
2343       /* Watch out for and handle nested regions.  */
2344       if (GET_CODE (insn) == NOTE
2345           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG)
2346         {
2347           insn = scan_region (insn, NOTE_BLOCK_NUMBER (insn), &delete);
2348         }
2349
2350       insn = NEXT_INSN (insn);
2351     }
2352
2353   /* The _BEG/_END NOTEs must match and nest.  */
2354   if (NOTE_BLOCK_NUMBER (insn) != n)
2355     abort ();
2356
2357   /* If anything in this exception region can throw, we can throw.  */
2358   if (! delete)
2359     *delete_outer = 0;
2360   else
2361     {
2362       /* Delete the start and end of the region.  */
2363       delete_insn (start);
2364       delete_insn (insn);
2365
2366 /* We no longer removed labels here, since flow will now remove any
2367    handler which cannot be called any more. */
2368    
2369 #if 0
2370       /* Only do this part if we have built the exception handler
2371          labels.  */
2372       if (exception_handler_labels)
2373         {
2374           rtx x, *prev = &exception_handler_labels;
2375
2376           /* Find it in the list of handlers.  */
2377           for (x = exception_handler_labels; x; x = XEXP (x, 1))
2378             {
2379               rtx label = XEXP (x, 0);
2380               if (CODE_LABEL_NUMBER (label) == n)
2381                 {
2382                   /* If we are the last reference to the handler,
2383                      delete it.  */
2384                   if (--LABEL_NUSES (label) == 0)
2385                     delete_insn (label);
2386
2387                   if (optimize)
2388                     {
2389                       /* Remove it from the list of exception handler
2390                          labels, if we are optimizing.  If we are not, then
2391                          leave it in the list, as we are not really going to
2392                          remove the region.  */
2393                       *prev = XEXP (x, 1);
2394                       XEXP (x, 1) = 0;
2395                       XEXP (x, 0) = 0;
2396                     }
2397
2398                   break;
2399                 }
2400               prev = &XEXP (x, 1);
2401             }
2402         }
2403 #endif
2404     }
2405   return insn;
2406 }
2407
2408 /* Perform various interesting optimizations for exception handling
2409    code.
2410
2411    We look for empty exception regions and make them go (away). The
2412    jump optimization code will remove the handler if nothing else uses
2413    it.  */
2414
2415 void
2416 exception_optimize ()
2417 {
2418   rtx insn;
2419   int n;
2420
2421   /* Remove empty regions.  */
2422   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2423     {
2424       if (GET_CODE (insn) == NOTE
2425           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG)
2426         {
2427           /* Since scan_region will return the NOTE_INSN_EH_REGION_END
2428              insn, we will indirectly skip through all the insns
2429              inbetween. We are also guaranteed that the value of insn
2430              returned will be valid, as otherwise scan_region won't
2431              return.  */
2432           insn = scan_region (insn, NOTE_BLOCK_NUMBER (insn), &n);
2433         }
2434     }
2435 }
2436 \f
2437 /* Various hooks for the DWARF 2 __throw routine.  */
2438
2439 /* Do any necessary initialization to access arbitrary stack frames.
2440    On the SPARC, this means flushing the register windows.  */
2441
2442 void
2443 expand_builtin_unwind_init ()
2444 {
2445   /* Set this so all the registers get saved in our frame; we need to be
2446      able to copy the saved values for any registers from frames we unwind. */
2447   current_function_has_nonlocal_label = 1;
2448
2449 #ifdef SETUP_FRAME_ADDRESSES
2450   SETUP_FRAME_ADDRESSES ();
2451 #endif
2452 }
2453
2454 /* Given a value extracted from the return address register or stack slot,
2455    return the actual address encoded in that value.  */
2456
2457 rtx
2458 expand_builtin_extract_return_addr (addr_tree)
2459      tree addr_tree;
2460 {
2461   rtx addr = expand_expr (addr_tree, NULL_RTX, Pmode, 0);
2462   return eh_outer_context (addr);
2463 }
2464
2465 /* Given an actual address in addr_tree, do any necessary encoding
2466    and return the value to be stored in the return address register or
2467    stack slot so the epilogue will return to that address.  */
2468
2469 rtx
2470 expand_builtin_frob_return_addr (addr_tree)
2471      tree addr_tree;
2472 {
2473   rtx addr = expand_expr (addr_tree, NULL_RTX, Pmode, 0);
2474 #ifdef RETURN_ADDR_OFFSET
2475   addr = plus_constant (addr, -RETURN_ADDR_OFFSET);
2476 #endif
2477   return addr;
2478 }
2479
2480 /* Choose three registers for communication between the main body of
2481    __throw and the epilogue (or eh stub) and the exception handler. 
2482    We must do this with hard registers because the epilogue itself
2483    will be generated after reload, at which point we may not reference
2484    pseudos at all.
2485
2486    The first passes the exception context to the handler.  For this
2487    we use the return value register for a void*.
2488
2489    The second holds the stack pointer value to be restored.  For
2490    this we use the static chain register if it exists and is different
2491    from the previous, otherwise some arbitrary call-clobbered register.
2492
2493    The third holds the address of the handler itself.  Here we use
2494    some arbitrary call-clobbered register.  */
2495
2496 static void
2497 eh_regs (pcontext, psp, pra, outgoing)
2498      rtx *pcontext, *psp, *pra;
2499      int outgoing;
2500 {
2501   rtx rcontext, rsp, rra;
2502   int i;
2503
2504 #ifdef FUNCTION_OUTGOING_VALUE
2505   if (outgoing)
2506     rcontext = FUNCTION_OUTGOING_VALUE (build_pointer_type (void_type_node),
2507                                         current_function_decl);
2508   else
2509 #endif
2510     rcontext = FUNCTION_VALUE (build_pointer_type (void_type_node),
2511                                current_function_decl);
2512
2513 #ifdef STATIC_CHAIN_REGNUM
2514   if (outgoing)
2515     rsp = static_chain_incoming_rtx;
2516   else
2517     rsp = static_chain_rtx;
2518   if (REGNO (rsp) == REGNO (rcontext))
2519 #endif /* STATIC_CHAIN_REGNUM */
2520     rsp = NULL_RTX;
2521
2522   if (rsp == NULL_RTX)
2523     {
2524       for (i = 0; i < FIRST_PSEUDO_REGISTER; ++i)
2525         if (call_used_regs[i] && ! fixed_regs[i] && i != REGNO (rcontext))
2526           break;
2527       if (i == FIRST_PSEUDO_REGISTER)
2528         abort();
2529
2530       rsp = gen_rtx_REG (Pmode, i);
2531     }
2532
2533   for (i = 0; i < FIRST_PSEUDO_REGISTER; ++i)
2534     if (call_used_regs[i] && ! fixed_regs[i]
2535         && i != REGNO (rcontext) && i != REGNO (rsp))
2536       break;
2537   if (i == FIRST_PSEUDO_REGISTER)
2538     abort();
2539
2540   rra = gen_rtx_REG (Pmode, i);
2541
2542   *pcontext = rcontext;
2543   *psp = rsp;
2544   *pra = rra;
2545 }
2546
2547 /* Retrieve the register which contains the pointer to the eh_context
2548    structure set the __throw. */
2549
2550 rtx 
2551 get_reg_for_handler ()
2552 {
2553   rtx reg1;
2554   reg1 = FUNCTION_VALUE (build_pointer_type (void_type_node),
2555                            current_function_decl);
2556   return reg1;
2557 }
2558
2559 /* Set up the epilogue with the magic bits we'll need to return to the
2560    exception handler.  */
2561
2562 void
2563 expand_builtin_eh_return (context, stack, handler)
2564     tree context, stack, handler;
2565 {
2566   if (eh_return_context)
2567     error("Duplicate call to __builtin_eh_return");
2568
2569   eh_return_context
2570     = copy_to_reg (expand_expr (context, NULL_RTX, VOIDmode, 0));
2571   eh_return_stack_adjust
2572     = copy_to_reg (expand_expr (stack, NULL_RTX, VOIDmode, 0));
2573   eh_return_handler
2574     = copy_to_reg (expand_expr (handler, NULL_RTX, VOIDmode, 0));
2575 }
2576
2577 void
2578 expand_eh_return ()
2579 {
2580   rtx reg1, reg2, reg3;
2581   rtx stub_start, after_stub;
2582   rtx ra, tmp;
2583
2584   if (!eh_return_context)
2585     return;
2586
2587   eh_regs (&reg1, &reg2, &reg3, 1);
2588   emit_move_insn (reg1, eh_return_context);
2589   emit_move_insn (reg2, eh_return_stack_adjust);
2590   emit_move_insn (reg3, eh_return_handler);
2591
2592   /* Talk directly to the target's epilogue code when possible.  */
2593
2594 #ifdef HAVE_eh_epilogue
2595   if (HAVE_eh_epilogue)
2596     {
2597       emit_insn (gen_eh_epilogue (reg1, reg2, reg3));
2598       return;
2599     }
2600 #endif
2601
2602   /* Otherwise, use the same stub technique we had before.  */
2603
2604   eh_return_stub_label = stub_start = gen_label_rtx ();
2605   after_stub = gen_label_rtx ();
2606
2607   /* Set the return address to the stub label.  */
2608
2609   ra = expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
2610                                    0, hard_frame_pointer_rtx);
2611   if (GET_CODE (ra) == REG && REGNO (ra) >= FIRST_PSEUDO_REGISTER)
2612     abort();
2613
2614   tmp = memory_address (Pmode, gen_rtx_LABEL_REF (Pmode, stub_start)); 
2615 #ifdef RETURN_ADDR_OFFSET
2616   tmp = plus_constant (tmp, -RETURN_ADDR_OFFSET);
2617 #endif
2618   emit_move_insn (ra, tmp);
2619
2620   /* Indicate that the registers are in fact used.  */
2621   emit_insn (gen_rtx_USE (VOIDmode, reg1));
2622   emit_insn (gen_rtx_USE (VOIDmode, reg2));
2623   emit_insn (gen_rtx_USE (VOIDmode, reg3));
2624   if (GET_CODE (ra) == REG)
2625     emit_insn (gen_rtx_USE (VOIDmode, ra));
2626
2627   /* Generate the stub.  */
2628
2629   emit_jump (after_stub);
2630   emit_label (stub_start);
2631
2632   eh_regs (&reg1, &reg2, &reg3, 0);
2633   adjust_stack (reg2);
2634   emit_indirect_jump (reg3);
2635
2636   emit_label (after_stub);
2637 }
2638 \f
2639
2640 /* This contains the code required to verify whether arbitrary instructions
2641    are in the same exception region. */
2642
2643 static int *insn_eh_region = (int *)0;
2644 static int maximum_uid;
2645
2646 static void
2647 set_insn_eh_region (first, region_num)
2648      rtx *first;
2649      int region_num;
2650 {
2651   rtx insn;
2652   int rnum;
2653
2654   for (insn = *first; insn; insn = NEXT_INSN (insn))
2655     {
2656       if ((GET_CODE (insn) == NOTE) && 
2657                         (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG))
2658         {
2659           rnum = NOTE_BLOCK_NUMBER (insn);
2660           insn_eh_region[INSN_UID (insn)] =  rnum;
2661           insn = NEXT_INSN (insn);
2662           set_insn_eh_region (&insn, rnum);
2663           /* Upon return, insn points to the EH_REGION_END of nested region */
2664           continue;
2665         }
2666       insn_eh_region[INSN_UID (insn)] = region_num;
2667       if ((GET_CODE (insn) == NOTE) && 
2668             (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END))
2669         break;
2670     }
2671   *first = insn;
2672 }
2673
2674 /* Free the insn table, an make sure it cannot be used again. */
2675
2676 void 
2677 free_insn_eh_region () 
2678 {
2679   if (!doing_eh (0))
2680     return;
2681
2682   if (insn_eh_region)
2683     {
2684       free (insn_eh_region);
2685       insn_eh_region = (int *)0;
2686     }
2687 }
2688
2689 /* Initialize the table. max_uid must be calculated and handed into 
2690    this routine. If it is unavailable, passing a value of 0 will 
2691    cause this routine to calculate it as well. */
2692
2693 void 
2694 init_insn_eh_region (first, max_uid)
2695      rtx first;
2696      int max_uid;
2697 {
2698   rtx insn;
2699
2700   if (!doing_eh (0))
2701     return;
2702
2703   if (insn_eh_region)
2704     free_insn_eh_region();
2705
2706   if (max_uid == 0) 
2707     for (insn = first; insn; insn = NEXT_INSN (insn))
2708       if (INSN_UID (insn) > max_uid)       /* find largest UID */
2709         max_uid = INSN_UID (insn);
2710
2711   maximum_uid = max_uid;
2712   insn_eh_region = (int *) malloc ((max_uid + 1) * sizeof (int));
2713   insn = first;
2714   set_insn_eh_region (&insn, 0);
2715 }
2716
2717
2718 /* Check whether 2 instructions are within the same region. */
2719
2720 int 
2721 in_same_eh_region (insn1, insn2) 
2722      rtx insn1, insn2;
2723 {
2724   int ret, uid1, uid2;
2725
2726   /* If no exceptions, instructions are always in same region. */
2727   if (!doing_eh (0))
2728     return 1;
2729
2730   /* If the table isn't allocated, assume the worst. */
2731   if (!insn_eh_region)  
2732     return 0;
2733
2734   uid1 = INSN_UID (insn1);
2735   uid2 = INSN_UID (insn2);
2736
2737   /* if instructions have been allocated beyond the end, either
2738      the table is out of date, or this is a late addition, or
2739      something... Assume the worst. */
2740   if (uid1 > maximum_uid || uid2 > maximum_uid)
2741     return 0;
2742
2743   ret = (insn_eh_region[uid1] == insn_eh_region[uid2]);
2744   return ret;
2745 }
2746