mbschenkel
mbschenkel

Reputation: 1905

Trying to skip vtable and inline call in a case where type is known

Update: This seems to be specific to gcc < 4.9, which improved devirtualization.


On a polymorphic class hierarchy I have a non-virtual interface function (let's call her algorithm) that calls some (here for simplicity just one) virtual method (call it customization) of the class. When this algorithm is invoqued on a specific instance of a derived class, vtable calls would not be needed, because the exact type is known.

Now I've ended up having such a call at an inner loop and would like to have it inlined. How can this be achieved?

struct Base 
{
    inline virtual void customization(int i) {};
    inline void algorithm(int i) { customization(i); }
};

struct Derived : public Base
{
    // Adding this to every derived class instead of just the base will help, 
    // but is the kind of duplication I would like to avoid:
    // inline void algorithm(int i) { customization(i); }
    inline void customization(int i) override final { helper(i) };
};

void my_main()
{
    // Note that these are concrete instances, not references ..
    Derived d1, d2; 
    d1.algorithm(111);
    d2.algorithm(222);

    // ... which could just be optimized into the following, ...
    helper(111);
    helper(222);

    // ... but instead vtable calls to Base::algorithms result, behaving just as if it was
    static_cast<Base&>(d1).algorithm(111);
    static_cast<Base&>(d2).algorithm(222);
}

The following snippets from this godbolt example illustrates that.

Actual result:

enter image description here

Desired result:

enter image description here

Upvotes: 3

Views: 153

Answers (0)

Related Questions