如何写的Int64 = INT32 * INT32在标准/便携和高效的方式? [英] How to write int64=int32*int32 in a standard/portable and efficient way?

查看:148
本文介绍了如何写的Int64 = INT32 * INT32在标准/便携和高效的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关报道:
<一href=\"http://stackoverflow.com/questions/29578540/is-this-treatment-of-int64-t-a-gcc-and-clang-bug/29578958?noredirect=1#comment47306355_29578958\">Is这种治疗方法一的int64_t GCC和Clang的错误!?

我能想到的唯一的办法是显式转换一个操作数为int64,迫使该产品是至少也在64位整数。

The only solution I can think of is to explicitly convert one of the operands to int64, forcing the product to be also at least int64.

但是,如果这样做的方式,那么它是由编译器的智能,能实际做到的Int64 * INT32 的Int64 *的Int64 或理想,优化回 INT32 * INT32

But if done this way, then it's up to the compiler's intelligence to actually do int64*int32, or int64*int64, or ideally, optimize it back to int32*int32.

由于在相关问题的讨论,INT32分配的结果* INT32 的Int64 不改变事实上 INT32 * INT32 已导致UB。

As discussed in the related question, assigning the result of int32*int32 to int64 doesn't change the fact that int32*int32 already causes UB.

任何想法?

推荐答案

您已经指示如何做到这一点的标准,便携,高效的方式:

You've already indicated how to do this in a standard, portable, and efficient way:

int64_t mul(int32_t x, int32_t y) {
    return (int64_t)x * y;
    // or static_cast<int64_t>(x) * y if you prefer not to use C-style casts
    // or static_cast<int64_t>(x) * static_cast<int64_t>(y) if you don't want
    // the integral promotion to remain implicit
}


您的问题似乎是关于具有对应于函数签名汇编指令的假想结构


Your question seems to be about a hypothetical architecture that has assembly instructions corresponding to the function signatures

int64_t intrinsic_mul(int32_t x, int32_t y);
int64_t intrinsic_mul(int64_t x, int64_t y);
int64_t intrinsic_mul(int64_t x, int32_t y); // and maybe this too

,并在此假设的架构,其中的第一个具有相关优势,的此外的,你的编译器无法使用该指令编译上面的功能时,并在最严重的是,它失败提供访问上述固有

and, on this hypothetical architecture, the first of these has relevant advantages, and furthermore, your compiler fails to use this instruction when compiling the function above, and on top of all that, it fails to provide access to the above intrinsic.

我希望这样的情景,真正做到罕见的,但如果你真的发现自己在这种情况下,大多数编译器还允许你写的内联汇编的,所以你可以编写调用这个函数特殊指令直接,仍然提供足够的元数据,以便优化器可以稍微有效地使用它(例如,使用符号的输入和输出寄存器,这样优化器可以使用它想任何注册,而不是寄存器选择硬codeD)。

I expect such a scenario to be really rare, but if you truly find yourself in such a situation, most compilers also allow you to write inline assembly, so you can write a function that invokes this special instruction directly, and still provides enough metadata so the optimizer can make somewhat efficient use of it (e.g. using symbolic input and output registers so the optimizer can use whichever registers it wants, rather than having the register choice hardcoded).

这篇关于如何写的Int64 = INT32 * INT32在标准/便携和高效的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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