1

Can we convert llvm::FunctionType's object into a C/C++-styled function raw pointer?

A example for a C/C++-styled function raw pointer: uint64_t (*funPtr)(uint64_t* args);

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Jigao Luo
  • 127
  • 1
  • 6
  • Why do you want to do this? Calling such pointer would cause UB. – arrowd Jul 08 '20 at 07:07
  • @arrowd I would like to construct a llvm::Function. Then to call it in order to have the return value: in our example the `uint64_t`. – Jigao Luo Jul 08 '20 at 08:51

2 Answers2

2

llvm::Function is represented as an abstract syntax tree. You can't call it, just like you can't call arrays, lists, or any other data structures.

Instead, you need to leverage LLVM's ExecutionEngine functionality to be able to call llvm::Functions. Internally, the engine will compile it into native executable code and return a void* (I don't remember the API details, but something like that) to that code. Then you will be able to cast this pointer to a function pointer and finally use it to call the function.

arrowd
  • 33,231
  • 8
  • 79
  • 110
1

I'm not 100% sure with regards to the capabilities of llvm, but this text from n4659 may be helpful:

Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.

I'm pretty sure that function pointers aren't like regular pointers, and so these conversions are problematic. I think they discuss the issue at length in this stack overflow question.

Nathan Chappell
  • 2,099
  • 18
  • 21