hello.
I’m trying to implement a function with an array argument. I’m stucked on how to get address of that argument.
llvm::ArrayType* array_type = llvm::ArrayType::get(llvm::Type::getInt32Ty(*TheContext), 4);
/*
* int foo(int array[4]){
* return array[0];
* }
*/
{
llvm::FunctionType* fn_type = llvm::FunctionType::get(llvm::Type::getInt32Ty(*TheContext), std::vector<llvm::Type*>{array_type}, false);
llvm::Function* fn = llvm::Function::Create(fn_type, llvm::Function::ExternalLinkage, "foo", TheModule.get());
llvm::BasicBlock* entry_block = llvm::BasicBlock::Create(*TheContext, "entry", fn);
Builder->SetInsertPoint(entry_block);
// how to get address of array[0] ??
}
/*
* int main(){
* int array[4]={1,2,3,4};
* foo(array);
* return 0;
* }
*/
{
llvm::FunctionType* fn_type = llvm::FunctionType::get(llvm::Type::getInt32Ty(*TheContext), std::vector<llvm::Type*>{}, false);
llvm::Function* fn = llvm::Function::Create(fn_type, llvm::Function::ExternalLinkage, "main", TheModule.get());
llvm::BasicBlock* entry_block = llvm::BasicBlock::Create(*TheContext, "entry", fn);
Builder->SetInsertPoint(entry_block);
llvm::AllocaInst* array = Builder->CreateAlloca(array_type, nullptr, "array");
for (int i = 0; i < 4; i++) {
llvm::Value* ptr_element = Builder->CreateConstGEP2_64(array_type, array, 0, i);
Builder->CreateStore(llvm::ConstantInt::get(*TheContext, llvm::APInt(32, i + 1, true)), ptr_element);
}
llvm::Value* loaded_array = Builder->CreateLoad(array_type, array);
llvm::Function* fn_foo = TheModule->getFunction("foo");
std::vector<llvm::Value*> args{
loaded_array,
};
llvm::CallInst* result_v = Builder->CreateCall(fn_foo, args, "s");
Builder->CreateRet(Builder->getInt32(0));
}
I have tried this instructions below.
- GEP
The second parameter of GEP is required to be a pointer. But the array is stored in register. I have to alloca/store to get address. I want to avoid this unnecessary memory access. - extractelement
The first parameter is required to be a vector. So I think this instruction is not help. - extractvalue
This instruction is almost the perfect choice. The only problem is it only receive constant index.
Is there an instruction that can get address of array element that stored in registers? Is it a bad idea to pass array itself (instead of passing array address) as an argument?
Please help.