aot_llvm_extra.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <llvm/Passes/StandardInstrumentations.h>
  6. #include <llvm/Support/Error.h>
  7. #include <llvm/ADT/None.h>
  8. #include <llvm/ADT/Optional.h>
  9. #include <llvm/ADT/SmallVector.h>
  10. #include <llvm/ADT/Twine.h>
  11. #include <llvm/ADT/Triple.h>
  12. #include <llvm/Analysis/TargetTransformInfo.h>
  13. #include <llvm/CodeGen/TargetPassConfig.h>
  14. #include <llvm/ExecutionEngine/ExecutionEngine.h>
  15. #include <llvm/MC/MCSubtargetInfo.h>
  16. #include <llvm/Support/TargetSelect.h>
  17. #include <llvm/Target/TargetMachine.h>
  18. #include <llvm-c/Core.h>
  19. #include <llvm-c/ExecutionEngine.h>
  20. #include <llvm-c/Initialization.h>
  21. #include <llvm/ExecutionEngine/GenericValue.h>
  22. #include <llvm/ExecutionEngine/JITEventListener.h>
  23. #include <llvm/ExecutionEngine/RTDyldMemoryManager.h>
  24. #include <llvm/ExecutionEngine/Orc/LLJIT.h>
  25. #include <llvm/IR/DerivedTypes.h>
  26. #include <llvm/IR/Module.h>
  27. #include <llvm/IR/Instructions.h>
  28. #include <llvm/IR/IntrinsicInst.h>
  29. #include <llvm/IR/LegacyPassManager.h>
  30. #include <llvm/Support/CommandLine.h>
  31. #include <llvm/Support/ErrorHandling.h>
  32. #include <llvm/Target/CodeGenCWrappers.h>
  33. #include <llvm/Target/TargetMachine.h>
  34. #include <llvm/Target/TargetOptions.h>
  35. #include <llvm/Transforms/Utils/LowerMemIntrinsics.h>
  36. #include <llvm/Transforms/Vectorize/LoopVectorize.h>
  37. #include <llvm/Transforms/Vectorize/LoadStoreVectorizer.h>
  38. #include <llvm/Transforms/Vectorize/SLPVectorizer.h>
  39. #include <llvm/Transforms/Scalar/LoopRotation.h>
  40. #include <llvm/Transforms/Scalar/SimpleLoopUnswitch.h>
  41. #include <llvm/Transforms/Scalar/LICM.h>
  42. #include <llvm/Transforms/Scalar/GVN.h>
  43. #include <llvm/Passes/PassBuilder.h>
  44. #include <llvm/Analysis/TargetLibraryInfo.h>
  45. #if LLVM_VERSION_MAJOR >= 12
  46. #include <llvm/Analysis/AliasAnalysis.h>
  47. #endif
  48. #include <llvm/ProfileData/InstrProf.h>
  49. #include <cstring>
  50. #include "../aot/aot_runtime.h"
  51. #include "aot_llvm.h"
  52. using namespace llvm;
  53. using namespace llvm::orc;
  54. LLVM_C_EXTERN_C_BEGIN
  55. bool
  56. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str);
  57. void
  58. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass);
  59. void
  60. aot_add_simple_loop_unswitch_pass(LLVMPassManagerRef pass);
  61. void
  62. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module);
  63. LLVM_C_EXTERN_C_END
  64. ExitOnError ExitOnErr;
  65. class ExpandMemoryOpPass : public llvm::ModulePass
  66. {
  67. public:
  68. static char ID;
  69. ExpandMemoryOpPass()
  70. : ModulePass(ID)
  71. {}
  72. bool runOnModule(Module &M) override;
  73. bool expandMemIntrinsicUses(Function &F);
  74. StringRef getPassName() const override
  75. {
  76. return "Expand memory operation intrinsics";
  77. }
  78. void getAnalysisUsage(AnalysisUsage &AU) const override
  79. {
  80. AU.addRequired<TargetTransformInfoWrapperPass>();
  81. }
  82. };
  83. char ExpandMemoryOpPass::ID = 0;
  84. bool
  85. ExpandMemoryOpPass::expandMemIntrinsicUses(Function &F)
  86. {
  87. Intrinsic::ID ID = F.getIntrinsicID();
  88. bool Changed = false;
  89. for (auto I = F.user_begin(), E = F.user_end(); I != E;) {
  90. Instruction *Inst = cast<Instruction>(*I);
  91. ++I;
  92. switch (ID) {
  93. case Intrinsic::memcpy:
  94. {
  95. auto *Memcpy = cast<MemCpyInst>(Inst);
  96. Function *ParentFunc = Memcpy->getParent()->getParent();
  97. const TargetTransformInfo &TTI =
  98. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  99. *ParentFunc);
  100. expandMemCpyAsLoop(Memcpy, TTI);
  101. Changed = true;
  102. Memcpy->eraseFromParent();
  103. break;
  104. }
  105. case Intrinsic::memmove:
  106. {
  107. auto *Memmove = cast<MemMoveInst>(Inst);
  108. expandMemMoveAsLoop(Memmove);
  109. Changed = true;
  110. Memmove->eraseFromParent();
  111. break;
  112. }
  113. case Intrinsic::memset:
  114. {
  115. auto *Memset = cast<MemSetInst>(Inst);
  116. expandMemSetAsLoop(Memset);
  117. Changed = true;
  118. Memset->eraseFromParent();
  119. break;
  120. }
  121. default:
  122. break;
  123. }
  124. }
  125. return Changed;
  126. }
  127. bool
  128. ExpandMemoryOpPass::runOnModule(Module &M)
  129. {
  130. bool Changed = false;
  131. for (Function &F : M) {
  132. if (!F.isDeclaration())
  133. continue;
  134. switch (F.getIntrinsicID()) {
  135. case Intrinsic::memcpy:
  136. case Intrinsic::memmove:
  137. case Intrinsic::memset:
  138. if (expandMemIntrinsicUses(F))
  139. Changed = true;
  140. break;
  141. default:
  142. break;
  143. }
  144. }
  145. return Changed;
  146. }
  147. void
  148. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass)
  149. {
  150. reinterpret_cast<legacy::PassManager *>(pass)->add(
  151. new ExpandMemoryOpPass());
  152. }
  153. void
  154. aot_add_simple_loop_unswitch_pass(LLVMPassManagerRef pass)
  155. {
  156. reinterpret_cast<legacy::PassManager *>(pass)->add(
  157. createSimpleLoopUnswitchLegacyPass());
  158. }
  159. bool
  160. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str)
  161. {
  162. #if WASM_ENABLE_SIMD != 0
  163. if (!arch_c_str || !cpu_c_str) {
  164. return false;
  165. }
  166. llvm::SmallVector<std::string, 1> targetAttributes;
  167. llvm::Triple targetTriple(arch_c_str, "", "");
  168. auto targetMachine =
  169. std::unique_ptr<llvm::TargetMachine>(llvm::EngineBuilder().selectTarget(
  170. targetTriple, "", std::string(cpu_c_str), targetAttributes));
  171. if (!targetMachine) {
  172. return false;
  173. }
  174. const llvm::Triple::ArchType targetArch =
  175. targetMachine->getTargetTriple().getArch();
  176. const llvm::MCSubtargetInfo *subTargetInfo =
  177. targetMachine->getMCSubtargetInfo();
  178. if (subTargetInfo == nullptr) {
  179. return false;
  180. }
  181. if (targetArch == llvm::Triple::x86_64) {
  182. return subTargetInfo->checkFeatures("+sse4.1");
  183. }
  184. else if (targetArch == llvm::Triple::aarch64) {
  185. return subTargetInfo->checkFeatures("+neon");
  186. }
  187. else {
  188. return false;
  189. }
  190. #else
  191. (void)arch_c_str;
  192. (void)cpu_c_str;
  193. return true;
  194. #endif /* WASM_ENABLE_SIMD */
  195. }
  196. void
  197. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module)
  198. {
  199. TargetMachine *TM =
  200. reinterpret_cast<TargetMachine *>(comp_ctx->target_machine);
  201. PipelineTuningOptions PTO;
  202. PTO.LoopVectorization = true;
  203. PTO.SLPVectorization = true;
  204. PTO.LoopUnrolling = true;
  205. Optional<PGOOptions> PGO = None;
  206. if (comp_ctx->enable_llvm_pgo) {
  207. /* Disable static counter allocation for value profiler,
  208. it will be allocated by runtime */
  209. const char *argv[] = { "", "-vp-static-alloc=false" };
  210. cl::ParseCommandLineOptions(2, argv);
  211. PGO = PGOOptions("", "", "", PGOOptions::IRInstr);
  212. }
  213. else if (comp_ctx->use_prof_file) {
  214. PGO = PGOOptions(comp_ctx->use_prof_file, "", "", PGOOptions::IRUse);
  215. }
  216. #ifdef DEBUG_PASS
  217. PassInstrumentationCallbacks PIC;
  218. PassBuilder PB(TM, PTO, PGO, &PIC);
  219. #else
  220. #if LLVM_VERSION_MAJOR == 12
  221. PassBuilder PB(false, TM, PTO, PGO);
  222. #else
  223. PassBuilder PB(TM, PTO, PGO);
  224. #endif
  225. #endif
  226. /* Register all the basic analyses with the managers */
  227. LoopAnalysisManager LAM;
  228. FunctionAnalysisManager FAM;
  229. CGSCCAnalysisManager CGAM;
  230. ModuleAnalysisManager MAM;
  231. /* Register the target library analysis directly and give it a
  232. customized preset TLI */
  233. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  234. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  235. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  236. /* Register the AA manager first so that our version is the one used */
  237. AAManager AA = PB.buildDefaultAAPipeline();
  238. FAM.registerPass([&] { return std::move(AA); });
  239. #ifdef DEBUG_PASS
  240. StandardInstrumentations SI(true, false);
  241. SI.registerCallbacks(PIC, &FAM);
  242. #endif
  243. PB.registerFunctionAnalyses(FAM);
  244. PB.registerLoopAnalyses(LAM);
  245. PB.registerModuleAnalyses(MAM);
  246. PB.registerCGSCCAnalyses(CGAM);
  247. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  248. #if LLVM_VERSION_MAJOR <= 13
  249. PassBuilder::OptimizationLevel OL;
  250. switch (comp_ctx->opt_level) {
  251. case 0:
  252. OL = PassBuilder::OptimizationLevel::O0;
  253. break;
  254. case 1:
  255. OL = PassBuilder::OptimizationLevel::O1;
  256. break;
  257. case 2:
  258. OL = PassBuilder::OptimizationLevel::O2;
  259. break;
  260. case 3:
  261. default:
  262. OL = PassBuilder::OptimizationLevel::O3;
  263. break;
  264. }
  265. #else
  266. OptimizationLevel OL;
  267. switch (comp_ctx->opt_level) {
  268. case 0:
  269. OL = OptimizationLevel::O0;
  270. break;
  271. case 1:
  272. OL = OptimizationLevel::O1;
  273. break;
  274. case 2:
  275. OL = OptimizationLevel::O2;
  276. break;
  277. case 3:
  278. default:
  279. OL = OptimizationLevel::O3;
  280. break;
  281. }
  282. #endif /* end of LLVM_VERSION_MAJOR */
  283. bool disable_llvm_lto = comp_ctx->disable_llvm_lto;
  284. #if WASM_ENABLE_SPEC_TEST != 0
  285. disable_llvm_lto = true;
  286. #endif
  287. Module *M = reinterpret_cast<Module *>(module);
  288. if (disable_llvm_lto) {
  289. for (Function &F : *M) {
  290. F.addFnAttr("disable-tail-calls", "true");
  291. }
  292. }
  293. ModulePassManager MPM;
  294. if (comp_ctx->is_jit_mode) {
  295. const char *Passes =
  296. "mem2reg,instcombine,simplifycfg,jump-threading,indvars";
  297. ExitOnErr(PB.parsePassPipeline(MPM, Passes));
  298. }
  299. else {
  300. FunctionPassManager FPM;
  301. /* Apply Vectorize related passes for AOT mode */
  302. FPM.addPass(LoopVectorizePass());
  303. FPM.addPass(SLPVectorizerPass());
  304. FPM.addPass(LoadStoreVectorizerPass());
  305. if (comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file) {
  306. /* LICM pass: loop invariant code motion, attempting to remove
  307. as much code from the body of a loop as possible. Experiments
  308. show it is good to enable it when pgo is enabled. */
  309. #if LLVM_VERSION_MAJOR >= 15
  310. LICMOptions licm_opt;
  311. FPM.addPass(
  312. createFunctionToLoopPassAdaptor(LICMPass(licm_opt), true));
  313. #else
  314. FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), true));
  315. #endif
  316. }
  317. /*
  318. FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
  319. FPM.addPass(createFunctionToLoopPassAdaptor(SimpleLoopUnswitchPass()));
  320. */
  321. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  322. if (!disable_llvm_lto) {
  323. /* Apply LTO for AOT mode */
  324. if (comp_ctx->comp_data->func_count >= 10
  325. || comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file)
  326. /* Add the pre-link optimizations if the func count
  327. is large enough or PGO is enabled */
  328. MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(OL));
  329. else
  330. MPM.addPass(PB.buildLTODefaultPipeline(OL, NULL));
  331. }
  332. else {
  333. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  334. }
  335. }
  336. MPM.run(*M, MAM);
  337. }
  338. char *
  339. aot_compress_aot_func_names(AOTCompContext *comp_ctx, uint32 *p_size)
  340. {
  341. std::vector<std::string> NameStrs;
  342. std::string Result;
  343. char buf[32], *compressed_str;
  344. uint32 compressed_str_len, i;
  345. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  346. snprintf(buf, sizeof(buf), "%s%d", AOT_FUNC_PREFIX, i);
  347. std::string str(buf);
  348. NameStrs.push_back(str);
  349. }
  350. if (collectPGOFuncNameStrings(NameStrs, true, Result)) {
  351. aot_set_last_error("collect pgo func name strings failed");
  352. return NULL;
  353. }
  354. compressed_str_len = Result.size();
  355. if (!(compressed_str = (char *)wasm_runtime_malloc(compressed_str_len))) {
  356. aot_set_last_error("allocate memory failed");
  357. return NULL;
  358. }
  359. bh_memcpy_s(compressed_str, compressed_str_len, Result.c_str(),
  360. compressed_str_len);
  361. *p_size = compressed_str_len;
  362. return compressed_str;
  363. }