ExceptionHandling.rst 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. ==========================
  2. Exception Handling in LLVM
  3. ==========================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document is the central repository for all information pertaining to
  9. exception handling in LLVM. It describes the format that LLVM exception
  10. handling information takes, which is useful for those interested in creating
  11. front-ends or dealing directly with the information. Further, this document
  12. provides specific examples of what exception handling information is used for in
  13. C and C++.
  14. Itanium ABI Zero-cost Exception Handling
  15. ----------------------------------------
  16. Exception handling for most programming languages is designed to recover from
  17. conditions that rarely occur during general use of an application. To that end,
  18. exception handling should not interfere with the main flow of an application's
  19. algorithm by performing checkpointing tasks, such as saving the current pc or
  20. register state.
  21. The Itanium ABI Exception Handling Specification defines a methodology for
  22. providing outlying data in the form of exception tables without inlining
  23. speculative exception handling code in the flow of an application's main
  24. algorithm. Thus, the specification is said to add "zero-cost" to the normal
  25. execution of an application.
  26. A more complete description of the Itanium ABI exception handling runtime
  27. support of can be found at `Itanium C++ ABI: Exception Handling
  28. <http://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html>`_. A description of the
  29. exception frame format can be found at `Exception Frames
  30. <http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html>`_,
  31. with details of the DWARF 4 specification at `DWARF 4 Standard
  32. <http://dwarfstd.org/Dwarf4Std.php>`_. A description for the C++ exception
  33. table formats can be found at `Exception Handling Tables
  34. <http://itanium-cxx-abi.github.io/cxx-abi/exceptions.pdf>`_.
  35. Setjmp/Longjmp Exception Handling
  36. ---------------------------------
  37. Setjmp/Longjmp (SJLJ) based exception handling uses LLVM intrinsics
  38. `llvm.eh.sjlj.setjmp`_ and `llvm.eh.sjlj.longjmp`_ to handle control flow for
  39. exception handling.
  40. For each function which does exception processing --- be it ``try``/``catch``
  41. blocks or cleanups --- that function registers itself on a global frame
  42. list. When exceptions are unwinding, the runtime uses this list to identify
  43. which functions need processing.
  44. Landing pad selection is encoded in the call site entry of the function
  45. context. The runtime returns to the function via `llvm.eh.sjlj.longjmp`_, where
  46. a switch table transfers control to the appropriate landing pad based on the
  47. index stored in the function context.
  48. In contrast to DWARF exception handling, which encodes exception regions and
  49. frame information in out-of-line tables, SJLJ exception handling builds and
  50. removes the unwind frame context at runtime. This results in faster exception
  51. handling at the expense of slower execution when no exceptions are thrown. As
  52. exceptions are, by their nature, intended for uncommon code paths, DWARF
  53. exception handling is generally preferred to SJLJ.
  54. Windows Runtime Exception Handling
  55. -----------------------------------
  56. LLVM supports handling exceptions produced by the Windows runtime, but it
  57. requires a very different intermediate representation. It is not based on the
  58. ":ref:`landingpad <i_landingpad>`" instruction like the other two models, and is
  59. described later in this document under :ref:`wineh`.
  60. Overview
  61. --------
  62. When an exception is thrown in LLVM code, the runtime does its best to find a
  63. handler suited to processing the circumstance.
  64. The runtime first attempts to find an *exception frame* corresponding to the
  65. function where the exception was thrown. If the programming language supports
  66. exception handling (e.g. C++), the exception frame contains a reference to an
  67. exception table describing how to process the exception. If the language does
  68. not support exception handling (e.g. C), or if the exception needs to be
  69. forwarded to a prior activation, the exception frame contains information about
  70. how to unwind the current activation and restore the state of the prior
  71. activation. This process is repeated until the exception is handled. If the
  72. exception is not handled and no activations remain, then the application is
  73. terminated with an appropriate error message.
  74. Because different programming languages have different behaviors when handling
  75. exceptions, the exception handling ABI provides a mechanism for
  76. supplying *personalities*. An exception handling personality is defined by
  77. way of a *personality function* (e.g. ``__gxx_personality_v0`` in C++),
  78. which receives the context of the exception, an *exception structure*
  79. containing the exception object type and value, and a reference to the exception
  80. table for the current function. The personality function for the current
  81. compile unit is specified in a *common exception frame*.
  82. The organization of an exception table is language dependent. For C++, an
  83. exception table is organized as a series of code ranges defining what to do if
  84. an exception occurs in that range. Typically, the information associated with a
  85. range defines which types of exception objects (using C++ *type info*) that are
  86. handled in that range, and an associated action that should take place. Actions
  87. typically pass control to a *landing pad*.
  88. A landing pad corresponds roughly to the code found in the ``catch`` portion of
  89. a ``try``/``catch`` sequence. When execution resumes at a landing pad, it
  90. receives an *exception structure* and a *selector value* corresponding to the
  91. *type* of exception thrown. The selector is then used to determine which *catch*
  92. should actually process the exception.
  93. LLVM Code Generation
  94. ====================
  95. From a C++ developer's perspective, exceptions are defined in terms of the
  96. ``throw`` and ``try``/``catch`` statements. In this section we will describe the
  97. implementation of LLVM exception handling in terms of C++ examples.
  98. Throw
  99. -----
  100. Languages that support exception handling typically provide a ``throw``
  101. operation to initiate the exception process. Internally, a ``throw`` operation
  102. breaks down into two steps.
  103. #. A request is made to allocate exception space for an exception structure.
  104. This structure needs to survive beyond the current activation. This structure
  105. will contain the type and value of the object being thrown.
  106. #. A call is made to the runtime to raise the exception, passing the exception
  107. structure as an argument.
  108. In C++, the allocation of the exception structure is done by the
  109. ``__cxa_allocate_exception`` runtime function. The exception raising is handled
  110. by ``__cxa_throw``. The type of the exception is represented using a C++ RTTI
  111. structure.
  112. Try/Catch
  113. ---------
  114. A call within the scope of a *try* statement can potentially raise an
  115. exception. In those circumstances, the LLVM C++ front-end replaces the call with
  116. an ``invoke`` instruction. Unlike a call, the ``invoke`` has two potential
  117. continuation points:
  118. #. where to continue when the call succeeds as per normal, and
  119. #. where to continue if the call raises an exception, either by a throw or the
  120. unwinding of a throw
  121. The term used to define the place where an ``invoke`` continues after an
  122. exception is called a *landing pad*. LLVM landing pads are conceptually
  123. alternative function entry points where an exception structure reference and a
  124. type info index are passed in as arguments. The landing pad saves the exception
  125. structure reference and then proceeds to select the catch block that corresponds
  126. to the type info of the exception object.
  127. The LLVM :ref:`i_landingpad` is used to convey information about the landing
  128. pad to the back end. For C++, the ``landingpad`` instruction returns a pointer
  129. and integer pair corresponding to the pointer to the *exception structure* and
  130. the *selector value* respectively.
  131. The ``landingpad`` instruction looks for a reference to the personality
  132. function to be used for this ``try``/``catch`` sequence in the parent
  133. function's attribute list. The instruction contains a list of *cleanup*,
  134. *catch*, and *filter* clauses. The exception is tested against the clauses
  135. sequentially from first to last. The clauses have the following meanings:
  136. - ``catch <type> @ExcType``
  137. - This clause means that the landingpad block should be entered if the
  138. exception being thrown is of type ``@ExcType`` or a subtype of
  139. ``@ExcType``. For C++, ``@ExcType`` is a pointer to the ``std::type_info``
  140. object (an RTTI object) representing the C++ exception type.
  141. - If ``@ExcType`` is ``null``, any exception matches, so the landingpad
  142. should always be entered. This is used for C++ catch-all blocks ("``catch
  143. (...)``").
  144. - When this clause is matched, the selector value will be equal to the value
  145. returned by "``@llvm.eh.typeid.for(i8* @ExcType)``". This will always be a
  146. positive value.
  147. - ``filter <type> [<type> @ExcType1, ..., <type> @ExcTypeN]``
  148. - This clause means that the landingpad should be entered if the exception
  149. being thrown does *not* match any of the types in the list (which, for C++,
  150. are again specified as ``std::type_info`` pointers).
  151. - C++ front-ends use this to implement C++ exception specifications, such as
  152. "``void foo() throw (ExcType1, ..., ExcTypeN) { ... }``".
  153. - When this clause is matched, the selector value will be negative.
  154. - The array argument to ``filter`` may be empty; for example, "``[0 x i8**]
  155. undef``". This means that the landingpad should always be entered. (Note
  156. that such a ``filter`` would not be equivalent to "``catch i8* null``",
  157. because ``filter`` and ``catch`` produce negative and positive selector
  158. values respectively.)
  159. - ``cleanup``
  160. - This clause means that the landingpad should always be entered.
  161. - C++ front-ends use this for calling objects' destructors.
  162. - When this clause is matched, the selector value will be zero.
  163. - The runtime may treat "``cleanup``" differently from "``catch <type>
  164. null``".
  165. In C++, if an unhandled exception occurs, the language runtime will call
  166. ``std::terminate()``, but it is implementation-defined whether the runtime
  167. unwinds the stack and calls object destructors first. For example, the GNU
  168. C++ unwinder does not call object destructors when an unhandled exception
  169. occurs. The reason for this is to improve debuggability: it ensures that
  170. ``std::terminate()`` is called from the context of the ``throw``, so that
  171. this context is not lost by unwinding the stack. A runtime will typically
  172. implement this by searching for a matching non-``cleanup`` clause, and
  173. aborting if it does not find one, before entering any landingpad blocks.
  174. Once the landing pad has the type info selector, the code branches to the code
  175. for the first catch. The catch then checks the value of the type info selector
  176. against the index of type info for that catch. Since the type info index is not
  177. known until all the type infos have been gathered in the backend, the catch code
  178. must call the `llvm.eh.typeid.for`_ intrinsic to determine the index for a given
  179. type info. If the catch fails to match the selector then control is passed on to
  180. the next catch.
  181. Finally, the entry and exit of catch code is bracketed with calls to
  182. ``__cxa_begin_catch`` and ``__cxa_end_catch``.
  183. * ``__cxa_begin_catch`` takes an exception structure reference as an argument
  184. and returns the value of the exception object.
  185. * ``__cxa_end_catch`` takes no arguments. This function:
  186. #. Locates the most recently caught exception and decrements its handler
  187. count,
  188. #. Removes the exception from the *caught* stack if the handler count goes to
  189. zero, and
  190. #. Destroys the exception if the handler count goes to zero and the exception
  191. was not re-thrown by throw.
  192. .. note::
  193. a rethrow from within the catch may replace this call with a
  194. ``__cxa_rethrow``.
  195. Cleanups
  196. --------
  197. A cleanup is extra code which needs to be run as part of unwinding a scope. C++
  198. destructors are a typical example, but other languages and language extensions
  199. provide a variety of different kinds of cleanups. In general, a landing pad may
  200. need to run arbitrary amounts of cleanup code before actually entering a catch
  201. block. To indicate the presence of cleanups, a :ref:`i_landingpad` should have
  202. a *cleanup* clause. Otherwise, the unwinder will not stop at the landing pad if
  203. there are no catches or filters that require it to.
  204. .. note::
  205. Do not allow a new exception to propagate out of the execution of a
  206. cleanup. This can corrupt the internal state of the unwinder. Different
  207. languages describe different high-level semantics for these situations: for
  208. example, C++ requires that the process be terminated, whereas Ada cancels both
  209. exceptions and throws a third.
  210. When all cleanups are finished, if the exception is not handled by the current
  211. function, resume unwinding by calling the :ref:`resume instruction <i_resume>`,
  212. passing in the result of the ``landingpad`` instruction for the original
  213. landing pad.
  214. Throw Filters
  215. -------------
  216. C++ allows the specification of which exception types may be thrown from a
  217. function. To represent this, a top level landing pad may exist to filter out
  218. invalid types. To express this in LLVM code the :ref:`i_landingpad` will have a
  219. filter clause. The clause consists of an array of type infos.
  220. ``landingpad`` will return a negative value
  221. if the exception does not match any of the type infos. If no match is found then
  222. a call to ``__cxa_call_unexpected`` should be made, otherwise
  223. ``_Unwind_Resume``. Each of these functions requires a reference to the
  224. exception structure. Note that the most general form of a ``landingpad``
  225. instruction can have any number of catch, cleanup, and filter clauses (though
  226. having more than one cleanup is pointless). The LLVM C++ front-end can generate
  227. such ``landingpad`` instructions due to inlining creating nested exception
  228. handling scopes.
  229. .. _undefined:
  230. Restrictions
  231. ------------
  232. The unwinder delegates the decision of whether to stop in a call frame to that
  233. call frame's language-specific personality function. Not all unwinders guarantee
  234. that they will stop to perform cleanups. For example, the GNU C++ unwinder
  235. doesn't do so unless the exception is actually caught somewhere further up the
  236. stack.
  237. In order for inlining to behave correctly, landing pads must be prepared to
  238. handle selector results that they did not originally advertise. Suppose that a
  239. function catches exceptions of type ``A``, and it's inlined into a function that
  240. catches exceptions of type ``B``. The inliner will update the ``landingpad``
  241. instruction for the inlined landing pad to include the fact that ``B`` is also
  242. caught. If that landing pad assumes that it will only be entered to catch an
  243. ``A``, it's in for a rude awakening. Consequently, landing pads must test for
  244. the selector results they understand and then resume exception propagation with
  245. the `resume instruction <LangRef.html#i_resume>`_ if none of the conditions
  246. match.
  247. Exception Handling Intrinsics
  248. =============================
  249. In addition to the ``landingpad`` and ``resume`` instructions, LLVM uses several
  250. intrinsic functions (name prefixed with ``llvm.eh``) to provide exception
  251. handling information at various points in generated code.
  252. .. _llvm.eh.typeid.for:
  253. ``llvm.eh.typeid.for``
  254. ----------------------
  255. .. code-block:: llvm
  256. i32 @llvm.eh.typeid.for(i8* %type_info)
  257. This intrinsic returns the type info index in the exception table of the current
  258. function. This value can be used to compare against the result of
  259. ``landingpad`` instruction. The single argument is a reference to a type info.
  260. Uses of this intrinsic are generated by the C++ front-end.
  261. .. _llvm.eh.begincatch:
  262. ``llvm.eh.begincatch``
  263. ----------------------
  264. .. code-block:: llvm
  265. void @llvm.eh.begincatch(i8* %ehptr, i8* %ehobj)
  266. This intrinsic marks the beginning of catch handling code within the blocks
  267. following a ``landingpad`` instruction. The exact behavior of this function
  268. depends on the compilation target and the personality function associated
  269. with the ``landingpad`` instruction.
  270. The first argument to this intrinsic is a pointer that was previously extracted
  271. from the aggregate return value of the ``landingpad`` instruction. The second
  272. argument to the intrinsic is a pointer to stack space where the exception object
  273. should be stored. The runtime handles the details of copying the exception
  274. object into the slot. If the second parameter is null, no copy occurs.
  275. Uses of this intrinsic are generated by the C++ front-end. Many targets will
  276. use implementation-specific functions (such as ``__cxa_begin_catch``) instead
  277. of this intrinsic. The intrinsic is provided for targets that require a more
  278. abstract interface.
  279. When used in the native Windows C++ exception handling implementation, this
  280. intrinsic serves as a placeholder to delimit code before a catch handler is
  281. outlined. When the handler is outlined, this intrinsic will be replaced
  282. by instructions that retrieve the exception object pointer from the frame
  283. allocation block.
  284. .. _llvm.eh.endcatch:
  285. ``llvm.eh.endcatch``
  286. ----------------------
  287. .. code-block:: llvm
  288. void @llvm.eh.endcatch()
  289. This intrinsic marks the end of catch handling code within the current block,
  290. which will be a successor of a block which called ``llvm.eh.begincatch''.
  291. The exact behavior of this function depends on the compilation target and the
  292. personality function associated with the corresponding ``landingpad``
  293. instruction.
  294. There may be more than one call to ``llvm.eh.endcatch`` for any given call to
  295. ``llvm.eh.begincatch`` with each ``llvm.eh.endcatch`` call corresponding to the
  296. end of a different control path. All control paths following a call to
  297. ``llvm.eh.begincatch`` must reach a call to ``llvm.eh.endcatch``.
  298. Uses of this intrinsic are generated by the C++ front-end. Many targets will
  299. use implementation-specific functions (such as ``__cxa_begin_catch``) instead
  300. of this intrinsic. The intrinsic is provided for targets that require a more
  301. abstract interface.
  302. When used in the native Windows C++ exception handling implementation, this
  303. intrinsic serves as a placeholder to delimit code before a catch handler is
  304. outlined. After the handler is outlined, this intrinsic is simply removed.
  305. .. _llvm.eh.exceptionpointer:
  306. ``llvm.eh.exceptionpointer``
  307. ----------------------------
  308. .. code-block:: text
  309. i8 addrspace(N)* @llvm.eh.padparam.pNi8(token %catchpad)
  310. This intrinsic retrieves a pointer to the exception caught by the given
  311. ``catchpad``.
  312. SJLJ Intrinsics
  313. ---------------
  314. The ``llvm.eh.sjlj`` intrinsics are used internally within LLVM's
  315. backend. Uses of them are generated by the backend's
  316. ``SjLjEHPrepare`` pass.
  317. .. _llvm.eh.sjlj.setjmp:
  318. ``llvm.eh.sjlj.setjmp``
  319. ~~~~~~~~~~~~~~~~~~~~~~~
  320. .. code-block:: text
  321. i32 @llvm.eh.sjlj.setjmp(i8* %setjmp_buf)
  322. For SJLJ based exception handling, this intrinsic forces register saving for the
  323. current function and stores the address of the following instruction for use as
  324. a destination address by `llvm.eh.sjlj.longjmp`_. The buffer format and the
  325. overall functioning of this intrinsic is compatible with the GCC
  326. ``__builtin_setjmp`` implementation allowing code built with the clang and GCC
  327. to interoperate.
  328. The single parameter is a pointer to a five word buffer in which the calling
  329. context is saved. The front end places the frame pointer in the first word, and
  330. the target implementation of this intrinsic should place the destination address
  331. for a `llvm.eh.sjlj.longjmp`_ in the second word. The following three words are
  332. available for use in a target-specific manner.
  333. .. _llvm.eh.sjlj.longjmp:
  334. ``llvm.eh.sjlj.longjmp``
  335. ~~~~~~~~~~~~~~~~~~~~~~~~
  336. .. code-block:: llvm
  337. void @llvm.eh.sjlj.longjmp(i8* %setjmp_buf)
  338. For SJLJ based exception handling, the ``llvm.eh.sjlj.longjmp`` intrinsic is
  339. used to implement ``__builtin_longjmp()``. The single parameter is a pointer to
  340. a buffer populated by `llvm.eh.sjlj.setjmp`_. The frame pointer and stack
  341. pointer are restored from the buffer, then control is transferred to the
  342. destination address.
  343. ``llvm.eh.sjlj.lsda``
  344. ~~~~~~~~~~~~~~~~~~~~~
  345. .. code-block:: llvm
  346. i8* @llvm.eh.sjlj.lsda()
  347. For SJLJ based exception handling, the ``llvm.eh.sjlj.lsda`` intrinsic returns
  348. the address of the Language Specific Data Area (LSDA) for the current
  349. function. The SJLJ front-end code stores this address in the exception handling
  350. function context for use by the runtime.
  351. ``llvm.eh.sjlj.callsite``
  352. ~~~~~~~~~~~~~~~~~~~~~~~~~
  353. .. code-block:: llvm
  354. void @llvm.eh.sjlj.callsite(i32 %call_site_num)
  355. For SJLJ based exception handling, the ``llvm.eh.sjlj.callsite`` intrinsic
  356. identifies the callsite value associated with the following ``invoke``
  357. instruction. This is used to ensure that landing pad entries in the LSDA are
  358. generated in matching order.
  359. Asm Table Formats
  360. =================
  361. There are two tables that are used by the exception handling runtime to
  362. determine which actions should be taken when an exception is thrown.
  363. Exception Handling Frame
  364. ------------------------
  365. An exception handling frame ``eh_frame`` is very similar to the unwind frame
  366. used by DWARF debug info. The frame contains all the information necessary to
  367. tear down the current frame and restore the state of the prior frame. There is
  368. an exception handling frame for each function in a compile unit, plus a common
  369. exception handling frame that defines information common to all functions in the
  370. unit.
  371. The format of this call frame information (CFI) is often platform-dependent,
  372. however. ARM, for example, defines their own format. Apple has their own compact
  373. unwind info format. On Windows, another format is used for all architectures
  374. since 32-bit x86. LLVM will emit whatever information is required by the
  375. target.
  376. Exception Tables
  377. ----------------
  378. An exception table contains information about what actions to take when an
  379. exception is thrown in a particular part of a function's code. This is typically
  380. referred to as the language-specific data area (LSDA). The format of the LSDA
  381. table is specific to the personality function, but the majority of personalities
  382. out there use a variation of the tables consumed by ``__gxx_personality_v0``.
  383. There is one exception table per function, except leaf functions and functions
  384. that have calls only to non-throwing functions. They do not need an exception
  385. table.
  386. .. _wineh:
  387. Exception Handling using the Windows Runtime
  388. =================================================
  389. Background on Windows exceptions
  390. ---------------------------------
  391. Interacting with exceptions on Windows is significantly more complicated than
  392. on Itanium C++ ABI platforms. The fundamental difference between the two models
  393. is that Itanium EH is designed around the idea of "successive unwinding," while
  394. Windows EH is not.
  395. Under Itanium, throwing an exception typically involes allocating thread local
  396. memory to hold the exception, and calling into the EH runtime. The runtime
  397. identifies frames with appropriate exception handling actions, and successively
  398. resets the register context of the current thread to the most recently active
  399. frame with actions to run. In LLVM, execution resumes at a ``landingpad``
  400. instruction, which produces register values provided by the runtime. If a
  401. function is only cleaning up allocated resources, the function is responsible
  402. for calling ``_Unwind_Resume`` to transition to the next most recently active
  403. frame after it is finished cleaning up. Eventually, the frame responsible for
  404. handling the exception calls ``__cxa_end_catch`` to destroy the exception,
  405. release its memory, and resume normal control flow.
  406. The Windows EH model does not use these successive register context resets.
  407. Instead, the active exception is typically described by a frame on the stack.
  408. In the case of C++ exceptions, the exception object is allocated in stack memory
  409. and its address is passed to ``__CxxThrowException``. General purpose structured
  410. exceptions (SEH) are more analogous to Linux signals, and they are dispatched by
  411. userspace DLLs provided with Windows. Each frame on the stack has an assigned EH
  412. personality routine, which decides what actions to take to handle the exception.
  413. There are a few major personalities for C and C++ code: the C++ personality
  414. (``__CxxFrameHandler3``) and the SEH personalities (``_except_handler3``,
  415. ``_except_handler4``, and ``__C_specific_handler``). All of them implement
  416. cleanups by calling back into a "funclet" contained in the parent function.
  417. Funclets, in this context, are regions of the parent function that can be called
  418. as though they were a function pointer with a very special calling convention.
  419. The frame pointer of the parent frame is passed into the funclet either using
  420. the standard EBP register or as the first parameter register, depending on the
  421. architecture. The funclet implements the EH action by accessing local variables
  422. in memory through the frame pointer, and returning some appropriate value,
  423. continuing the EH process. No variables live in to or out of the funclet can be
  424. allocated in registers.
  425. The C++ personality also uses funclets to contain the code for catch blocks
  426. (i.e. all user code between the braces in ``catch (Type obj) { ... }``). The
  427. runtime must use funclets for catch bodies because the C++ exception object is
  428. allocated in a child stack frame of the function handling the exception. If the
  429. runtime rewound the stack back to frame of the catch, the memory holding the
  430. exception would be overwritten quickly by subsequent function calls. The use of
  431. funclets also allows ``__CxxFrameHandler3`` to implement rethrow without
  432. resorting to TLS. Instead, the runtime throws a special exception, and then uses
  433. SEH (``__try / __except``) to resume execution with new information in the child
  434. frame.
  435. In other words, the successive unwinding approach is incompatible with Visual
  436. C++ exceptions and general purpose Windows exception handling. Because the C++
  437. exception object lives in stack memory, LLVM cannot provide a custom personality
  438. function that uses landingpads. Similarly, SEH does not provide any mechanism
  439. to rethrow an exception or continue unwinding. Therefore, LLVM must use the IR
  440. constructs described later in this document to implement compatible exception
  441. handling.
  442. SEH filter expressions
  443. -----------------------
  444. The SEH personality functions also use funclets to implement filter expressions,
  445. which allow executing arbitrary user code to decide which exceptions to catch.
  446. Filter expressions should not be confused with the ``filter`` clause of the LLVM
  447. ``landingpad`` instruction. Typically filter expressions are used to determine
  448. if the exception came from a particular DLL or code region, or if code faulted
  449. while accessing a particular memory address range. LLVM does not currently have
  450. IR to represent filter expressions because it is difficult to represent their
  451. control dependencies. Filter expressions run during the first phase of EH,
  452. before cleanups run, making it very difficult to build a faithful control flow
  453. graph. For now, the new EH instructions cannot represent SEH filter
  454. expressions, and frontends must outline them ahead of time. Local variables of
  455. the parent function can be escaped and accessed using the ``llvm.localescape``
  456. and ``llvm.localrecover`` intrinsics.
  457. New exception handling instructions
  458. ------------------------------------
  459. The primary design goal of the new EH instructions is to support funclet
  460. generation while preserving information about the CFG so that SSA formation
  461. still works. As a secondary goal, they are designed to be generic across MSVC
  462. and Itanium C++ exceptions. They make very few assumptions about the data
  463. required by the personality, so long as it uses the familiar core EH actions:
  464. catch, cleanup, and terminate. However, the new instructions are hard to modify
  465. without knowing details of the EH personality. While they can be used to
  466. represent Itanium EH, the landingpad model is strictly better for optimization
  467. purposes.
  468. The following new instructions are considered "exception handling pads", in that
  469. they must be the first non-phi instruction of a basic block that may be the
  470. unwind destination of an EH flow edge:
  471. ``catchswitch``, ``catchpad``, and ``cleanuppad``.
  472. As with landingpads, when entering a try scope, if the
  473. frontend encounters a call site that may throw an exception, it should emit an
  474. invoke that unwinds to a ``catchswitch`` block. Similarly, inside the scope of a
  475. C++ object with a destructor, invokes should unwind to a ``cleanuppad``.
  476. New instructions are also used to mark the points where control is transferred
  477. out of a catch/cleanup handler (which will correspond to exits from the
  478. generated funclet). A catch handler which reaches its end by normal execution
  479. executes a ``catchret`` instruction, which is a terminator indicating where in
  480. the function control is returned to. A cleanup handler which reaches its end
  481. by normal execution executes a ``cleanupret`` instruction, which is a terminator
  482. indicating where the active exception will unwind to next.
  483. Each of these new EH pad instructions has a way to identify which action should
  484. be considered after this action. The ``catchswitch`` instruction is a terminator
  485. and has an unwind destination operand analogous to the unwind destination of an
  486. invoke. The ``cleanuppad`` instruction is not
  487. a terminator, so the unwind destination is stored on the ``cleanupret``
  488. instruction instead. Successfully executing a catch handler should resume
  489. normal control flow, so neither ``catchpad`` nor ``catchret`` instructions can
  490. unwind. All of these "unwind edges" may refer to a basic block that contains an
  491. EH pad instruction, or they may unwind to the caller. Unwinding to the caller
  492. has roughly the same semantics as the ``resume`` instruction in the landingpad
  493. model. When inlining through an invoke, instructions that unwind to the caller
  494. are hooked up to unwind to the unwind destination of the call site.
  495. Putting things together, here is a hypothetical lowering of some C++ that uses
  496. all of the new IR instructions:
  497. .. code-block:: c
  498. struct Cleanup {
  499. Cleanup();
  500. ~Cleanup();
  501. int m;
  502. };
  503. void may_throw();
  504. int f() noexcept {
  505. try {
  506. Cleanup obj;
  507. may_throw();
  508. } catch (int e) {
  509. may_throw();
  510. return e;
  511. }
  512. return 0;
  513. }
  514. .. code-block:: text
  515. define i32 @f() nounwind personality i32 (...)* @__CxxFrameHandler3 {
  516. entry:
  517. %obj = alloca %struct.Cleanup, align 4
  518. %e = alloca i32, align 4
  519. %call = invoke %struct.Cleanup* @"\01??0Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj)
  520. to label %invoke.cont unwind label %lpad.catch
  521. invoke.cont: ; preds = %entry
  522. invoke void @"\01?may_throw@@YAXXZ"()
  523. to label %invoke.cont.2 unwind label %lpad.cleanup
  524. invoke.cont.2: ; preds = %invoke.cont
  525. call void @"\01??_DCleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
  526. br label %return
  527. return: ; preds = %invoke.cont.3, %invoke.cont.2
  528. %retval.0 = phi i32 [ 0, %invoke.cont.2 ], [ %3, %invoke.cont.3 ]
  529. ret i32 %retval.0
  530. lpad.cleanup: ; preds = %invoke.cont.2
  531. %0 = cleanuppad within none []
  532. call void @"\01??1Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
  533. cleanupret %0 unwind label %lpad.catch
  534. lpad.catch: ; preds = %lpad.cleanup, %entry
  535. %1 = catchswitch within none [label %catch.body] unwind label %lpad.terminate
  536. catch.body: ; preds = %lpad.catch
  537. %catch = catchpad within %1 [%rtti.TypeDescriptor2* @"\01??_R0H@8", i32 0, i32* %e]
  538. invoke void @"\01?may_throw@@YAXXZ"()
  539. to label %invoke.cont.3 unwind label %lpad.terminate
  540. invoke.cont.3: ; preds = %catch.body
  541. %3 = load i32, i32* %e, align 4
  542. catchret from %catch to label %return
  543. lpad.terminate: ; preds = %catch.body, %lpad.catch
  544. cleanuppad within none []
  545. call void @"\01?terminate@@YAXXZ"
  546. unreachable
  547. }
  548. Funclet parent tokens
  549. -----------------------
  550. In order to produce tables for EH personalities that use funclets, it is
  551. necessary to recover the nesting that was present in the source. This funclet
  552. parent relationship is encoded in the IR using tokens produced by the new "pad"
  553. instructions. The token operand of a "pad" or "ret" instruction indicates which
  554. funclet it is in, or "none" if it is not nested within another funclet.
  555. The ``catchpad`` and ``cleanuppad`` instructions establish new funclets, and
  556. their tokens are consumed by other "pad" instructions to establish membership.
  557. The ``catchswitch`` instruction does not create a funclet, but it produces a
  558. token that is always consumed by its immediate successor ``catchpad``
  559. instructions. This ensures that every catch handler modelled by a ``catchpad``
  560. belongs to exactly one ``catchswitch``, which models the dispatch point after a
  561. C++ try.
  562. Here is an example of what this nesting looks like using some hypothetical
  563. C++ code:
  564. .. code-block:: c
  565. void f() {
  566. try {
  567. throw;
  568. } catch (...) {
  569. try {
  570. throw;
  571. } catch (...) {
  572. }
  573. }
  574. }
  575. .. code-block:: text
  576. define void @f() #0 personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*) {
  577. entry:
  578. invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
  579. to label %unreachable unwind label %catch.dispatch
  580. catch.dispatch: ; preds = %entry
  581. %0 = catchswitch within none [label %catch] unwind to caller
  582. catch: ; preds = %catch.dispatch
  583. %1 = catchpad within %0 [i8* null, i32 64, i8* null]
  584. invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
  585. to label %unreachable unwind label %catch.dispatch2
  586. catch.dispatch2: ; preds = %catch
  587. %2 = catchswitch within %1 [label %catch3] unwind to caller
  588. catch3: ; preds = %catch.dispatch2
  589. %3 = catchpad within %2 [i8* null, i32 64, i8* null]
  590. catchret from %3 to label %try.cont
  591. try.cont: ; preds = %catch3
  592. catchret from %1 to label %try.cont6
  593. try.cont6: ; preds = %try.cont
  594. ret void
  595. unreachable: ; preds = %catch, %entry
  596. unreachable
  597. }
  598. The "inner" ``catchswitch`` consumes ``%1`` which is produced by the outer
  599. catchswitch.
  600. .. _wineh-constraints:
  601. Funclet transitions
  602. -----------------------
  603. The EH tables for personalities that use funclets make implicit use of the
  604. funclet nesting relationship to encode unwind destinations, and so are
  605. constrained in the set of funclet transitions they can represent. The related
  606. LLVM IR instructions accordingly have constraints that ensure encodability of
  607. the EH edges in the flow graph.
  608. A ``catchswitch``, ``catchpad``, or ``cleanuppad`` is said to be "entered"
  609. when it executes. It may subsequently be "exited" by any of the following
  610. means:
  611. * A ``catchswitch`` is immediately exited when none of its constituent
  612. ``catchpad``\ s are appropriate for the in-flight exception and it unwinds
  613. to its unwind destination or the caller.
  614. * A ``catchpad`` and its parent ``catchswitch`` are both exited when a
  615. ``catchret`` from the ``catchpad`` is executed.
  616. * A ``cleanuppad`` is exited when a ``cleanupret`` from it is executed.
  617. * Any of these pads is exited when control unwinds to the function's caller,
  618. either by a ``call`` which unwinds all the way to the function's caller,
  619. a nested ``catchswitch`` marked "``unwinds to caller``", or a nested
  620. ``cleanuppad``\ 's ``cleanupret`` marked "``unwinds to caller"``.
  621. * Any of these pads is exited when an unwind edge (from an ``invoke``,
  622. nested ``catchswitch``, or nested ``cleanuppad``\ 's ``cleanupret``)
  623. unwinds to a destination pad that is not a descendant of the given pad.
  624. Note that the ``ret`` instruction is *not* a valid way to exit a funclet pad;
  625. it is undefined behavior to execute a ``ret`` when a pad has been entered but
  626. not exited.
  627. A single unwind edge may exit any number of pads (with the restrictions that
  628. the edge from a ``catchswitch`` must exit at least itself, and the edge from
  629. a ``cleanupret`` must exit at least its ``cleanuppad``), and then must enter
  630. exactly one pad, which must be distinct from all the exited pads. The parent
  631. of the pad that an unwind edge enters must be the most-recently-entered
  632. not-yet-exited pad (after exiting from any pads that the unwind edge exits),
  633. or "none" if there is no such pad. This ensures that the stack of executing
  634. funclets at run-time always corresponds to some path in the funclet pad tree
  635. that the parent tokens encode.
  636. All unwind edges which exit any given funclet pad (including ``cleanupret``
  637. edges exiting their ``cleanuppad`` and ``catchswitch`` edges exiting their
  638. ``catchswitch``) must share the same unwind destination. Similarly, any
  639. funclet pad which may be exited by unwind to caller must not be exited by
  640. any exception edges which unwind anywhere other than the caller. This
  641. ensures that each funclet as a whole has only one unwind destination, which
  642. EH tables for funclet personalities may require. Note that any unwind edge
  643. which exits a ``catchpad`` also exits its parent ``catchswitch``, so this
  644. implies that for any given ``catchswitch``, its unwind destination must also
  645. be the unwind destination of any unwind edge that exits any of its constituent
  646. ``catchpad``\s. Because ``catchswitch`` has no ``nounwind`` variant, and
  647. because IR producers are not *required* to annotate calls which will not
  648. unwind as ``nounwind``, it is legal to nest a ``call`` or an "``unwind to
  649. caller``\ " ``catchswitch`` within a funclet pad that has an unwind
  650. destination other than caller; it is undefined behavior for such a ``call``
  651. or ``catchswitch`` to unwind.
  652. Finally, the funclet pads' unwind destinations cannot form a cycle. This
  653. ensures that EH lowering can construct "try regions" with a tree-like
  654. structure, which funclet-based personalities may require.
  655. Exception Handling support on the target
  656. =================================================
  657. In order to support exception handling on particular target, there are a few
  658. items need to be implemented.
  659. * CFI directives
  660. First, you have to assign each target register with a unique DWARF number.
  661. Then in ``TargetFrameLowering``'s ``emitPrologue``, you have to emit `CFI
  662. directives <https://sourceware.org/binutils/docs/as/CFI-directives.html>`_
  663. to specify how to calculate the CFA (Canonical Frame Address) and how register
  664. is restored from the address pointed by the CFA with an offset. The assembler
  665. is instructed by CFI directives to build ``.eh_frame`` section, which is used
  666. by th unwinder to unwind stack during exception handling.
  667. * ``getExceptionPointerRegister`` and ``getExceptionSelectorRegister``
  668. ``TargetLowering`` must implement both functions. The *personality function*
  669. passes the *exception structure* (a pointer) and *selector value* (an integer)
  670. to the landing pad through the registers specified by ``getExceptionPointerRegister``
  671. and ``getExceptionSelectorRegister`` respectively. On most platforms, they
  672. will be GPRs and will be the same as the ones specified in the calling convention.
  673. * ``EH_RETURN``
  674. The ISD node represents the undocumented GCC extension ``__builtin_eh_return (offset, handler)``,
  675. which adjusts the stack by offset and then jumps to the handler. ``__builtin_eh_return``
  676. is used in GCC unwinder (`libgcc <https://gcc.gnu.org/onlinedocs/gccint/Libgcc.html>`_),
  677. but not in LLVM unwinder (`libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_).
  678. If you are on the top of ``libgcc`` and have particular requirement on your target,
  679. you have to handle ``EH_RETURN`` in ``TargetLowering``.
  680. If you don't leverage the existing runtime (``libstdc++`` and ``libgcc``),
  681. you have to take a look on `libc++ <https://libcxx.llvm.org/>`_ and
  682. `libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_
  683. to see what have to be done there. For ``libunwind``, you have to do the following
  684. * ``__libunwind_config.h``
  685. Define macros for your target.
  686. * ``include/libunwind.h``
  687. Define enum for the target registers.
  688. * ``src/Registers.hpp``
  689. Define ``Registers`` class for your target, implement setter and getter functions.
  690. * ``src/UnwindCursor.hpp``
  691. Define ``dwarfEncoding`` and ``stepWithCompactEncoding`` for your ``Registers``
  692. class.
  693. * ``src/UnwindRegistersRestore.S``
  694. Write an assembly function to restore all your target registers from the memory.
  695. * ``src/UnwindRegistersSave.S``
  696. Write an assembly function to save all your target registers on the memory.