联合代码生成,用于字节序交换 [英] Union code generation for endian swapping

查看:88
本文介绍了联合代码生成,用于字节序交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于字节序交换基本类型的简单函数,但是cl(版本15和16)会为x86上的浮点类型生成冗余的加载/存储.

I have some simple functions for endian swapping fundamental types, however cl (version 15 and 16) generates redundant load/stores for floating point types on x86. 

以下代码:


float EndianSwap(float value)
{
  union Alias
  {
    float native;
    unsigned long convert;
  };

  Alias asrc;
  asrc.native = value;
    
  Alias adst;
  adst.convert = _byteswap_ulong(asrc.convert);

  return adst.native;
}

推荐答案

c2_0写道:

c2_0 wrote:

我有一些简单的函数用于字节序交换基本类型,但是cl(版本15和16)会产生冗余
在x86上加载/存储浮点类型.

I have some simple functions for endian swapping fundamental types,  however cl (version 15 and 16) generates redundant
load/stores for floating point types on x86.

以下代码:

The following code:

[代码]

[code]

float EndianSwap(浮点值)

float EndianSwap(float value)

这看起来很冒险.如果,您采用有效的浮点值并交换其字节,它将变成信号NaN?根据FPU标志的不同,可能会产生硬件.号码打断时 已加载以返回.

This looks like a pretty risky thing to do. Isn't it possible that, if  you take a valid floating point value and swap its bytes, it turns into  a signalling NaN? Depending on FPU flags, that may produce a hardware  interrupt when the number is loaded to be returned.

因此,看起来编译器正在重新使用 的堆栈空间输入参数和转换联合,这很好,但是
并没有意识到完全加载并存储回去多余的.我可以使用reinterpret_cast<>解决它但是
我在其他平台上遇到了此类隐式别名的问题编译器将无法跟踪不相关的别名
输入并生成无效代码.

So, it looks like the compiler is re-using the stack space of the  input parameter and the conversion union, which is good, but
doesn't realize that loading it and storing it back is completely  redundant. I can work around it with reinterpret_cast<> but
I've had issues with such implicit aliasing on other platforms where  the compiler will fail to track aliasing across unrelated
types and generate invalid code.

它已经违反了别名规则,导致未定义.行为,先写信给工会的一名成员,然后再从中读取其他.访问附件的二进制表示形式的唯一便携式方法对象是将其地址强制转换为[signed | unsigned] char *或memcpy it 放入足够大的char缓冲区.

It is already a violation of aliasing rules, leading to undefined  behavior, to write to one member of the union and then read from  another. The only portable way to access binary representation of an  object is to cast its address to [signed|unsigned] char*, or memcpy it  into a large enough buffer of char's.


这篇关于联合代码生成,用于字节序交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