【问题标题】:How to access C struct/variables from inline asm?如何从内联 asm 访问 C 结构/变量?
【发布时间】:2015-12-20 20:34:31
【问题描述】:

考虑以下代码:

    int bn_div(bn_t *bn1, bn_t *bn2, bn_t *bnr)
  {
    uint32 q, m;        /* Division Result */
    uint32 i;           /* Loop Counter */
    uint32 j;           /* Loop Counter */

    /* Check Input */
    if (bn1 == NULL) return(EFAULT);
    if (bn1->dat == NULL) return(EFAULT);
    if (bn2 == NULL) return(EFAULT);
    if (bn2->dat == NULL) return(EFAULT);
    if (bnr == NULL) return(EFAULT);
    if (bnr->dat == NULL) return(EFAULT);


    #if defined(__i386__) || defined(__amd64__)
    __asm__ (".intel_syntax noprefix");
    __asm__ ("pushl %eax");
    __asm__ ("pushl %edx");
    __asm__ ("pushf");
    __asm__ ("movl %eax, (bn1->dat[i])");
    __asm__ ("xorl %edx, %edx");
    __asm__ ("divl (bn2->dat[j])");
    __asm__ ("movl (q), %eax");
    __asm__ ("movl (m), %edx");
    __asm__ ("popf");
    __asm__ ("popl %edx");
    __asm__ ("popl %eax");
    #else
    q = bn->dat[i] / bn->dat[j];
    m = bn->dat[i] % bn->dat[j];
    #endif
    /* Return */
    return(0);
  }

数据类型 uint32 基本上是 unsigned long int 或 uint32_t 无符号 32 位整数。 bnint 类型是 unsigned short int (uint16_t) 或 uint32_t,具体取决于 64 位数据类型是否可用。如果 64 位可用,则 bnint 为 uint32,否则为 uint16。这样做是为了在代码的其他部分捕获进位/溢出。结构体bn_t定义如下:

typedef struct bn_data_t bn_t;
struct bn_data_t
  {
    uint32 sz1;         /* Bit Size */
    uint32 sz8;         /* Byte Size */
    uint32 szw;         /* Word Count */
    bnint *dat;         /* Data Array */
    uint32 flags;       /* Operational Flags */
  };

该函数从我的源代码的第 300 行开始。所以当我尝试编译/制作它时,我收到以下错误:

system:/home/user/c/m3/bn 1036 $$$ ->make
clang -I. -I/home/user/c/m3/bn/.. -I/home/user/c/m3/bn/../include  -std=c99 -pedantic -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-align -Wstrict-prototypes  -Wmissing-prototypes -Wnested-externs -Wwrite-strings -Wfloat-equal  -Winline -Wunknown-pragmas -Wundef -Wendif-labels  -c /home/user/c/m3/bn/bn.c
/home/user/c/m3/bn/bn.c:302:12: warning: unused variable 'q' [-Wunused-variable]
    uint32 q, m;        /* Division Result */
           ^
/home/user/c/m3/bn/bn.c:302:15: warning: unused variable 'm' [-Wunused-variable]
    uint32 q, m;        /* Division Result */
              ^
/home/user/c/m3/bn/bn.c:303:12: warning: unused variable 'i' [-Wunused-variable]
    uint32 i;           /* Loop Counter */
           ^
/home/user/c/m3/bn/bn.c:304:12: warning: unused variable 'j' [-Wunused-variable]
    uint32 j;           /* Loop Counter */
           ^
/home/user/c/m3/bn/bn.c:320:14: error: unknown token in expression
    __asm__ ("movl %eax, (bn1->dat[i])");
             ^
<inline asm>:1:18: note: instantiated into assembly here
        movl %eax, (bn1->dat[i])
                        ^
/home/user/c/m3/bn/bn.c:322:14: error: unknown token in expression
    __asm__ ("divl (bn2->dat[j])");
             ^
<inline asm>:1:12: note: instantiated into assembly here
        divl (bn2->dat[j])
                  ^
4 warnings and 2 errors generated.
*** [bn.o] Error code 1

