How Do I Use Labels In GCC Inline Assembly?

后端 未结 3 1235
攒了一身酷
攒了一身酷 2020-12-10 09:29

I\'m trying to learn x86-64 inline assembly and decided to implement this very simple swap method that simply orders a and b in ascending order:

3条回答
  •  执笔经年
    2020-12-10 10:12

    You cannot just put a bunch of asm statements inline like that. The optimizer is free to re-order, duplicate, and drop them based on what constraints it knows. (In your case, it knows none.)

    So firstly, you should consolidate the asm together, with proper read/write/clobber constraints. Secondly, there is a special asm goto form that gives assembly to C-level labels.

    void swap(int *a, int *b) {
        int tmp1, tmp2;
        asm(
            "mov (%2), %0\n"
            "mov (%3), %1\n"
            : "=r" (tmp1), "=r" (tmp2)
            : "r" (a), "r" (b)
            : "memory"   // pointer in register doesn't imply that the pointed-to memory has to be "in sync"
            // or use "m" memory source operands to let the compiler pick the addressing mode
        );
        asm goto(
            "cmp %1, %0\n"
            "jle %l4\n"
            "mov %1, (%2)\n"
            "mov %0, (%3)\n"
            :
            : "r" (tmp1), "r" (tmp2), "r" (a), "r" (b)
            : "cc", "memory"
            : L1
        );
    L1:
        return;
    }
    

提交回复
热议问题