Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM IR Function with an array parameter

I want to generate LLVM IR code from two basic c++ functions which are like 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 an index of the array parameter using the LLVM API. Any ideas ? Thank you so 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 the LLVM IR that is generated :

; ModuleID = 'AST'

define i32 @newFun2(i32 %x) {
entry:
  %tmp = add i32 %x, %x
  ret i32 %tmp
}

define i32 @newFun(i32*) {
entry:
}

I am stuck on the body of newFun because of the array access.

like image 497
kayhan Avatar asked May 29 '13 20:05

kayhan


1 Answers

I think that you first need to understand how the IR should look like. It can be done by peering into the language specification or by using Clang to compile the C code into IR and taking a look at the result.

In any case, the way to access an array element at a given index is either with extractvalue (which only accepts constant indices) or with a gep. Both of these have corresponding constructors / factory methods and IRBuilder methods to construct them, for example

builder.CreateExtractValue(y, 3);

Creating a gep is a little more complicated; I recommend taking a look at the gep guide.

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

  • Possible to auto-generate llvm c++ api code from LLVM-IR?
  • Generate LLVM C++ API code as backend
like image 180
Oak Avatar answered Sep 21 '22 22:09

Oak