C++ llvm getelementptr获取错误的值
我正在学习llvm getelementptr指令,并尝试从结构中获取元素。我的结构是这样的C++ llvm getelementptr获取错误的值,c++,llvm,C++,Llvm,我正在学习llvm getelementptr指令,并尝试从结构中获取元素。我的结构是这样的 structfoo{ int32_t a; int32_t b; int32_t c; }; 相应的llvm类型: Type*getType(){ 载体tps; tps.push_back(类型::getInt32Ty(上下文)); tps.push_back(类型::getInt32Ty(上下文)); tps.push_back(类型::getInt32Ty(上下文)); StructType*tp
structfoo{
int32_t a;
int32_t b;
int32_t c;
};
相应的llvm类型:
Type*getType(){
载体tps;
tps.push_back(类型::getInt32Ty(上下文));
tps.push_back(类型::getInt32Ty(上下文));
tps.push_back(类型::getInt32Ty(上下文));
StructType*tp=StructType::create(上下文,tps,“foo_type”);
返回tp;
}
和一个测试函数
%foo_type = type { i32, i32, i32 }
define i32 @_func_(%foo_type) {
entry:
%1 = alloca %foo_type
store %foo_type %0, %foo_type* %1
%2 = getelementptr %foo_type, %foo_type* %1, i32 0, i32 1
%3 = load i32, i32* %2
ret i32 %3
}
但是通过运行编译后的函数,我总是得到第三个元素,即Foo::c,而不是Foo::b,那么我的代码有什么问题?我想问题可能是商店的说明书
编辑2019.12.13
通过传递指针作为参数,我得到了正确的答案
define i32 @_func_(%foo_type*) {
entry:
%1 = alloca %foo_type*
store %foo_type* %0, %foo_type** %1
%ptr = load %foo_type*, %foo_type** %1
%2 = getelementptr %foo_type, %foo_type* %ptr, i32 0, i32 1
%3 = load i32, i32* %2
ret i32 %3
}
因此问题一定是
FP(f)
实际上没有将f
传递给上一版本中的编译函数。如果用c编写函数并让clang为其发出IR,您可以看到:
structfoo{
INTA;
int b;
INTC;
};
整型条(Foo-f){
返回f.b;
}
这意味着bar(Foo())
实际上接受int64
和int32
作为参数,而不是Foo
本身。可能是一些我不太了解的c/cpp ABI
但当通过指针时,不会出现这样的问题,因此它会按预期工作。如果这解决了您的问题。请将其添加为答案:)
define dso_local i32 @_Z3bar3Foo(i64, i32) #0 {
%3 = alloca %struct.Foo, align 4
%4 = alloca { i64, i32 }, align 4
%5 = getelementptr inbounds { i64, i32 }, { i64, i32 }* %4, i32 0, i32 0
store i64 %0, i64* %5, align 4
%6 = getelementptr inbounds { i64, i32 }, { i64, i32 }* %4, i32 0, i32 1
store i32 %1, i32* %6, align 4
%7 = bitcast %struct.Foo* %3 to i8*
%8 = bitcast { i64, i32 }* %4 to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %7, i8* align 4 %8, i64 12, i1 false)
%9 = getelementptr inbounds %struct.Foo, %struct.Foo* %3, i32 0, i32 1
%10 = load i32, i32* %9, align 4
ret i32 %10
}