c - GCC 扩展 asm,struct 元素偏移编码

标签 c gcc inline-assembly i386

我正在尝试用 GCC 风格的扩展 asm(x86-64 目标)编写一小段代码,但在编码结构偏移量时遇到了问题。

我有一个struct s,它有一个成员size_t a[],一个指向这样一个结构的指针和一个索引,它们都是在asm block 中生成的。

现在我需要在 asm 中处理该元素

asm (
    "mov %[displ](%[s], %[index], 8), %%rbx"
    : [s] "+r" (s)
    , [index] "+r" (i)
    : "memory", "cc", "rax", "rbx"
);

如何将 displ 编码到 asm block 中?将 offsetof(struct s, a) 作为立即前缀传递给 $ 并生成无效程序集。

asm (
    "mov %[displ](%[s], %[index], 8), %%rbx"
    : [s] "+r" (s)
    , [index] "+r" (i)
    : [displ] "i" (offsetof(struct s, a))
    : "memory", "cc", "rax", "rbx"
);

最佳答案

实际上 是可能的,使用 %c... 操作数修饰符:

#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;
}

感谢该感谢的地方 - 发现 here .有 a gcc mailing list posting也引用这个;那里的关键字是“输出替换”。
stackoverflow 发帖 What does %c mean in GCC inline assembly code?也有关于 %c 特别的解释。

关于c - GCC 扩展 asm,struct 元素偏移编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254512/

相关文章:

c - 涉及 sin() 的两个非常相似的函数表现出截然不同的性能——为什么?

c++ - DLL 加载时未解析的符号

gcc - 在扩展内联 ASM 中调用 printf

c - asm、asm volatile 和 clobbering 内存之间的区别

c - 如果malloc()仅分配一个只能为一个变量存储的内存块,如何将其用于创建动态数组?

c - 如何在 int main() C 编程中调用您创建的函数?

c - 在 C 中省略变量的 extern,但仍然有效?

c++ - 在条件表达式中使用时,gcc 或其他编译器是否自动将按位或转换为 bool 值或?

c - gcc 删除内联汇编代码

c - 将十六进制格式的整数数组保存到 char "string"