jjzjj

c++ - 使用(float&)int可以进行类型修剪,(float const&)int可以像(float)int那样转换吗?

coder 2024-01-31 原文

VS2019版本x86。

template <int i> float get() const {
    int f = _mm_extract_ps(fmm, i);
    return (float const&)f;
}

当使用return (float&)f;编译器使用时
extractps m32, ...
movss xmm0, m32

。正确的结果

当使用return (float const&)f;编译器使用时
extractps eax, ...
movd xmm0, eax

。错误的结果

T&和T const&首先是T,然后是const的主要思想。 const只是程序员的某种协议(protocol)。您知道您可以解决它。但是汇编代码中没有任何const,只能输入float IS。而且我认为对于float&和float const&,它都必须是汇编中的float表示形式(cpu寄存器)。我们可以使用中间int reg32,但最终解释必须是float。

此时,它看起来像回归,因为它以前工作得很好。而且在这种情况下使用float&绝对是奇怪的,因为我们不应该涉及float const&安全性,但是float&的temp var确实值得怀疑。

微软回答:

Hi Truthfinder, thanks for the self-contained repro. As it happens, this behavior is actually correct. As my colleague @Xiang Fan [MSFT] described in an internal email:

The conversions performed by [a c-style cast] tries the following sequence: (4.1) — a const_cast (7.6.1.11), (4.2) — a static_cast (7.6.1.9), (4.3) — a static_cast followed by a const_cast, (4.4) — a reinterpret_cast (7.6.1.10), or (4.5) — a reinterpret_cast followed by a const_cast,

If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used.

So in your case, (const float &) is converted to static_cast, which has the effect "the initializer expression is implicitly converted to a prvalue of type “cv1 T1”. The temporary materialization conversion is applied and the reference is bound to the result."

But in the other case, (float &) is converted to reinterpret_cast because static_cast isn’t valid, which is the same as reinterpret_cast(&operand).

The actual "bug" you're observing is that one cast does: "transform the float-typed value "1.0" into the equivalent int-typed value "1"", while the other cast says "find the bit representation of 1.0 as a float, and then interpret those bits as an int".

For this reason we recommend against c-style casts.

Thanks!



MS论坛链接:https://developercommunity.visualstudio.com/content/problem/411552/extract-ps-intrinsics-bug.html

有任何想法吗?

P.S.我真正想要的是:
float val = _mm_extract_ps(xmm, 3);

在手动汇编中,我可以编写:extractps val, xmm0, 3其中val是float 32内存变量。只有一个!操作说明。我想在编译器生成的汇编代码中看到相同的结果。请勿乱序播放或进行其他任何过多的指示。最糟糕的可接受情况是:extractps reg32, xmm0, 3; mov val, reg32

关于T&和T const&的观点:
对于这两种情况,变量的类型必须相同。但是现在float&将m32解释为float32,而float const&将m32解释为int32。
int main() {
    int z = 1;
    float x = (float&)z;
    float y = (float const&)z;
    printf("%f %f %i", x, y, x==y);
    return 0;
}

Out: 0.000000 1.000000 0



真的可以吗?

最好的祝福,
真理发现者

最佳答案

关于C++强制转换语义存在一个有趣的问题(Microsoft已经为您简短地回答了这个问题),但是它与您对_mm_extract_ps的误用混合在一起,导致首先需要进行类型双关。 (并且仅显示等效的asm,省略了int-> float转换。)如果其他人想在另一个答案中扩展标准ese的话,那就太好了。

TL:DR:改用它:0或1 shufps。没有提取物,没有类型修剪。

template <int i> float get(__m128 input) {
    __m128 tmp = input;
    if (i)     // constexpr i means this branch is compile-time-only
        tmp = _mm_shuffle_ps(tmp,tmp,i);  // shuffle it to the bottom.
    return _mm_cvtss_f32(tmp);
}

如果您确实有一个内存目标用例,则应该在asm中查找需要float*输出arg的函数,而不是需要xmm0中的结果的函数。 (是的,这是extractps指令的用例,但可以说不是_mm_extract_ps内在函数。gcc和clang在优化extractps时使用*out = get<2>(in),尽管MSVC忽略了它,但仍使用shufps + movss。)

您显示的两个asm块都只是将xmm0的低32位复制到某个地方,而没有转换为int。您忽略了重要的区别,只展示了无用的部分,它以2种不同的方式(注册或存储)无用地从xmm0中复制了float位模式,然后又将其复制回来。 movd是未经修改的位的纯拷贝,就像movss负载一样。

在迫使编译器完全使用extractps之后,使用的是编译器的选择。通过寄存器来回执行的延迟比存储/重新加载要低,但是要处理更多的ALU。

尝试对punt键入(float const&)确实包括从FP到整数的转换,您没有显示。好像我们需要更多的理由来避免指针/引用强制转换进行类型绑定(bind)一样,这的确意味着不同:(float const&)f将整数位模式(来自_mm_extract_ps)用作int并将其转换为float

,我将您的代码on the Godbolt compiler explorer放入,以查看您遗漏的内容。
float get1_with_extractps_const(__m128 fmm) {
    int f = _mm_extract_ps(fmm, 1);
    return (float const&)f;
}

;; from MSVC -O2 -Gv  (vectorcall passes __m128 in xmm0)
float get1_with_extractps_const(__m128) PROC   ; get1_with_extractps_const, COMDAT
    extractps eax, xmm0, 1   ; copy the bit-pattern to eax

    movd    xmm0, eax      ; these 2 insns are an alternative to pxor xmm0,xmm0 + cvtsi2ss xmm0,eax to avoid false deps and zero the upper elements
    cvtdq2ps xmm0, xmm0    ; packed conversion is 1 uop
    ret     0

