Get pointer to llvm::Value previously allocated for CreateLoad function

ぃ、小莉子 提交于 2019-12-08 07:34:16

问题


I'm new to llvm and I'm writing a small llvm IR Builder. I use the IRBuilder and all these Create* functions to generate my IR. What I'm trying to do is to create a load instruction which create a new SSA local variable with value of a previously allocated llvm::Value.

What I expected to have :

%2 = load i32* %1

With %2 results of load instruction and %1 my previously allocated Value (CreateAlloca)

Here is what I tried :

// Get Ptr from Val
Value* ptr = ConstantExpr::getIntToPtr((Constant*)loc[n],PointerType::getUnqual(builder->getInt32Ty()));

// Générate load instruction with the new Ptr
builder->CreateLoad(ptr);

And here is what I have :

%2 = load i32* null

loc is an array which contains all my llvm::Value*

Can you please tell me what I'm doing wrong ? Or maybe if I'm on a bad way ? Thanks.


回答1:


ConstantExpr::getIntToPtr() creates a constant expression. So in effect, what you're trying to generate is equivalent to this IR:

%2 = load i32* inttoptr (i32 %1 to i32*)

But this is illegal since a constant expression, as hinted by its name, only supports constants, and %1 isn't a constant. ConstantExpr::getIntToPtr() requires a Constant as a first argument to verify it, but you passed it a non-constant value which was forcefully cast to a constant.

The correct way to convert a non-constant integer to a pointer is with IRBuilder::createIntToPtr. However, since you say the previous value (loc[n]) was created via an alloca then it's already a pointer, and you don't need to perform any conversion: just do builder->CreateLoad(loc[n]).

By the way, the proper way to cast a Value to a Constant in LLVM is not via a c-style cast but via cast<>, like so: cast<Constant>(loc[n]).



来源:https://stackoverflow.com/questions/16692984/get-pointer-to-llvmvalue-previously-allocated-for-createload-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!