c - 限制关键字 - 优化和别名影响

标签 c compiler-optimization restrict-qualifier

我在 C11 标准中看到了这两个部分,它们指的是 restrict 限定符:

1#

6.7.3-8

An object that is accessed through a restrict-qualified pointer has a special association with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.135) The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).

你能解释一下草书片段的意思吗?在我的解释中,因为它没有改变它的意思,所以看起来 restrict 的使用是毫无意义的......

2#

6.7.3.1-6

A translator is free to ignore any or all aliasing implications of uses of restrict.

这些别名可能意味着什么?你能给我举一些例子吗?

最佳答案

Restrict 并非毫无意义,它允许编译器进行优化,如果可能存在指针别名,则不允许进行优化。例如下面的函数:

int foo(int *a, int *b)
{
    *a = 5;
    *b = 6;
    return (*a + *b);
}

这个函数返回什么?如果您说 11,那么您只说对了一部分。它返回 11 除非 a == b,在这种情况下它返回 12,或者更糟的是,a 与 b 部分重叠,这可能是以下之一几个值。为了确保它的行为正确,编译器必须发出代码

1) stores 5 to a
2) stores 6 to b
3) loads a into a temporary register
4) adds the temp and 6
5) returns the sum

如果您作为程序员知道 a == b 永远不会发生,您可以使用 restrict 关键字告诉编译器您不希望它担心这种情况。

int foo(int * restrict a, int * restrict b)

将为该函数生成的代码将是:

1) store 5 to a
2) store 6 to b
3) return 11

编译器能够进行优化,因为您向它保证不会出现别名问题。而且,根据标准,如果编译器只是选择忽略 restrict 关键字,那么它生成的代码将只是第一种情况下的符合(未优化)代码,对于您关心的所有实例,它仍然以相同的方式工作。

关于c - 限制关键字 - 优化和别名影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12220706/

相关文章:

c - 通过示例了解限制限定符

c - 使用相对路径打开文件

java - 用于访问 Java Web 服务的 gSOAP C 客户端

tensorflow - 如何用SSE4.2和AVX指令编译Tensorflow?

haskell - 如何在 GHCI 中加载优化代码?

c - 为什么clang用-O0产生效率低的asm(对于这个简单的 float 和)?

c - C99 'restrict' 关键字的实际用法?

c - 在c中打开文件进行读取

c - 在尝试释放()之前确定结构成员是否具有有效数据

c - 将受限指针分配给另一个指针,并使用第二个指针修改值是否合法?