aot_llvm_extra.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <llvm/ADT/SmallVector.h>
  6. #include <llvm/ADT/Twine.h>
  7. #include <llvm/ADT/Triple.h>
  8. #include <llvm/Analysis/TargetTransformInfo.h>
  9. #include <llvm/CodeGen/TargetPassConfig.h>
  10. #include <llvm/ExecutionEngine/ExecutionEngine.h>
  11. #include <llvm/MC/MCSubtargetInfo.h>
  12. #include <llvm/Support/TargetSelect.h>
  13. #include <llvm/Target/TargetMachine.h>
  14. #include <llvm-c/Core.h>
  15. #include <llvm-c/ExecutionEngine.h>
  16. #include <llvm-c/Initialization.h>
  17. #include <llvm/ExecutionEngine/GenericValue.h>
  18. #include <llvm/ExecutionEngine/JITEventListener.h>
  19. #include <llvm/ExecutionEngine/RTDyldMemoryManager.h>
  20. #include <llvm/ExecutionEngine/Orc/LLJIT.h>
  21. #include <llvm/IR/DerivedTypes.h>
  22. #include <llvm/IR/Module.h>
  23. #include <llvm/IR/Instructions.h>
  24. #include <llvm/IR/IntrinsicInst.h>
  25. #include <llvm/IR/LegacyPassManager.h>
  26. #include <llvm/Support/CommandLine.h>
  27. #include <llvm/Support/ErrorHandling.h>
  28. #include <llvm/Target/CodeGenCWrappers.h>
  29. #include <llvm/Target/TargetMachine.h>
  30. #include <llvm/Target/TargetOptions.h>
  31. #include <llvm/Transforms/Utils/LowerMemIntrinsics.h>
  32. #include <llvm/Transforms/Vectorize/LoopVectorize.h>
  33. #include <llvm/Transforms/Vectorize/LoadStoreVectorizer.h>
  34. #include <llvm/Transforms/Vectorize/SLPVectorizer.h>
  35. #include <llvm/Transforms/Scalar/LoopRotation.h>
  36. #include <llvm/Transforms/Scalar/SimpleLoopUnswitch.h>
  37. #include <llvm/Transforms/Scalar/LICM.h>
  38. #include <llvm/Transforms/Scalar/GVN.h>
  39. #include <llvm/Passes/PassBuilder.h>
  40. #include <llvm/Analysis/TargetLibraryInfo.h>
  41. #if LLVM_VERSION_MAJOR >= 12
  42. #include <llvm/Analysis/AliasAnalysis.h>
  43. #endif
  44. #include <cstring>
  45. #if WASM_ENABLE_LAZY_JIT != 0
  46. #include "../aot/aot_runtime.h"
  47. #endif
  48. #include "aot_llvm.h"
  49. using namespace llvm;
  50. using namespace llvm::orc;
  51. extern "C" {
  52. LLVMBool
  53. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  54. LLVMModuleRef M,
  55. LLVMMCJITCompilerOptions *PassedOptions,
  56. size_t SizeOfPassedOptions, char **OutError);
  57. bool
  58. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str);
  59. void
  60. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass);
  61. void
  62. aot_func_disable_tce(LLVMValueRef func);
  63. void
  64. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx);
  65. }
  66. static TargetMachine *
  67. unwrap(LLVMTargetMachineRef P)
  68. {
  69. return reinterpret_cast<TargetMachine *>(P);
  70. }
  71. LLVMBool
  72. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  73. LLVMModuleRef M,
  74. LLVMMCJITCompilerOptions *PassedOptions,
  75. size_t SizeOfPassedOptions, char **OutError)
  76. {
  77. LLVMMCJITCompilerOptions options;
  78. // If the user passed a larger sized options struct, then they were compiled
  79. // against a newer LLVM. Tell them that something is wrong.
  80. if (SizeOfPassedOptions > sizeof(options)) {
  81. *OutError = strdup("Refusing to use options struct that is larger than "
  82. "my own; assuming LLVM library mismatch.");
  83. return 1;
  84. }
  85. // Defend against the user having an old version of the API by ensuring that
  86. // any fields they didn't see are cleared. We must defend against fields
  87. // being set to the bitwise equivalent of zero, and assume that this means
  88. // "do the default" as if that option hadn't been available.
  89. LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
  90. memcpy(&options, PassedOptions, SizeOfPassedOptions);
  91. TargetOptions targetOptions;
  92. targetOptions.EnableFastISel = options.EnableFastISel;
  93. std::unique_ptr<Module> Mod(unwrap(M));
  94. if (Mod) {
  95. // Set function attribute "frame-pointer" based on
  96. // NoFramePointerElim.
  97. for (auto &F : *Mod) {
  98. auto Attrs = F.getAttributes();
  99. StringRef Value = options.NoFramePointerElim ? "all" : "none";
  100. Attrs =
  101. Attrs.addAttribute(F.getContext(), AttributeList::FunctionIndex,
  102. "frame-pointer", Value);
  103. F.setAttributes(Attrs);
  104. }
  105. }
  106. std::string Error;
  107. bool JIT;
  108. char *host_cpu = LLVMGetHostCPUName();
  109. if (!host_cpu) {
  110. *OutError = NULL;
  111. return false;
  112. }
  113. std::string mcpu(host_cpu);
  114. LLVMDisposeMessage(host_cpu);
  115. EngineBuilder builder(std::move(Mod));
  116. builder.setEngineKind(EngineKind::JIT)
  117. .setErrorStr(&Error)
  118. .setMCPU(mcpu)
  119. .setOptLevel((CodeGenOpt::Level)options.OptLevel)
  120. .setTargetOptions(targetOptions);
  121. if (Optional<CodeModel::Model> CM = unwrap(options.CodeModel, JIT))
  122. builder.setCodeModel(*CM);
  123. if (options.MCJMM)
  124. builder.setMCJITMemoryManager(
  125. std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
  126. if (ExecutionEngine *JIT = builder.create()) {
  127. *OutJIT = wrap(JIT);
  128. return 0;
  129. }
  130. *OutError = strdup(Error.c_str());
  131. return 1;
  132. }
  133. class ExpandMemoryOpPass : public llvm::ModulePass
  134. {
  135. public:
  136. static char ID;
  137. ExpandMemoryOpPass()
  138. : ModulePass(ID)
  139. {}
  140. bool runOnModule(Module &M) override;
  141. bool expandMemIntrinsicUses(Function &F);
  142. StringRef getPassName() const override
  143. {
  144. return "Expand memory operation intrinsics";
  145. }
  146. void getAnalysisUsage(AnalysisUsage &AU) const override
  147. {
  148. AU.addRequired<TargetTransformInfoWrapperPass>();
  149. }
  150. };
  151. char ExpandMemoryOpPass::ID = 0;
  152. bool
  153. ExpandMemoryOpPass::expandMemIntrinsicUses(Function &F)
  154. {
  155. Intrinsic::ID ID = F.getIntrinsicID();
  156. bool Changed = false;
  157. for (auto I = F.user_begin(), E = F.user_end(); I != E;) {
  158. Instruction *Inst = cast<Instruction>(*I);
  159. ++I;
  160. switch (ID) {
  161. case Intrinsic::memcpy:
  162. {
  163. auto *Memcpy = cast<MemCpyInst>(Inst);
  164. Function *ParentFunc = Memcpy->getParent()->getParent();
  165. const TargetTransformInfo &TTI =
  166. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  167. *ParentFunc);
  168. expandMemCpyAsLoop(Memcpy, TTI);
  169. Changed = true;
  170. Memcpy->eraseFromParent();
  171. break;
  172. }
  173. case Intrinsic::memmove:
  174. {
  175. auto *Memmove = cast<MemMoveInst>(Inst);
  176. expandMemMoveAsLoop(Memmove);
  177. Changed = true;
  178. Memmove->eraseFromParent();
  179. break;
  180. }
  181. case Intrinsic::memset:
  182. {
  183. auto *Memset = cast<MemSetInst>(Inst);
  184. expandMemSetAsLoop(Memset);
  185. Changed = true;
  186. Memset->eraseFromParent();
  187. break;
  188. }
  189. default:
  190. break;
  191. }
  192. }
  193. return Changed;
  194. }
  195. bool
  196. ExpandMemoryOpPass::runOnModule(Module &M)
  197. {
  198. bool Changed = false;
  199. for (Function &F : M) {
  200. if (!F.isDeclaration())
  201. continue;
  202. switch (F.getIntrinsicID()) {
  203. case Intrinsic::memcpy:
  204. case Intrinsic::memmove:
  205. case Intrinsic::memset:
  206. if (expandMemIntrinsicUses(F))
  207. Changed = true;
  208. break;
  209. default:
  210. break;
  211. }
  212. }
  213. return Changed;
  214. }
  215. void
  216. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass)
  217. {
  218. unwrap(pass)->add(new ExpandMemoryOpPass());
  219. }
  220. bool
  221. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str)
  222. {
  223. #if WASM_ENABLE_SIMD != 0
  224. if (!arch_c_str || !cpu_c_str) {
  225. return false;
  226. }
  227. llvm::SmallVector<std::string, 1> targetAttributes;
  228. llvm::Triple targetTriple(arch_c_str, "", "");
  229. auto targetMachine =
  230. std::unique_ptr<llvm::TargetMachine>(llvm::EngineBuilder().selectTarget(
  231. targetTriple, "", std::string(cpu_c_str), targetAttributes));
  232. if (!targetMachine) {
  233. return false;
  234. }
  235. const llvm::Triple::ArchType targetArch =
  236. targetMachine->getTargetTriple().getArch();
  237. const llvm::MCSubtargetInfo *subTargetInfo =
  238. targetMachine->getMCSubtargetInfo();
  239. if (subTargetInfo == nullptr) {
  240. return false;
  241. }
  242. if (targetArch == llvm::Triple::x86_64) {
  243. return subTargetInfo->checkFeatures("+sse4.1");
  244. }
  245. else if (targetArch == llvm::Triple::aarch64) {
  246. return subTargetInfo->checkFeatures("+neon");
  247. }
  248. else {
  249. return false;
  250. }
  251. #else
  252. (void)arch_c_str;
  253. (void)cpu_c_str;
  254. return true;
  255. #endif /* WASM_ENABLE_SIMD */
  256. }
  257. #if LLVM_VERSION_MAJOR < 12
  258. LLVMOrcJITTargetMachineBuilderRef
  259. LLVMOrcJITTargetMachineBuilderFromTargetMachine(LLVMTargetMachineRef TM);
  260. LLVMOrcJITTargetMachineBuilderRef
  261. LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(LLVMTargetMachineRef TM)
  262. {
  263. return LLVMOrcJITTargetMachineBuilderFromTargetMachine(TM);
  264. }
  265. #endif
  266. #if WASM_ENABLE_LAZY_JIT != 0
  267. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLJITBuilder, LLVMOrcLLJITBuilderRef)
  268. void
  269. LLVMOrcLLJITBuilderSetNumCompileThreads(LLVMOrcLLJITBuilderRef orcjit_builder,
  270. unsigned num_compile_threads)
  271. {
  272. unwrap(orcjit_builder)->setNumCompileThreads(num_compile_threads);
  273. }
  274. void *
  275. aot_lookup_orcjit_func(LLVMOrcLLJITRef orc_lazyjit, void *module_inst,
  276. uint32 func_idx)
  277. {
  278. char func_name[32], buf[128], *err_msg = NULL;
  279. LLVMErrorRef error;
  280. LLVMOrcJITTargetAddress func_addr = 0;
  281. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  282. AOTModule *aot_module = (AOTModule *)aot_inst->aot_module.ptr;
  283. void **func_ptrs = (void **)aot_inst->func_ptrs.ptr;
  284. /**
  285. * No need to lock the func_ptr[func_idx] here as it is basic
  286. * data type, the load/store for it can be finished by one cpu
  287. * instruction, and there can be only one cpu instruction
  288. * loading/storing at the same time.
  289. */
  290. if (func_ptrs[func_idx])
  291. return func_ptrs[func_idx];
  292. snprintf(func_name, sizeof(func_name), "%s%d", AOT_FUNC_PREFIX,
  293. func_idx - aot_module->import_func_count);
  294. if ((error = LLVMOrcLLJITLookup(orc_lazyjit, &func_addr, func_name))) {
  295. err_msg = LLVMGetErrorMessage(error);
  296. snprintf(buf, sizeof(buf), "failed to lookup orcjit function: %s",
  297. err_msg);
  298. aot_set_exception(aot_inst, buf);
  299. LLVMDisposeErrorMessage(err_msg);
  300. return NULL;
  301. }
  302. func_ptrs[func_idx] = (void *)func_addr;
  303. return (void *)func_addr;
  304. }
  305. #endif
  306. void
  307. aot_func_disable_tce(LLVMValueRef func)
  308. {
  309. Function *F = unwrap<Function>(func);
  310. auto Attrs = F->getAttributes();
  311. Attrs = Attrs.addAttribute(F->getContext(), AttributeList::FunctionIndex,
  312. "disable-tail-calls", "true");
  313. F->setAttributes(Attrs);
  314. }
  315. void
  316. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx)
  317. {
  318. Module *M;
  319. TargetMachine *TM = unwrap(comp_ctx->target_machine);
  320. bool disable_llvm_lto = false;
  321. LoopAnalysisManager LAM;
  322. FunctionAnalysisManager FAM;
  323. CGSCCAnalysisManager CGAM;
  324. ModuleAnalysisManager MAM;
  325. PipelineTuningOptions PTO;
  326. PTO.LoopVectorization = true;
  327. PTO.SLPVectorization = true;
  328. PTO.LoopUnrolling = true;
  329. #if LLVM_VERSION_MAJOR == 12
  330. PassBuilder PB(false, TM, PTO);
  331. #else
  332. PassBuilder PB(TM, PTO);
  333. #endif
  334. // Register the target library analysis directly and give it a
  335. // customized preset TLI.
  336. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  337. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  338. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  339. // Register the AA manager first so that our version is the one used.
  340. AAManager AA = PB.buildDefaultAAPipeline();
  341. FAM.registerPass([&] { return std::move(AA); });
  342. // Register all the basic analyses with the managers.
  343. PB.registerModuleAnalyses(MAM);
  344. PB.registerCGSCCAnalyses(CGAM);
  345. PB.registerFunctionAnalyses(FAM);
  346. PB.registerLoopAnalyses(LAM);
  347. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  348. ModulePassManager MPM;
  349. PassBuilder::OptimizationLevel OL;
  350. switch (comp_ctx->opt_level) {
  351. case 0:
  352. OL = PassBuilder::OptimizationLevel::O0;
  353. break;
  354. case 1:
  355. OL = PassBuilder::OptimizationLevel::O1;
  356. break;
  357. case 2:
  358. OL = PassBuilder::OptimizationLevel::O2;
  359. break;
  360. case 3:
  361. default:
  362. OL = PassBuilder::OptimizationLevel::O3;
  363. break;
  364. }
  365. if (comp_ctx->disable_llvm_lto) {
  366. disable_llvm_lto = true;
  367. }
  368. #if WASM_ENABLE_SPEC_TEST != 0
  369. disable_llvm_lto = true;
  370. #endif
  371. if (disable_llvm_lto) {
  372. uint32 i;
  373. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  374. aot_func_disable_tce(comp_ctx->func_ctxes[i]->func);
  375. }
  376. }
  377. if (comp_ctx->is_jit_mode) {
  378. /* Apply normal pipeline for JIT mode, without
  379. Vectorize related passes, without LTO */
  380. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  381. }
  382. else {
  383. FunctionPassManager FPM;
  384. /* Apply Vectorize related passes for AOT mode */
  385. FPM.addPass(LoopVectorizePass());
  386. FPM.addPass(SLPVectorizerPass());
  387. FPM.addPass(LoadStoreVectorizerPass());
  388. /*
  389. FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
  390. FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
  391. FPM.addPass(createFunctionToLoopPassAdaptor(SimpleLoopUnswitchPass()));
  392. */
  393. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  394. if (!disable_llvm_lto) {
  395. /* Apply LTO for AOT mode */
  396. MPM.addPass(PB.buildLTODefaultPipeline(OL, NULL));
  397. }
  398. else {
  399. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  400. }
  401. }
  402. #if WASM_ENABLE_LAZY_JIT == 0
  403. M = unwrap(comp_ctx->module);
  404. MPM.run(*M, MAM);
  405. #else
  406. uint32 i;
  407. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  408. M = unwrap(comp_ctx->modules[i]);
  409. MPM.run(*M, MAM);
  410. }
  411. #endif
  412. }