funnypig run
funnypig run

Reputation: 302

llvm calling an external function with char * as argument

I want to call an external function with char * as argument in a created call but I have been struggling.

I tried looking at the documents but it only shows how to pass constant integers.

Here is the relevant part of the code:

// not sure if the line below is correct. I am trying to call an external function: FPRCLAP_path(char * string)
std::vector<llvm::Type*> arg_types = {llvm::Type::getInt8PtrTy(context)};

llvm::FunctionType *function_type = llvm::FunctionType::get(llvm::Type::getVoidTy(context), arg_types, false);
llvm::FunctionCallee instrumentation_function = function.getParent()->getOrInsertFunction("FPRCLAP_path", function_type);

llvm::IRBuilder<> builder(&instruction);
builder.SetInsertPoint(&basic_block, ++builder.GetInsertPoint());
// I want to pass a string for instrumentation but I am not sure how to do it using llvm. I think I am supposed to allocate a string or reference an existing string.
llvm::ArrayRef<llvm::Value*> arguments = {???};
builder.CreateCall(instrumentation_function, arguments);

Upvotes: 1

Views: 4565

Answers (1)

JKRT
JKRT

Reputation: 1207

Considering your code

llvm::IRBuilder<> builder(&instruction);
builder.SetInsertPoint(&basic_block, ++builder.GetInsertPoint());
// I want to pass a string for instrumentation but I am not sure how to do it using llvm. I think I am supposed to allocate a string or reference an existing string.
llvm::ArrayRef<llvm::Value*> arguments = {???};
builder.CreateCall(instrumentation_function, arguments);

The following snippet should do what you want

LLVM optimisation will make the string local, if it is run. If you generate IR without optimisation you might be allowed to be a bit sloppy.

//str is a char*
 llvm::Value *strPointer = program->builder.CreateGlobalStringPtr(str);
//Using a Vector instead of ArrayRef
 const std::vector<llvm::Value *> args{strPointer};
 builder.CreateCall(instrumentation_function, args);

Upvotes: 1

Related Questions