Escape analysis

Chad J gamerchad at __spam.is.bad__gmail.com
Thu Oct 30 08:35:20 PDT 2008


I wonder if it would be easy enough to allocate closures lazily at runtime.

So the compiler scans executable code, and any time there is an 
assignment (passing as function args doesn't count, returning does) 
involving delegates, it inserts code that will do the following:
- Check whether the delegate being assigned from is on the stack or the 
heap.
- If it's on the stack, make a copy on the heap, and use that.

Scope (partial) closures never get assigned to other things, so no extra 
code will ever be generated or executed for them.

I worry that this might be more complicated with multithreading though.

Also, I'm not sure how to make sure all calls to the closure access the 
same context, and that the function that contains the context also knows 
when it's context has moved off of the stack and into the heap.  I'm not 
sure of this because I'm also not sure how that's handled anyways.

Also notable is that the heuristic I suggest is just that; it is not 
necessarily optimal or even strictly lazy.  There are cases where 
delegates could be passed around by assignment yet never escape their 
scope.  Maybe it is easy enough to add that as another condition for the 
runtime check: is this delegate being assigned to some place in the heap 
or too far up (down?) in the stack?  Just an optimization though, and 
probably one not nearly as important.

OK so all of this doesn't help much with the more general problem of 
/static/ escape analysis.  Oh well.



More information about the Digitalmars-d mailing list