什么是constexpr的等效函数参数? [英] What is the function parameter equivalent of constexpr?

查看:147
本文介绍了什么是constexpr的等效函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正试图加速Clang和Visual C ++下的一些代码(GCC和ICC是OK)。我们认为我们可以使用 constexpr 来告诉Clang一个值是一个编译时常数,但它导致编译错误:

We are trying to speedup some code under Clang and Visual C++ (GCC and ICC is OK). We thought we could use constexpr to tell Clang a value is a compile time constant but its causing a compile error:

$ clang++ -g2 -O3 -std=c++11 test.cxx -o test.exe
test.cxx:11:46: error: function parameter cannot be constexpr
unsigned int RightRotate(unsigned int value, constexpr unsigned int rotate)
                                             ^
1 error generated.

以下是减少的情况:

$ cat test.cxx
#include <iostream>

unsigned int RightRotate(unsigned int value, constexpr unsigned int rotate);

int main(int argc, char* argv[])
{
  std::cout << "Rotated: " << RightRotate(argc, 2) << std::endl;
  return 0;
}

unsigned int RightRotate(unsigned int value, constexpr unsigned int rotate)
{
  // x = value; y = rotate
  __asm__ ("rorl %1, %0" : "+mq" (value) : "I" ((unsigned char)rotate));
  return value;
}

GCC和ICC会做正确的事。他们识别表达式 RightRotate(argc,2)中的 2 的值不能根据物理宇宙的规律改变因为我们知道它们,它会将 2 作为编译时常数,并将其传播到汇编代码中。

GCC and ICC will do the right thing. They recognize a value like 2 in the expression RightRotate(argc, 2) cannot change under the laws of the physical universe as we know them, and it will treat 2 as a compile time constant and propagate it into the assembly code.

如果我们删除 constexpr ,则Clang和VC ++将函数集合到 rotate REGISTER 中, 旋转IMMEDIATE

If we remove the constexpr, then Clang and VC++ aseembles the function into a rotate REGISTER, which is up to 3x slower than a rotate IMMEDIATE.

我们如何告诉Clang函数参数 rotate 是一个编译时常数,它应该被组装成 rotate IMMEDIATE ,而不是 rotate REGISTER

How do we tell Clang the function parameter rotate is a compile time constant, and it should be assembled into a rotate IMMEDIATE rather than a rotate REGISTER?

推荐答案

您可以使用非类型模板参数:

You could use non-type template arguments for this:

template <unsigned int rotate> RightRotate(unsigned int value) {
     ...
}

d然后调用它

RightRotate<137>(argument); // rotate is 137 here

这篇关于什么是constexpr的等效函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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