2

So, I have this code that works as expected:

#include <stdio.h>

int main () {
    unsigned int i;
    int x=5;

    __asm__ ("movl %1, %0;"
             "subl %2, %0;"
           : "=r" (i)
           : "r" (4), "r" (x)
           : "0");

     __asm__ ("movl %1, %0;"
           : "=r" (x)
           : "r" (i)
           : "0");

    printf("%d\n", x);
    return 0;
}

How do I merge the two calls into one?

2 Answers 2

1

The first __asm__ sets: i <- 4 - x. The second sets: x <- i. They can be combined as:

__asm__ ("subl %k2, %k0" : "=r" (x) : "0" ((unsigned)(4)), "g" (x));

No clobbers are needed (unless you want to include "cc", which is always assumed by gcc anyway), and there's no issue of inputs being overwritten before they are read. The "g" constraint indicates that a register, memory, or immediate operand is acceptable. The output should be: "-1" in this case: x <- 4 - 5

Note: the first __asm__ should have =&r for its output. Furthermore, neither should list %0 as clobbered - this is implicit, as %0 is an output in both cases.

Sign up to request clarification or add additional context in comments.

Comments

1

Those are nonsensical asm blocks to start with. Rule of thumb is, if you ever use a mov you are probably doing it wrong. Also, even though you claimed it works as expected, the code is broken. Nothing stops the compiler from allocating %2 to the same register as %0 producing wrong code. You were just lucky it didn't happen for you.

Anyway, the second asm block simply copies i into x. As such a merged asm could look like:

__asm__ ("movl %2, %0;"
         "subl %3, %0;"
         "movl %0, %1;"
           : "=&r" (i), "=r" (x)
           : "r" (4), "r" (x));

This is of course still silly, but at least it isn't technically wrong. Notice the early-clobber & modifier for the first output. It isn't needed for the second, however.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.