簡體   English   中英

cmpl和jge無法正常工作,x86

[英]cmpl and jge not working as exected, x86

我必須翻譯以下簡單的C代碼:

int add(int a, int b);

int main()
{
    int a,b;
    a = 0;
    while(a<5)
    {
        a++;
        printi(a);
        prints("\n");
    }
    return 0;
}

int add(int a, int b)
{
    char cx = 'a';
    int x = a-b;
    return x;
}

我制作了一個編譯器,將其翻譯為以下GNU x86匯編代碼。 (printi和prints是我翻譯后鏈接的庫函數)。

.section    .rodata
.LC0:
    .string "\n"
    .text
    .globl  main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    movl    $0, -4(%ebp)
    movl    -4(%ebp), %eax
    movl    %eax, -12(%ebp)
.L0:
    movl    $5, %eax
    movl    -4(%ebp), %edx
    cmpl    %edx, %eax
    jge .CH1
.CH0:
    movl    $1, -16(%ebp)
    jmp .CH2
.CH1:
    movl    $0, -16(%ebp)
.CH2:
    movl    $0, %eax
    cmpl    -16(%ebp), %eax
    je  .L2
    jmp .L1
.L1:
    movl    -4(%ebp), %eax
    movl    %eax, -20(%ebp)
    movl    -20(%ebp), %eax
    movl    $1, %edx
    addl    %edx, %eax
    movl    %eax, -4(%ebp)
    movl    -4(%ebp), %eax
    movl    %eax, (%esp)
    call    printi
    movl    %eax, -24(%ebp)
    movl    $.LC0, (%esp)
    call    prints
    movl    %eax, -28(%ebp)
    jmp .L0
.L2:
    movl    $0, %eax
    leave
    ret
    .size   main, .-main
    .globl  add
    .type   add, @function
add:
    pushl   %ebp
    movl    %esp, %ebp
    movb    $97, -1(%ebp)
    movl    4(%ebp), %eax
    movl    8(%ebp), %edx
    subl    %edx, %eax
    movl    %eax, -9(%ebp)
    movl    -9(%ebp), %eax
    movl    %eax, -5(%ebp)
    movl    -5(%ebp), %eax
    leave
    ret
    .size   add, .-add

但是該程序不輸出任何內容。 看來我在while的檢查表達式周圍某個地方犯了一個錯誤。

cmpl %edx, %eax指令cmpl %edx, %eax標志設置為0-5,即-5。 因此jge不應將其分支到.CH1。 因此,應該將-16(%ebp)設置為1,然后進入.CH2。 當1!= 0時,它應該進入L1。 我不知道我要去哪里錯了。

cmpl %edx, %eax指令cmpl %edx, %eax標志設置為0-5,即-5。 Ĵ

不。 請記住,在AT&T語法中,操作數的順序是source, destination 您已經有了eax = 5edx = 0 ,因此cmpl %edx, %eax基於5-0設置標志,之后jge 應該跳轉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM