GCC extended asm, struct element offset encoding

前端 未结 2 1206
情深已故
情深已故 2021-01-12 09:57

I am trying to write a small piece of my code in GCC style extended asm (x86-64 target) and am having trouble encoding struct offsets.

I have a struct s

相关标签:
2条回答
  • 2021-01-12 10:04

    Your only option is to use Intel syntax. GCC, of course, can generate insn like mov off(base, index, scale), but does this on the level of whole MEM RTL expressions, i.e. not having offset, base, etc like individual operands.

    So, Intel syntax, compile the following with gcc -c -masm=intel x.c:

    #include <stddef.h>
    
    struct s
    {
      int a, b;
    };
    
    int foo (struct s *s, int i)
    {
      int r;
      asm (
           "mov %[r], dword ptr [%[s]+%[index]*8 + %[displ]] "
           : [r] "=r" (r)
           : [s] "r" (s) , [index] "r" (i),
             [displ] "e" (offsetof(struct s, b))
           :
           );
    
      return r;
    }
    
    0 讨论(0)
  • 2021-01-12 10:12

    It actually is possible, using the %c... operand modifier:

    #include <stddef.h>
    #include <stdint.h>
    
    struct s
    {
      int a, b;
    };
    
    int foo (struct s *s, int i)
    {
      int r;
      asm (
           "movl %c[displ](%[s],%[index],8), %[r]\n\t"
           : [r] "=r" (r)
           : [s] "r" (s) , [index] "r" ((uintptr_t)i),
             [displ] "e" (offsetof(struct s, b))
           :
           );
    
      return r;
    }

    Thanks where thanks is due - found that here. There's a gcc mailing list posting referring to this as well; the keywords there are "output substitution".
    The stackoverflow posting What does %c mean in GCC inline assembly code? also has an explanation about %c in particular.

    0 讨论(0)
提交回复
热议问题