[LLVMdev] Implementing try/catch/finally

Joachim Durchholz jo at durchholz.org
Mon Apr 21 04:31:25 PDT 2008


Am Montag, den 21.04.2008, 01:31 -0700 schrieb Talin:
> Duncan Sands wrote:
> >> One approach would be to simply duplicate the code in the 'finally' 
> >> block for each exit, but that seems sub-optimal. It would be better, I 
> >> think, to set a state variable before entering the 'finally' block, and 
> >> then have it do a switch instruction at the end and transfer to the 
> >> appropriate block.
> >>     
> >
> > I think gcc just duplicates the block (see tree-eh.c).  I suggest that
> > to start with you do the same, because it is simple to do, and then once
> > everything is working well look into improving the code quality.
> >
> > Ciao,
> >
> > Duncan.
> >   
> Interesting.
> 
> After doing some more research, I noticed that Java uses a jsr to 
> implement 'finally', at least according to this document:
> 
>   http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html

That's to prevent the code duplication mentioned above.
(The JVM could handle it via code duplication, too.)

Another way to compile (pseudocode)
  try
    a
  catch
    e1 -> h1
    e2 -> h2
  finally
    f

might be

  code for a
  _f: code for f
  ret

  _h1: code for h1
  jmp _f

  _h2: code for h2
  jmp _f

  exception table:
    Code for a, type e1: _h1
    Code for a, type e2: _h2

This would even keep the normal a-f-return flow in line, with no code
duplication - with the constraint that you have an exception table that
maps code ranges and exception types to jump addresses. (I don't know
what mechanism LLVM uses, but I'd expect it's similar enough.)

Regards,
Jo




More information about the llvm-dev mailing list