Stop in /home/user/c/m3/bn.
system:/home/user/c/m3/bn 1037 $$$ ->

我所知道的:

我认为自己相当精通 x86 汇编程序(从我上面编写的代码中可以看出)。然而,我最后一次混合高级语言和汇编程序是在大约 15 到 20 年前为游戏编写图形驱动程序时使用 Borland Pascal(Windows 95 之前的时代)。我熟悉 Intel 语法。

我不知道的:

如何从 asm 访问 bn_t 的成员(尤其是 *dat)?由于 *dat 是指向 uint32 的指针,因此我将元素作为数组访问(例如 bn1->dat[i])。

如何访问在堆栈上声明的局部变量?

我正在使用 push/pop 将破坏的寄存器恢复到以前的值,以免扰乱编译器。但是,我是否也需要在局部变量中包含 volatile 关键字?

或者,有没有我不知道的更好的方法?由于调用开销,我不想将它放在单独的函数调用中,因为此函数对性能至关重要。

补充:

现在,我刚刚开始编写这个函数,所以它还没有完成。缺少循环和其他此类支持/粘合代码。但是,主要的要点是访问局部变量/结构元素。

编辑 1:

我使用的语法似乎是 clang 唯一支持的语法。我尝试了以下代码,clang 给了我各种错误:

__asm__ ("pushl %%eax",
    "pushl %%edx",
    "pushf",
    "movl (bn1->dat[i]), %%eax",
    "xorl %%edx, %%edx",
    "divl ($0x0c + bn2 + j)",
    "movl %%eax, (q)",
    "movl %%edx, (m)",
    "popf",
    "popl %%edx",
    "popl %%eax"
    );

它希望我在第一行加上右括号,替换逗号。我改用 %% 而不是 % 因为我在某处读到内联汇编需要 %% 来表示 CPU 寄存器,而 clang 告诉我我使用了无效的转义序列。

【问题讨论】:

  • 您是否知道编译器可能会相对于其他语句重新排序 __asm__ 语句?我非常确信这是不需要的,因此请使用 single __asm__ 声明。
  • "数据类型 uint32 基本上是一个 unsigned long int" 不,不是。它基本上是一个保证为 32 位宽的无符号整数类型。
  • 我尝试使用单个 asm 语句,编译器将其扔回给我。我会再试一次。
  • 请阅读文档。我不知道 clang,但是对于 gcc,您必须使用附加参数指定 C 参数(和 afaik clang 类似)。基本上,字符串通过一些文本替换(如果您指定 C 参数)传递给汇编器,而汇编器显然不知道 C 构造。
  • gcc inline assembly(也被 clang 使用)不检查汇编语句。有一个很好的教程here

标签: c x86 clang freebsd inline-assembly


【解决方案1】:

如果您只需要 32b / 32b => 32 位除法,让编译器同时使用 div 的两个输出,gcc、clang 和 icc 都可以,正如您在Godbolt compiler explorer:

uint32_t q = bn1->dat[i] / bn2->dat[j];
uint32_t m = bn1->dat[i] % bn2->dat[j];

编译器非常擅长将 CSE 合并为一个 div。只要确保您没有将除法结果存储在 gcc 无法证明不会影响余数输入的地方。

例如*m = dat[i] / dat[j] 可能会重叠(别名)dat[i]dat[j],因此 gcc 必须重新加载操作数并为 % 操作重做 div。有关坏/好示例,请参见 godbolt 链接。


对 32bit / 32bit = 32bit div 使用内联 asm 并没有为您带来任何好处,而且实际上使用 clang 会使代码变得更糟(请参阅 godbolt 链接)。

如果您需要 64 位 / 32 位 = 32 位,那么您可能需要 asm,如果没有内置的编译器。 (GNU C 没有,AFAICT)。 C 中的明显方式(将操作数转换为uint64_t)生成对 64bit/64bit = 64bit libgcc 函数的调用,该函数具有分支和多个div 指令。 gcc 不擅长证明结果适合 32 位,因此单个 div 指令不会导致 #DE

