c - 这两条指令在下面的函数中做了什么?

标签 c assembly x86

所以我几乎是 IA32 汇编语言的菜鸟。我尝试将此 C 函数编译为 IA32 程序集 (-mpreferred-stack-boundary=2):

__attribute__((cdecl))
int odd_sum(int a[], int n, int sum) {
  if (n == 0) return sum;
  else if ((a[n-1] % 2) == 0)
    return odd_sum(a, n-1, sum);
  else return odd_sum(a, n-1, sum + a[n-1]);
}

GCC 输出如下:

    .file   "test.c"
    .text
    .globl  _odd_sum
    .def    _odd_sum;   .scl    2;  .type   32; .endef
_odd_sum:
LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    subl    $12, %esp
    cmpl    $0, 12(%ebp)
    jne L2
    movl    16(%ebp), %eax
    jmp L3
L2:
    movl    12(%ebp), %eax
    addl    $1073741823, %eax
    leal    0(,%eax,4), %edx
    movl    8(%ebp), %eax
    addl    %edx, %eax
    movl    (%eax), %eax
    andl    $1, %eax
    testl   %eax, %eax
    jne L4
    movl    12(%ebp), %eax
    leal    -1(%eax), %edx
    movl    16(%ebp), %eax
    movl    %eax, 8(%esp)
    movl    %edx, 4(%esp)
    movl    8(%ebp), %eax
    movl    %eax, (%esp)
    call    _odd_sum
    jmp L3
L4:
    movl    12(%ebp), %eax
    addl    $1073741823, %eax
    leal    0(,%eax,4), %edx
    movl    8(%ebp), %eax
    addl    %edx, %eax
    movl    (%eax), %edx
    movl    16(%ebp), %eax
    addl    %eax, %edx
    movl    12(%ebp), %eax
    subl    $1, %eax
    movl    %edx, 8(%esp)
    movl    %eax, 4(%esp)
    movl    8(%ebp), %eax
    movl    %eax, (%esp)
    call    _odd_sum
L3:
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
LFE0:
    .ident  "GCC: (MinGW.org GCC-8.2.0-3) 8.2.0"

我无法理解的是这两行:

   addl    $1073741823, %eax
   leal    0(,%eax,4), %edx

我知道这两行应该与 a[n-1] 有关,但我似乎无法理解它们在这个过程中到底做了什么。有人可以帮我解决这个问题吗?

最佳答案

这只是一种计算数组 a[n-1] 偏移量的奇特方法。

10737418230x3fffffff。例如,如果 n 为 3,它将添加它们并得到 0x40000002。然后它用第二条指令乘以 4,得到 0x00000008,丢弃最高位。

所以我们剩下 8 个字节的偏移量,这正是 a[n-1] 所需的偏移量(以字节为单位),即 a[2](当 int 的大小为 4 个字节时)。

关于c - 这两条指令在下面的函数中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65607463/

相关文章:

c - c 指针字符串的问题

c - 使用 "="为内部的 char 数组分配结构有效吗?

c - 如何查看errno的值?

assembly - 68k ASM 寻址模式

assembly - 引用没有美元符号的常量是否有不同的含义?

c - 如何将反汇编的C代码划分为函数?

c - 在串行通信的情况下,tcgetattr 的错误 9 是什么

assembly - 'callq *(%rax)' 是什么意思?

assembly - 有没有一种简单的方法可以在 AT&T 程序集 : %eax * %ebx = %ecx 中将两个寄存器相乘

assembly - MOV EAX, DWORD PTR DS :[ESI] mean and what does it do? 是什么意思