ExecutionEngineBindings.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the C bindings for the ExecutionEngine library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm-c/ExecutionEngine.h"
  13. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  14. #include "llvm/ExecutionEngine/GenericValue.h"
  15. #include "llvm/ExecutionEngine/JITEventListener.h"
  16. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/Target/CodeGenCWrappers.h"
  21. #include "llvm/Target/TargetOptions.h"
  22. #include <cstring>
  23. #include <optional>
  24. using namespace llvm;
  25. #define DEBUG_TYPE "jit"
  26. // Wrapping the C bindings types.
  27. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
  28. static LLVMTargetMachineRef wrap(const TargetMachine *P) {
  29. return
  30. reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
  31. }
  32. /*===-- Operations on generic values --------------------------------------===*/
  33. LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
  34. unsigned long long N,
  35. LLVMBool IsSigned) {
  36. GenericValue *GenVal = new GenericValue();
  37. GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
  38. return wrap(GenVal);
  39. }
  40. LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
  41. GenericValue *GenVal = new GenericValue();
  42. GenVal->PointerVal = P;
  43. return wrap(GenVal);
  44. }
  45. LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
  46. GenericValue *GenVal = new GenericValue();
  47. switch (unwrap(TyRef)->getTypeID()) {
  48. case Type::FloatTyID:
  49. GenVal->FloatVal = N;
  50. break;
  51. case Type::DoubleTyID:
  52. GenVal->DoubleVal = N;
  53. break;
  54. default:
  55. llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
  56. }
  57. return wrap(GenVal);
  58. }
  59. unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
  60. return unwrap(GenValRef)->IntVal.getBitWidth();
  61. }
  62. unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
  63. LLVMBool IsSigned) {
  64. GenericValue *GenVal = unwrap(GenValRef);
  65. if (IsSigned)
  66. return GenVal->IntVal.getSExtValue();
  67. else
  68. return GenVal->IntVal.getZExtValue();
  69. }
  70. void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
  71. return unwrap(GenVal)->PointerVal;
  72. }
  73. double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
  74. switch (unwrap(TyRef)->getTypeID()) {
  75. case Type::FloatTyID:
  76. return unwrap(GenVal)->FloatVal;
  77. case Type::DoubleTyID:
  78. return unwrap(GenVal)->DoubleVal;
  79. default:
  80. llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
  81. }
  82. }
  83. void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
  84. delete unwrap(GenVal);
  85. }
  86. /*===-- Operations on execution engines -----------------------------------===*/
  87. LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
  88. LLVMModuleRef M,
  89. char **OutError) {
  90. std::string Error;
  91. EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
  92. builder.setEngineKind(EngineKind::Either)
  93. .setErrorStr(&Error);
  94. if (ExecutionEngine *EE = builder.create()){
  95. *OutEE = wrap(EE);
  96. return 0;
  97. }
  98. *OutError = strdup(Error.c_str());
  99. return 1;
  100. }
  101. LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
  102. LLVMModuleRef M,
  103. char **OutError) {
  104. std::string Error;
  105. EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
  106. builder.setEngineKind(EngineKind::Interpreter)
  107. .setErrorStr(&Error);
  108. if (ExecutionEngine *Interp = builder.create()) {
  109. *OutInterp = wrap(Interp);
  110. return 0;
  111. }
  112. *OutError = strdup(Error.c_str());
  113. return 1;
  114. }
  115. LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  116. LLVMModuleRef M,
  117. unsigned OptLevel,
  118. char **OutError) {
  119. std::string Error;
  120. EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
  121. builder.setEngineKind(EngineKind::JIT)
  122. .setErrorStr(&Error)
  123. .setOptLevel((CodeGenOpt::Level)OptLevel);
  124. if (ExecutionEngine *JIT = builder.create()) {
  125. *OutJIT = wrap(JIT);
  126. return 0;
  127. }
  128. *OutError = strdup(Error.c_str());
  129. return 1;
  130. }
  131. void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
  132. size_t SizeOfPassedOptions) {
  133. LLVMMCJITCompilerOptions options;
  134. memset(&options, 0, sizeof(options)); // Most fields are zero by default.
  135. options.CodeModel = LLVMCodeModelJITDefault;
  136. memcpy(PassedOptions, &options,
  137. std::min(sizeof(options), SizeOfPassedOptions));
  138. }
  139. LLVMBool LLVMCreateMCJITCompilerForModule(
  140. LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
  141. LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
  142. char **OutError) {
  143. LLVMMCJITCompilerOptions options;
  144. // If the user passed a larger sized options struct, then they were compiled
  145. // against a newer LLVM. Tell them that something is wrong.
  146. if (SizeOfPassedOptions > sizeof(options)) {
  147. *OutError = strdup(
  148. "Refusing to use options struct that is larger than my own; assuming "
  149. "LLVM library mismatch.");
  150. return 1;
  151. }
  152. // Defend against the user having an old version of the API by ensuring that
  153. // any fields they didn't see are cleared. We must defend against fields being
  154. // set to the bitwise equivalent of zero, and assume that this means "do the
  155. // default" as if that option hadn't been available.
  156. LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
  157. memcpy(&options, PassedOptions, SizeOfPassedOptions);
  158. TargetOptions targetOptions;
  159. targetOptions.EnableFastISel = options.EnableFastISel;
  160. std::unique_ptr<Module> Mod(unwrap(M));
  161. if (Mod)
  162. // Set function attribute "frame-pointer" based on
  163. // NoFramePointerElim.
  164. for (auto &F : *Mod) {
  165. auto Attrs = F.getAttributes();
  166. StringRef Value = options.NoFramePointerElim ? "all" : "none";
  167. Attrs = Attrs.addFnAttribute(F.getContext(), "frame-pointer", Value);
  168. F.setAttributes(Attrs);
  169. }
  170. std::string Error;
  171. EngineBuilder builder(std::move(Mod));
  172. builder.setEngineKind(EngineKind::JIT)
  173. .setErrorStr(&Error)
  174. .setOptLevel((CodeGenOpt::Level)options.OptLevel)
  175. .setTargetOptions(targetOptions);
  176. bool JIT;
  177. if (std::optional<CodeModel::Model> CM = unwrap(options.CodeModel, JIT))
  178. builder.setCodeModel(*CM);
  179. if (options.MCJMM)
  180. builder.setMCJITMemoryManager(
  181. std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
  182. if (ExecutionEngine *JIT = builder.create()) {
  183. *OutJIT = wrap(JIT);
  184. return 0;
  185. }
  186. *OutError = strdup(Error.c_str());
  187. return 1;
  188. }
  189. void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
  190. delete unwrap(EE);
  191. }
  192. void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
  193. unwrap(EE)->finalizeObject();
  194. unwrap(EE)->runStaticConstructorsDestructors(false);
  195. }
  196. void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
  197. unwrap(EE)->finalizeObject();
  198. unwrap(EE)->runStaticConstructorsDestructors(true);
  199. }
  200. int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
  201. unsigned ArgC, const char * const *ArgV,
  202. const char * const *EnvP) {
  203. unwrap(EE)->finalizeObject();
  204. std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
  205. return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
  206. }
  207. LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
  208. unsigned NumArgs,
  209. LLVMGenericValueRef *Args) {
  210. unwrap(EE)->finalizeObject();
  211. std::vector<GenericValue> ArgVec;
  212. ArgVec.reserve(NumArgs);
  213. for (unsigned I = 0; I != NumArgs; ++I)
  214. ArgVec.push_back(*unwrap(Args[I]));
  215. GenericValue *Result = new GenericValue();
  216. *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
  217. return wrap(Result);
  218. }
  219. void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
  220. }
  221. void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
  222. unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
  223. }
  224. LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
  225. LLVMModuleRef *OutMod, char **OutError) {
  226. Module *Mod = unwrap(M);
  227. unwrap(EE)->removeModule(Mod);
  228. *OutMod = wrap(Mod);
  229. return 0;
  230. }
  231. LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
  232. LLVMValueRef *OutFn) {
  233. if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
  234. *OutFn = wrap(F);
  235. return 0;
  236. }
  237. return 1;
  238. }
  239. void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
  240. LLVMValueRef Fn) {
  241. return nullptr;
  242. }
  243. LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
  244. return wrap(&unwrap(EE)->getDataLayout());
  245. }
  246. LLVMTargetMachineRef
  247. LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
  248. return wrap(unwrap(EE)->getTargetMachine());
  249. }
  250. void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
  251. void* Addr) {
  252. unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
  253. }
  254. void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
  255. unwrap(EE)->finalizeObject();
  256. return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
  257. }
  258. uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
  259. return unwrap(EE)->getGlobalValueAddress(Name);
  260. }
  261. uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
  262. return unwrap(EE)->getFunctionAddress(Name);
  263. }
  264. LLVMBool LLVMExecutionEngineGetErrMsg(LLVMExecutionEngineRef EE,
  265. char **OutError) {
  266. assert(OutError && "OutError must be non-null");
  267. auto *ExecEngine = unwrap(EE);
  268. if (ExecEngine->hasError()) {
  269. *OutError = strdup(ExecEngine->getErrorMessage().c_str());
  270. ExecEngine->clearErrorMessage();
  271. return true;
  272. }
  273. return false;
  274. }
  275. /*===-- Operations on memory managers -------------------------------------===*/
  276. namespace {
  277. struct SimpleBindingMMFunctions {
  278. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
  279. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
  280. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
  281. LLVMMemoryManagerDestroyCallback Destroy;
  282. };
  283. class SimpleBindingMemoryManager : public RTDyldMemoryManager {
  284. public:
  285. SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
  286. void *Opaque);
  287. ~SimpleBindingMemoryManager() override;
  288. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  289. unsigned SectionID,
  290. StringRef SectionName) override;
  291. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  292. unsigned SectionID, StringRef SectionName,
  293. bool isReadOnly) override;
  294. bool finalizeMemory(std::string *ErrMsg) override;
  295. private:
  296. SimpleBindingMMFunctions Functions;
  297. void *Opaque;
  298. };
  299. SimpleBindingMemoryManager::SimpleBindingMemoryManager(
  300. const SimpleBindingMMFunctions& Functions,
  301. void *Opaque)
  302. : Functions(Functions), Opaque(Opaque) {
  303. assert(Functions.AllocateCodeSection &&
  304. "No AllocateCodeSection function provided!");
  305. assert(Functions.AllocateDataSection &&
  306. "No AllocateDataSection function provided!");
  307. assert(Functions.FinalizeMemory &&
  308. "No FinalizeMemory function provided!");
  309. assert(Functions.Destroy &&
  310. "No Destroy function provided!");
  311. }
  312. SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
  313. Functions.Destroy(Opaque);
  314. }
  315. uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
  316. uintptr_t Size, unsigned Alignment, unsigned SectionID,
  317. StringRef SectionName) {
  318. return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
  319. SectionName.str().c_str());
  320. }
  321. uint8_t *SimpleBindingMemoryManager::allocateDataSection(
  322. uintptr_t Size, unsigned Alignment, unsigned SectionID,
  323. StringRef SectionName, bool isReadOnly) {
  324. return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
  325. SectionName.str().c_str(),
  326. isReadOnly);
  327. }
  328. bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
  329. char *errMsgCString = nullptr;
  330. bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
  331. assert((result || !errMsgCString) &&
  332. "Did not expect an error message if FinalizeMemory succeeded");
  333. if (errMsgCString) {
  334. if (ErrMsg)
  335. *ErrMsg = errMsgCString;
  336. free(errMsgCString);
  337. }
  338. return result;
  339. }
  340. } // anonymous namespace
  341. LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
  342. void *Opaque,
  343. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
  344. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
  345. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
  346. LLVMMemoryManagerDestroyCallback Destroy) {
  347. if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
  348. !Destroy)
  349. return nullptr;
  350. SimpleBindingMMFunctions functions;
  351. functions.AllocateCodeSection = AllocateCodeSection;
  352. functions.AllocateDataSection = AllocateDataSection;
  353. functions.FinalizeMemory = FinalizeMemory;
  354. functions.Destroy = Destroy;
  355. return wrap(new SimpleBindingMemoryManager(functions, Opaque));
  356. }
  357. void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
  358. delete unwrap(MM);
  359. }
  360. /*===-- JIT Event Listener functions -------------------------------------===*/
  361. #if !LLVM_USE_INTEL_JITEVENTS
  362. LLVMJITEventListenerRef LLVMCreateIntelJITEventListener(void)
  363. {
  364. return nullptr;
  365. }
  366. #endif
  367. #if !LLVM_USE_OPROFILE
  368. LLVMJITEventListenerRef LLVMCreateOProfileJITEventListener(void)
  369. {
  370. return nullptr;
  371. }
  372. #endif
  373. #if !LLVM_USE_PERF
  374. LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void)
  375. {
  376. return nullptr;
  377. }
  378. #endif