aot_llvm.c 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "aot_llvm.h"
  6. #include "aot_compiler.h"
  7. #include "aot_emit_exception.h"
  8. #include "../aot/aot_runtime.h"
  9. #include "../aot/aot_intrinsic.h"
  10. #if WASM_ENABLE_DEBUG_AOT != 0
  11. #include "debug/dwarf_extractor.h"
  12. #endif
  13. LLVMTypeRef
  14. wasm_type_to_llvm_type(AOTLLVMTypes *llvm_types, uint8 wasm_type)
  15. {
  16. switch (wasm_type) {
  17. case VALUE_TYPE_I32:
  18. case VALUE_TYPE_FUNCREF:
  19. case VALUE_TYPE_EXTERNREF:
  20. return llvm_types->int32_type;
  21. case VALUE_TYPE_I64:
  22. return llvm_types->int64_type;
  23. case VALUE_TYPE_F32:
  24. return llvm_types->float32_type;
  25. case VALUE_TYPE_F64:
  26. return llvm_types->float64_type;
  27. case VALUE_TYPE_V128:
  28. return llvm_types->i64x2_vec_type;
  29. case VALUE_TYPE_VOID:
  30. return llvm_types->void_type;
  31. default:
  32. break;
  33. }
  34. return NULL;
  35. }
  36. /**
  37. * Add LLVM function
  38. */
  39. static LLVMValueRef
  40. aot_add_llvm_func(AOTCompContext *comp_ctx, AOTFuncType *aot_func_type,
  41. uint32 func_index, LLVMTypeRef *p_func_type)
  42. {
  43. LLVMValueRef func = NULL;
  44. LLVMTypeRef *param_types, ret_type, func_type;
  45. LLVMValueRef local_value;
  46. char func_name[32];
  47. uint64 size;
  48. uint32 i, j = 0, param_count = (uint64)aot_func_type->param_count;
  49. /* exec env as first parameter */
  50. param_count++;
  51. /* Extra wasm function results(except the first one)'s address are
  52. * appended to aot function parameters. */
  53. if (aot_func_type->result_count > 1)
  54. param_count += aot_func_type->result_count - 1;
  55. /* Initialize parameter types of the LLVM function */
  56. size = sizeof(LLVMTypeRef) * ((uint64)param_count);
  57. if (size >= UINT32_MAX
  58. || !(param_types = wasm_runtime_malloc((uint32)size))) {
  59. aot_set_last_error("allocate memory failed.");
  60. return NULL;
  61. }
  62. /* exec env as first parameter */
  63. param_types[j++] = comp_ctx->exec_env_type;
  64. for (i = 0; i < aot_func_type->param_count; i++)
  65. param_types[j++] = TO_LLVM_TYPE(aot_func_type->types[i]);
  66. /* Extra results' address */
  67. for (i = 1; i < aot_func_type->result_count; i++, j++) {
  68. param_types[j] =
  69. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count + i]);
  70. if (!(param_types[j] = LLVMPointerType(param_types[j], 0))) {
  71. aot_set_last_error("llvm get pointer type failed.");
  72. goto fail;
  73. }
  74. }
  75. /* Resolve return type of the LLVM function */
  76. if (aot_func_type->result_count)
  77. ret_type =
  78. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count]);
  79. else
  80. ret_type = VOID_TYPE;
  81. /* Resolve function prototype */
  82. if (!(func_type =
  83. LLVMFunctionType(ret_type, param_types, param_count, false))) {
  84. aot_set_last_error("create LLVM function type failed.");
  85. goto fail;
  86. }
  87. /* Add LLVM function */
  88. snprintf(func_name, sizeof(func_name), "%s%d", AOT_FUNC_PREFIX, func_index);
  89. if (!(func = LLVMAddFunction(comp_ctx->module, func_name, func_type))) {
  90. aot_set_last_error("add LLVM function failed.");
  91. goto fail;
  92. }
  93. j = 0;
  94. local_value = LLVMGetParam(func, j++);
  95. LLVMSetValueName(local_value, "exec_env");
  96. /* Set parameter names */
  97. for (i = 0; i < aot_func_type->param_count; i++) {
  98. local_value = LLVMGetParam(func, j++);
  99. LLVMSetValueName(local_value, "");
  100. }
  101. if (p_func_type)
  102. *p_func_type = func_type;
  103. fail:
  104. wasm_runtime_free(param_types);
  105. return func;
  106. }
  107. static void
  108. free_block_memory(AOTBlock *block)
  109. {
  110. if (block->param_types)
  111. wasm_runtime_free(block->param_types);
  112. if (block->result_types)
  113. wasm_runtime_free(block->result_types);
  114. wasm_runtime_free(block);
  115. }
  116. /**
  117. * Create first AOTBlock, or function block for the function
  118. */
  119. static AOTBlock *
  120. aot_create_func_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  121. AOTFunc *func, AOTFuncType *aot_func_type)
  122. {
  123. AOTBlock *aot_block;
  124. uint32 param_count = aot_func_type->param_count,
  125. result_count = aot_func_type->result_count;
  126. /* Allocate memory */
  127. if (!(aot_block = wasm_runtime_malloc(sizeof(AOTBlock)))) {
  128. aot_set_last_error("allocate memory failed.");
  129. return NULL;
  130. }
  131. memset(aot_block, 0, sizeof(AOTBlock));
  132. if (param_count
  133. && !(aot_block->param_types = wasm_runtime_malloc(param_count))) {
  134. aot_set_last_error("allocate memory failed.");
  135. goto fail;
  136. }
  137. if (result_count) {
  138. if (!(aot_block->result_types = wasm_runtime_malloc(result_count))) {
  139. aot_set_last_error("allocate memory failed.");
  140. goto fail;
  141. }
  142. }
  143. /* Set block data */
  144. aot_block->label_type = LABEL_TYPE_FUNCTION;
  145. aot_block->param_count = param_count;
  146. if (param_count) {
  147. bh_memcpy_s(aot_block->param_types, param_count, aot_func_type->types,
  148. param_count);
  149. }
  150. aot_block->result_count = result_count;
  151. if (result_count) {
  152. bh_memcpy_s(aot_block->result_types, result_count,
  153. aot_func_type->types + param_count, result_count);
  154. }
  155. aot_block->wasm_code_end = func->code + func->code_size;
  156. /* Add function entry block */
  157. if (!(aot_block->llvm_entry_block = LLVMAppendBasicBlockInContext(
  158. comp_ctx->context, func_ctx->func, "func_begin"))) {
  159. aot_set_last_error("add LLVM basic block failed.");
  160. goto fail;
  161. }
  162. return aot_block;
  163. fail:
  164. free_block_memory(aot_block);
  165. return NULL;
  166. }
  167. static bool
  168. create_memory_info(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  169. LLVMTypeRef int8_ptr_type, uint32 func_index)
  170. {
  171. LLVMValueRef offset, mem_info_base;
  172. uint32 memory_count;
  173. WASMModule *module = comp_ctx->comp_data->wasm_module;
  174. WASMFunction *func = module->functions[func_index];
  175. LLVMTypeRef bound_check_type;
  176. bool mem_space_unchanged =
  177. (!func->has_op_memory_grow && !func->has_op_func_call)
  178. || (!module->possible_memory_grow);
  179. #if WASM_ENABLE_SHARED_MEMORY != 0
  180. bool is_shared_memory;
  181. #endif
  182. func_ctx->mem_space_unchanged = mem_space_unchanged;
  183. memory_count = module->memory_count + module->import_memory_count;
  184. /* If the module dosen't have memory, reserve
  185. one mem_info space with empty content */
  186. if (memory_count == 0)
  187. memory_count = 1;
  188. if (!(func_ctx->mem_info =
  189. wasm_runtime_malloc(sizeof(AOTMemInfo) * memory_count))) {
  190. return false;
  191. }
  192. memset(func_ctx->mem_info, 0, sizeof(AOTMemInfo));
  193. /* Currently we only create memory info for memory 0 */
  194. /* Load memory base address */
  195. #if WASM_ENABLE_SHARED_MEMORY != 0
  196. is_shared_memory =
  197. comp_ctx->comp_data->memories[0].memory_flags & 0x02 ? true : false;
  198. if (is_shared_memory) {
  199. LLVMValueRef shared_mem_addr;
  200. offset = I32_CONST(offsetof(AOTModuleInstance, memories));
  201. if (!offset) {
  202. aot_set_last_error("create llvm const failed.");
  203. return false;
  204. }
  205. /* aot_inst->memories */
  206. if (!(shared_mem_addr =
  207. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  208. &offset, 1, "shared_mem_addr_offset"))) {
  209. aot_set_last_error("llvm build in bounds gep failed");
  210. return false;
  211. }
  212. if (!(shared_mem_addr =
  213. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  214. int8_ptr_type, "shared_mem_addr_ptr"))) {
  215. aot_set_last_error("llvm build bit cast failed");
  216. return false;
  217. }
  218. /* aot_inst->memories[0] */
  219. if (!(shared_mem_addr = LLVMBuildLoad(
  220. comp_ctx->builder, shared_mem_addr, "shared_mem_addr"))) {
  221. aot_set_last_error("llvm build load failed");
  222. return false;
  223. }
  224. if (!(shared_mem_addr =
  225. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  226. int8_ptr_type, "shared_mem_addr_ptr"))) {
  227. aot_set_last_error("llvm build bit cast failed");
  228. return false;
  229. }
  230. if (!(shared_mem_addr = LLVMBuildLoad(
  231. comp_ctx->builder, shared_mem_addr, "shared_mem_addr"))) {
  232. aot_set_last_error("llvm build load failed");
  233. return false;
  234. }
  235. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data.ptr));
  236. if (!(func_ctx->mem_info[0].mem_base_addr =
  237. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  238. &offset, 1, "mem_base_addr_offset"))) {
  239. aot_set_last_error("llvm build in bounds gep failed");
  240. return false;
  241. }
  242. offset = I32_CONST(offsetof(AOTMemoryInstance, cur_page_count));
  243. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  244. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  245. &offset, 1, "mem_cur_page_offset"))) {
  246. aot_set_last_error("llvm build in bounds gep failed");
  247. return false;
  248. }
  249. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data_size));
  250. if (!(func_ctx->mem_info[0].mem_data_size_addr =
  251. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  252. &offset, 1, "mem_data_size_offset"))) {
  253. aot_set_last_error("llvm build in bounds gep failed");
  254. return false;
  255. }
  256. }
  257. else
  258. #endif
  259. {
  260. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  261. + offsetof(AOTMemoryInstance, memory_data.ptr));
  262. if (!(func_ctx->mem_info[0].mem_base_addr =
  263. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  264. &offset, 1, "mem_base_addr_offset"))) {
  265. aot_set_last_error("llvm build in bounds gep failed");
  266. return false;
  267. }
  268. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  269. + offsetof(AOTMemoryInstance, cur_page_count));
  270. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  271. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  272. &offset, 1, "mem_cur_page_offset"))) {
  273. aot_set_last_error("llvm build in bounds gep failed");
  274. return false;
  275. }
  276. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  277. + offsetof(AOTMemoryInstance, memory_data_size));
  278. if (!(func_ctx->mem_info[0].mem_data_size_addr =
  279. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  280. &offset, 1, "mem_data_size_offset"))) {
  281. aot_set_last_error("llvm build in bounds gep failed");
  282. return false;
  283. }
  284. }
  285. /* Store mem info base address before cast */
  286. mem_info_base = func_ctx->mem_info[0].mem_base_addr;
  287. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildBitCast(
  288. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  289. int8_ptr_type, "mem_base_addr_ptr"))) {
  290. aot_set_last_error("llvm build bit cast failed");
  291. return false;
  292. }
  293. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr = LLVMBuildBitCast(
  294. comp_ctx->builder, func_ctx->mem_info[0].mem_cur_page_count_addr,
  295. INT32_PTR_TYPE, "mem_cur_page_ptr"))) {
  296. aot_set_last_error("llvm build bit cast failed");
  297. return false;
  298. }
  299. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildBitCast(
  300. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  301. INT32_PTR_TYPE, "mem_data_size_ptr"))) {
  302. aot_set_last_error("llvm build bit cast failed");
  303. return false;
  304. }
  305. if (mem_space_unchanged) {
  306. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad(
  307. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  308. "mem_base_addr"))) {
  309. aot_set_last_error("llvm build load failed");
  310. return false;
  311. }
  312. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  313. LLVMBuildLoad(comp_ctx->builder,
  314. func_ctx->mem_info[0].mem_cur_page_count_addr,
  315. "mem_cur_page_count"))) {
  316. aot_set_last_error("llvm build load failed");
  317. return false;
  318. }
  319. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildLoad(
  320. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  321. "mem_data_size"))) {
  322. aot_set_last_error("llvm build load failed");
  323. return false;
  324. }
  325. }
  326. #if WASM_ENABLE_SHARED_MEMORY != 0
  327. else if (is_shared_memory) {
  328. /* The base address for shared memory will never changed,
  329. we can load the value here */
  330. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad(
  331. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  332. "mem_base_addr"))) {
  333. aot_set_last_error("llvm build load failed");
  334. return false;
  335. }
  336. }
  337. #endif
  338. bound_check_type = (comp_ctx->pointer_size == sizeof(uint64))
  339. ? INT64_PTR_TYPE
  340. : INT32_PTR_TYPE;
  341. /* Load memory bound check constants */
  342. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_1byte)
  343. - offsetof(AOTMemoryInstance, memory_data.ptr));
  344. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  345. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  346. "bound_check_1byte_offset"))) {
  347. aot_set_last_error("llvm build in bounds gep failed");
  348. return false;
  349. }
  350. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildBitCast(
  351. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_1byte,
  352. bound_check_type, "bound_check_1byte_ptr"))) {
  353. aot_set_last_error("llvm build bit cast failed");
  354. return false;
  355. }
  356. if (mem_space_unchanged) {
  357. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  358. LLVMBuildLoad(comp_ctx->builder,
  359. func_ctx->mem_info[0].mem_bound_check_1byte,
  360. "bound_check_1byte"))) {
  361. aot_set_last_error("llvm build load failed");
  362. return false;
  363. }
  364. }
  365. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_2bytes)
  366. - offsetof(AOTMemoryInstance, memory_data.ptr));
  367. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  368. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  369. "bound_check_2bytes_offset"))) {
  370. aot_set_last_error("llvm build in bounds gep failed");
  371. return false;
  372. }
  373. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildBitCast(
  374. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_2bytes,
  375. bound_check_type, "bound_check_2bytes_ptr"))) {
  376. aot_set_last_error("llvm build bit cast failed");
  377. return false;
  378. }
  379. if (mem_space_unchanged) {
  380. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  381. LLVMBuildLoad(comp_ctx->builder,
  382. func_ctx->mem_info[0].mem_bound_check_2bytes,
  383. "bound_check_2bytes"))) {
  384. aot_set_last_error("llvm build load failed");
  385. return false;
  386. }
  387. }
  388. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_4bytes)
  389. - offsetof(AOTMemoryInstance, memory_data.ptr));
  390. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  391. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  392. "bound_check_4bytes_offset"))) {
  393. aot_set_last_error("llvm build in bounds gep failed");
  394. return false;
  395. }
  396. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildBitCast(
  397. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_4bytes,
  398. bound_check_type, "bound_check_4bytes_ptr"))) {
  399. aot_set_last_error("llvm build bit cast failed");
  400. return false;
  401. }
  402. if (mem_space_unchanged) {
  403. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  404. LLVMBuildLoad(comp_ctx->builder,
  405. func_ctx->mem_info[0].mem_bound_check_4bytes,
  406. "bound_check_4bytes"))) {
  407. aot_set_last_error("llvm build load failed");
  408. return false;
  409. }
  410. }
  411. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_8bytes)
  412. - offsetof(AOTMemoryInstance, memory_data.ptr));
  413. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  414. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  415. "bound_check_8bytes_offset"))) {
  416. aot_set_last_error("llvm build in bounds gep failed");
  417. return false;
  418. }
  419. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildBitCast(
  420. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_8bytes,
  421. bound_check_type, "bound_check_8bytes_ptr"))) {
  422. aot_set_last_error("llvm build bit cast failed");
  423. return false;
  424. }
  425. if (mem_space_unchanged) {
  426. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  427. LLVMBuildLoad(comp_ctx->builder,
  428. func_ctx->mem_info[0].mem_bound_check_8bytes,
  429. "bound_check_8bytes"))) {
  430. aot_set_last_error("llvm build load failed");
  431. return false;
  432. }
  433. }
  434. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_16bytes)
  435. - offsetof(AOTMemoryInstance, memory_data.ptr));
  436. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes =
  437. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  438. "bound_check_16bytes_offset"))) {
  439. aot_set_last_error("llvm build in bounds gep failed");
  440. return false;
  441. }
  442. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildBitCast(
  443. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_16bytes,
  444. bound_check_type, "bound_check_16bytes_ptr"))) {
  445. aot_set_last_error("llvm build bit cast failed");
  446. return false;
  447. }
  448. if (mem_space_unchanged) {
  449. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes =
  450. LLVMBuildLoad(comp_ctx->builder,
  451. func_ctx->mem_info[0].mem_bound_check_16bytes,
  452. "bound_check_16bytes"))) {
  453. aot_set_last_error("llvm build load failed");
  454. return false;
  455. }
  456. }
  457. return true;
  458. }
  459. static bool
  460. create_cur_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  461. {
  462. LLVMValueRef offset;
  463. offset = I32_CONST(offsetof(AOTModuleInstance, cur_exception));
  464. func_ctx->cur_exception = LLVMBuildInBoundsGEP(
  465. comp_ctx->builder, func_ctx->aot_inst, &offset, 1, "cur_execption");
  466. if (!func_ctx->cur_exception) {
  467. aot_set_last_error("llvm build in bounds gep failed.");
  468. return false;
  469. }
  470. return true;
  471. }
  472. static bool
  473. create_func_type_indexes(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  474. {
  475. LLVMValueRef offset, func_type_indexes_ptr;
  476. LLVMTypeRef int32_ptr_type;
  477. offset = I32_CONST(offsetof(AOTModuleInstance, func_type_indexes.ptr));
  478. func_type_indexes_ptr =
  479. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst, &offset, 1,
  480. "func_type_indexes_ptr");
  481. if (!func_type_indexes_ptr) {
  482. aot_set_last_error("llvm build add failed.");
  483. return false;
  484. }
  485. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  486. aot_set_last_error("llvm get pointer type failed.");
  487. return false;
  488. }
  489. func_ctx->func_type_indexes =
  490. LLVMBuildBitCast(comp_ctx->builder, func_type_indexes_ptr,
  491. int32_ptr_type, "func_type_indexes_tmp");
  492. if (!func_ctx->func_type_indexes) {
  493. aot_set_last_error("llvm build bit cast failed.");
  494. return false;
  495. }
  496. func_ctx->func_type_indexes = LLVMBuildLoad(
  497. comp_ctx->builder, func_ctx->func_type_indexes, "func_type_indexes");
  498. if (!func_ctx->func_type_indexes) {
  499. aot_set_last_error("llvm build load failed.");
  500. return false;
  501. }
  502. return true;
  503. }
  504. static bool
  505. create_func_ptrs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  506. {
  507. LLVMValueRef offset;
  508. offset = I32_CONST(offsetof(AOTModuleInstance, func_ptrs));
  509. func_ctx->func_ptrs = LLVMBuildInBoundsGEP(
  510. comp_ctx->builder, func_ctx->aot_inst, &offset, 1, "func_ptrs_offset");
  511. if (!func_ctx->func_ptrs) {
  512. aot_set_last_error("llvm build in bounds gep failed.");
  513. return false;
  514. }
  515. func_ctx->func_ptrs =
  516. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  517. comp_ctx->exec_env_type, "func_ptrs_tmp");
  518. if (!func_ctx->func_ptrs) {
  519. aot_set_last_error("llvm build bit cast failed.");
  520. return false;
  521. }
  522. func_ctx->func_ptrs =
  523. LLVMBuildLoad(comp_ctx->builder, func_ctx->func_ptrs, "func_ptrs_ptr");
  524. if (!func_ctx->func_ptrs) {
  525. aot_set_last_error("llvm build load failed.");
  526. return false;
  527. }
  528. func_ctx->func_ptrs =
  529. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  530. comp_ctx->exec_env_type, "func_ptrs");
  531. if (!func_ctx->func_ptrs) {
  532. aot_set_last_error("llvm build bit cast failed.");
  533. return false;
  534. }
  535. return true;
  536. }
  537. /**
  538. * Create function compiler context
  539. */
  540. static AOTFuncContext *
  541. aot_create_func_context(AOTCompData *comp_data, AOTCompContext *comp_ctx,
  542. AOTFunc *func, uint32 func_index)
  543. {
  544. AOTFuncContext *func_ctx;
  545. AOTFuncType *aot_func_type = comp_data->func_types[func->func_type_index];
  546. AOTBlock *aot_block;
  547. LLVMTypeRef int8_ptr_type, int32_ptr_type;
  548. LLVMValueRef aot_inst_offset = I32_TWO, aot_inst_addr;
  549. LLVMValueRef argv_buf_offset = I32_THREE, argv_buf_addr;
  550. LLVMValueRef stack_bound_offset = I32_FOUR, stack_bound_addr;
  551. LLVMValueRef aux_stack_bound_offset = I32_SIX, aux_stack_bound_addr;
  552. LLVMValueRef aux_stack_bottom_offset = I32_SEVEN, aux_stack_bottom_addr;
  553. LLVMValueRef native_symbol_offset = I32_EIGHT, native_symbol_addr;
  554. char local_name[32];
  555. uint64 size;
  556. uint32 i, j = 0;
  557. /* Allocate memory for the function context */
  558. size = offsetof(AOTFuncContext, locals)
  559. + sizeof(LLVMValueRef)
  560. * ((uint64)aot_func_type->param_count + func->local_count);
  561. if (size >= UINT32_MAX || !(func_ctx = wasm_runtime_malloc((uint32)size))) {
  562. aot_set_last_error("allocate memory failed.");
  563. return NULL;
  564. }
  565. memset(func_ctx, 0, (uint32)size);
  566. func_ctx->aot_func = func;
  567. /* Add LLVM function */
  568. if (!(func_ctx->func = aot_add_llvm_func(comp_ctx, aot_func_type,
  569. func_index, &func_ctx->func_type)))
  570. goto fail;
  571. /* Create function's first AOTBlock */
  572. if (!(aot_block =
  573. aot_create_func_block(comp_ctx, func_ctx, func, aot_func_type)))
  574. goto fail;
  575. #if WASM_ENABLE_DEBUG_AOT != 0
  576. func_ctx->debug_func = dwarf_gen_func_info(comp_ctx, func_ctx);
  577. #endif
  578. aot_block_stack_push(&func_ctx->block_stack, aot_block);
  579. /* Add local variables */
  580. LLVMPositionBuilderAtEnd(comp_ctx->builder, aot_block->llvm_entry_block);
  581. /* Save the pameters for fast access */
  582. func_ctx->exec_env = LLVMGetParam(func_ctx->func, j++);
  583. /* Get aot inst address, the layout of exec_env is:
  584. exec_env->next, exec_env->prev, exec_env->module_inst, and argv_buf */
  585. if (!(aot_inst_addr =
  586. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->exec_env,
  587. &aot_inst_offset, 1, "aot_inst_addr"))) {
  588. aot_set_last_error("llvm build in bounds gep failed");
  589. goto fail;
  590. }
  591. /* Load aot inst */
  592. if (!(func_ctx->aot_inst =
  593. LLVMBuildLoad(comp_ctx->builder, aot_inst_addr, "aot_inst"))) {
  594. aot_set_last_error("llvm build load failed");
  595. goto fail;
  596. }
  597. /* Get argv buffer address */
  598. if (!(argv_buf_addr =
  599. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->exec_env,
  600. &argv_buf_offset, 1, "argv_buf_addr"))) {
  601. aot_set_last_error("llvm build in bounds gep failed");
  602. goto fail;
  603. }
  604. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  605. aot_set_last_error("llvm add pointer type failed");
  606. goto fail;
  607. }
  608. /* Convert to int32 pointer type */
  609. if (!(argv_buf_addr = LLVMBuildBitCast(comp_ctx->builder, argv_buf_addr,
  610. int32_ptr_type, "argv_buf_ptr"))) {
  611. aot_set_last_error("llvm build load failed");
  612. goto fail;
  613. }
  614. if (!(func_ctx->argv_buf =
  615. LLVMBuildLoad(comp_ctx->builder, argv_buf_addr, "argv_buf"))) {
  616. aot_set_last_error("llvm build load failed");
  617. goto fail;
  618. }
  619. /* Get native stack boundary address */
  620. if (!(stack_bound_addr = LLVMBuildInBoundsGEP(
  621. comp_ctx->builder, func_ctx->exec_env, &stack_bound_offset, 1,
  622. "stack_bound_addr"))) {
  623. aot_set_last_error("llvm build in bounds gep failed");
  624. goto fail;
  625. }
  626. if (!(func_ctx->native_stack_bound = LLVMBuildLoad(
  627. comp_ctx->builder, stack_bound_addr, "native_stack_bound"))) {
  628. aot_set_last_error("llvm build load failed");
  629. goto fail;
  630. }
  631. /* Get aux stack boundary address */
  632. if (!(aux_stack_bound_addr = LLVMBuildInBoundsGEP(
  633. comp_ctx->builder, func_ctx->exec_env, &aux_stack_bound_offset, 1,
  634. "aux_stack_bound_addr"))) {
  635. aot_set_last_error("llvm build in bounds gep failed");
  636. goto fail;
  637. }
  638. if (!(aux_stack_bound_addr =
  639. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bound_addr,
  640. INT32_PTR_TYPE, "aux_stack_bound_ptr"))) {
  641. aot_set_last_error("llvm build bit cast failed");
  642. goto fail;
  643. }
  644. if (!(func_ctx->aux_stack_bound = LLVMBuildLoad(
  645. comp_ctx->builder, aux_stack_bound_addr, "aux_stack_bound"))) {
  646. aot_set_last_error("llvm build load failed");
  647. goto fail;
  648. }
  649. /* Get aux stack bottom address */
  650. if (!(aux_stack_bottom_addr = LLVMBuildInBoundsGEP(
  651. comp_ctx->builder, func_ctx->exec_env, &aux_stack_bottom_offset,
  652. 1, "aux_stack_bottom_addr"))) {
  653. aot_set_last_error("llvm build in bounds gep failed");
  654. goto fail;
  655. }
  656. if (!(aux_stack_bottom_addr =
  657. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bottom_addr,
  658. INT32_PTR_TYPE, "aux_stack_bottom_ptr"))) {
  659. aot_set_last_error("llvm build bit cast failed");
  660. goto fail;
  661. }
  662. if (!(func_ctx->aux_stack_bottom = LLVMBuildLoad(
  663. comp_ctx->builder, aux_stack_bottom_addr, "aux_stack_bottom"))) {
  664. aot_set_last_error("llvm build load failed");
  665. goto fail;
  666. }
  667. if (!(native_symbol_addr = LLVMBuildInBoundsGEP(
  668. comp_ctx->builder, func_ctx->exec_env, &native_symbol_offset, 1,
  669. "native_symbol_addr"))) {
  670. aot_set_last_error("llvm build in bounds gep failed");
  671. goto fail;
  672. }
  673. if (!(func_ctx->native_symbol = LLVMBuildLoad(
  674. comp_ctx->builder, native_symbol_addr, "native_symbol_tmp"))) {
  675. aot_set_last_error("llvm build bit cast failed");
  676. goto fail;
  677. }
  678. if (!(func_ctx->native_symbol =
  679. LLVMBuildBitCast(comp_ctx->builder, func_ctx->native_symbol,
  680. comp_ctx->exec_env_type, "native_symbol"))) {
  681. aot_set_last_error("llvm build bit cast failed");
  682. goto fail;
  683. }
  684. for (i = 0; i < aot_func_type->param_count; i++, j++) {
  685. snprintf(local_name, sizeof(local_name), "l%d", i);
  686. func_ctx->locals[i] =
  687. LLVMBuildAlloca(comp_ctx->builder,
  688. TO_LLVM_TYPE(aot_func_type->types[i]), local_name);
  689. if (!func_ctx->locals[i]) {
  690. aot_set_last_error("llvm build alloca failed.");
  691. goto fail;
  692. }
  693. if (!LLVMBuildStore(comp_ctx->builder, LLVMGetParam(func_ctx->func, j),
  694. func_ctx->locals[i])) {
  695. aot_set_last_error("llvm build store failed.");
  696. goto fail;
  697. }
  698. }
  699. for (i = 0; i < func->local_count; i++) {
  700. LLVMTypeRef local_type;
  701. LLVMValueRef local_value = NULL;
  702. snprintf(local_name, sizeof(local_name), "l%d",
  703. aot_func_type->param_count + i);
  704. local_type = TO_LLVM_TYPE(func->local_types[i]);
  705. func_ctx->locals[aot_func_type->param_count + i] =
  706. LLVMBuildAlloca(comp_ctx->builder, local_type, local_name);
  707. if (!func_ctx->locals[aot_func_type->param_count + i]) {
  708. aot_set_last_error("llvm build alloca failed.");
  709. goto fail;
  710. }
  711. switch (func->local_types[i]) {
  712. case VALUE_TYPE_I32:
  713. local_value = I32_ZERO;
  714. break;
  715. case VALUE_TYPE_I64:
  716. local_value = I64_ZERO;
  717. break;
  718. case VALUE_TYPE_F32:
  719. local_value = F32_ZERO;
  720. break;
  721. case VALUE_TYPE_F64:
  722. local_value = F64_ZERO;
  723. break;
  724. case VALUE_TYPE_V128:
  725. local_value = V128_i64x2_ZERO;
  726. break;
  727. case VALUE_TYPE_FUNCREF:
  728. case VALUE_TYPE_EXTERNREF:
  729. local_value = REF_NULL;
  730. break;
  731. default:
  732. bh_assert(0);
  733. break;
  734. }
  735. if (!LLVMBuildStore(comp_ctx->builder, local_value,
  736. func_ctx->locals[aot_func_type->param_count + i])) {
  737. aot_set_last_error("llvm build store failed.");
  738. goto fail;
  739. }
  740. }
  741. if (aot_func_type->param_count + func->local_count > 0) {
  742. func_ctx->last_alloca =
  743. func_ctx
  744. ->locals[aot_func_type->param_count + func->local_count - 1];
  745. if (!(func_ctx->last_alloca =
  746. LLVMBuildBitCast(comp_ctx->builder, func_ctx->last_alloca,
  747. INT8_PTR_TYPE, "stack_ptr"))) {
  748. aot_set_last_error("llvm build bit cast failed.");
  749. goto fail;
  750. }
  751. }
  752. else {
  753. if (!(func_ctx->last_alloca =
  754. LLVMBuildAlloca(comp_ctx->builder, INT8_TYPE, "stack_ptr"))) {
  755. aot_set_last_error("llvm build alloca failed.");
  756. goto fail;
  757. }
  758. }
  759. if (!(int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0))) {
  760. aot_set_last_error("llvm add pointer type failed.");
  761. goto fail;
  762. }
  763. /* Create base addr, end addr, data size of mem, heap */
  764. if (!create_memory_info(comp_ctx, func_ctx, int8_ptr_type, func_index))
  765. goto fail;
  766. /* Load current exception */
  767. if (!create_cur_exception(comp_ctx, func_ctx))
  768. goto fail;
  769. /* Load function type indexes */
  770. if (!create_func_type_indexes(comp_ctx, func_ctx))
  771. goto fail;
  772. /* Load function pointers */
  773. if (!create_func_ptrs(comp_ctx, func_ctx))
  774. goto fail;
  775. return func_ctx;
  776. fail:
  777. if (func_ctx->mem_info)
  778. wasm_runtime_free(func_ctx->mem_info);
  779. aot_block_stack_destroy(&func_ctx->block_stack);
  780. wasm_runtime_free(func_ctx);
  781. return NULL;
  782. }
  783. static void
  784. aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count)
  785. {
  786. uint32 i;
  787. for (i = 0; i < count; i++)
  788. if (func_ctxes[i]) {
  789. if (func_ctxes[i]->mem_info)
  790. wasm_runtime_free(func_ctxes[i]->mem_info);
  791. aot_block_stack_destroy(&func_ctxes[i]->block_stack);
  792. aot_checked_addr_list_destroy(func_ctxes[i]);
  793. wasm_runtime_free(func_ctxes[i]);
  794. }
  795. wasm_runtime_free(func_ctxes);
  796. }
  797. /**
  798. * Create function compiler contexts
  799. */
  800. static AOTFuncContext **
  801. aot_create_func_contexts(AOTCompData *comp_data, AOTCompContext *comp_ctx)
  802. {
  803. AOTFuncContext **func_ctxes;
  804. uint64 size;
  805. uint32 i;
  806. /* Allocate memory */
  807. size = sizeof(AOTFuncContext *) * (uint64)comp_data->func_count;
  808. if (size >= UINT32_MAX
  809. || !(func_ctxes = wasm_runtime_malloc((uint32)size))) {
  810. aot_set_last_error("allocate memory failed.");
  811. return NULL;
  812. }
  813. memset(func_ctxes, 0, size);
  814. /* Create each function context */
  815. for (i = 0; i < comp_data->func_count; i++) {
  816. AOTFunc *func = comp_data->funcs[i];
  817. if (!(func_ctxes[i] =
  818. aot_create_func_context(comp_data, comp_ctx, func, i))) {
  819. aot_destroy_func_contexts(func_ctxes, comp_data->func_count);
  820. return NULL;
  821. }
  822. }
  823. return func_ctxes;
  824. }
  825. static bool
  826. aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context)
  827. {
  828. basic_types->int1_type = LLVMInt1TypeInContext(context);
  829. basic_types->int8_type = LLVMInt8TypeInContext(context);
  830. basic_types->int16_type = LLVMInt16TypeInContext(context);
  831. basic_types->int32_type = LLVMInt32TypeInContext(context);
  832. basic_types->int64_type = LLVMInt64TypeInContext(context);
  833. basic_types->float32_type = LLVMFloatTypeInContext(context);
  834. basic_types->float64_type = LLVMDoubleTypeInContext(context);
  835. basic_types->void_type = LLVMVoidTypeInContext(context);
  836. basic_types->meta_data_type = LLVMMetadataTypeInContext(context);
  837. basic_types->int8_ptr_type = LLVMPointerType(basic_types->int8_type, 0);
  838. if (basic_types->int8_ptr_type) {
  839. basic_types->int8_pptr_type =
  840. LLVMPointerType(basic_types->int8_ptr_type, 0);
  841. }
  842. basic_types->int16_ptr_type = LLVMPointerType(basic_types->int16_type, 0);
  843. basic_types->int32_ptr_type = LLVMPointerType(basic_types->int32_type, 0);
  844. basic_types->int64_ptr_type = LLVMPointerType(basic_types->int64_type, 0);
  845. basic_types->float32_ptr_type =
  846. LLVMPointerType(basic_types->float32_type, 0);
  847. basic_types->float64_ptr_type =
  848. LLVMPointerType(basic_types->float64_type, 0);
  849. basic_types->i8x16_vec_type = LLVMVectorType(basic_types->int8_type, 16);
  850. basic_types->i16x8_vec_type = LLVMVectorType(basic_types->int16_type, 8);
  851. basic_types->i32x4_vec_type = LLVMVectorType(basic_types->int32_type, 4);
  852. basic_types->i64x2_vec_type = LLVMVectorType(basic_types->int64_type, 2);
  853. basic_types->f32x4_vec_type = LLVMVectorType(basic_types->float32_type, 4);
  854. basic_types->f64x2_vec_type = LLVMVectorType(basic_types->float64_type, 2);
  855. basic_types->v128_type = basic_types->i64x2_vec_type;
  856. basic_types->v128_ptr_type = LLVMPointerType(basic_types->v128_type, 0);
  857. basic_types->i1x2_vec_type = LLVMVectorType(basic_types->int1_type, 2);
  858. basic_types->funcref_type = LLVMInt32TypeInContext(context);
  859. basic_types->externref_type = LLVMInt32TypeInContext(context);
  860. return (basic_types->int8_ptr_type && basic_types->int8_pptr_type
  861. && basic_types->int16_ptr_type && basic_types->int32_ptr_type
  862. && basic_types->int64_ptr_type && basic_types->float32_ptr_type
  863. && basic_types->float64_ptr_type && basic_types->i8x16_vec_type
  864. && basic_types->i16x8_vec_type && basic_types->i32x4_vec_type
  865. && basic_types->i64x2_vec_type && basic_types->f32x4_vec_type
  866. && basic_types->f64x2_vec_type && basic_types->i1x2_vec_type
  867. && basic_types->meta_data_type && basic_types->funcref_type
  868. && basic_types->externref_type)
  869. ? true
  870. : false;
  871. }
  872. static bool
  873. aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx)
  874. {
  875. #define CREATE_I1_CONST(name, value) \
  876. if (!(consts->i1_##name = \
  877. LLVMConstInt(comp_ctx->basic_types.int1_type, value, true))) \
  878. return false;
  879. CREATE_I1_CONST(zero, 0)
  880. CREATE_I1_CONST(one, 1)
  881. #undef CREATE_I1_CONST
  882. if (!(consts->i8_zero = I8_CONST(0)))
  883. return false;
  884. if (!(consts->f32_zero = F32_CONST(0)))
  885. return false;
  886. if (!(consts->f64_zero = F64_CONST(0)))
  887. return false;
  888. #define CREATE_I32_CONST(name, value) \
  889. if (!(consts->i32_##name = LLVMConstInt(I32_TYPE, value, true))) \
  890. return false;
  891. CREATE_I32_CONST(min, (uint32)INT32_MIN)
  892. CREATE_I32_CONST(neg_one, (uint32)-1)
  893. CREATE_I32_CONST(zero, 0)
  894. CREATE_I32_CONST(one, 1)
  895. CREATE_I32_CONST(two, 2)
  896. CREATE_I32_CONST(three, 3)
  897. CREATE_I32_CONST(four, 4)
  898. CREATE_I32_CONST(five, 5)
  899. CREATE_I32_CONST(six, 6)
  900. CREATE_I32_CONST(seven, 7)
  901. CREATE_I32_CONST(eight, 8)
  902. CREATE_I32_CONST(nine, 9)
  903. CREATE_I32_CONST(ten, 10)
  904. CREATE_I32_CONST(eleven, 11)
  905. CREATE_I32_CONST(twelve, 12)
  906. CREATE_I32_CONST(thirteen, 13)
  907. CREATE_I32_CONST(fourteen, 14)
  908. CREATE_I32_CONST(fifteen, 15)
  909. CREATE_I32_CONST(31, 31)
  910. CREATE_I32_CONST(32, 32)
  911. #undef CREATE_I32_CONST
  912. #define CREATE_I64_CONST(name, value) \
  913. if (!(consts->i64_##name = LLVMConstInt(I64_TYPE, value, true))) \
  914. return false;
  915. CREATE_I64_CONST(min, (uint64)INT64_MIN)
  916. CREATE_I64_CONST(neg_one, (uint64)-1)
  917. CREATE_I64_CONST(zero, 0)
  918. CREATE_I64_CONST(63, 63)
  919. CREATE_I64_CONST(64, 64)
  920. #undef CREATE_I64_CONST
  921. #define CREATE_V128_CONST(name, type) \
  922. if (!(consts->name##_vec_zero = LLVMConstNull(type))) \
  923. return false; \
  924. if (!(consts->name##_undef = LLVMGetUndef(type))) \
  925. return false;
  926. CREATE_V128_CONST(i8x16, V128_i8x16_TYPE)
  927. CREATE_V128_CONST(i16x8, V128_i16x8_TYPE)
  928. CREATE_V128_CONST(i32x4, V128_i32x4_TYPE)
  929. CREATE_V128_CONST(i64x2, V128_i64x2_TYPE)
  930. CREATE_V128_CONST(f32x4, V128_f32x4_TYPE)
  931. CREATE_V128_CONST(f64x2, V128_f64x2_TYPE)
  932. #undef CREATE_V128_CONST
  933. #define CREATE_VEC_ZERO_MASK(slot) \
  934. { \
  935. LLVMTypeRef type = LLVMVectorType(I32_TYPE, slot); \
  936. if (!type || !(consts->i32x##slot##_zero = LLVMConstNull(type))) \
  937. return false; \
  938. }
  939. CREATE_VEC_ZERO_MASK(16)
  940. CREATE_VEC_ZERO_MASK(8)
  941. CREATE_VEC_ZERO_MASK(4)
  942. CREATE_VEC_ZERO_MASK(2)
  943. #undef CREATE_VEC_ZERO_MASK
  944. return true;
  945. }
  946. typedef struct ArchItem {
  947. char *arch;
  948. bool support_eb;
  949. } ArchItem;
  950. /* clang-format off */
  951. static ArchItem valid_archs[] = {
  952. { "x86_64", false },
  953. { "i386", false },
  954. { "xtensa", false },
  955. { "mips", true },
  956. { "mipsel", false },
  957. { "aarch64v8", false },
  958. { "aarch64v8.1", false },
  959. { "aarch64v8.2", false },
  960. { "aarch64v8.3", false },
  961. { "aarch64v8.4", false },
  962. { "aarch64v8.5", false },
  963. { "aarch64_bev8", false }, /* big endian */
  964. { "aarch64_bev8.1", false },
  965. { "aarch64_bev8.2", false },
  966. { "aarch64_bev8.3", false },
  967. { "aarch64_bev8.4", false },
  968. { "aarch64_bev8.5", false },
  969. { "armv4", true },
  970. { "armv4t", true },
  971. { "armv5t", true },
  972. { "armv5te", true },
  973. { "armv5tej", true },
  974. { "armv6", true },
  975. { "armv6kz", true },
  976. { "armv6t2", true },
  977. { "armv6k", true },
  978. { "armv7", true },
  979. { "armv6m", true },
  980. { "armv6sm", true },
  981. { "armv7em", true },
  982. { "armv8a", true },
  983. { "armv8r", true },
  984. { "armv8m.base", true },
  985. { "armv8m.main", true },
  986. { "armv8.1m.main", true },
  987. { "thumbv4", true },
  988. { "thumbv4t", true },
  989. { "thumbv5t", true },
  990. { "thumbv5te", true },
  991. { "thumbv5tej", true },
  992. { "thumbv6", true },
  993. { "thumbv6kz", true },
  994. { "thumbv6t2", true },
  995. { "thumbv6k", true },
  996. { "thumbv7", true },
  997. { "thumbv6m", true },
  998. { "thumbv6sm", true },
  999. { "thumbv7em", true },
  1000. { "thumbv8a", true },
  1001. { "thumbv8r", true },
  1002. { "thumbv8m.base", true },
  1003. { "thumbv8m.main", true },
  1004. { "thumbv8.1m.main", true },
  1005. { "riscv32", true },
  1006. { "riscv64", true },
  1007. { "arc", true }
  1008. };
  1009. static const char *valid_abis[] = {
  1010. "gnu",
  1011. "eabi",
  1012. "gnueabihf",
  1013. "msvc",
  1014. "ilp32",
  1015. "ilp32f",
  1016. "ilp32d",
  1017. "lp64",
  1018. "lp64f",
  1019. "lp64d"
  1020. };
  1021. /* clang-format on */
  1022. static void
  1023. print_supported_targets()
  1024. {
  1025. uint32 i;
  1026. os_printf("Supported targets:\n");
  1027. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1028. os_printf("%s ", valid_archs[i].arch);
  1029. if (valid_archs[i].support_eb)
  1030. os_printf("%seb ", valid_archs[i].arch);
  1031. }
  1032. os_printf("\n");
  1033. }
  1034. static void
  1035. print_supported_abis()
  1036. {
  1037. uint32 i;
  1038. os_printf("Supported ABI: ");
  1039. for (i = 0; i < sizeof(valid_abis) / sizeof(const char *); i++)
  1040. os_printf("%s ", valid_abis[i]);
  1041. os_printf("\n");
  1042. }
  1043. static bool
  1044. check_target_arch(const char *target_arch)
  1045. {
  1046. uint32 i;
  1047. char *arch;
  1048. bool support_eb;
  1049. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1050. arch = valid_archs[i].arch;
  1051. support_eb = valid_archs[i].support_eb;
  1052. if (!strncmp(target_arch, arch, strlen(arch))
  1053. && ((support_eb
  1054. && (!strcmp(target_arch + strlen(arch), "eb")
  1055. || !strcmp(target_arch + strlen(arch), "")))
  1056. || (!support_eb && !strcmp(target_arch + strlen(arch), "")))) {
  1057. return true;
  1058. }
  1059. }
  1060. return false;
  1061. }
  1062. static bool
  1063. check_target_abi(const char *target_abi)
  1064. {
  1065. uint32 i;
  1066. for (i = 0; i < sizeof(valid_abis) / sizeof(char *); i++) {
  1067. if (!strcmp(target_abi, valid_abis[i]))
  1068. return true;
  1069. }
  1070. return false;
  1071. }
  1072. static void
  1073. get_target_arch_from_triple(const char *triple, char *arch_buf, uint32 buf_size)
  1074. {
  1075. uint32 i = 0;
  1076. while (*triple != '-' && *triple != '\0' && i < buf_size - 1)
  1077. arch_buf[i++] = *triple++;
  1078. /* Make sure buffer is long enough */
  1079. bh_assert(*triple == '-' || *triple == '\0');
  1080. }
  1081. LLVMBool
  1082. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  1083. LLVMModuleRef M,
  1084. struct LLVMMCJITCompilerOptions *Options,
  1085. size_t SizeOfOptions, char **OutError);
  1086. void
  1087. LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM);
  1088. #if WASM_ENABLE_LAZY_JIT != 0
  1089. void
  1090. aot_handle_llvm_errmsg(char *error_buf, uint32 error_buf_size,
  1091. const char *string, LLVMErrorRef error)
  1092. {
  1093. char *err_msg = LLVMGetErrorMessage(error);
  1094. if (error_buf != NULL) {
  1095. snprintf(error_buf, error_buf_size, "%s: %s", string, err_msg);
  1096. }
  1097. LLVMDisposeErrorMessage(err_msg);
  1098. }
  1099. static bool
  1100. llvm_orcjit_create(AOTCompContext *comp_ctx)
  1101. {
  1102. char *err_msg = NULL;
  1103. char *cpu = NULL;
  1104. char *features = NULL;
  1105. char *llvm_triple = NULL;
  1106. char buf[128] = { 0 };
  1107. LLVMErrorRef error;
  1108. LLVMTargetRef llvm_targetref = NULL;
  1109. LLVMTargetMachineRef tm_opt = NULL;
  1110. LLVMTargetMachineRef tm_opt2 = NULL;
  1111. LLVMOrcLLLazyJITRef lazy_orcjit = NULL;
  1112. LLVMOrcJITTargetMachineBuilderRef tm_builder = NULL;
  1113. LLVMOrcLLLazyJITBuilderRef lazy_orcjit_builder = NULL;
  1114. #if LLVM_VERSION_MAJOR < 12
  1115. LLVMOrcJITDylibDefinitionGeneratorRef main_gen = NULL;
  1116. #else
  1117. LLVMOrcDefinitionGeneratorRef main_gen = NULL;
  1118. #endif
  1119. llvm_triple = LLVMGetDefaultTargetTriple();
  1120. if (llvm_triple == NULL) {
  1121. snprintf(buf, sizeof(buf), "failed to get default target triple.");
  1122. goto fail;
  1123. }
  1124. if (LLVMGetTargetFromTriple(llvm_triple, &llvm_targetref, &err_msg) != 0) {
  1125. snprintf(buf, sizeof(buf),
  1126. "failed to get target reference from triple %s.", err_msg);
  1127. LLVMDisposeMessage(err_msg);
  1128. goto fail;
  1129. }
  1130. if (!LLVMTargetHasJIT(llvm_targetref)) {
  1131. snprintf(buf, sizeof(buf), "unspported JIT on this platform.");
  1132. goto fail;
  1133. }
  1134. cpu = LLVMGetHostCPUName();
  1135. if (cpu == NULL) {
  1136. snprintf(buf, sizeof(buf), "failed to get host cpu information.");
  1137. goto fail;
  1138. }
  1139. features = LLVMGetHostCPUFeatures();
  1140. if (features == NULL) {
  1141. snprintf(buf, sizeof(buf), "failed to get host cpu features.");
  1142. goto fail;
  1143. }
  1144. LOG_VERBOSE("LLVM ORCJIT detected CPU \"%s\", with features \"%s\"\n", cpu,
  1145. features);
  1146. tm_opt = LLVMCreateTargetMachine(llvm_targetref, llvm_triple, cpu, features,
  1147. LLVMCodeGenLevelAggressive,
  1148. LLVMRelocDefault, LLVMCodeModelJITDefault);
  1149. if (!tm_opt) {
  1150. snprintf(buf, sizeof(buf), "failed to create target machine.");
  1151. goto fail;
  1152. }
  1153. tm_opt2 = LLVMCreateTargetMachine(
  1154. llvm_targetref, llvm_triple, cpu, features, LLVMCodeGenLevelAggressive,
  1155. LLVMRelocDefault, LLVMCodeModelJITDefault);
  1156. if (!tm_opt2) {
  1157. snprintf(buf, sizeof(buf), "failed to create target machine2.");
  1158. goto fail;
  1159. }
  1160. /* if success, it will dispose tm_opt2 memory. */
  1161. tm_builder = LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(tm_opt2);
  1162. if (!tm_builder) {
  1163. snprintf(buf, sizeof(buf), "failed to create target machine builder.");
  1164. goto fail;
  1165. }
  1166. tm_opt2 = NULL;
  1167. lazy_orcjit_builder = LLVMOrcCreateLLLazyJITBuilder();
  1168. if (!lazy_orcjit_builder) {
  1169. snprintf(buf, sizeof(buf), "failed to create lazy jit builder.");
  1170. goto fail;
  1171. }
  1172. LLVMOrcLLLazyJITBuilderSetJITTargetMachineBuilder(lazy_orcjit_builder,
  1173. tm_builder);
  1174. /* if success, it will dispose lazy_orcjit_builder memory */
  1175. error = LLVMOrcCreateLLLazyJIT(&lazy_orcjit, lazy_orcjit_builder);
  1176. if (error) {
  1177. aot_handle_llvm_errmsg(buf, sizeof(buf),
  1178. "failed to create llvm lazy orcjit instance",
  1179. error);
  1180. goto fail;
  1181. }
  1182. lazy_orcjit_builder = NULL;
  1183. error = LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(
  1184. &main_gen, LLVMOrcLLLazyJITGetGlobalPrefix(lazy_orcjit), 0, NULL);
  1185. if (error) {
  1186. aot_handle_llvm_errmsg(
  1187. buf, sizeof(buf),
  1188. "failed to create dynmaic library search generator", error);
  1189. goto fail;
  1190. }
  1191. LLVMOrcJITDylibAddGenerator(LLVMOrcLLLazyJITGetMainJITDylib(lazy_orcjit),
  1192. main_gen);
  1193. comp_ctx->lazy_orcjit = lazy_orcjit;
  1194. comp_ctx->target_machine = tm_opt;
  1195. comp_ctx->tm_builder = tm_builder;
  1196. LLVMDisposeMessage(llvm_triple);
  1197. LLVMDisposeMessage(cpu);
  1198. LLVMDisposeMessage(features);
  1199. return true;
  1200. fail:
  1201. if (lazy_orcjit)
  1202. LLVMOrcDisposeLLLazyJIT(lazy_orcjit);
  1203. if (tm_builder)
  1204. LLVMOrcDisposeJITTargetMachineBuilder(tm_builder);
  1205. if (lazy_orcjit_builder)
  1206. LLVMOrcDisposeLLLazyJITBuilder(lazy_orcjit_builder);
  1207. if (tm_opt2)
  1208. LLVMDisposeTargetMachine(tm_opt2);
  1209. if (tm_opt)
  1210. LLVMDisposeTargetMachine(tm_opt);
  1211. if (features)
  1212. LLVMDisposeMessage(features);
  1213. if (cpu)
  1214. LLVMDisposeMessage(cpu);
  1215. if (llvm_triple)
  1216. LLVMDisposeMessage(llvm_triple);
  1217. aot_set_last_error(buf);
  1218. return false;
  1219. }
  1220. #endif /* WASM_ENABLE_LAZY_JIT != 0 */
  1221. AOTCompContext *
  1222. aot_create_comp_context(AOTCompData *comp_data, aot_comp_option_t option)
  1223. {
  1224. AOTCompContext *comp_ctx, *ret = NULL;
  1225. #if WASM_ENABLE_LAZY_JIT == 0
  1226. struct LLVMMCJITCompilerOptions jit_options;
  1227. #endif
  1228. LLVMTargetRef target;
  1229. char *triple = NULL, *triple_norm, *arch, *abi;
  1230. char *cpu = NULL, *features, buf[128];
  1231. char *triple_norm_new = NULL, *cpu_new = NULL;
  1232. char *err = NULL, *fp_round = "round.tonearest",
  1233. *fp_exce = "fpexcept.strict";
  1234. char triple_buf[32] = { 0 }, features_buf[128] = { 0 };
  1235. uint32 opt_level, size_level;
  1236. LLVMCodeModel code_model;
  1237. LLVMTargetDataRef target_data_ref;
  1238. /* Initialize LLVM environment */
  1239. #if WASM_ENABLE_LAZY_JIT != 0
  1240. LLVMInitializeCore(LLVMGetGlobalPassRegistry());
  1241. LLVMInitializeNativeTarget();
  1242. LLVMInitializeNativeAsmPrinter();
  1243. LLVMInitializeNativeAsmParser();
  1244. #else
  1245. LLVMInitializeAllTargetInfos();
  1246. LLVMInitializeAllTargets();
  1247. LLVMInitializeAllTargetMCs();
  1248. LLVMInitializeAllAsmPrinters();
  1249. LLVMLinkInMCJIT();
  1250. #endif
  1251. /* Allocate memory */
  1252. if (!(comp_ctx = wasm_runtime_malloc(sizeof(AOTCompContext)))) {
  1253. aot_set_last_error("allocate memory failed.");
  1254. return NULL;
  1255. }
  1256. memset(comp_ctx, 0, sizeof(AOTCompContext));
  1257. comp_ctx->comp_data = comp_data;
  1258. /* Create LLVM context, module and builder */
  1259. #if WASM_ENABLE_LAZY_JIT != 0
  1260. comp_ctx->ts_context = LLVMOrcCreateNewThreadSafeContext();
  1261. if (!comp_ctx->ts_context) {
  1262. aot_set_last_error("create LLVM ThreadSafeContext failed.");
  1263. return NULL;
  1264. }
  1265. /* Get a reference to the underlying LLVMContext */
  1266. if (!(comp_ctx->context =
  1267. LLVMOrcThreadSafeContextGetContext(comp_ctx->ts_context))) {
  1268. aot_set_last_error("get context from LLVM ThreadSafeContext failed.");
  1269. goto fail;
  1270. }
  1271. #else
  1272. if (!(comp_ctx->context = LLVMContextCreate())) {
  1273. aot_set_last_error("create LLVM context failed.");
  1274. goto fail;
  1275. }
  1276. #endif
  1277. if (!(comp_ctx->builder = LLVMCreateBuilderInContext(comp_ctx->context))) {
  1278. aot_set_last_error("create LLVM builder failed.");
  1279. goto fail;
  1280. }
  1281. if (!(comp_ctx->module = LLVMModuleCreateWithNameInContext(
  1282. "WASM Module", comp_ctx->context))) {
  1283. aot_set_last_error("create LLVM module failed.");
  1284. goto fail;
  1285. }
  1286. if (BH_LIST_ERROR == bh_list_init(&comp_ctx->native_symbols)) {
  1287. goto fail;
  1288. }
  1289. #if WASM_ENABLE_DEBUG_AOT != 0
  1290. if (!(comp_ctx->debug_builder = LLVMCreateDIBuilder(comp_ctx->module))) {
  1291. aot_set_last_error("create LLVM Debug Infor builder failed.");
  1292. goto fail;
  1293. }
  1294. LLVMAddModuleFlag(
  1295. comp_ctx->module, LLVMModuleFlagBehaviorWarning, "Debug Info Version",
  1296. strlen("Debug Info Version"),
  1297. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32Type(), 3, false)));
  1298. comp_ctx->debug_file = dwarf_gen_file_info(comp_ctx);
  1299. if (!comp_ctx->debug_file) {
  1300. aot_set_last_error("dwarf generate file info failed");
  1301. goto fail;
  1302. }
  1303. comp_ctx->debug_comp_unit = dwarf_gen_comp_unit_info(comp_ctx);
  1304. if (!comp_ctx->debug_comp_unit) {
  1305. aot_set_last_error("dwarf generate compile unit info failed");
  1306. goto fail;
  1307. }
  1308. #endif
  1309. if (option->enable_bulk_memory)
  1310. comp_ctx->enable_bulk_memory = true;
  1311. if (option->enable_thread_mgr)
  1312. comp_ctx->enable_thread_mgr = true;
  1313. if (option->enable_tail_call)
  1314. comp_ctx->enable_tail_call = true;
  1315. if (option->enable_ref_types)
  1316. comp_ctx->enable_ref_types = true;
  1317. if (option->enable_aux_stack_frame)
  1318. comp_ctx->enable_aux_stack_frame = true;
  1319. if (option->enable_aux_stack_check)
  1320. comp_ctx->enable_aux_stack_check = true;
  1321. if (option->is_indirect_mode)
  1322. comp_ctx->is_indirect_mode = true;
  1323. if (option->disable_llvm_intrinsics)
  1324. comp_ctx->disable_llvm_intrinsics = true;
  1325. if (option->disable_llvm_lto)
  1326. comp_ctx->disable_llvm_lto = true;
  1327. comp_ctx->opt_level = option->opt_level;
  1328. comp_ctx->size_level = option->size_level;
  1329. if (option->is_jit_mode) {
  1330. char *triple_jit = NULL;
  1331. #if WASM_ENABLE_LAZY_JIT != 0
  1332. /* Create LLLazyJIT Instance */
  1333. if (!llvm_orcjit_create(comp_ctx)) {
  1334. aot_set_last_error("create LLVM Lazy JIT Compiler failed.");
  1335. goto fail;
  1336. }
  1337. #else
  1338. /* Create LLVM execution engine */
  1339. LLVMInitializeMCJITCompilerOptions(&jit_options, sizeof(jit_options));
  1340. jit_options.OptLevel = LLVMCodeGenLevelAggressive;
  1341. jit_options.EnableFastISel = true;
  1342. /*jit_options.CodeModel = LLVMCodeModelSmall;*/
  1343. if (WAMRCreateMCJITCompilerForModule(&comp_ctx->exec_engine,
  1344. comp_ctx->module, &jit_options,
  1345. sizeof(jit_options), &err)
  1346. != 0) {
  1347. if (err) {
  1348. LLVMDisposeMessage(err);
  1349. err = NULL;
  1350. }
  1351. aot_set_last_error("create LLVM JIT compiler failed.");
  1352. goto fail;
  1353. }
  1354. comp_ctx->target_machine =
  1355. LLVMGetExecutionEngineTargetMachine(comp_ctx->exec_engine);
  1356. #endif
  1357. comp_ctx->is_jit_mode = true;
  1358. #ifndef OS_ENABLE_HW_BOUND_CHECK
  1359. comp_ctx->enable_bound_check = true;
  1360. #else
  1361. comp_ctx->enable_bound_check = false;
  1362. #endif
  1363. #if WASM_ENABLE_LAZY_JIT != 0
  1364. if (!(triple_jit = (char *)LLVMOrcLLLazyJITGetTripleString(
  1365. comp_ctx->lazy_orcjit))) {
  1366. aot_set_last_error("can not get triple from the target machine");
  1367. goto fail;
  1368. }
  1369. /* Save target arch */
  1370. get_target_arch_from_triple(triple_jit, comp_ctx->target_arch,
  1371. sizeof(comp_ctx->target_arch));
  1372. #else
  1373. if (!(triple_jit =
  1374. LLVMGetTargetMachineTriple(comp_ctx->target_machine))) {
  1375. aot_set_last_error("can not get triple from the target machine");
  1376. goto fail;
  1377. }
  1378. /* Save target arch */
  1379. get_target_arch_from_triple(triple_jit, comp_ctx->target_arch,
  1380. sizeof(comp_ctx->target_arch));
  1381. LLVMDisposeMessage(triple_jit);
  1382. #endif
  1383. }
  1384. else {
  1385. /* Create LLVM target machine */
  1386. arch = option->target_arch;
  1387. abi = option->target_abi;
  1388. cpu = option->target_cpu;
  1389. features = option->cpu_features;
  1390. opt_level = option->opt_level;
  1391. size_level = option->size_level;
  1392. if (arch) {
  1393. /* Add default sub-arch if not specified */
  1394. if (!strcmp(arch, "arm"))
  1395. arch = "armv4";
  1396. else if (!strcmp(arch, "armeb"))
  1397. arch = "armv4eb";
  1398. else if (!strcmp(arch, "thumb"))
  1399. arch = "thumbv4t";
  1400. else if (!strcmp(arch, "thumbeb"))
  1401. arch = "thumbv4teb";
  1402. else if (!strcmp(arch, "aarch64"))
  1403. arch = "aarch64v8";
  1404. else if (!strcmp(arch, "aarch64_be"))
  1405. arch = "aarch64_bev8";
  1406. }
  1407. /* Check target arch */
  1408. if (arch && !check_target_arch(arch)) {
  1409. if (!strcmp(arch, "help"))
  1410. print_supported_targets();
  1411. else
  1412. aot_set_last_error(
  1413. "Invalid target. "
  1414. "Use --target=help to list all supported targets");
  1415. goto fail;
  1416. }
  1417. /* Check target ABI */
  1418. if (abi && !check_target_abi(abi)) {
  1419. if (!strcmp(abi, "help"))
  1420. print_supported_abis();
  1421. else
  1422. aot_set_last_error(
  1423. "Invalid target ABI. "
  1424. "Use --target-abi=help to list all supported ABI");
  1425. goto fail;
  1426. }
  1427. /* Set default abi for riscv target */
  1428. if (arch && !strncmp(arch, "riscv", 5) && !abi) {
  1429. if (!strcmp(arch, "riscv64"))
  1430. abi = "lp64d";
  1431. else
  1432. abi = "ilp32d";
  1433. }
  1434. if (arch) {
  1435. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  1436. const char *vendor_sys;
  1437. char *default_triple = LLVMGetDefaultTargetTriple();
  1438. if (!default_triple) {
  1439. aot_set_last_error("llvm get default target triple failed.");
  1440. goto fail;
  1441. }
  1442. if (strstr(default_triple, "windows")) {
  1443. vendor_sys = "-pc-windows-";
  1444. if (!abi)
  1445. abi = "msvc";
  1446. }
  1447. else if (strstr(default_triple, "win32")) {
  1448. vendor_sys = "-pc-win32-";
  1449. if (!abi)
  1450. abi = "msvc";
  1451. }
  1452. else {
  1453. vendor_sys = "-pc-linux-";
  1454. if (!abi)
  1455. abi = "gnu";
  1456. }
  1457. LLVMDisposeMessage(default_triple);
  1458. bh_assert(strlen(arch) + strlen(vendor_sys) + strlen(abi)
  1459. < sizeof(triple_buf));
  1460. memcpy(triple_buf, arch, strlen(arch));
  1461. memcpy(triple_buf + strlen(arch), vendor_sys, strlen(vendor_sys));
  1462. memcpy(triple_buf + strlen(arch) + strlen(vendor_sys), abi,
  1463. strlen(abi));
  1464. triple = triple_buf;
  1465. }
  1466. if (!cpu && features) {
  1467. aot_set_last_error("cpu isn't specified for cpu features.");
  1468. goto fail;
  1469. }
  1470. if (!triple && !cpu) {
  1471. /* Get a triple for the host machine */
  1472. if (!(triple_norm = triple_norm_new =
  1473. LLVMGetDefaultTargetTriple())) {
  1474. aot_set_last_error("llvm get default target triple failed.");
  1475. goto fail;
  1476. }
  1477. /* Get CPU name of the host machine */
  1478. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  1479. aot_set_last_error("llvm get host cpu name failed.");
  1480. goto fail;
  1481. }
  1482. }
  1483. else if (triple) {
  1484. /* Normalize a target triple */
  1485. if (!(triple_norm = triple_norm_new =
  1486. LLVMNormalizeTargetTriple(triple))) {
  1487. snprintf(buf, sizeof(buf),
  1488. "llvm normlalize target triple (%s) failed.", triple);
  1489. aot_set_last_error(buf);
  1490. goto fail;
  1491. }
  1492. if (!cpu)
  1493. cpu = "";
  1494. }
  1495. else {
  1496. /* triple is NULL, cpu isn't NULL */
  1497. snprintf(buf, sizeof(buf), "target isn't specified for cpu %s.",
  1498. cpu);
  1499. aot_set_last_error(buf);
  1500. goto fail;
  1501. }
  1502. /* Add module flag and cpu feature for riscv target */
  1503. if (arch && !strncmp(arch, "riscv", 5)) {
  1504. LLVMMetadataRef meta_target_abi;
  1505. if (!(meta_target_abi = LLVMMDStringInContext2(comp_ctx->context,
  1506. abi, strlen(abi)))) {
  1507. aot_set_last_error("create metadata string failed.");
  1508. goto fail;
  1509. }
  1510. LLVMAddModuleFlag(comp_ctx->module, LLVMModuleFlagBehaviorError,
  1511. "target-abi", strlen("target-abi"),
  1512. meta_target_abi);
  1513. if (!strcmp(abi, "lp64d") || !strcmp(abi, "ilp32d")) {
  1514. if (features) {
  1515. snprintf(features_buf, sizeof(features_buf), "%s%s",
  1516. features, ",+d");
  1517. features = features_buf;
  1518. }
  1519. else
  1520. features = "+d";
  1521. }
  1522. }
  1523. if (!features)
  1524. features = "";
  1525. /* Get target with triple, note that LLVMGetTargetFromTriple()
  1526. return 0 when success, but not true. */
  1527. if (LLVMGetTargetFromTriple(triple_norm, &target, &err) != 0) {
  1528. if (err) {
  1529. LLVMDisposeMessage(err);
  1530. err = NULL;
  1531. }
  1532. snprintf(buf, sizeof(buf),
  1533. "llvm get target from triple (%s) failed", triple_norm);
  1534. aot_set_last_error(buf);
  1535. goto fail;
  1536. }
  1537. /* Save target arch */
  1538. get_target_arch_from_triple(triple_norm, comp_ctx->target_arch,
  1539. sizeof(comp_ctx->target_arch));
  1540. if (option->bounds_checks == 1 || option->bounds_checks == 0) {
  1541. /* Set by user */
  1542. comp_ctx->enable_bound_check =
  1543. (option->bounds_checks == 1) ? true : false;
  1544. }
  1545. else {
  1546. /* Unset by user, use default value */
  1547. if (strstr(comp_ctx->target_arch, "64")
  1548. && !option->is_sgx_platform) {
  1549. comp_ctx->enable_bound_check = false;
  1550. }
  1551. else {
  1552. comp_ctx->enable_bound_check = true;
  1553. }
  1554. }
  1555. os_printf("Create AoT compiler with:\n");
  1556. os_printf(" target: %s\n", comp_ctx->target_arch);
  1557. os_printf(" target cpu: %s\n", cpu);
  1558. os_printf(" cpu features: %s\n", features);
  1559. os_printf(" opt level: %d\n", opt_level);
  1560. os_printf(" size level: %d\n", size_level);
  1561. switch (option->output_format) {
  1562. case AOT_LLVMIR_UNOPT_FILE:
  1563. os_printf(" output format: unoptimized LLVM IR\n");
  1564. break;
  1565. case AOT_LLVMIR_OPT_FILE:
  1566. os_printf(" output format: optimized LLVM IR\n");
  1567. break;
  1568. case AOT_FORMAT_FILE:
  1569. os_printf(" output format: AoT file\n");
  1570. break;
  1571. case AOT_OBJECT_FILE:
  1572. os_printf(" output format: native object file\n");
  1573. break;
  1574. }
  1575. if (!LLVMTargetHasTargetMachine(target)) {
  1576. snprintf(buf, sizeof(buf),
  1577. "no target machine for this target (%s).", triple_norm);
  1578. aot_set_last_error(buf);
  1579. goto fail;
  1580. }
  1581. /* Report error if target isn't arc and hasn't asm backend.
  1582. For arc target, as it cannot emit to memory buffer of elf file
  1583. currently, we let it emit to assembly file instead, and then call
  1584. arc-gcc to compile
  1585. asm file to elf file, and read elf file to memory buffer. */
  1586. if (strncmp(comp_ctx->target_arch, "arc", 3)
  1587. && !LLVMTargetHasAsmBackend(target)) {
  1588. snprintf(buf, sizeof(buf), "no asm backend for this target (%s).",
  1589. LLVMGetTargetName(target));
  1590. aot_set_last_error(buf);
  1591. goto fail;
  1592. }
  1593. /* Set code model */
  1594. if (size_level == 0)
  1595. code_model = LLVMCodeModelLarge;
  1596. else if (size_level == 1)
  1597. code_model = LLVMCodeModelMedium;
  1598. else if (size_level == 2)
  1599. code_model = LLVMCodeModelKernel;
  1600. else
  1601. code_model = LLVMCodeModelSmall;
  1602. /* Create the target machine */
  1603. if (!(comp_ctx->target_machine = LLVMCreateTargetMachine(
  1604. target, triple_norm, cpu, features, opt_level,
  1605. LLVMRelocStatic, code_model))) {
  1606. aot_set_last_error("create LLVM target machine failed.");
  1607. goto fail;
  1608. }
  1609. }
  1610. if (option->enable_simd && strcmp(comp_ctx->target_arch, "x86_64") != 0
  1611. && strncmp(comp_ctx->target_arch, "aarch64", 7) != 0) {
  1612. /* Disable simd if it isn't supported by target arch */
  1613. option->enable_simd = false;
  1614. }
  1615. if (option->enable_simd) {
  1616. char *tmp;
  1617. bool check_simd_ret;
  1618. comp_ctx->enable_simd = true;
  1619. if (!(tmp = LLVMGetTargetMachineCPU(comp_ctx->target_machine))) {
  1620. aot_set_last_error("get CPU from Target Machine fail");
  1621. goto fail;
  1622. }
  1623. check_simd_ret =
  1624. aot_check_simd_compatibility(comp_ctx->target_arch, tmp);
  1625. LLVMDisposeMessage(tmp);
  1626. if (!check_simd_ret) {
  1627. aot_set_last_error("SIMD compatibility check failed, "
  1628. "try adding --cpu=<cpu> to specify a cpu "
  1629. "or adding --disable-simd to disable SIMD");
  1630. goto fail;
  1631. }
  1632. }
  1633. if (!(target_data_ref =
  1634. LLVMCreateTargetDataLayout(comp_ctx->target_machine))) {
  1635. aot_set_last_error("create LLVM target data layout failed.");
  1636. goto fail;
  1637. }
  1638. comp_ctx->pointer_size = LLVMPointerSize(target_data_ref);
  1639. LLVMDisposeTargetData(target_data_ref);
  1640. comp_ctx->optimize = true;
  1641. if (option->output_format == AOT_LLVMIR_UNOPT_FILE)
  1642. comp_ctx->optimize = false;
  1643. if (!(comp_ctx->pass_mgr =
  1644. LLVMCreateFunctionPassManagerForModule(comp_ctx->module))) {
  1645. aot_set_last_error("create LLVM pass manager failed.");
  1646. goto fail;
  1647. }
  1648. LLVMAddPromoteMemoryToRegisterPass(comp_ctx->pass_mgr);
  1649. LLVMAddInstructionCombiningPass(comp_ctx->pass_mgr);
  1650. LLVMAddCFGSimplificationPass(comp_ctx->pass_mgr);
  1651. LLVMAddJumpThreadingPass(comp_ctx->pass_mgr);
  1652. #if LLVM_VERSION_MAJOR < 12
  1653. LLVMAddConstantPropagationPass(comp_ctx->pass_mgr);
  1654. #endif
  1655. LLVMAddIndVarSimplifyPass(comp_ctx->pass_mgr);
  1656. if (!option->is_jit_mode) {
  1657. LLVMAddLoopRotatePass(comp_ctx->pass_mgr);
  1658. LLVMAddLoopUnswitchPass(comp_ctx->pass_mgr);
  1659. LLVMAddInstructionCombiningPass(comp_ctx->pass_mgr);
  1660. LLVMAddCFGSimplificationPass(comp_ctx->pass_mgr);
  1661. if (!option->enable_thread_mgr) {
  1662. /* These two passes may destroy the volatile semantics,
  1663. disable them when building as multi-thread mode */
  1664. LLVMAddGVNPass(comp_ctx->pass_mgr);
  1665. LLVMAddLICMPass(comp_ctx->pass_mgr);
  1666. }
  1667. LLVMAddLoopVectorizePass(comp_ctx->pass_mgr);
  1668. LLVMAddSLPVectorizePass(comp_ctx->pass_mgr);
  1669. LLVMAddInstructionCombiningPass(comp_ctx->pass_mgr);
  1670. LLVMAddCFGSimplificationPass(comp_ctx->pass_mgr);
  1671. }
  1672. /* Create metadata for llvm float experimental constrained intrinsics */
  1673. if (!(comp_ctx->fp_rounding_mode = LLVMMDStringInContext(
  1674. comp_ctx->context, fp_round, (uint32)strlen(fp_round)))
  1675. || !(comp_ctx->fp_exception_behavior = LLVMMDStringInContext(
  1676. comp_ctx->context, fp_exce, (uint32)strlen(fp_exce)))) {
  1677. aot_set_last_error("create float llvm metadata failed.");
  1678. goto fail;
  1679. }
  1680. if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context)) {
  1681. aot_set_last_error("create LLVM basic types failed.");
  1682. goto fail;
  1683. }
  1684. if (!aot_create_llvm_consts(&comp_ctx->llvm_consts, comp_ctx)) {
  1685. aot_set_last_error("create LLVM const values failed.");
  1686. goto fail;
  1687. }
  1688. /* set exec_env data type to int8** */
  1689. comp_ctx->exec_env_type = comp_ctx->basic_types.int8_pptr_type;
  1690. /* set aot_inst data type to int8* */
  1691. comp_ctx->aot_inst_type = INT8_PTR_TYPE;
  1692. /* Create function context for each function */
  1693. comp_ctx->func_ctx_count = comp_data->func_count;
  1694. if (comp_data->func_count > 0
  1695. && !(comp_ctx->func_ctxes =
  1696. aot_create_func_contexts(comp_data, comp_ctx)))
  1697. goto fail;
  1698. if (cpu) {
  1699. uint32 len = (uint32)strlen(cpu) + 1;
  1700. if (!(comp_ctx->target_cpu = wasm_runtime_malloc(len))) {
  1701. aot_set_last_error("allocate memory failed");
  1702. goto fail;
  1703. }
  1704. bh_memcpy_s(comp_ctx->target_cpu, len, cpu, len);
  1705. }
  1706. if (comp_ctx->disable_llvm_intrinsics)
  1707. aot_intrinsic_fill_capability_flags(comp_ctx);
  1708. ret = comp_ctx;
  1709. fail:
  1710. if (triple_norm_new)
  1711. LLVMDisposeMessage(triple_norm_new);
  1712. if (cpu_new)
  1713. LLVMDisposeMessage(cpu_new);
  1714. if (!ret)
  1715. aot_destroy_comp_context(comp_ctx);
  1716. return ret;
  1717. }
  1718. void
  1719. aot_destroy_comp_context(AOTCompContext *comp_ctx)
  1720. {
  1721. if (!comp_ctx)
  1722. return;
  1723. if (comp_ctx->pass_mgr) {
  1724. LLVMFinalizeFunctionPassManager(comp_ctx->pass_mgr);
  1725. LLVMDisposePassManager(comp_ctx->pass_mgr);
  1726. }
  1727. #if WASM_ENABLE_LAZY_JIT != 0
  1728. if (comp_ctx->target_machine && comp_ctx->is_jit_mode)
  1729. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  1730. if (comp_ctx->builder)
  1731. LLVMDisposeBuilder(comp_ctx->builder);
  1732. if (comp_ctx->lazy_orcjit)
  1733. LLVMOrcDisposeLLLazyJIT(comp_ctx->lazy_orcjit);
  1734. if (comp_ctx->ts_context)
  1735. LLVMOrcDisposeThreadSafeContext(comp_ctx->ts_context);
  1736. if (comp_ctx->tm_builder)
  1737. LLVMOrcDisposeJITTargetMachineBuilder(comp_ctx->tm_builder);
  1738. LLVMShutdown();
  1739. #else
  1740. if (comp_ctx->target_machine && !comp_ctx->is_jit_mode)
  1741. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  1742. if (comp_ctx->builder)
  1743. LLVMDisposeBuilder(comp_ctx->builder);
  1744. if (comp_ctx->exec_engine) {
  1745. LLVMDisposeExecutionEngine(comp_ctx->exec_engine);
  1746. /* The LLVM module is freed when disposing execution engine,
  1747. no need to dispose it again. */
  1748. }
  1749. else if (comp_ctx->module)
  1750. LLVMDisposeModule(comp_ctx->module);
  1751. if (comp_ctx->context)
  1752. LLVMContextDispose(comp_ctx->context);
  1753. #endif
  1754. if (comp_ctx->func_ctxes)
  1755. aot_destroy_func_contexts(comp_ctx->func_ctxes,
  1756. comp_ctx->func_ctx_count);
  1757. if (bh_list_length(&comp_ctx->native_symbols) > 0) {
  1758. AOTNativeSymbol *sym = bh_list_first_elem(&comp_ctx->native_symbols);
  1759. while (sym) {
  1760. AOTNativeSymbol *t = bh_list_elem_next(sym);
  1761. bh_list_remove(&comp_ctx->native_symbols, sym);
  1762. wasm_runtime_free(sym);
  1763. sym = t;
  1764. }
  1765. }
  1766. if (comp_ctx->target_cpu) {
  1767. wasm_runtime_free(comp_ctx->target_cpu);
  1768. }
  1769. wasm_runtime_free(comp_ctx);
  1770. }
  1771. static bool
  1772. insert_native_symbol(AOTCompContext *comp_ctx, const char *symbol, int32 idx)
  1773. {
  1774. AOTNativeSymbol *sym = wasm_runtime_malloc(sizeof(AOTNativeSymbol));
  1775. if (!sym) {
  1776. aot_set_last_error("alloc native symbol failed.");
  1777. return false;
  1778. }
  1779. memset(sym, 0, sizeof(AOTNativeSymbol));
  1780. bh_assert(strlen(symbol) <= sizeof(sym->symbol));
  1781. snprintf(sym->symbol, sizeof(sym->symbol), "%s", symbol);
  1782. sym->index = idx;
  1783. if (BH_LIST_ERROR == bh_list_insert(&comp_ctx->native_symbols, sym)) {
  1784. wasm_runtime_free(sym);
  1785. aot_set_last_error("insert native symbol to list failed.");
  1786. return false;
  1787. }
  1788. return true;
  1789. }
  1790. int32
  1791. aot_get_native_symbol_index(AOTCompContext *comp_ctx, const char *symbol)
  1792. {
  1793. int32 idx = -1;
  1794. AOTNativeSymbol *sym = NULL;
  1795. sym = bh_list_first_elem(&comp_ctx->native_symbols);
  1796. /* Lookup an existing symobl record */
  1797. while (sym) {
  1798. if (strcmp(sym->symbol, symbol) == 0) {
  1799. idx = sym->index;
  1800. break;
  1801. }
  1802. sym = bh_list_elem_next(sym);
  1803. }
  1804. /* Given symbol is not exist in list, then we alloc a new index for it */
  1805. if (idx < 0) {
  1806. if (comp_ctx->pointer_size == sizeof(uint32)
  1807. && !strncmp(symbol, "f64#", 4)) {
  1808. idx = bh_list_length(&comp_ctx->native_symbols);
  1809. /* Add 4 bytes padding on 32-bit target to make sure that
  1810. the f64 const is stored on 8-byte aligned address */
  1811. if ((idx & 1) && !strncmp(comp_ctx->target_arch, "i386", 4)) {
  1812. if (!insert_native_symbol(comp_ctx, "__ignore", idx)) {
  1813. return -1;
  1814. }
  1815. }
  1816. }
  1817. idx = bh_list_length(&comp_ctx->native_symbols);
  1818. if (!insert_native_symbol(comp_ctx, symbol, idx)) {
  1819. return -1;
  1820. }
  1821. if (comp_ctx->pointer_size == sizeof(uint32)
  1822. && !strncmp(symbol, "f64#", 4)) {
  1823. /* f64 const occupies 2 pointer slots on 32-bit target */
  1824. if (!insert_native_symbol(comp_ctx, "__ignore", idx + 1)) {
  1825. return -1;
  1826. }
  1827. }
  1828. }
  1829. return idx;
  1830. }
  1831. void
  1832. aot_value_stack_push(AOTValueStack *stack, AOTValue *value)
  1833. {
  1834. if (!stack->value_list_head)
  1835. stack->value_list_head = stack->value_list_end = value;
  1836. else {
  1837. stack->value_list_end->next = value;
  1838. value->prev = stack->value_list_end;
  1839. stack->value_list_end = value;
  1840. }
  1841. }
  1842. AOTValue *
  1843. aot_value_stack_pop(AOTValueStack *stack)
  1844. {
  1845. AOTValue *value = stack->value_list_end;
  1846. bh_assert(stack->value_list_end);
  1847. if (stack->value_list_head == stack->value_list_end)
  1848. stack->value_list_head = stack->value_list_end = NULL;
  1849. else {
  1850. stack->value_list_end = stack->value_list_end->prev;
  1851. stack->value_list_end->next = NULL;
  1852. value->prev = NULL;
  1853. }
  1854. return value;
  1855. }
  1856. void
  1857. aot_value_stack_destroy(AOTValueStack *stack)
  1858. {
  1859. AOTValue *value = stack->value_list_head, *p;
  1860. while (value) {
  1861. p = value->next;
  1862. wasm_runtime_free(value);
  1863. value = p;
  1864. }
  1865. }
  1866. void
  1867. aot_block_stack_push(AOTBlockStack *stack, AOTBlock *block)
  1868. {
  1869. if (!stack->block_list_head)
  1870. stack->block_list_head = stack->block_list_end = block;
  1871. else {
  1872. stack->block_list_end->next = block;
  1873. block->prev = stack->block_list_end;
  1874. stack->block_list_end = block;
  1875. }
  1876. }
  1877. AOTBlock *
  1878. aot_block_stack_pop(AOTBlockStack *stack)
  1879. {
  1880. AOTBlock *block = stack->block_list_end;
  1881. bh_assert(stack->block_list_end);
  1882. if (stack->block_list_head == stack->block_list_end)
  1883. stack->block_list_head = stack->block_list_end = NULL;
  1884. else {
  1885. stack->block_list_end = stack->block_list_end->prev;
  1886. stack->block_list_end->next = NULL;
  1887. block->prev = NULL;
  1888. }
  1889. return block;
  1890. }
  1891. void
  1892. aot_block_stack_destroy(AOTBlockStack *stack)
  1893. {
  1894. AOTBlock *block = stack->block_list_head, *p;
  1895. while (block) {
  1896. p = block->next;
  1897. aot_value_stack_destroy(&block->value_stack);
  1898. wasm_runtime_free(block);
  1899. block = p;
  1900. }
  1901. }
  1902. void
  1903. aot_block_destroy(AOTBlock *block)
  1904. {
  1905. aot_value_stack_destroy(&block->value_stack);
  1906. if (block->param_types)
  1907. wasm_runtime_free(block->param_types);
  1908. if (block->param_phis)
  1909. wasm_runtime_free(block->param_phis);
  1910. if (block->else_param_phis)
  1911. wasm_runtime_free(block->else_param_phis);
  1912. if (block->result_types)
  1913. wasm_runtime_free(block->result_types);
  1914. if (block->result_phis)
  1915. wasm_runtime_free(block->result_phis);
  1916. wasm_runtime_free(block);
  1917. }
  1918. bool
  1919. aot_checked_addr_list_add(AOTFuncContext *func_ctx, uint32 local_idx,
  1920. uint32 offset, uint32 bytes)
  1921. {
  1922. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  1923. if (!(node = wasm_runtime_malloc(sizeof(AOTCheckedAddr)))) {
  1924. aot_set_last_error("allocate memory failed.");
  1925. return false;
  1926. }
  1927. node->local_idx = local_idx;
  1928. node->offset = offset;
  1929. node->bytes = bytes;
  1930. node->next = func_ctx->checked_addr_list;
  1931. func_ctx->checked_addr_list = node;
  1932. return true;
  1933. }
  1934. void
  1935. aot_checked_addr_list_del(AOTFuncContext *func_ctx, uint32 local_idx)
  1936. {
  1937. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  1938. AOTCheckedAddr *node_prev = NULL, *node_next;
  1939. while (node) {
  1940. node_next = node->next;
  1941. if (node->local_idx == local_idx) {
  1942. if (!node_prev)
  1943. func_ctx->checked_addr_list = node_next;
  1944. else
  1945. node_prev->next = node_next;
  1946. wasm_runtime_free(node);
  1947. }
  1948. else {
  1949. node_prev = node;
  1950. }
  1951. node = node_next;
  1952. }
  1953. }
  1954. bool
  1955. aot_checked_addr_list_find(AOTFuncContext *func_ctx, uint32 local_idx,
  1956. uint32 offset, uint32 bytes)
  1957. {
  1958. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  1959. while (node) {
  1960. if (node->local_idx == local_idx && node->offset == offset
  1961. && node->bytes >= bytes) {
  1962. return true;
  1963. }
  1964. node = node->next;
  1965. }
  1966. return false;
  1967. }
  1968. void
  1969. aot_checked_addr_list_destroy(AOTFuncContext *func_ctx)
  1970. {
  1971. AOTCheckedAddr *node = func_ctx->checked_addr_list, *node_next;
  1972. while (node) {
  1973. node_next = node->next;
  1974. wasm_runtime_free(node);
  1975. node = node_next;
  1976. }
  1977. func_ctx->checked_addr_list = NULL;
  1978. }
  1979. bool
  1980. aot_build_zero_function_ret(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  1981. AOTFuncType *func_type)
  1982. {
  1983. LLVMValueRef ret = NULL;
  1984. if (func_type->result_count) {
  1985. switch (func_type->types[func_type->param_count]) {
  1986. case VALUE_TYPE_I32:
  1987. ret = LLVMBuildRet(comp_ctx->builder, I32_ZERO);
  1988. break;
  1989. case VALUE_TYPE_I64:
  1990. ret = LLVMBuildRet(comp_ctx->builder, I64_ZERO);
  1991. break;
  1992. case VALUE_TYPE_F32:
  1993. ret = LLVMBuildRet(comp_ctx->builder, F32_ZERO);
  1994. break;
  1995. case VALUE_TYPE_F64:
  1996. ret = LLVMBuildRet(comp_ctx->builder, F64_ZERO);
  1997. break;
  1998. case VALUE_TYPE_V128:
  1999. ret =
  2000. LLVMBuildRet(comp_ctx->builder, LLVM_CONST(i64x2_vec_zero));
  2001. break;
  2002. case VALUE_TYPE_FUNCREF:
  2003. case VALUE_TYPE_EXTERNREF:
  2004. ret = LLVMBuildRet(comp_ctx->builder, REF_NULL);
  2005. break;
  2006. default:
  2007. bh_assert(0);
  2008. }
  2009. }
  2010. else {
  2011. ret = LLVMBuildRetVoid(comp_ctx->builder);
  2012. }
  2013. if (!ret) {
  2014. aot_set_last_error("llvm build ret failed.");
  2015. return false;
  2016. }
  2017. #if WASM_ENABLE_DEBUG_AOT != 0
  2018. LLVMMetadataRef return_location =
  2019. dwarf_gen_func_ret_location(comp_ctx, func_ctx);
  2020. LLVMInstructionSetDebugLoc(ret, return_location);
  2021. #endif
  2022. return true;
  2023. }
  2024. static LLVMValueRef
  2025. __call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2026. const AOTFuncContext *func_ctx, const char *name,
  2027. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2028. int param_count, LLVMValueRef *param_values)
  2029. {
  2030. LLVMValueRef func, ret;
  2031. LLVMTypeRef func_type;
  2032. const char *symname;
  2033. int32 func_idx;
  2034. if (comp_ctx->disable_llvm_intrinsics
  2035. && aot_intrinsic_check_capability(comp_ctx, name)) {
  2036. if (func_ctx == NULL) {
  2037. aot_set_last_error_v("invalid func_ctx for intrinsic: %s", name);
  2038. return NULL;
  2039. }
  2040. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2041. (uint32)param_count, false))) {
  2042. aot_set_last_error("create LLVM intrinsic function type failed.");
  2043. return NULL;
  2044. }
  2045. if (!(func_type = LLVMPointerType(func_type, 0))) {
  2046. aot_set_last_error(
  2047. "create LLVM intrinsic function pointer type failed.");
  2048. return NULL;
  2049. }
  2050. if (!(symname = aot_intrinsic_get_symbol(name))) {
  2051. aot_set_last_error_v("runtime intrinsic not implemented: %s\n",
  2052. name);
  2053. return NULL;
  2054. }
  2055. func_idx =
  2056. aot_get_native_symbol_index((AOTCompContext *)comp_ctx, symname);
  2057. if (func_idx < 0) {
  2058. aot_set_last_error_v("get runtime intrinsc index failed: %s\n",
  2059. name);
  2060. return NULL;
  2061. }
  2062. if (!(func = aot_get_func_from_table(comp_ctx, func_ctx->native_symbol,
  2063. func_type, func_idx))) {
  2064. aot_set_last_error_v("get runtime intrinsc failed: %s\n", name);
  2065. return NULL;
  2066. }
  2067. }
  2068. else {
  2069. /* Declare llvm intrinsic function if necessary */
  2070. if (!(func = LLVMGetNamedFunction(comp_ctx->module, name))) {
  2071. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2072. (uint32)param_count, false))) {
  2073. aot_set_last_error(
  2074. "create LLVM intrinsic function type failed.");
  2075. return NULL;
  2076. }
  2077. if (!(func = LLVMAddFunction(comp_ctx->module, name, func_type))) {
  2078. aot_set_last_error("add LLVM intrinsic function failed.");
  2079. return NULL;
  2080. }
  2081. }
  2082. }
  2083. /* Call the LLVM intrinsic function */
  2084. if (!(ret = LLVMBuildCall(comp_ctx->builder, func, param_values,
  2085. (uint32)param_count, "call"))) {
  2086. aot_set_last_error("llvm build intrinsic call failed.");
  2087. return NULL;
  2088. }
  2089. return ret;
  2090. }
  2091. LLVMValueRef
  2092. aot_call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2093. const AOTFuncContext *func_ctx, const char *intrinsic,
  2094. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2095. int param_count, ...)
  2096. {
  2097. LLVMValueRef *param_values, ret;
  2098. va_list argptr;
  2099. uint64 total_size;
  2100. int i = 0;
  2101. /* Create param values */
  2102. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2103. if (total_size >= UINT32_MAX
  2104. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2105. aot_set_last_error("allocate memory for param values failed.");
  2106. return false;
  2107. }
  2108. /* Load each param value */
  2109. va_start(argptr, param_count);
  2110. while (i < param_count)
  2111. param_values[i++] = va_arg(argptr, LLVMValueRef);
  2112. va_end(argptr);
  2113. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2114. param_types, param_count, param_values);
  2115. wasm_runtime_free(param_values);
  2116. return ret;
  2117. }
  2118. LLVMValueRef
  2119. aot_call_llvm_intrinsic_v(const AOTCompContext *comp_ctx,
  2120. const AOTFuncContext *func_ctx, const char *intrinsic,
  2121. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2122. int param_count, va_list param_value_list)
  2123. {
  2124. LLVMValueRef *param_values, ret;
  2125. uint64 total_size;
  2126. int i = 0;
  2127. /* Create param values */
  2128. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2129. if (total_size >= UINT32_MAX
  2130. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2131. aot_set_last_error("allocate memory for param values failed.");
  2132. return false;
  2133. }
  2134. /* Load each param value */
  2135. while (i < param_count)
  2136. param_values[i++] = va_arg(param_value_list, LLVMValueRef);
  2137. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2138. param_types, param_count, param_values);
  2139. wasm_runtime_free(param_values);
  2140. return ret;
  2141. }
  2142. LLVMValueRef
  2143. aot_get_func_from_table(const AOTCompContext *comp_ctx, LLVMValueRef base,
  2144. LLVMTypeRef func_type, int32 index)
  2145. {
  2146. LLVMValueRef func;
  2147. LLVMValueRef func_addr;
  2148. if (!(func_addr = I32_CONST(index))) {
  2149. aot_set_last_error("construct function index failed.");
  2150. goto fail;
  2151. }
  2152. if (!(func_addr = LLVMBuildInBoundsGEP(comp_ctx->builder, base, &func_addr,
  2153. 1, "func_addr"))) {
  2154. aot_set_last_error("get function addr by index failed.");
  2155. goto fail;
  2156. }
  2157. func = LLVMBuildLoad(comp_ctx->builder, func_addr, "func_tmp");
  2158. if (func == NULL) {
  2159. aot_set_last_error("get function pointer failed.");
  2160. goto fail;
  2161. }
  2162. if (!(func =
  2163. LLVMBuildBitCast(comp_ctx->builder, func, func_type, "func"))) {
  2164. aot_set_last_error("cast function fialed.");
  2165. goto fail;
  2166. }
  2167. return func;
  2168. fail:
  2169. return NULL;
  2170. }
  2171. LLVMValueRef
  2172. aot_load_const_from_table(AOTCompContext *comp_ctx, LLVMValueRef base,
  2173. const WASMValue *value, uint8 value_type)
  2174. {
  2175. LLVMValueRef const_index, const_addr, const_value;
  2176. LLVMTypeRef const_ptr_type;
  2177. char buf[128] = { 0 };
  2178. int32 index;
  2179. switch (value_type) {
  2180. case VALUE_TYPE_F32:
  2181. /* Store the raw int bits of f32 const as a hex string */
  2182. snprintf(buf, sizeof(buf), "f32#%08X", value->i32);
  2183. const_ptr_type = F32_PTR_TYPE;
  2184. break;
  2185. case VALUE_TYPE_F64:
  2186. /* Store the raw int bits of f64 const as a hex string */
  2187. snprintf(buf, sizeof(buf), "f64#%016" PRIx64, value->i64);
  2188. const_ptr_type = F64_PTR_TYPE;
  2189. break;
  2190. default:
  2191. bh_assert(0);
  2192. return NULL;
  2193. }
  2194. /* Load f32/f64 const from exec_env->native_symbol[index] */
  2195. index = aot_get_native_symbol_index(comp_ctx, buf);
  2196. if (index < 0) {
  2197. return NULL;
  2198. }
  2199. if (!(const_index = I32_CONST(index))) {
  2200. aot_set_last_error("construct const index failed.");
  2201. return NULL;
  2202. }
  2203. if (!(const_addr = LLVMBuildInBoundsGEP(
  2204. comp_ctx->builder, base, &const_index, 1, "const_addr_tmp"))) {
  2205. aot_set_last_error("get const addr by index failed.");
  2206. return NULL;
  2207. }
  2208. if (!(const_addr = LLVMBuildBitCast(comp_ctx->builder, const_addr,
  2209. const_ptr_type, "const_addr"))) {
  2210. aot_set_last_error("cast const fialed.");
  2211. return NULL;
  2212. }
  2213. if (!(const_value =
  2214. LLVMBuildLoad(comp_ctx->builder, const_addr, "const_value"))) {
  2215. aot_set_last_error("load const failed.");
  2216. return NULL;
  2217. }
  2218. return const_value;
  2219. }