2
0

ExecutionEngineBindings.cpp 15 KB

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