为什么在 C 中没有优化本地函数指针调用?

问题描述

使用编译器资源管理器,我发现本地函数指针调用没有被优化掉:

static int action1(void) { return 1; }
static int action2(void) { return 2; }
int test(int x) {
   int (*const action)() = x > 5 ? action1 : action2;
   return 1 + action();
}

// yielded :

action1():
       mov     eax,1
       ret
action2():
       mov     eax,2
       ret
test(int):
       sub     rsp,8
       mov     edx,OFFSET FLAT:action2()
       cmp     edi,5
       mov     eax,OFFSET FLAT:action1()
       cmovle  rax,rdx
       call    rax
       add     rsp,8
       add     eax,1
       ret

然而:

int test2(void) { return test(6); }

// yields

test2:                                  # @test2
        mov     eax,2
        ret

建议动作调用的结果可以在编译时确定。

x86 gcc 10.2 和 clang 11.0 (-O2) 上的行为似乎相同。

Q0) 是否有某种原因无法优化掉函数指针调用

Q1) 如果可以做到,有什么理由不可以吗?

Q2) 也许更重要的是,我如何写这样的东西,但让它内联 action1 和 action2 :

static int testHelper6(int x,int callback(int)) {
    return 1 + callback(x);
}
int test6(int x) {
    return testHelper6(x,x > 5 ? action1 : action2);
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)