gpt4 book ai didi

c - 在 x86 中,为什么我有两次相同的指令,但操作数相反?

转载 作者:IT王子 更新时间:2023-10-29 00:05:58 27 4
gpt4 key购买 nike

我正在对 x86 asm 进行多项实验,试图了解通用语言构造如何映射到汇编中。在我目前的实验中,我试图具体了解 C 语言指针如何映射到寄存器间接寻址。我写了一个非常像指针程序的 hello-world:

#include <stdio.h>

int
main (void)
{
int value = 5;
int *int_val = &value;

printf ("The value we have is %d\n", *int_val);
return 0;
}

并使用以下代码将其编译为以下 asm:gcc -o pointer.s -fno-asynchronous-unwind-tables pointer.c:[1][2]

        .file   "pointer.c"
.section .rodata
.LC0:
.string "The value we have is %d\n"
.text
.globl main
.type main, @function
main:
;------- function prologue
pushq %rbp
movq %rsp, %rbp
;---------------------------------
subq $32, %rsp
movq %fs:40, %rax
movq %rax, -8(%rbp)
xorl %eax, %eax
;----------------------------------
movl $5, -20(%rbp) ; This is where the value 5 is stored in `value` (automatic allocation)
;----------------------------------
leaq -20(%rbp), %rax ;; (GUESS) If I have understood correctly, this is where the address of `value` is
;; extracted, and stored into %rax
;----------------------------------
movq %rax, -16(%rbp) ;;
movq -16(%rbp), %rax ;; Why do I have two times the same instructions, with reversed operands???
;----------------------------------
movl (%rax), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
;----------------------------------
movl $0, %eax
movq -8(%rbp), %rdx
xorq %fs:40, %rdx
je .L3
call __stack_chk_fail
.L3:
leave
ret
.size main, .-main
.ident "GCC: (Ubuntu 4.9.1-16ubuntu6) 4.9.1"
.section .note.GNU-stack,"",@progbits

我的问题是我不明白为什么它包含指令 movq 两次,操作数相反。有人可以向我解释一下吗?

[1]:当我根本不需要它们时,我想避免让我的 asm 代码与 cfi 指令交织在一起。

[2]: 我的环境是Ubuntu 14.10, gcc 4.9.1 (由ubuntu修改), Gnu assembler (GNU Binutils for Ubuntu) 2.24 .90.20141014,配置为目标 x86_64-linux-gnu

最佳答案

如果你重新组织你的 block ,也许会更清楚:

;----------------------------------
leaq -20(%rbp), %rax ; &value
movq %rax, -16(%rbp) ; int_val
;----------------------------------
movq -16(%rbp), %rax ; int_val
movl (%rax), %eax ; *int_val
movl %eax, %esi ; printf-argument
movl $.LC0, %edi ; printf-argument (format-string)
movl $0, %eax ; no floating-point numbers
call printf
;----------------------------------

第一个 block 执行int *int_val = &value;,第二个 block 执行printf ...。没有优化, block 是独立的。

关于c - 在 x86 中,为什么我有两次相同的指令,但操作数相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28174710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com