LLVM IR Function with Array Parameter

I want to generate LLVM IR code from the two main C ++ functions that are given below.

int newFun2(int x){ int z = x + x; return z; } int newFun(int *y){ int first = y[3]; //How to define it using the LLVM API? int num = newFun2(first); return num; } 

My problem is to get the index of an array parameter using the LLVM API. Any ideas? Thank you very much.

Editted

This is my code using the API:

 llvm::LLVMContext &context = llvm::getGlobalContext(); llvm::Module *module = new llvm::Module("AST", context); llvm::IRBuilder<> builder(context); //newFun2 llvm::FunctionType *newFunc2Type = llvm::FunctionType::get(builder.getInt32Ty(), builder.getInt32Ty(), false); llvm::Function *newFunc2 = llvm::Function::Create(newFunc2Type, llvm::Function::ExternalLinkage, "newFun2", module); llvm::Function::arg_iterator argsFun2 = newFunc2->arg_begin(); llvm::Value* x = argsFun2++; x->setName("x"); llvm::BasicBlock* block = llvm::BasicBlock::Create(context, "entry", newFunc2); llvm::IRBuilder<> builder2(block); llvm::Value* tmp = builder2.CreateBinOp(llvm::Instruction::Add, x, x, "tmp"); builder2.CreateRet(tmp); //newFun llvm::FunctionType *newFuncType = llvm::FunctionType::get(builder.getInt32Ty(), builder.getInt32Ty()->getPointerTo(), false); llvm::Function *newFunc = llvm::Function::Create(newFuncType, llvm::Function::ExternalLinkage, "newFun", module); llvm::BasicBlock* block2 = llvm::BasicBlock::Create(context, "entry", newFunc); llvm::IRBuilder<> builder3(block2); module->dump(); 

And this is generated by LLVM IR:

 ; ModuleID = 'AST' define i32 @newFun2(i32 %x) { entry: %tmp = add i32 %x, %x ret i32 %tmp } define i32 @newFun(i32*) { entry: } 

I am stuck in the body of newFun due to access to the array.

+4
source share
1 answer

I think you first need to understand how IR should look. This can be done by looking at the language specification or using Clang to compile the C code in IR and take a look at the result.

In any case, the way to access the array element at the specified index is either with extractvalue (which accepts only constant indexes) or with gep . Both of them have corresponding constructors / factory methods and IRBuilder methods for their construction, for example

 builder.CreateExtractValue(y, 3); 

Creating a gep is a little trickier; I recommend a look at the gep manual .

However, a good way to see how to invoke the LLVM API to create the desired IR is to use llc (one of the LLVM command line tools) to generate the source file with these calls from the IR file, see these two related questions:

+4
source

Source: https://habr.com/ru/post/1483451/


All Articles