c++ - GNU 内置函数 `__builtin_unreachable ` 如何在此代码片段中工作?

标签 c++ c gcc compilation gnu

我的项目中有一个代码片段,其中使用了 __builtin_unreachable 函数,但我不知道为什么这里需要它。

我从 GNU __builtin_unreachable 读到, 好像是通过__builtin_unreachable函数来通知编译器CPU运行时永远不会到达这一行,这样就可以提前防止很多编译报错。但是我不明白为什么在这个代码片段中需要这个特性,删除 __builtin_unreachable 似乎什么也不会发生。

# define ATHCONTAINERS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while(0)


inline
void*
AuxVectorData::Cache::getDataArray (SG::auxid_t auxid,
                                    AuxVectorData& parent)
{
  // This function is important for performance.
  // Be careful when changing it.

  void* ptr = cachePtr (auxid);
  if (ATHCONTAINERS_UNLIKELY (ptr == 0)) {
    // We don't have the variable cached.
    // Call the out-of-line routine to get it cached.
    ptr = parent.getDataOol (auxid, false);

    // These inform the compiler of what the previous call did.
    // They tell the optimizer that it can now assume that this cache
    // entry is valid.
    ATHCONTAINERS_ASSUME (ptr != 0); 
    ATHCONTAINERS_ASSUME (cachePtr (auxid) != 0); 
    ATHCONTAINERS_ASSUME (cachePtr (auxid) == ptr);
  }
  return ptr;
}

最佳答案

ATHCONTAINERS_ASSUME 告诉编译器它的参数 x 不能为假。这使编译器不必生成任何代码来适应 x 为假的可能性。例如,当编译器看到 ATHCONTAINERS_ASSUME (ptr != 0) 时,它可以假设 ptr 不为空,并且可以优化掉任何与该假设相矛盾的代码,因为它将是未定义的行为。

例如,由于 getDataArray()inline,编译器可以在每个调用点知道返回的指针永远不会为 null。因此,如果调用者这样做:

if (void* p = cache.getDataArray(aux, parent))
    memcpy(p, "OK", 2);

编译器可以生成直接写“OK”而不执行空检查的代码。

关于c++ - GNU 内置函数 `__builtin_unreachable ` 如何在此代码片段中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710534/

相关文章:

c - 如何在C中写入excel中的第二列

c - Unix pthreads 和信号 : per thread signal handlers

performance - ccache的缺点

c++ - 配置文件引导优化 (C)

ruby - 安装 libv8 3.11.8.3 时出错

c++ - 包含对象和容器的容器

c++ - 调整 vector 大小 C++

c++ - 缺少 libnoise.dll 会阻止程序运行

c - 在我的例子中是 strncpy 或 strlcpy

c++ - unsigned int 值没有给出正确的结果