gpt4 book ai didi

将汇编内联从 32 位转换为 64 位

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:51 26 4
gpt4 key购买 nike

有谁知道如何更改此函数以处理 64 位?

{
unsigned int prev;

__asm__ __volatile__ (
" lock; cmpxchgl %1,%2; "
: "=a"(prev)
: "q"(new_value), "m"(*(int *)ptr), "0"(old_value)
: "memory");

return prev;
}

使用 unsigned long prev;cmpxchgq 而不是 Brett Hale 善意建议的 cmpxchgl 会导致以下错误:

include/cs.h: Assembler messages:
include/cs.h:26: Error: incorrect register `%esi' used with `q' suffix
include/cs.h:26: Error: incorrect register `%esi' used with `q' suffix
include/cs.h:26: Error: incorrect register `%esi' used with `q' suffix
include/cs.h:26: Error: incorrect register `%r13d' used with `q' suffix
error: command 'gcc' failed with exit status 1

我想我找到了 Brett 的建议对我不起作用的原因。我不得不将函数输入中的变量类型从 int 更改为 long。为了完整起见,我在这里添加它:

#ifndef __cs__include
#define __cs__include

static inline unsigned int CS(volatile void *ptr,
unsigned long old_value, /* was int */
unsigned long new_value) /* was int too */
{
unsigned long prev; /* result */
volatile unsigned long *vptr = (volatile unsigned long *) ptr;

__asm__ __volatile__ (

" lock; cmpxchgq %2, %1; "
: "=a" (prev), "+m" (*vptr)
: "r" (new_value), "0" (old_value)
: "memory");

return prev;
}

代码编译没有错误(尽管有很多警告)。然而,不幸的是,该程序仍然无法在 64 位上运行。

最佳答案

内置版本(带有 __sync 样式)如下所示:

#include <stdint.h>
#include <stdio.h>

uint64_t cas(uint64_t* ptr, uint64_t old_value, uint64_t new_value)
{
return __sync_val_compare_and_swap(ptr, old_value, new_value);
}

int main()
{
uint64_t foo = 42;
uint64_t old = cas(&foo, 42, 1);
printf("foo=%llu old=%llu\n", (unsigned long long)foo, (unsigned long long)old);
return 0;
}

它的美妙之处在于它适用于许多架构。在 x86 上,它在 32 位模式下使用 cmpxchg8b,在 64 位模式下使用 cmpxchgq。

您的问题不太清楚,也许您打算在针对 64 位模式进行编译时保留 32 位操作。在这种情况下,请使用 uint32_t 而不是 uint64_t。

关于将汇编内联从 32 位转换为 64 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17091523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com