如何在 clang++ 中禁用自动"pass by pointer"优化?

How to disable automatic "pass by pointer" optimization in clang++?

本文关键字:pass by pointer 优化 clang++      更新时间:2023-10-16

我有一个函数

void X(Object o)
{
 ....
}
当我编译它时,我看到clang将其签名更改为
void X(Object* o)

这很不方便,因为我直接从一些llvm IR代码中使用这个函数。如何禁止它做这种优化?

编辑:最小工作示例:

#include <stdio.h>
class Object
{
public:
    Object();
    ~Object();
    int* pointer;
};
void Function(Object o)
{
    o.pointer = 0;
}
int main()
{
    Object a;
    Function(a);
    return 0;
}

clang++ tst.cpp -emit-llvm -O0 tst.cpp -S -std=c++11

Function被翻译成:

define void @_Z8Function6Object(%class.Object* %o) nounwind uwtable {
  %1 = getelementptr inbounds %class.Object* %o, i32 0, i32 0
  store i32* null, i32** %1, align 8
  ret void
}

您需要添加选项-mdisable-fp-elim

禁用帧指针消除优化。

在这里我找到了这个选项:clang option

这里我很好地解释了为什么clang这样做:理解选项'省略帧指针'

*编辑:*

经过检查,我发现如下:

  • 你的对象在编译后正确地通过拷贝传递:

的例子:

#include <stdio.h>
#include <iostream>
class Object
{
public:
    std::string test;
    Object() {
    this->test = "I'm an object";
    std::cout << "Object created" << std::endl;
    }
    Object(Object &o) {
    this->test = "I'm a object copy";
    std::cout << "Object copy created" << std::endl;    
}
    ~Object() {
}
    int* pointer;
};
void Function(Object o)
{
    o.pointer = 0;
    std::cout << o.test << std::endl;
}
int main()
{
    Object a;
    Function(a);
    std::cout << a.test << std::endl;
    return 0;
}
输出:

对象创建

创建对象副本

我是object copy

I'm an object

  • 第二点:

你可以看到在函数原型

之后
; Function Attrs: uwtable
define void @_Z8Function6Object(%class.Object* %o) #3 {
  %1 = getelementptr inbounds %class.Object* %o, i32 0, i32 1 // Get 
  store i32* null, i32** %1, align 8

函数得到对象的副本。你可以在main中看到对象

的副本

所以你的代码似乎工作得很好,事实上;)