You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GCC中两个代码完全相同的函数为何生成的汇编代码不同?

GCC中代码一致的函数生成不同汇编的问题

问题描述

在GCC编译器中,存在两个代码完全一致的函数foo和bar,但它们生成的汇编代码却存在差异。

代码示例

#define OPPOSITE(c) (*((typeof(x) *)&(x)))

int foo(volatile int x)
{
    OPPOSITE(x) = OPPOSITE(x) + OPPOSITE(x);
    return x;
}

int bar(volatile int x)
{
    OPPOSITE(x) = OPPOSITE(x) + OPPOSITE(x);
    return x;
}

x86平台编译结果(-Os优化级别)

foo:
        mov     DWORD PTR [rsp-4], edi
        mov     eax, DWORD PTR [rsp-4]
        mov     edx, DWORD PTR [rsp-4]
        add     eax, edx
        mov     DWORD PTR [rsp-4], eax
        mov     eax, DWORD PTR [rsp-4]
        ret
bar:
        mov     DWORD PTR [rsp-4], edi
        mov     eax, DWORD PTR [rsp-4]
        add     eax, eax
        ret

ARM平台编译结果(-O3优化级别)

foo:
        sub     sp, sp, #8
        str     r0, [sp, #4]
        ldr     r3, [sp, #4]
        ldr     r2, [sp, #4]
        add     r3, r3, r2
        str     r3, [sp, #4]
        ldr     r0, [sp, #4]
        add     sp, sp, #8
        bx      lr
bar:
        sub     sp, sp, #8
        str     r0, [sp, #4]
        ldr     r0, [sp, #4]
        lsl     r0, r0, #1
        add     sp, sp, #8
        bx      lr

内容的提问来源于stack exchange,提问作者0___________

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:10:26