842 lines · plain
1==========================2Exception Handling in LLVM3==========================4 5.. contents::6 :local:7 8Introduction9============10 11This document is the central repository for all information pertaining to12exception handling in LLVM. It describes the format that LLVM exception13handling information takes, which is useful for those interested in creating14front-ends or dealing directly with the information. Further, this document15provides specific examples of what exception handling information is used for in16C and C++.17 18Itanium ABI Zero-cost Exception Handling19----------------------------------------20 21Exception handling for most programming languages is designed to recover from22conditions that rarely occur during general use of an application. To that end,23exception handling should not interfere with the main flow of an application's24algorithm by performing checkpointing tasks, such as saving the current pc or25register state.26 27The Itanium ABI Exception Handling Specification defines a methodology for28providing outlying data in the form of exception tables without inlining29speculative exception handling code in the flow of an application's main30algorithm. Thus, the specification is said to add "zero-cost" to the normal31execution of an application.32 33A more complete description of the Itanium ABI exception handling runtime34support can be found at `Itanium C++ ABI: Exception Handling35<http://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html>`_. A description of the36exception frame format can be found at `Exception Frames37<http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html>`_,38with details of the DWARF 4 specification at `DWARF 4 Standard39<http://dwarfstd.org/Dwarf4Std.php>`_. A description for the C++ exception40table formats can be found at `Exception Handling Tables41<http://itanium-cxx-abi.github.io/cxx-abi/exceptions.pdf>`_.42 43Setjmp/Longjmp Exception Handling44---------------------------------45 46Setjmp/Longjmp (SJLJ) based exception handling uses LLVM intrinsics47`llvm.eh.sjlj.setjmp`_ and `llvm.eh.sjlj.longjmp`_ to handle control flow for48exception handling.49 50For each function which does exception processing --- be it ``try``/``catch``51blocks or cleanups --- that function registers itself on a global frame52list. When exceptions are unwinding, the runtime uses this list to identify53which functions need processing.54 55Landing pad selection is encoded in the call site entry of the function56context. The runtime returns to the function via `llvm.eh.sjlj.longjmp`_, where57a switch table transfers control to the appropriate landing pad based on the58index stored in the function context.59 60In contrast to DWARF exception handling, which encodes exception regions and61frame information in out-of-line tables, SJLJ exception handling builds and62removes the unwind frame context at runtime. This results in faster exception63handling at the expense of slower execution when no exceptions are thrown. As64exceptions are, by their nature, intended for uncommon code paths, DWARF65exception handling is generally preferred to SJLJ.66 67Windows Runtime Exception Handling68-----------------------------------69 70LLVM supports handling exceptions produced by the Windows runtime, but it71requires a very different intermediate representation. It is not based on the72":ref:`landingpad <i_landingpad>`" instruction like the other two models, and is73described later in this document under :ref:`wineh`.74 75Overview76--------77 78When an exception is thrown in LLVM code, the runtime does its best to find a79handler suited to processing the circumstance.80 81The runtime first attempts to find an *exception frame* corresponding to the82function where the exception was thrown. If the programming language supports83exception handling (e.g. C++), the exception frame contains a reference to an84exception table describing how to process the exception. If the language does85not support exception handling (e.g. C), or if the exception needs to be86forwarded to a prior activation, the exception frame contains information about87how to unwind the current activation and restore the state of the prior88activation. This process is repeated until the exception is handled. If the89exception is not handled and no activations remain, then the application is90terminated with an appropriate error message.91 92Because different programming languages have different behaviors when handling93exceptions, the exception handling ABI provides a mechanism for94supplying *personalities*. An exception handling personality is defined by95way of a *personality function* (e.g. ``__gxx_personality_v0`` in C++),96which receives the context of the exception, an *exception structure*97containing the exception object type and value, and a reference to the exception98table for the current function. The personality function for the current99compile unit is specified in a *common exception frame*.100 101The organization of an exception table is language dependent. For C++, an102exception table is organized as a series of code ranges defining what to do if103an exception occurs in that range. Typically, the information associated with a104range defines which types of exception objects (using C++ *type info*) that are105handled in that range, and an associated action that should take place. Actions106typically pass control to a *landing pad*.107 108A landing pad corresponds roughly to the code found in the ``catch`` portion of109a ``try``/``catch`` sequence. When execution resumes at a landing pad, it110receives an *exception structure* and a *selector value* corresponding to the111*type* of exception thrown. The selector is then used to determine which *catch*112should actually process the exception.113 114LLVM Code Generation115====================116 117From a C++ developer's perspective, exceptions are defined in terms of the118``throw`` and ``try``/``catch`` statements. In this section we will describe the119implementation of LLVM exception handling in terms of C++ examples.120 121Throw122-----123 124Languages that support exception handling typically provide a ``throw``125operation to initiate the exception process. Internally, a ``throw`` operation126breaks down into two steps.127 128#. A request is made to allocate exception space for an exception structure.129 This structure needs to survive beyond the current activation. This structure130 will contain the type and value of the object being thrown.131 132#. A call is made to the runtime to raise the exception, passing the exception133 structure as an argument.134 135In C++, the allocation of the exception structure is done by the136``__cxa_allocate_exception`` runtime function. The exception raising is handled137by ``__cxa_throw``. The type of the exception is represented using a C++ RTTI138structure.139 140Try/Catch141---------142 143A call within the scope of a *try* statement can potentially raise an144exception. In those circumstances, the LLVM C++ front-end replaces the call with145an ``invoke`` instruction. Unlike a call, the ``invoke`` has two potential146continuation points:147 148#. where to continue when the call succeeds normally, and149 150#. where to continue if the call raises an exception, either by a throw or the151 unwinding of a throw152 153The term used to define the place where an ``invoke`` continues after an154exception is called a *landing pad*. LLVM landing pads are conceptually155alternative function entry points where an exception structure reference and a156type info index are passed in as arguments. The landing pad saves the exception157structure reference and then proceeds to select the catch block that corresponds158to the type info of the exception object.159 160The LLVM :ref:`i_landingpad` is used to convey information about the landing161pad to the back end. For C++, the ``landingpad`` instruction returns a pointer162and integer pair corresponding to the pointer to the *exception structure* and163the *selector value* respectively.164 165The ``landingpad`` instruction looks for a reference to the personality166function to be used for this ``try``/``catch`` sequence in the parent167function's attribute list. The instruction contains a list of *cleanup*,168*catch*, and *filter* clauses. The exception is tested against the clauses169sequentially from first to last. The clauses have the following meanings:170 171- ``catch <type> @ExcType``172 173 - This clause means that the landingpad block should be entered if the174 exception being thrown is of type ``@ExcType`` or a subtype of175 ``@ExcType``. For C++, ``@ExcType`` is a pointer to the ``std::type_info``176 object (an RTTI object) representing the C++ exception type.177 178 - If ``@ExcType`` is ``null``, any exception matches, so the landingpad179 should always be entered. This is used for C++ catch-all blocks ("``catch180 (...)``").181 182 - When this clause is matched, the selector value will be equal to the value183 returned by "``@llvm.eh.typeid.for(i8* @ExcType)``". This will always be a184 positive value.185 186- ``filter <type> [<type> @ExcType1, ..., <type> @ExcTypeN]``187 188 - This clause means that the landingpad should be entered if the exception189 being thrown does *not* match any of the types in the list (which, for C++,190 are again specified as ``std::type_info`` pointers).191 192 - C++ front-ends use this to implement the C++ exception specifications, such as193 "``void foo() throw (ExcType1, ..., ExcTypeN) { ... }``". (Note: this194 functionality was deprecated in C++11 and removed in C++17.)195 196 - When this clause is matched, the selector value will be negative.197 198 - The array argument to ``filter`` may be empty; for example, "``[0 x i8**]199 undef``". This means that the landingpad should always be entered. (Note200 that such a ``filter`` would not be equivalent to "``catch i8* null``",201 because ``filter`` and ``catch`` produce negative and positive selector202 values respectively.)203 204- ``cleanup``205 206 - This clause means that the landingpad should always be entered.207 208 - C++ front-ends use this for calling objects' destructors.209 210 - When this clause is matched, the selector value will be zero.211 212 - The runtime may treat "``cleanup``" differently from "``catch <type>213 null``".214 215 In C++, if an unhandled exception occurs, the language runtime will call216 ``std::terminate()``, but it is implementation-defined whether the runtime217 unwinds the stack and calls object destructors first. For example, the GNU218 C++ unwinder does not call object destructors when an unhandled exception219 occurs. The reason for this is to improve debuggability: it ensures that220 ``std::terminate()`` is called from the context of the ``throw``, so that221 this context is not lost by unwinding the stack. A runtime will typically222 implement this by searching for a matching non-``cleanup`` clause, and223 aborting if it does not find one, before entering any landingpad blocks.224 225Once the landing pad has the type info selector, the code branches to the code226for the first catch. The catch then checks the value of the type info selector227against the index of type info for that catch. Since the type info index is not228known until all the type infos have been gathered in the backend, the catch code229must call the `llvm.eh.typeid.for`_ intrinsic to determine the index for a given230type info. If the catch fails to match the selector then control is passed on to231the next catch.232 233Finally, the entry and exit of catch code is bracketed with calls to234``__cxa_begin_catch`` and ``__cxa_end_catch``.235 236* ``__cxa_begin_catch`` takes an exception structure reference as an argument237 and returns the value of the exception object.238 239* ``__cxa_end_catch`` takes no arguments. This function:240 241 #. Locates the most recently caught exception and decrements its handler242 count,243 244 #. Removes the exception from the *caught* stack if the handler count goes to245 zero, and246 247 #. Destroys the exception if the handler count goes to zero and the exception248 was not re-thrown by throw.249 250 .. note::251 252 a rethrow from within the catch may replace this call with a253 ``__cxa_rethrow``.254 255Cleanups256--------257 258A cleanup is extra code which needs to be run as part of unwinding a scope. C++259destructors are a typical example, but other languages and language extensions260provide a variety of different kinds of cleanups. In general, a landing pad may261need to run arbitrary amounts of cleanup code before actually entering a catch262block. To indicate the presence of cleanups, a :ref:`i_landingpad` should have263a *cleanup* clause. Otherwise, the unwinder will not stop at the landing pad if264there are no catches or filters that require it to.265 266.. note::267 268 Do not allow a new exception to propagate out of the execution of a269 cleanup. This can corrupt the internal state of the unwinder. Different270 languages describe different high-level semantics for these situations: for271 example, C++ requires that the process be terminated, whereas Ada cancels both272 exceptions and throws a third.273 274When all cleanups are finished, if the exception is not handled by the current275function, resume unwinding by calling the :ref:`resume instruction <i_resume>`,276passing in the result of the ``landingpad`` instruction for the original277landing pad.278 279Throw Filters280-------------281 282Prior to C++17, C++ allowed the specification of which exception types may be283thrown from a function. To represent this, a top-level landing pad may exist to284filter out invalid types. To express this in LLVM code the :ref:`i_landingpad`285will have a filter clause. The clause consists of an array of type infos.286``landingpad`` will return a negative value287if the exception does not match any of the type infos. If no match is found then288a call to ``__cxa_call_unexpected`` should be made, otherwise289``_Unwind_Resume``. Each of these functions requires a reference to the290exception structure. Note that the most general form of a ``landingpad``291instruction can have any number of catch, cleanup, and filter clauses (though292having more than one cleanup is pointless). The LLVM C++ front-end can generate293such ``landingpad`` instructions due to inlining creating nested exception294handling scopes.295 296Restrictions297------------298 299The unwinder delegates the decision of whether to stop in a call frame to that300call frame's language-specific personality function. Not all unwinders guarantee301that they will stop to perform cleanups. For example, the GNU C++ unwinder302doesn't do so unless the exception is actually caught somewhere further up the303stack.304 305In order for inlining to behave correctly, landing pads must be prepared to306handle selector results that they did not originally advertise. Suppose that a307function catches exceptions of type ``A``, and it's inlined into a function that308catches exceptions of type ``B``. The inliner will update the ``landingpad``309instruction for the inlined landing pad to include the fact that ``B`` is also310caught. If that landing pad assumes that it will only be entered to catch an311``A``, it's in for a rude awakening. Consequently, landing pads must test for312the selector results they understand and then resume exception propagation with313the `resume instruction <LangRef.html#i_resume>`_ if none of the conditions314match.315 316Exception Handling Intrinsics317=============================318 319In addition to the ``landingpad`` and ``resume`` instructions, LLVM uses several320intrinsic functions (name prefixed with ``llvm.eh``) to provide exception321handling information at various points in generated code.322 323.. _llvm.eh.typeid.for:324 325``llvm.eh.typeid.for``326----------------------327 328.. code-block:: llvm329 330 i32 @llvm.eh.typeid.for(i8* %type_info)331 332 333This intrinsic returns the type info index in the exception table of the current334function. This value can be used to compare against the result of335``landingpad`` instruction. The single argument is a reference to a type info.336 337Uses of this intrinsic are generated by the C++ front-end.338 339.. _llvm.eh.exceptionpointer:340 341``llvm.eh.exceptionpointer``342----------------------------343 344.. code-block:: text345 346 i8 addrspace(N)* @llvm.eh.padparam.pNi8(token %catchpad)347 348 349This intrinsic retrieves a pointer to the exception caught by the given350``catchpad``.351 352 353SJLJ Intrinsics354---------------355 356The ``llvm.eh.sjlj`` intrinsics are used internally within LLVM's357backend. Uses of them are generated by the backend's358``SjLjEHPrepare`` pass.359 360.. _llvm.eh.sjlj.setjmp:361 362``llvm.eh.sjlj.setjmp``363~~~~~~~~~~~~~~~~~~~~~~~364 365.. code-block:: text366 367 i32 @llvm.eh.sjlj.setjmp(i8* %setjmp_buf)368 369For SJLJ based exception handling, this intrinsic forces register saving for the370current function and stores the address of the following instruction for use as371a destination address by `llvm.eh.sjlj.longjmp`_. The buffer format and the372overall functioning of this intrinsic is compatible with the GCC373``__builtin_setjmp`` implementation allowing code built with the clang and GCC374to interoperate.375 376The single parameter is a pointer to a five word buffer in which the calling377context is saved. The format and contents of the buffer are target-specific.378On certain targets (ARM, PowerPC, VE, X86), the front end places the 379frame pointer in the first word and the stack pointer in the third word, 380while the target implementation of this intrinsic fills in the remaining 381words. On other targets (SystemZ), saving the calling context to the buffer 382is left completely to the target implementation. 383 384.. _llvm.eh.sjlj.longjmp:385 386``llvm.eh.sjlj.longjmp``387~~~~~~~~~~~~~~~~~~~~~~~~388 389.. code-block:: llvm390 391 void @llvm.eh.sjlj.longjmp(i8* %setjmp_buf)392 393For SJLJ based exception handling, the ``llvm.eh.sjlj.longjmp`` intrinsic is394used to implement ``__builtin_longjmp()``. The single parameter is a pointer to395a buffer populated by `llvm.eh.sjlj.setjmp`_. The frame pointer and stack396pointer are restored from the buffer, then control is transferred to the397destination address.398 399``llvm.eh.sjlj.lsda``400~~~~~~~~~~~~~~~~~~~~~401 402.. code-block:: llvm403 404 i8* @llvm.eh.sjlj.lsda()405 406For SJLJ based exception handling, the ``llvm.eh.sjlj.lsda`` intrinsic returns407the address of the Language Specific Data Area (LSDA) for the current408function. The SJLJ front-end code stores this address in the exception handling409function context for use by the runtime.410 411``llvm.eh.sjlj.callsite``412~~~~~~~~~~~~~~~~~~~~~~~~~413 414.. code-block:: llvm415 416 void @llvm.eh.sjlj.callsite(i32 %call_site_num)417 418For SJLJ based exception handling, the ``llvm.eh.sjlj.callsite`` intrinsic419identifies the callsite value associated with the following ``invoke``420instruction. This is used to ensure that landing pad entries in the LSDA are421generated in matching order.422 423Asm Table Formats424=================425 426There are two tables that are used by the exception handling runtime to427determine which actions should be taken when an exception is thrown.428 429Exception Handling Frame430------------------------431 432An exception handling frame ``eh_frame`` is very similar to the unwind frame433used by DWARF debug info. The frame contains all the information necessary to434tear down the current frame and restore the state of the prior frame. There is435an exception handling frame for each function in a compile unit, plus a common436exception handling frame that defines information common to all functions in the437unit.438 439The format of this call frame information (CFI) is often platform-dependent,440however. ARM, for example, defines its own format. Apple has its own compact441unwind info format. On Windows, another format is used for all architectures442since 32-bit x86. LLVM will emit whatever information is required by the443target.444 445Exception Tables446----------------447 448An exception table contains information about what actions to take when an449exception is thrown in a particular part of a function's code. This is typically450referred to as the language-specific data area (LSDA). The format of the LSDA451table is specific to the personality function, but the majority of personalities452out there use a variation of the tables consumed by ``__gxx_personality_v0``.453There is one exception table per function, except leaf functions and functions454that have calls only to non-throwing functions. They do not need an exception455table.456 457.. _wineh:458 459Exception Handling using the Windows Runtime460=================================================461 462Background on Windows exceptions463---------------------------------464 465Interacting with exceptions on Windows is significantly more complicated than466on Itanium C++ ABI platforms. The fundamental difference between the two models467is that Itanium EH is designed around the idea of "successive unwinding," while468Windows EH is not.469 470Under Itanium, throwing an exception typically involves allocating thread-local471memory to hold the exception, and calling into the EH runtime. The runtime472identifies frames with appropriate exception handling actions, and successively473resets the register context of the current thread to the most recently active474frame with actions to run. In LLVM, execution resumes at a ``landingpad``475instruction, which produces register values provided by the runtime. If a476function is only cleaning up allocated resources, the function is responsible477for calling ``_Unwind_Resume`` to transition to the next most recently active478frame after it is finished cleaning up. Eventually, the frame responsible for479handling the exception calls ``__cxa_end_catch`` to destroy the exception,480release its memory, and resume normal control flow.481 482The Windows EH model does not use these successive register context resets.483Instead, the active exception is typically described by a frame on the stack.484In the case of C++ exceptions, the exception object is allocated in stack memory485and its address is passed to ``__CxxThrowException``. General-purpose structured486exceptions (SEH) are more analogous to Linux signals, and they are dispatched by487userspace DLLs provided with Windows. Each frame on the stack has an assigned EH488personality routine, which decides what actions to take to handle the exception.489There are a few major personalities for C and C++ code: the C++ personality490(``__CxxFrameHandler3``) and the SEH personalities (``_except_handler3``,491``_except_handler4``, and ``__C_specific_handler``). All of them implement492cleanups by calling back into a "funclet" contained in the parent function.493 494Funclets, in this context, are regions of the parent function that can be called495as though they were a function pointer with a very special calling convention.496The frame pointer of the parent frame is passed into the funclet either using497the standard EBP register or as the first parameter register, depending on the498architecture. The funclet implements the EH action by accessing local variables499in memory through the frame pointer, and returning some appropriate value,500continuing the EH process. No variables live in to or out of the funclet can be501allocated in registers.502 503The C++ personality also uses funclets to contain the code for catch blocks504(i.e. all user code between the braces in ``catch (Type obj) { ... }``). The505runtime must use funclets for catch bodies because the C++ exception object is506allocated in a child stack frame of the function handling the exception. If the507runtime rewound the stack back to the frame of the catch, the memory holding the508exception would be overwritten quickly by subsequent function calls. The use of509funclets also allows ``__CxxFrameHandler3`` to implement rethrow without510resorting to TLS. Instead, the runtime throws a special exception, and then uses511SEH (``__try / __except``) to resume execution with new information in the child512frame.513 514In other words, the successive unwinding approach is incompatible with Visual515C++ exceptions and general-purpose Windows exception handling. Because the C++516exception object lives in stack memory, LLVM cannot provide a custom personality517function that uses landingpads. Similarly, SEH does not provide any mechanism518to rethrow an exception or continue unwinding. Therefore, LLVM must use the IR519constructs described later in this document to implement compatible exception520handling.521 522SEH filter expressions523-----------------------524 525The SEH personality functions also use funclets to implement filter expressions,526which allow executing arbitrary user code to decide which exceptions to catch.527Filter expressions should not be confused with the ``filter`` clause of the LLVM528``landingpad`` instruction. Typically filter expressions are used to determine529if the exception came from a particular DLL or code region, or if code faulted530while accessing a particular memory address range. LLVM does not currently have531IR to represent filter expressions because it is difficult to represent their532control dependencies. Filter expressions run during the first phase of EH,533before cleanups run, making it very difficult to build a faithful control flow534graph. For now, the new EH instructions cannot represent SEH filter535expressions, and frontends must outline them ahead of time. Local variables of536the parent function can be escaped and accessed using the ``llvm.localescape``537and ``llvm.localrecover`` intrinsics.538 539New exception handling instructions540------------------------------------541 542The primary design goal of the new EH instructions is to support funclet543generation while preserving information about the CFG so that SSA formation544still works. As a secondary goal, they are designed to be generic across MSVC545and Itanium C++ exceptions. They make very few assumptions about the data546required by the personality, so long as it uses the familiar core EH actions:547catch, cleanup, and terminate. However, the new instructions are hard to modify548without knowing details of the EH personality. While they can be used to549represent Itanium EH, the landingpad model is strictly better for optimization550purposes.551 552The following new instructions are considered "exception handling pads", in that553they must be the first non-phi instruction of a basic block that may be the554unwind destination of an EH flow edge:555``catchswitch``, ``catchpad``, and ``cleanuppad``.556As with landingpads, when entering a try scope, if the557frontend encounters a call site that may throw an exception, it should emit an558invoke that unwinds to a ``catchswitch`` block. Similarly, inside the scope of a559C++ object with a destructor, invokes should unwind to a ``cleanuppad``.560 561New instructions are also used to mark the points where control is transferred562out of a catch/cleanup handler (which will correspond to exits from the563generated funclet). A catch handler which reaches its end by normal execution564executes a ``catchret`` instruction, which is a terminator indicating where in565the function control is returned to. A cleanup handler which reaches its end566by normal execution executes a ``cleanupret`` instruction, which is a terminator567indicating where the active exception will unwind to next.568 569Each of these new EH pad instructions has a way to identify which action should570be considered after this action. The ``catchswitch`` instruction is a terminator571and has an unwind destination operand analogous to the unwind destination of an572invoke. The ``cleanuppad`` instruction is not573a terminator, so the unwind destination is stored on the ``cleanupret``574instruction instead. Successfully executing a catch handler should resume575normal control flow, so neither ``catchpad`` nor ``catchret`` instructions can576unwind. All of these "unwind edges" may refer to a basic block that contains an577EH pad instruction, or they may unwind to the caller. Unwinding to the caller578has roughly the same semantics as the ``resume`` instruction in the landingpad579model. When inlining through an invoke, instructions that unwind to the caller580are hooked up to unwind to the unwind destination of the call site.581 582Putting things together, here is a hypothetical lowering of some C++ that uses583all of the new IR instructions:584 585.. code-block:: c586 587 struct Cleanup {588 Cleanup();589 ~Cleanup();590 int m;591 };592 void may_throw();593 int f() noexcept {594 try {595 Cleanup obj;596 may_throw();597 } catch (int e) {598 may_throw();599 return e;600 }601 return 0;602 }603 604.. code-block:: text605 606 define i32 @f() nounwind personality ptr @__CxxFrameHandler3 {607 entry:608 %obj = alloca %struct.Cleanup, align 4609 %e = alloca i32, align 4610 %call = invoke ptr @"??0Cleanup@@QEAA@XZ"(ptr nonnull %obj)611 to label %invoke.cont unwind label %lpad.catch612 613 invoke.cont: ; preds = %entry614 invoke void @"?may_throw@@YAXXZ"()615 to label %invoke.cont.2 unwind label %lpad.cleanup616 617 invoke.cont.2: ; preds = %invoke.cont618 call void @"??_DCleanup@@QEAA@XZ"(ptr nonnull %obj) nounwind619 br label %return620 621 return: ; preds = %invoke.cont.3, %invoke.cont.2622 %retval.0 = phi i32 [ 0, %invoke.cont.2 ], [ %3, %invoke.cont.3 ]623 ret i32 %retval.0624 625 lpad.cleanup: ; preds = %invoke.cont.2626 %0 = cleanuppad within none []627 call void @"??1Cleanup@@QEAA@XZ"(ptr nonnull %obj) nounwind628 cleanupret from %0 unwind label %lpad.catch629 630 lpad.catch: ; preds = %lpad.cleanup, %entry631 %1 = catchswitch within none [label %catch.body] unwind label %lpad.terminate632 633 catch.body: ; preds = %lpad.catch634 %catch = catchpad within %1 [ptr @"??_R0H@8", i32 0, ptr %e]635 invoke void @"?may_throw@@YAXXZ"()636 to label %invoke.cont.3 unwind label %lpad.terminate637 638 invoke.cont.3: ; preds = %catch.body639 %3 = load i32, ptr %e, align 4640 catchret from %catch to label %return641 642 lpad.terminate: ; preds = %catch.body, %lpad.catch643 cleanuppad within none []644 call void @"?terminate@@YAXXZ"()645 unreachable646 }647 648Funclet parent tokens649-----------------------650 651In order to produce tables for EH personalities that use funclets, it is652necessary to recover the nesting that was present in the source. This funclet653parent relationship is encoded in the IR using tokens produced by the new "pad"654instructions. The token operand of a "pad" or "ret" instruction indicates which655funclet it is in, or "none" if it is not nested within another funclet.656 657The ``catchpad`` and ``cleanuppad`` instructions establish new funclets, and658their tokens are consumed by other "pad" instructions to establish membership.659The ``catchswitch`` instruction does not create a funclet, but it produces a660token that is always consumed by its immediate successor ``catchpad``661instructions. This ensures that every catch handler modelled by a ``catchpad``662belongs to exactly one ``catchswitch``, which models the dispatch point after a663C++ try.664 665Here is an example of what this nesting looks like using some hypothetical666C++ code:667 668.. code-block:: c669 670 void f() {671 try {672 throw;673 } catch (...) {674 try {675 throw;676 } catch (...) {677 }678 }679 }680 681.. code-block:: text682 683 define void @f() #0 personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*) {684 entry:685 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1686 to label %unreachable unwind label %catch.dispatch687 688 catch.dispatch: ; preds = %entry689 %0 = catchswitch within none [label %catch] unwind to caller690 691 catch: ; preds = %catch.dispatch692 %1 = catchpad within %0 [i8* null, i32 64, i8* null]693 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1694 to label %unreachable unwind label %catch.dispatch2695 696 catch.dispatch2: ; preds = %catch697 %2 = catchswitch within %1 [label %catch3] unwind to caller698 699 catch3: ; preds = %catch.dispatch2700 %3 = catchpad within %2 [i8* null, i32 64, i8* null]701 catchret from %3 to label %try.cont702 703 try.cont: ; preds = %catch3704 catchret from %1 to label %try.cont6705 706 try.cont6: ; preds = %try.cont707 ret void708 709 unreachable: ; preds = %catch, %entry710 unreachable711 }712 713The "inner" ``catchswitch`` consumes ``%1`` which is produced by the outer714catchswitch.715 716.. _wineh-constraints:717 718Funclet transitions719-----------------------720 721The EH tables for personalities that use funclets make implicit use of the722funclet nesting relationship to encode unwind destinations, and so are723constrained in the set of funclet transitions they can represent. The related724LLVM IR instructions accordingly have constraints that ensure encodability of725the EH edges in the flow graph.726 727A ``catchswitch``, ``catchpad``, or ``cleanuppad`` is said to be "entered"728when it executes. It may subsequently be "exited" by any of the following729means:730 731* A ``catchswitch`` is immediately exited when none of its constituent732 ``catchpad``\ s are appropriate for the in-flight exception and it unwinds733 to its unwind destination or the caller.734* A ``catchpad`` and its parent ``catchswitch`` are both exited when a735 ``catchret`` from the ``catchpad`` is executed.736* A ``cleanuppad`` is exited when a ``cleanupret`` from it is executed.737* Any of these pads is exited when control unwinds to the function's caller,738 either by a ``call`` which unwinds all the way to the function's caller,739 a nested ``catchswitch`` marked "``unwinds to caller``", or a nested740 ``cleanuppad``\ 's ``cleanupret`` marked "``unwinds to caller"``.741* Any of these pads is exited when an unwind edge (from an ``invoke``,742 nested ``catchswitch``, or nested ``cleanuppad``\ 's ``cleanupret``)743 unwinds to a destination pad that is not a descendant of the given pad.744 745Note that the ``ret`` instruction is *not* a valid way to exit a funclet pad;746it is undefined behavior to execute a ``ret`` when a pad has been entered but747not exited.748 749A single unwind edge may exit any number of pads (with the restrictions that750the edge from a ``catchswitch`` must exit at least itself, and the edge from751a ``cleanupret`` must exit at least its ``cleanuppad``), and then must enter752exactly one pad, which must be distinct from all the exited pads. The parent753of the pad that an unwind edge enters must be the most-recently-entered754not-yet-exited pad (after exiting from any pads that the unwind edge exits),755or "none" if there is no such pad. This ensures that the stack of executing756funclets at run-time always corresponds to some path in the funclet pad tree757that the parent tokens encode.758 759All unwind edges which exit any given funclet pad (including ``cleanupret``760edges exiting their ``cleanuppad`` and ``catchswitch`` edges exiting their761``catchswitch``) must share the same unwind destination. Similarly, any762funclet pad which may be exited by unwind to caller must not be exited by763any exception edges which unwind anywhere other than the caller. This764ensures that each funclet as a whole has only one unwind destination, which765EH tables for funclet personalities may require. Note that any unwind edge766which exits a ``catchpad`` also exits its parent ``catchswitch``, so this767implies that for any given ``catchswitch``, its unwind destination must also768be the unwind destination of any unwind edge that exits any of its constituent769``catchpad``\s. Because ``catchswitch`` has no ``nounwind`` variant, and770because IR producers are not *required* to annotate calls which will not771unwind as ``nounwind``, it is legal to nest a ``call`` or an "``unwind to772caller``\ " ``catchswitch`` within a funclet pad that has an unwind773destination other than caller; it is undefined behavior for such a ``call``774or ``catchswitch`` to unwind.775 776Finally, the funclet pads' unwind destinations cannot form a cycle. This777ensures that EH lowering can construct "try regions" with a tree-like778structure, which funclet-based personalities may require.779 780Exception Handling support on the target781=================================================782 783In order to support exception handling on a particular target, there are a few784items that need to be implemented.785 786* CFI directives787 788 First, you have to assign each target register with a unique DWARF number.789 Then in ``TargetFrameLowering``'s ``emitPrologue``, you have to emit `CFI790 directives <https://sourceware.org/binutils/docs/as/CFI-directives.html>`_791 to specify how to calculate the CFA (Canonical Frame Address) and how register792 is restored from the address pointed by the CFA with an offset. The assembler793 is instructed by CFI directives to build ``.eh_frame`` section, which is used794 by the unwinder to unwind the stack during exception handling.795 796* ``getExceptionPointerRegister`` and ``getExceptionSelectorRegister``797 798 ``TargetLowering`` must implement both functions. The *personality function*799 passes the *exception structure* (a pointer) and *selector value* (an integer)800 to the landing pad through the registers specified by ``getExceptionPointerRegister``801 and ``getExceptionSelectorRegister`` respectively. On most platforms, they802 will be GPRs and will be the same as the ones specified in the calling convention.803 804* ``EH_RETURN``805 806 The ISD node represents the undocumented GCC extension ``__builtin_eh_return (offset, handler)``,807 which adjusts the stack by offset and then jumps to the handler. ``__builtin_eh_return``808 is used in GCC unwinder (`libgcc <https://gcc.gnu.org/onlinedocs/gccint/Libgcc.html>`_),809 but not in LLVM unwinder (`libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_).810 If you are on the top of ``libgcc`` and have a particular requirement on your target,811 you have to handle ``EH_RETURN`` in ``TargetLowering``.812 813If you don't leverage the existing runtime (``libstdc++`` and ``libgcc``),814you have to take a look at `libc++ <https://libcxx.llvm.org/>`_ and815`libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_816to see what has to be done there. For ``libunwind``, you have to do the following:817 818* ``__libunwind_config.h``819 820 Define macros for your target.821 822* ``include/libunwind.h``823 824 Define an enum for the target registers.825 826* ``src/Registers.hpp``827 828 Define a ``Registers`` class for your target, implement setter and getter functions.829 830* ``src/UnwindCursor.hpp``831 832 Define ``dwarfEncoding`` and ``stepWithCompactEncoding`` for your ``Registers``833 class.834 835* ``src/UnwindRegistersRestore.S``836 837 Write an assembly function to restore all your target registers from memory.838 839* ``src/UnwindRegistersSave.S``840 841 Write an assembly function to save all your target registers to memory.842