如何通过内联函数强制常量传播
How to force const propagation through an inline function?
我试图强制预处理器为我执行一些数学运算,以便将常量传播到内联程序集中。以下是简化的情况:
inline
unsigned int RotateRight(unsigned char value, unsigned int amount)
{
COMPILE_ASSERT(((unsigned char)(amount%32)) < 32);
__asm__ ("rorb %1, %0" : "+mq" (value) : "I" ((unsigned char)(amount%32)));
return value;
}
上面的代码依赖于 CPU 特定的功能,我可以接受它(当 GCC 可用时,它实际上是 x86/x64 Linux 上的模板专用化(。 "I"
约束表示整数值必须在[0,31]
(含(之间。
代码的调用方如下所示:
byte b1 = RotateRight(1, 1);
byte b2 = RotateRight(1, 31);
RotateRight(1, 31)
来自密码学家(它在 C/C++ 中未定义的行为,因为字节只能在 [0,7]
范围内旋转(。我可以使用 ASM 摆脱 C/C++ 约束。由于移位量在编译时是已知的,我希望在编译时减少它;我想要使用生成的即时 8 的 rorb
版本。
如果没有COMPILE_ASSERT
,代码可以编译,但我不确定常量是否正在传播。也就是说,它可能以意外的减少(% 32
(生成。使用COMPILE_ASSERT
,代码无法编译。
$ make validat1.o
g++ -DNDEBUG -g2 -O3 -march=native -pipe -c validat1.cpp
In file included from simple.h:10:0,
from filters.h:6,
from files.h:5,
from validat1.cpp:6:
misc.h: In function ‘T CryptoPP::rotlFixed(T, unsigned int) [with T = unsigned char]’:
misc.h:940:43: error: ‘y’ cannot appear in a constant-expression
CRYPTOPP_COMPILE_ASSERT(((unsigned char)(y%32)) < 32);
^
misc.h:72:85: note: in definition of macro ‘CRYPTOPP_COMPILE_ASSERT_INSTANCE’
_COMPILE_ASSERT_INSTANCE(assertion, instance) static CompileAssert<(assertion)>
我知道我不应该使用#define
,C++内联函数就是答案。但我觉得我正在遭受脱节。
如何强制编译器传播涉及const
值的值?
或者,如果COMPILE_ASSERT
是错误的工具(正在传播const
(,如何设置测试以便验证是否使用了 rorb
的 immediate-8 版本?
相关,这是一个C++03项目。它不使用Boost,不使用Cmake,不使用Autotools等。
将 amount 指定为函数参数时,会丢失其编译时恒常性。
你为什么不声明金额是模板参数?在这种情况下,函数用户也会被迫传递编译时常量,这也很好。
若要确保将 shift 用作编译时常量,可以创建一个静态 const 局部变量。
template<unsigned int amount> inline
unsigned int RotateRight(unsigned char value)
{
static const unsigned char shift = (unsigned char)(amount%32);
__asm__ ("rorb %1, %0" : "+mq" (value) : "I" (shift));
return value;
}
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何创建长度由常量参数指定的数组
- 应将常量传播到成员指针指针
- 场景图、共享指针和常量传播
- c++中的函数调用常量传播
- 如何通过内联函数强制常量传播
- g++关闭常量传播以进行基准测试