GCC通过以下方式进行编译:
get1_with_extractps_const(float __vector(4)):    # gcc8.2 -O3 -msse4
        extractps       eax, xmm0, 1
        pxor    xmm0, xmm0            ; cvtsi2ss has an output dependency so gcc always does this
        cvtsi2ss        xmm0, eax     ; MSVC's way is probably better for float.
        ret

显然,MSVC确实为类型绑定(bind)定义了指针/引用转换的行为。普通ISO C++不会(严格别名UB),其他编译器也不会。使用memcpy键入pun或进行 union (C++中的GNU C和MSVC支持扩展)。当然,在这种情况下,将要 vector 的 vector 元素类型化为整数然后返回是可怕的。

gcc仅针对(float &)f发出有关严格混叠违规的警告。 并且GCC/clang与MSVC一致,仅此版本是类型双关语,而不是通过隐式转换实现float C++很奇怪!
float get1_with_extractps_nonconst(__m128 fmm) {
    int f = _mm_extract_ps(fmm, 1);
    return (float &)f;
}

<source>: In function 'float get_with_extractps_nonconst(__m128)':
<source>:21:21: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
     return (float &)f;
                     ^

gcc完全优化了extractps
# gcc8.2 -O3 -msse4
get1_with_extractps_nonconst(float __vector(4)):
    shufps  xmm0, xmm0, 85    ; 0x55 = broadcast element 1 to all elements
    ret

Clang使用SSE3 movshdup将元素1复制到0。(并将元素3复制到2)。
但是MSVC没有,这是永远不要使用它的另一个原因:
float get1_with_extractps_nonconst(__m128) PROC
    extractps DWORD PTR f$[rsp], xmm0, 1     ; store
    movss   xmm0, DWORD PTR f$[rsp]          ; reload
    ret     0

不要为此使用_mm_extract_ps
您的两个版本都很糟糕,因为这不是_mm_extract_psextractpsIntel SSE: Why does `_mm_extract_ps` return `int` instead of `float`?

寄存器中的float与 vector 的低位元素相同。高元素不需要清零。如果这样做的话,您可能想使用insertps,它可以根据立即数来执行xmm,xmm和零元素。

使用_mm_shuffle_ps将所需的元素移到寄存器的低位,然后它是标量浮点数。 (并且您可以使用_mm_cvtss_f32告诉C++编译器)。这应该只编译为shufps xmm0,xmm0,2,而不能编译为extractps或任何mov
template <int i> float get() const {
    __m128 tmp = fmm;
    if (i)                               // i=0 means the element is already in place
        tmp = _mm_shuffle_ps(tmp,tmp,i);  // else shuffle it to the bottom.
    return _mm_cvtss_f32(tmp);
}

(我跳过了使用_MM_SHUFFLE(0,0,0,i),因为它等于i。)

如果您的fmm是在内存中,而不是在寄存器中,那么希望编译器可以优化shuffle,而不仅仅是movss xmm0, [mem]。 MSVC 19.14确实做到了这一点,至少对于堆栈情况下的function-arg而言。我没有测试其他编译器,但是clang应该可以设法优化_mm_shuffle_ps;它非常擅长于通过混洗。

测试用例证明可以有效地进行编译

例如一个带有您的函数的非类成员版本的测试用例,以及一个将其内联为特定i的调用方:
#include <immintrin.h>

template <int i> float get(__m128 input) {
    __m128 tmp = input;
    if (i)                  // i=0 means the element is already in place
        tmp = _mm_shuffle_ps(tmp,tmp,i);  // else shuffle it to the bottom.
    return _mm_cvtss_f32(tmp);
}

// MSVC -Gv (vectorcall) passes arg in xmm0
// With plain dumb x64 fastcall, arg is on the stack, and it *does* just MOVSS load without shuffling
float get2(__m128 in) {
    return get<2>(in);
}

From the Godbolt compiler explorer,来自MSVC,clang和gcc的asm输出:
;; MSVC -O2 -Gv
float get<2>(__m128) PROC               ; get<2>, COMDAT
        shufps  xmm0, xmm0, 2
        ret     0
float get<2>(__m128) ENDP               ; get<2>

;; MSVC -O2  (without Gv, so the vector comes from memory)
input$ = 8
float get<2>(__m128) PROC               ; get<2>, COMDAT
        movss   xmm0, DWORD PTR [rcx+8]
        ret     0
float get<2>(__m128) ENDP               ; get<2>
# gcc8.2 -O3 for x86-64 System V (arg in xmm0)
get2(float __vector(4)):
        shufps  xmm0, xmm0, 2   # with -msse4, we get unpckhps
        ret
# clang7.0 -O3 for x86-64 System V (arg in xmm0)
get2(float __vector(4)):
        unpckhpd        xmm0, xmm0      # xmm0 = xmm0[1,1]
        ret

clang的shuffle优化器简化为unpckhpd,在某些旧的CPU上速度更快。不幸的是,它没有注意到它可以使用movhlps xmm0,xmm0,它也很快并且短了1个字节。

关于c++ - 使用(float&)int可以进行类型修剪,(float const&)int可以像(float)int那样转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54454585/

有关c++ - 使用(float&)int可以进行类型修剪,(float const&)int可以像(float)int那样转换吗?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