llvm 调用一个以 char * 作为参数的外部函数

llvm calling an external function with char * as argument

本文关键字:参数 外部 函数 调用 一个以 char llvm      更新时间:2023-10-16

我想在创建的调用中调用一个带有 char * 作为参数的外部函数,但我一直在挣扎。

我尝试查看文档,但它只显示了如何传递常量整数。

以下是代码的相关部分:

// 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);

考虑你的代码

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);

以下代码片段应该可以执行您想要的操作

如果字符串正在运行,LLVM 优化将使字符串本地化。如果您在没有优化的情况下生成 IR,您可能会被允许有点草率。

//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);