在跳入函数之前有没有办法保存寄存器?

问题描述 投票:3回答:1

这是我的第一个问题,因为我找不到任何与此主题相关的内容。

最近,在为我的C游戏引擎项目制作课程时,我发现了一些有趣的东西:

struct Stack *S1 = new(Stack);
struct Stack *S2 = new(Stack);

S1->bPush(S1, 1, 2);               //at this point

bPush是结构中的函数指针。

所以我想知道,在这种情况下,运营商->是什么,我发现:

 mov         r8b,2                 ; a char, written to a low point of register r8
 mov         dl,1                  ; also a char, but to d this time
 mov         rcx,qword ptr [S1]    ; this is the 1st parameter of function
 mov         rax,qword ptr [S1]    ; !Why cannot I use this one?
 call        qword ptr [rax+1A0h]  ; pointer call

所以我假设 - >将对象指针写入rcx,我想在函数中使用它(它们应该是方法)。所以问题是,我怎样才能做同样的事情

 push        rcx
 // do other call vars
 pop         rcx
 mov         qword ptr [this], rcx

在它开始写函数的其他变量之前。有预处理器的东西吗?

c assembly visual-c++ x86-64 calling-convention
1个回答
2
投票

如果您使用C ++编写,那么看起来您将拥有更轻松的时间(并获得相同或更高效的asm),因此您可以使用语言内置支持虚拟函数,以及在初始化时运行构造函数。更不用说不必手动运行析构函数了。你不需要你的struct Class黑客。

我想暗中传递*this指针,因为如第二个asm部分所示,它执行两次相同的操作,是的,它是我正在寻找的,bPush是结构的一部分,它不能从外部调用,但我必须传递它已经拥有的指针S1。

由于您禁用了优化,因此效率低下。

MSVC -O2-Ox不会重新加载静态指针两次。它确实浪费了在寄存器之间复制的mov指令,但如果你想要更好的asm使用更好的编译器(如gcc或clang)。

Godbolt编译器资源管理器中最古老的MSVC是来自MSVC 2015的CL19.0,它编译了这个源代码

struct Stack {
    int stuff[4];
    void (*bPush)(struct Stack*, unsigned char value, unsigned char length);
};


struct Stack *const S1 = new(Stack);

int foo(){
    S1->bPush(S1, 1, 2);

    //S1->bPush(S1, 1, 2);
    return 0;  // prevent tailcall optimization
}

into this asm (Godbolt)

# MSVC 2015  -O2
int foo(void) PROC                                        ; foo, COMDAT
$LN4:
        sub     rsp, 40                             ; 00000028H
        mov     rax, QWORD PTR Stack * __ptr64 __ptr64 S1
        mov     r8b, 2
        mov     dl, 1
        mov     rcx, rax                   ;; copy RAX to the arg-passing register
        call    QWORD PTR [rax+16]
        xor     eax, eax
        add     rsp, 40                             ; 00000028H
        ret     0
int foo(void) ENDP                                        ; foo

(我在C ++模式下编译,所以我可以编写S1 = new(Stack)而无需复制你的github代码,并使用非常量初始化程序在全局范围内编写它。)

Clang7.0 -O3马上加载到RCX

# clang -O3
foo():
        sub     rsp, 40
        mov     rcx, qword ptr [rip + S1]
        mov     dl, 1
        mov     r8b, 2
        call    qword ptr [rcx + 16]          # uses the arg-passing register
        xor     eax, eax
        add     rsp, 40
        ret

奇怪的是,clang只在使用__attribute__((ms_abi))定位Windows ABI时决定使用低字节寄存器。它使用mov esi, 1来避免在定义其默认Linux调用约定时的错误依赖关系,而不是mov sil, 1


或者,如果您正在使用优化,那么这是因为即使是较旧的MSVC也会更糟。在这种情况下,您可能无法在C源代码中执行任何操作来修复它,尽管您可能尝试使用struct Stack *p = S1局部变量来手持编译器将其加载到寄存器中并从那里重新使用它。)

© www.soinside.com 2019 - 2024. All rights reserved.