[LLVMdev] Is there a "callback optimization"?

Eli Friedman eli.friedman at gmail.com
Fri Jun 4 11:30:06 PDT 2010


On Fri, Jun 4, 2010 at 7:53 AM, Kenneth Uildriks <kennethuil at gmail.com> wrote:
> By that I mean an optimization pass (or a combination of them) that turns:
>
> void useCallback(void (*callbackfn)())
> {
> // Do something
> callbackfn();
> // Do something else
> }
>
> void myCallback()
> {
> // Respond one way
> }
>
> void myOtherCallback()
> {
> // Respond another way
> }
>
> void foo()
> {
> useCallback(myCallback);
> useCallback(myOtherCallback);
> }
>
>
> into:
>
> // Keep the original; it'll get removed
> // by other passes if it's nonpublic and dead.
> void useCallback(void (*callbackfn)())
> {
> // Do something
> callbackfn();
> // Do something else
> }
>
> void myCallback()
> {
> // Respond one way
> }
>
> void myOtherCallback()
> {
> // Respond another way
> }
>
> // equivalent of useCallback(myCallback), but doesn't call through a
> function pointer.
> void useMyCallback()
> {
> // Do something.
> myCallback();
> // Do something else
> }
>
> // equivalent of useCallback(myOtherCallback), but doesn't call
> through a function pointer.
> void useMyOtherCallback()
> {
> // Do something
> myOtherCallback();
> // Do something else
> }
>
> // Changed to use non-virtual versions created above.
> void foo()
> {
> useMyCallback();
> useMyOtherCallback();
> }
>
> With that transform in place, lots of inlining becomes possible, and
> direct function calls replace indirect function calls if inlining
> isn't appropriate.  If this transform is combined with argpromotion
> and scalarrepl, it can be used for devirtualization of C++ virtual
> function calls.
>
> There seems to be an awful lot of C++ code out there that uses
> templates to perform this same optimization in source code.

There's a partial specialization pass that can do this sort of thing
(IIRC not enabled by default); if you really need the transformation
you're describing, you can adapt it appropriately.  That said, if the
inliner doesn't decide to inline useCallback, duplicating the function
without inlining it is probably a bad idea in terms of codesize.  IIRC
the inliner heuristics already strongly favor inlining in cases like
the given example, but it's possible that the inliner heuristics could
use some additional tweaking.

-Eli




More information about the llvm-dev mailing list