对于许多其他指令,您可以避免在 很多时间使用 builtin functions for things like popcount 编写内联 asm。使用-mpopcnt,它编译为popcnt 指令(并解释了英特尔CPU 对输出操作数的错误依赖性。)没有,它编译为libgcc 函数调用。

总是更喜欢内置函数,或编译为良好 asm 的纯 C,因此编译器知道代码的作用。当内联使某些参数在编译时已知时,纯 C 可以是 optimized away or simplified,但使用内联 asm 的代码只会将常量加载到寄存器中并在运行时执行 div。内联 asm 也会在相同数据的类似计算之间击败 CSE,当然不能自动矢量化。


正确使用 GNU C 语法

https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html 解释了如何告诉汇编器你想要寄存器中的哪些变量,以及输出是什么。

You can use Intel/MASM-like syntax and mnemonics, and non-% register names if you like,最好用-masm=intel编译。 AT&T 语法错误 (fsub and fsubr mnemonics are reversed) 可能仍存在于 intel-syntax 模式中;我忘记了。

大多数使用 GNU C 内联汇编的软件项目仅使用 AT&T 语法。

有关更多 GNU C 内联 asm 信息,另请参阅 the bottom of this answer,以及 标签 wiki。


asm 语句采用 一个 字符串 arg 和 3 组约束。使其成为多行的最简单方法是将每个 asm 行设为以 \n 结尾的单独字符串,并让编译器隐式连接它们。

另外,你告诉编译器你想在哪些寄存器中添加东西。然后,如果变量已经在寄存器中,编译器就不必溢出它们并让你加载和存储它们。这样做真的会在脚下开枪。在 cmets 中链接的 tutorial Brett Hale 希望涵盖所有这些。


div 与 GNU C 内联 asm 的正确示例

您可以在 godbolt 上查看此编译器的 asm 输出。

uint32_t q, m;  // this is unsigned int on every compiler that supports x86 inline asm with this syntax, but not when writing portable code.

asm ("divl %[bn2dat_j]\n"
      : "=a" (q), "=d" (m) // results are in eax, edx registers
      : "d" (0),           // zero edx for us, please
        "a" (bn1->dat[i]), // "a" means EAX / RAX
        [bn2dat_j] "mr" (bn2->dat[j]) // register or memory, compiler chooses which is more efficient
      : // no register clobbers, and we don't read/write "memory" other than operands
    );

"divl %4" 也可以,但是当您添加更多输入/输出约束时,命名输入/输出不会更改名称。

【讨论】:

  • 我以前从来没有搞过这个。从来没有必要这样做,直到现在。这种用于 asm 的 AT&T 语法充其量是很糟糕的,因为我所做的所有 asm 工作都是使用 MASM 和 TASM 之类的东西。除此之外还有其他问题需要解决,但这是一个单独的问题。
  • @DanielRudy:好吧,如果其他情况与此类似,请让编译器做正确的事情:请参阅我回答的最后一段。 gcc 内联 asm 真的很乱而且很难学习,有输入/输出约束,但至少它可以让你编写不像将变量溢出到内存那样愚蠢的代码,这样 MSVC 内联 asm 就可以用mov 加载它。
  • 我不知道编译器足够聪明,能够意识到在连续语句中使用 / 和 % 会导致编译器在一个 div 操作中同时使用这两种结果。这几乎消除了首先从水中使用 asm 的需要。
  • @EvanCarroll:这是第二部分;你在看这个答案的旧版本还是什么?第一部分说“如果你只需要 32b / 32b => 32bit 除法,让编译器同时使用 div 的输出
  • @EvanCarroll:使用当前的 gcc,我不知道。通常,暴露 div / idiv 的可能错误性质的内在函数是一种好方法。 (MSVC 有这个。)另一种方法是教编译器如何在可以证明除法不会溢出时进行优化,例如5 * (uint64_t)a / 111 或其他东西,在 32 位机器上。即教编译器寻找这种优化。 (x86-64 上的 gcc 将使用乘法逆运算,但 gcc 在需要扩展精度时选择不使用。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多