aot_llvm.c 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207
  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_llvm_extra2.h"
  7. #include "aot_compiler.h"
  8. #include "aot_emit_exception.h"
  9. #include "aot_emit_table.h"
  10. #include "../aot/aot_runtime.h"
  11. #include "../aot/aot_intrinsic.h"
  12. #include "../interpreter/wasm_runtime.h"
  13. #if WASM_ENABLE_DEBUG_AOT != 0
  14. #include "debug/dwarf_extractor.h"
  15. #endif
  16. static bool
  17. create_native_symbol(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx);
  18. static bool
  19. create_native_stack_bound(const AOTCompContext *comp_ctx,
  20. AOTFuncContext *func_ctx);
  21. static bool
  22. create_native_stack_top_min(const AOTCompContext *comp_ctx,
  23. AOTFuncContext *func_ctx);
  24. LLVMTypeRef
  25. wasm_type_to_llvm_type(const AOTCompContext *comp_ctx,
  26. const AOTLLVMTypes *llvm_types, uint8 wasm_type)
  27. {
  28. switch (wasm_type) {
  29. case VALUE_TYPE_I32:
  30. return llvm_types->int32_type;
  31. case VALUE_TYPE_FUNCREF:
  32. case VALUE_TYPE_EXTERNREF:
  33. if (comp_ctx->enable_ref_types)
  34. return llvm_types->int32_type;
  35. else {
  36. bh_assert(comp_ctx->enable_gc);
  37. return llvm_types->gc_ref_type;
  38. }
  39. case VALUE_TYPE_I64:
  40. return llvm_types->int64_type;
  41. case VALUE_TYPE_F32:
  42. return llvm_types->float32_type;
  43. case VALUE_TYPE_F64:
  44. return llvm_types->float64_type;
  45. case VALUE_TYPE_V128:
  46. return llvm_types->i64x2_vec_type;
  47. case VALUE_TYPE_VOID:
  48. return llvm_types->void_type;
  49. case REF_TYPE_NULLFUNCREF:
  50. case REF_TYPE_NULLEXTERNREF:
  51. case REF_TYPE_NULLREF:
  52. /* case REF_TYPE_FUNCREF: */
  53. /* case REF_TYPE_EXTERNREF: */
  54. case REF_TYPE_ANYREF:
  55. case REF_TYPE_EQREF:
  56. case REF_TYPE_HT_NULLABLE:
  57. case REF_TYPE_HT_NON_NULLABLE:
  58. case REF_TYPE_I31REF:
  59. case REF_TYPE_STRUCTREF:
  60. case REF_TYPE_ARRAYREF:
  61. #if WASM_ENABLE_STRINGREF != 0
  62. case REF_TYPE_STRINGREF:
  63. case REF_TYPE_STRINGVIEWWTF8:
  64. case REF_TYPE_STRINGVIEWWTF16:
  65. case REF_TYPE_STRINGVIEWITER:
  66. #endif
  67. case VALUE_TYPE_GC_REF:
  68. bh_assert(comp_ctx->enable_gc);
  69. return llvm_types->gc_ref_type;
  70. default:
  71. break;
  72. }
  73. bh_assert(0);
  74. return NULL;
  75. }
  76. static LLVMValueRef
  77. aot_add_llvm_func1(const AOTCompContext *comp_ctx, LLVMModuleRef module,
  78. uint32 func_index, uint32 param_count, LLVMTypeRef func_type,
  79. const char *prefix)
  80. {
  81. char func_name[48] = { 0 };
  82. LLVMValueRef func;
  83. LLVMValueRef local_value;
  84. uint32 i, j;
  85. /* Add LLVM function */
  86. snprintf(func_name, sizeof(func_name), "%s%d", prefix, func_index);
  87. if (!(func = LLVMAddFunction(module, func_name, func_type))) {
  88. aot_set_last_error("add LLVM function failed.");
  89. return NULL;
  90. }
  91. j = 0;
  92. local_value = LLVMGetParam(func, j++);
  93. LLVMSetValueName(local_value, "exec_env");
  94. /* Set parameter names */
  95. for (i = 0; i < param_count; i++) {
  96. local_value = LLVMGetParam(func, j++);
  97. LLVMSetValueName(local_value, "");
  98. }
  99. return func;
  100. }
  101. /*
  102. * create a basic func_ctx enough to call aot_emit_exception.
  103. *
  104. * that is:
  105. * - exec_env
  106. * - aot_inst
  107. * - native_symbol (if is_indirect_mode)
  108. */
  109. static bool
  110. create_basic_func_context(const AOTCompContext *comp_ctx,
  111. AOTFuncContext *func_ctx)
  112. {
  113. LLVMValueRef aot_inst_offset = I32_TWO, aot_inst_addr;
  114. /* Save the parameters for fast access */
  115. func_ctx->exec_env = LLVMGetParam(func_ctx->func, 0);
  116. /* Get aot inst address, the layout of exec_env is:
  117. exec_env->next, exec_env->prev, exec_env->module_inst, and argv_buf */
  118. if (!(aot_inst_addr = LLVMBuildInBoundsGEP2(
  119. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  120. &aot_inst_offset, 1, "aot_inst_addr"))) {
  121. aot_set_last_error("llvm build in bounds gep failed");
  122. goto fail;
  123. }
  124. /* Load aot inst */
  125. if (!(func_ctx->aot_inst = LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  126. aot_inst_addr, "aot_inst"))) {
  127. aot_set_last_error("llvm build load failed");
  128. goto fail;
  129. }
  130. if (comp_ctx->is_indirect_mode
  131. && !create_native_symbol(comp_ctx, func_ctx)) {
  132. goto fail;
  133. }
  134. return true;
  135. fail:
  136. return false;
  137. }
  138. /*
  139. * return if the "precheck" wrapper function can use tail call optimization
  140. */
  141. bool
  142. aot_target_precheck_can_use_musttail(const AOTCompContext *comp_ctx)
  143. {
  144. if (!strcmp(comp_ctx->target_arch, "xtensa")) {
  145. /*
  146. * xtensa windowed ABI doesn't have tail call optimization.
  147. *
  148. * Note: as of writing this, the xtensa version of LLVM
  149. * simply ignores the musttail attribute.
  150. * https://github.com/espressif/llvm-project/pull/73
  151. */
  152. return false;
  153. }
  154. if (!strcmp(comp_ctx->target_arch, "riscv32")
  155. || !strcmp(comp_ctx->target_arch, "riscv64")) {
  156. /*
  157. * REVISIT: actually, riscv can use tail call optimization
  158. * in some cases. I (yamamoto) don't know the exact conditions
  159. * though.
  160. */
  161. return false;
  162. }
  163. if (!strcmp(comp_ctx->target_arch, "mips")) {
  164. /*
  165. * cf.
  166. * https://github.com/bytecodealliance/wasm-micro-runtime/issues/2412
  167. */
  168. return false;
  169. }
  170. if (strstr(comp_ctx->target_arch, "thumb")) {
  171. /*
  172. * cf.
  173. * https://github.com/bytecodealliance/wasm-micro-runtime/issues/2412
  174. */
  175. return false;
  176. }
  177. /*
  178. * x86-64/i386: true
  179. *
  180. * others: assume true for now
  181. */
  182. return true;
  183. }
  184. unsigned int
  185. aot_estimate_stack_usage_for_function_call(const AOTCompContext *comp_ctx,
  186. const AOTFuncType *callee_func_type)
  187. {
  188. /*
  189. * Estimate how much stack is necessary to make a function call.
  190. * This does not include the stack consumption of the callee function.
  191. *
  192. * For precise estimation, ideally this function needs to be
  193. * target-specific.
  194. * However, this implementation aims to be target-independent,
  195. * allowing a small overstimation, which is probably ok for our purpose.
  196. * (overflow detection and memory profiling)
  197. * On the other hand, an underestimation should be avoided as it
  198. * can cause more serious problems like silent data corruptions.
  199. *
  200. * Assumptions:
  201. *
  202. * - the first result is returned via a register.
  203. *
  204. * - all parameters, including exec_env and pointers to non-first
  205. * results, are passed via stack.
  206. * (this is a bit pessimistic than many of real calling conventions,
  207. * where some of parameters are passed via register.)
  208. *
  209. * - N-byte value needs N-byte alignment on stack.
  210. *
  211. * - a value smaller than a pointer is extended.
  212. * (eg. 4 byte values are extended to 8 byte on x86-64.)
  213. */
  214. const unsigned int param_count = callee_func_type->param_count;
  215. const unsigned int result_count = callee_func_type->result_count;
  216. unsigned int size = 0;
  217. unsigned int i;
  218. unsigned int nb;
  219. if (!strcmp(comp_ctx->target_arch, "xtensa")) {
  220. /*
  221. * In the xtensa windowed ABI, outgoing arguments are already
  222. * included in the callee's stack frame size, which equals to
  223. * the operand of the ENTRY instruction and what LLVM
  224. * MFI->getStackSize returns.
  225. */
  226. return 0;
  227. }
  228. /* exec_env */
  229. size = comp_ctx->pointer_size;
  230. /* parameters */
  231. for (i = 0; i < param_count; i++) {
  232. nb = wasm_value_type_cell_num(callee_func_type->types[i]) * 4;
  233. if (nb < comp_ctx->pointer_size) {
  234. nb = comp_ctx->pointer_size;
  235. }
  236. size = align_uint(size, nb) + nb;
  237. }
  238. /* pointers to results */
  239. nb = comp_ctx->pointer_size;
  240. for (i = 1; i < result_count; i++) {
  241. size = align_uint(size, nb) + nb;
  242. }
  243. /* return address */
  244. nb = comp_ctx->pointer_size;
  245. size = align_uint(size, nb) + nb;
  246. /*
  247. * some extra for possible arch-dependent things like
  248. * 16-byte alignment for x86_64.
  249. */
  250. size += 16;
  251. return size;
  252. }
  253. /*
  254. * a "precheck" function performs a few things before calling wrapped_func.
  255. *
  256. * - update native_stack_top_min if necessary
  257. * - stack overflow check (if it does, trap)
  258. */
  259. static bool
  260. aot_build_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module,
  261. LLVMValueRef precheck_func, uint32 func_index,
  262. LLVMTypeRef func_type, LLVMValueRef wrapped_func)
  263. {
  264. LLVMBasicBlockRef begin = NULL;
  265. LLVMBasicBlockRef check_top_block = NULL;
  266. LLVMBasicBlockRef update_top_block = NULL;
  267. LLVMBasicBlockRef stack_bound_check_block = NULL;
  268. LLVMBasicBlockRef call_wrapped_func_block = NULL;
  269. LLVMValueRef *params = NULL;
  270. begin = LLVMAppendBasicBlockInContext(comp_ctx->context, precheck_func,
  271. "begin");
  272. check_top_block = LLVMAppendBasicBlockInContext(
  273. comp_ctx->context, precheck_func, "check_top_block");
  274. if (comp_ctx->enable_stack_estimation) {
  275. update_top_block = LLVMAppendBasicBlockInContext(
  276. comp_ctx->context, precheck_func, "update_top_block");
  277. if (!update_top_block) {
  278. goto fail;
  279. }
  280. }
  281. stack_bound_check_block = LLVMAppendBasicBlockInContext(
  282. comp_ctx->context, precheck_func, "stack_bound_check_block");
  283. call_wrapped_func_block = LLVMAppendBasicBlockInContext(
  284. comp_ctx->context, precheck_func, "call_wrapped_func");
  285. if (!begin || !check_top_block || !stack_bound_check_block
  286. || !call_wrapped_func_block) {
  287. goto fail;
  288. }
  289. LLVMBuilderRef b = comp_ctx->builder;
  290. LLVMPositionBuilderAtEnd(b, begin);
  291. /* create a temporary minimum func_ctx */
  292. AOTFuncContext tmp;
  293. AOTFuncContext *func_ctx = &tmp;
  294. memset(func_ctx, 0, sizeof(*func_ctx));
  295. func_ctx->func = precheck_func;
  296. func_ctx->module = module;
  297. func_ctx->aot_func = comp_ctx->comp_data->funcs[func_index];
  298. #if WASM_ENABLE_DEBUG_AOT != 0
  299. func_ctx->debug_func = NULL;
  300. #endif
  301. if (!create_basic_func_context(comp_ctx, func_ctx))
  302. goto fail;
  303. if (comp_ctx->enable_stack_bound_check
  304. && !create_native_stack_bound(comp_ctx, func_ctx))
  305. goto fail;
  306. if (comp_ctx->enable_stack_estimation
  307. && !create_native_stack_top_min(comp_ctx, func_ctx)) {
  308. goto fail;
  309. }
  310. uint32 param_count = LLVMCountParams(precheck_func);
  311. uint32 sz = param_count * (uint32)sizeof(LLVMValueRef);
  312. params = wasm_runtime_malloc(sz);
  313. if (params == NULL) {
  314. goto fail;
  315. }
  316. LLVMGetParams(precheck_func, params);
  317. const bool is_64bit = comp_ctx->pointer_size == sizeof(uint64);
  318. LLVMTypeRef uintptr_type;
  319. if (is_64bit)
  320. uintptr_type = I64_TYPE;
  321. else
  322. uintptr_type = I32_TYPE;
  323. /*
  324. * load the stack pointer
  325. */
  326. LLVMValueRef sp_ptr = LLVMBuildAlloca(b, I32_TYPE, "sp_ptr");
  327. if (!sp_ptr) {
  328. goto fail;
  329. }
  330. LLVMValueRef sp = LLVMBuildPtrToInt(b, sp_ptr, uintptr_type, "sp");
  331. if (!sp) {
  332. goto fail;
  333. }
  334. /*
  335. * load the value for this wrapped function from the stack_sizes array
  336. */
  337. LLVMValueRef stack_sizes;
  338. if (comp_ctx->is_indirect_mode) {
  339. uint32 offset_u32;
  340. LLVMValueRef offset;
  341. LLVMValueRef stack_sizes_p;
  342. offset_u32 = get_module_inst_extra_offset(comp_ctx);
  343. offset_u32 += offsetof(AOTModuleInstanceExtra, stack_sizes);
  344. offset = I32_CONST(offset_u32);
  345. if (!offset) {
  346. goto fail;
  347. }
  348. stack_sizes_p =
  349. LLVMBuildInBoundsGEP2(b, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  350. "aot_inst_stack_sizes_p");
  351. if (!stack_sizes_p) {
  352. goto fail;
  353. }
  354. stack_sizes =
  355. LLVMBuildLoad2(b, INT32_PTR_TYPE, stack_sizes_p, "stack_sizes");
  356. if (!stack_sizes) {
  357. goto fail;
  358. }
  359. }
  360. else {
  361. stack_sizes = comp_ctx->stack_sizes;
  362. }
  363. LLVMValueRef func_index_const = I32_CONST(func_index);
  364. LLVMValueRef sizes =
  365. LLVMBuildBitCast(b, stack_sizes, INT32_PTR_TYPE, "sizes");
  366. if (!sizes) {
  367. goto fail;
  368. }
  369. LLVMValueRef sizep = LLVMBuildInBoundsGEP2(b, I32_TYPE, sizes,
  370. &func_index_const, 1, "sizep");
  371. if (!sizep) {
  372. goto fail;
  373. }
  374. LLVMValueRef size32 = LLVMBuildLoad2(b, I32_TYPE, sizep, "size32");
  375. if (!size32) {
  376. goto fail;
  377. }
  378. LLVMValueRef size;
  379. if (is_64bit) {
  380. size = LLVMBuildZExt(b, size32, uintptr_type, "size");
  381. if (!size) {
  382. goto fail;
  383. }
  384. }
  385. else {
  386. size = size32;
  387. }
  388. /*
  389. * calculate new sp
  390. */
  391. LLVMValueRef underflow =
  392. LLVMBuildICmp(b, LLVMIntULT, sp, size, "underflow");
  393. if (!underflow) {
  394. goto fail;
  395. }
  396. LLVMValueRef new_sp = LLVMBuildSub(b, sp, size, "new_sp");
  397. if (!new_sp) {
  398. goto fail;
  399. }
  400. if (!LLVMBuildBr(b, check_top_block)) {
  401. goto fail;
  402. }
  403. LLVMPositionBuilderAtEnd(b, check_top_block);
  404. if (comp_ctx->enable_stack_estimation) {
  405. /*
  406. * load native_stack_top_min from the exec_env
  407. */
  408. LLVMValueRef top_min =
  409. LLVMBuildLoad2(b, OPQ_PTR_TYPE, func_ctx->native_stack_top_min_addr,
  410. "native_stack_top_min");
  411. if (!top_min) {
  412. goto fail;
  413. }
  414. LLVMValueRef top_min_int = LLVMBuildPtrToInt(
  415. b, top_min, uintptr_type, "native_stack_top_min_int");
  416. if (!top_min_int) {
  417. goto fail;
  418. }
  419. bh_assert(update_top_block);
  420. /*
  421. * update native_stack_top_min if
  422. * new_sp = sp - size < native_stack_top_min
  423. *
  424. * Note: unless the stack has already overflown in this exec_env,
  425. * native_stack_bound <= native_stack_top_min
  426. */
  427. LLVMValueRef cmp_top =
  428. LLVMBuildICmp(b, LLVMIntULT, new_sp, top_min_int, "cmp_top");
  429. if (!cmp_top) {
  430. goto fail;
  431. }
  432. cmp_top = LLVMBuildOr(b, underflow, cmp_top, "cmp_top2");
  433. if (!cmp_top) {
  434. goto fail;
  435. }
  436. if (!LLVMBuildCondBr(b, cmp_top, update_top_block,
  437. call_wrapped_func_block)) {
  438. aot_set_last_error("llvm build cond br failed.");
  439. goto fail;
  440. }
  441. /*
  442. * update native_stack_top_min
  443. */
  444. LLVMPositionBuilderAtEnd(b, update_top_block);
  445. LLVMValueRef new_sp_ptr =
  446. LLVMBuildIntToPtr(b, new_sp, INT8_PTR_TYPE, "new_sp_ptr");
  447. if (!new_sp_ptr) {
  448. goto fail;
  449. }
  450. if (!LLVMBuildStore(b, new_sp_ptr,
  451. func_ctx->native_stack_top_min_addr)) {
  452. goto fail;
  453. }
  454. if (!LLVMBuildBr(b, stack_bound_check_block)) {
  455. goto fail;
  456. }
  457. }
  458. else {
  459. if (!LLVMBuildBr(b, stack_bound_check_block)) {
  460. goto fail;
  461. }
  462. }
  463. LLVMPositionBuilderAtEnd(b, stack_bound_check_block);
  464. if (comp_ctx->enable_stack_bound_check) {
  465. /*
  466. * trap if new_sp < native_stack_bound
  467. */
  468. LLVMValueRef bound_int = LLVMBuildPtrToInt(
  469. b, func_ctx->native_stack_bound, uintptr_type, "bound_base_int");
  470. if (!bound_int) {
  471. goto fail;
  472. }
  473. LLVMValueRef cmp =
  474. LLVMBuildICmp(b, LLVMIntULT, new_sp, bound_int, "cmp");
  475. if (!cmp) {
  476. goto fail;
  477. }
  478. cmp = LLVMBuildOr(b, underflow, cmp, "cmp2");
  479. if (!cmp) {
  480. goto fail;
  481. }
  482. /* todo: @llvm.expect.i1(i1 %cmp, i1 0) */
  483. if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NATIVE_STACK_OVERFLOW,
  484. true, cmp, call_wrapped_func_block))
  485. goto fail;
  486. }
  487. else {
  488. if (!LLVMBuildBr(b, call_wrapped_func_block)) {
  489. goto fail;
  490. }
  491. }
  492. /*
  493. * call the wrapped function
  494. * use a tail-call if possible
  495. */
  496. LLVMPositionBuilderAtEnd(b, call_wrapped_func_block);
  497. const char *name = "tail_call";
  498. LLVMTypeRef ret_type = LLVMGetReturnType(func_type);
  499. if (ret_type == VOID_TYPE) {
  500. name = "";
  501. }
  502. LLVMValueRef retval =
  503. LLVMBuildCall2(b, func_type, wrapped_func, params, param_count, name);
  504. if (!retval) {
  505. goto fail;
  506. }
  507. wasm_runtime_free(params);
  508. params = NULL;
  509. if (aot_target_precheck_can_use_musttail(comp_ctx)) {
  510. LLVMSetTailCallKind(retval, LLVMTailCallKindMustTail);
  511. }
  512. else {
  513. LLVMSetTailCallKind(retval, LLVMTailCallKindTail);
  514. }
  515. if (ret_type == VOID_TYPE) {
  516. if (!LLVMBuildRetVoid(b)) {
  517. goto fail;
  518. }
  519. }
  520. else {
  521. if (!LLVMBuildRet(b, retval)) {
  522. goto fail;
  523. }
  524. }
  525. return true;
  526. fail:
  527. if (params != NULL) {
  528. wasm_runtime_free(params);
  529. }
  530. aot_set_last_error("failed to build precheck wrapper function.");
  531. return false;
  532. }
  533. static bool
  534. check_wasm_type(AOTCompContext *comp_ctx, uint8 type)
  535. {
  536. if (type == VALUE_TYPE_FUNCREF || type == VALUE_TYPE_EXTERNREF) {
  537. if (!comp_ctx->enable_ref_types && !comp_ctx->enable_gc) {
  538. aot_set_last_error("funcref or externref type was found, "
  539. "try removing --disable-ref-types option "
  540. "or adding --enable-gc option.");
  541. return false;
  542. }
  543. else
  544. return true;
  545. }
  546. else if (aot_is_type_gc_reftype(type)) {
  547. if (!comp_ctx->enable_gc) {
  548. aot_set_last_error("GC reference type was found, "
  549. "try adding --enable-gc option.");
  550. return false;
  551. }
  552. else
  553. return true;
  554. }
  555. else if (type == VALUE_TYPE_V128) {
  556. if (!comp_ctx->enable_simd) {
  557. aot_set_last_error("SIMD type was found, try removing "
  558. " --disable-simd option.");
  559. return false;
  560. }
  561. return true;
  562. }
  563. else if (type != VALUE_TYPE_I32 && type != VALUE_TYPE_I64
  564. && type != VALUE_TYPE_F32 && type != VALUE_TYPE_F64) {
  565. bh_assert(0);
  566. }
  567. return true;
  568. }
  569. /**
  570. * Add LLVM function
  571. */
  572. static LLVMValueRef
  573. aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module,
  574. const AOTFuncType *aot_func_type, uint32 func_index,
  575. LLVMTypeRef *p_func_type, LLVMValueRef *p_precheck_func)
  576. {
  577. WASMFunction *aot_func =
  578. comp_ctx->comp_data->wasm_module->functions[func_index];
  579. LLVMValueRef func = NULL;
  580. LLVMTypeRef *param_types, ret_type, func_type;
  581. LLVMTypeRef func_type_wrapper;
  582. LLVMValueRef func_wrapper;
  583. LLVMBasicBlockRef func_begin;
  584. char func_name[48];
  585. uint64 size;
  586. uint32 i, j = 0, param_count = (uint64)aot_func_type->param_count;
  587. uint32 backend_thread_num, compile_thread_num;
  588. /* Check function parameter types and result types */
  589. for (i = 0;
  590. i < (uint32)(aot_func_type->param_count + aot_func_type->result_count);
  591. i++) {
  592. if (!check_wasm_type(comp_ctx, aot_func_type->types[i]))
  593. return NULL;
  594. }
  595. /* Check function local types */
  596. for (i = 0; i < aot_func->local_count; i++) {
  597. if (!check_wasm_type(comp_ctx, aot_func->local_types[i]))
  598. return NULL;
  599. }
  600. /* exec env as first parameter */
  601. param_count++;
  602. /* Extra wasm function results(except the first one)'s address are
  603. * appended to aot function parameters. */
  604. if (aot_func_type->result_count > 1)
  605. param_count += aot_func_type->result_count - 1;
  606. /* Initialize parameter types of the LLVM function */
  607. size = sizeof(LLVMTypeRef) * ((uint64)param_count);
  608. if (size >= UINT32_MAX
  609. || !(param_types = wasm_runtime_malloc((uint32)size))) {
  610. aot_set_last_error("allocate memory failed.");
  611. return NULL;
  612. }
  613. /* exec env as first parameter */
  614. param_types[j++] = comp_ctx->exec_env_type;
  615. for (i = 0; i < aot_func_type->param_count; i++)
  616. param_types[j++] = TO_LLVM_TYPE(aot_func_type->types[i]);
  617. /* Extra results' address */
  618. for (i = 1; i < aot_func_type->result_count; i++, j++) {
  619. param_types[j] =
  620. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count + i]);
  621. if (!(param_types[j] = LLVMPointerType(param_types[j], 0))) {
  622. aot_set_last_error("llvm get pointer type failed.");
  623. goto fail;
  624. }
  625. }
  626. /* Resolve return type of the LLVM function */
  627. if (aot_func_type->result_count)
  628. ret_type =
  629. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count]);
  630. else
  631. ret_type = VOID_TYPE;
  632. /* Resolve function prototype */
  633. if (!(func_type =
  634. LLVMFunctionType(ret_type, param_types, param_count, false))) {
  635. aot_set_last_error("create LLVM function type failed.");
  636. goto fail;
  637. }
  638. bh_assert(func_index < comp_ctx->func_ctx_count);
  639. bh_assert(LLVMGetReturnType(func_type) == ret_type);
  640. const char *prefix = AOT_FUNC_PREFIX;
  641. const bool need_precheck =
  642. comp_ctx->enable_stack_bound_check || comp_ctx->enable_stack_estimation;
  643. LLVMValueRef precheck_func = NULL;
  644. if (need_precheck) {
  645. precheck_func = aot_add_llvm_func1(comp_ctx, module, func_index,
  646. aot_func_type->param_count,
  647. func_type, AOT_FUNC_PREFIX);
  648. if (!precheck_func) {
  649. goto fail;
  650. }
  651. /*
  652. * REVISIT: probably this breaks windows hw bound check
  653. * (the RtlAddFunctionTable stuff)
  654. */
  655. prefix = AOT_FUNC_INTERNAL_PREFIX;
  656. }
  657. if (!(func = aot_add_llvm_func1(comp_ctx, module, func_index,
  658. aot_func_type->param_count, func_type,
  659. prefix)))
  660. goto fail;
  661. if (comp_ctx->disable_llvm_jump_tables) {
  662. LLVMAttributeRef attr_no_jump_tables = LLVMCreateStringAttribute(
  663. comp_ctx->context, "no-jump-tables",
  664. (uint32)strlen("no-jump-tables"), "true", (uint32)strlen("true"));
  665. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex,
  666. attr_no_jump_tables);
  667. }
  668. /* spread fp.all to every function */
  669. if (comp_ctx->emit_frame_pointer) {
  670. const char *key = "frame-pointer";
  671. const char *val = "all";
  672. LLVMAttributeRef no_omit_fp = LLVMCreateStringAttribute(
  673. comp_ctx->context, key, (unsigned)strlen(key), val,
  674. (unsigned)strlen(val));
  675. if (!no_omit_fp) {
  676. aot_set_last_error("create LLVM attribute (frame-pointer) failed.");
  677. goto fail;
  678. }
  679. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex, no_omit_fp);
  680. }
  681. if (need_precheck) {
  682. if (!comp_ctx->is_jit_mode)
  683. LLVMSetLinkage(func, LLVMInternalLinkage);
  684. unsigned int kind =
  685. LLVMGetEnumAttributeKindForName("noinline", strlen("noinline"));
  686. LLVMAttributeRef attr_noinline =
  687. LLVMCreateEnumAttribute(comp_ctx->context, kind, 0);
  688. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex,
  689. attr_noinline);
  690. if (!strcmp(comp_ctx->target_arch, "xtensa")) {
  691. /* Because "func" is only called by "precheck_func", short-call
  692. * should be ok. We prefer short-call because it's smaller
  693. * and more importantly doesn't involve relocations.
  694. */
  695. LLVMAttributeRef attr_short_call = LLVMCreateStringAttribute(
  696. comp_ctx->context, "short-call", (unsigned)strlen("short-call"),
  697. "", 0);
  698. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex,
  699. attr_short_call);
  700. }
  701. if (!aot_build_precheck_function(comp_ctx, module, precheck_func,
  702. func_index, func_type, func))
  703. goto fail;
  704. LLVMAddAttributeAtIndex(precheck_func, LLVMAttributeFunctionIndex,
  705. attr_noinline);
  706. *p_precheck_func = precheck_func;
  707. }
  708. else {
  709. *p_precheck_func = func;
  710. }
  711. if (p_func_type)
  712. *p_func_type = func_type;
  713. backend_thread_num = WASM_ORC_JIT_BACKEND_THREAD_NUM;
  714. compile_thread_num = WASM_ORC_JIT_COMPILE_THREAD_NUM;
  715. /* Add the jit wrapper function with simple prototype, so that we
  716. can easily call it to trigger its compilation and let LLVM JIT
  717. compile the actual jit functions by adding them into the function
  718. list in the PartitionFunction callback */
  719. if (comp_ctx->is_jit_mode
  720. && (func_index % (backend_thread_num * compile_thread_num)
  721. < backend_thread_num)) {
  722. func_type_wrapper = LLVMFunctionType(VOID_TYPE, NULL, 0, false);
  723. if (!func_type_wrapper) {
  724. aot_set_last_error("create LLVM function type failed.");
  725. goto fail;
  726. }
  727. snprintf(func_name, sizeof(func_name), "%s%d%s", AOT_FUNC_PREFIX,
  728. func_index, "_wrapper");
  729. if (!(func_wrapper =
  730. LLVMAddFunction(module, func_name, func_type_wrapper))) {
  731. aot_set_last_error("add LLVM function failed.");
  732. goto fail;
  733. }
  734. if (!(func_begin = LLVMAppendBasicBlockInContext(
  735. comp_ctx->context, func_wrapper, "func_begin"))) {
  736. aot_set_last_error("add LLVM basic block failed.");
  737. goto fail;
  738. }
  739. LLVMPositionBuilderAtEnd(comp_ctx->builder, func_begin);
  740. if (!LLVMBuildRetVoid(comp_ctx->builder)) {
  741. aot_set_last_error("llvm build ret failed.");
  742. goto fail;
  743. }
  744. }
  745. fail:
  746. wasm_runtime_free(param_types);
  747. return func;
  748. }
  749. static void
  750. free_block_memory(AOTBlock *block)
  751. {
  752. if (block->param_types)
  753. wasm_runtime_free(block->param_types);
  754. if (block->result_types)
  755. wasm_runtime_free(block->result_types);
  756. wasm_runtime_free(block);
  757. }
  758. /**
  759. * Create first AOTBlock, or function block for the function
  760. */
  761. static AOTBlock *
  762. aot_create_func_block(const AOTCompContext *comp_ctx,
  763. const AOTFuncContext *func_ctx, const AOTFunc *func,
  764. const AOTFuncType *aot_func_type)
  765. {
  766. AOTBlock *aot_block;
  767. uint32 param_count = aot_func_type->param_count,
  768. result_count = aot_func_type->result_count;
  769. /* Allocate memory */
  770. if (!(aot_block = wasm_runtime_malloc(sizeof(AOTBlock)))) {
  771. aot_set_last_error("allocate memory failed.");
  772. return NULL;
  773. }
  774. memset(aot_block, 0, sizeof(AOTBlock));
  775. if (param_count
  776. && !(aot_block->param_types = wasm_runtime_malloc(param_count))) {
  777. aot_set_last_error("allocate memory failed.");
  778. goto fail;
  779. }
  780. if (result_count) {
  781. if (!(aot_block->result_types = wasm_runtime_malloc(result_count))) {
  782. aot_set_last_error("allocate memory failed.");
  783. goto fail;
  784. }
  785. }
  786. /* Set block data */
  787. aot_block->label_type = LABEL_TYPE_FUNCTION;
  788. aot_block->param_count = param_count;
  789. if (param_count) {
  790. bh_memcpy_s(aot_block->param_types, param_count, aot_func_type->types,
  791. param_count);
  792. }
  793. aot_block->result_count = result_count;
  794. if (result_count) {
  795. bh_memcpy_s(aot_block->result_types, result_count,
  796. aot_func_type->types + param_count, result_count);
  797. }
  798. aot_block->wasm_code_end = func->code + func->code_size;
  799. /* Add function entry block */
  800. if (!(aot_block->llvm_entry_block = LLVMAppendBasicBlockInContext(
  801. comp_ctx->context, func_ctx->func, "func_begin"))) {
  802. aot_set_last_error("add LLVM basic block failed.");
  803. goto fail;
  804. }
  805. return aot_block;
  806. fail:
  807. free_block_memory(aot_block);
  808. return NULL;
  809. }
  810. static bool
  811. create_argv_buf(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  812. {
  813. LLVMValueRef argv_buf_offset = I32_THREE, argv_buf_addr;
  814. LLVMTypeRef int32_ptr_type;
  815. /* Get argv buffer address */
  816. if (!(argv_buf_addr = LLVMBuildInBoundsGEP2(
  817. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  818. &argv_buf_offset, 1, "argv_buf_addr"))) {
  819. aot_set_last_error("llvm build in bounds gep failed");
  820. return false;
  821. }
  822. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  823. aot_set_last_error("llvm add pointer type failed");
  824. return false;
  825. }
  826. /* Convert to int32 pointer type */
  827. if (!(argv_buf_addr = LLVMBuildBitCast(comp_ctx->builder, argv_buf_addr,
  828. int32_ptr_type, "argv_buf_ptr"))) {
  829. aot_set_last_error("llvm build load failed");
  830. return false;
  831. }
  832. if (!(func_ctx->argv_buf = LLVMBuildLoad2(comp_ctx->builder, INT32_PTR_TYPE,
  833. argv_buf_addr, "argv_buf"))) {
  834. aot_set_last_error("llvm build load failed");
  835. return false;
  836. }
  837. return true;
  838. }
  839. static bool
  840. create_native_stack_bound(const AOTCompContext *comp_ctx,
  841. AOTFuncContext *func_ctx)
  842. {
  843. LLVMValueRef stack_bound_offset = I32_FOUR, stack_bound_addr;
  844. if (!(stack_bound_addr = LLVMBuildInBoundsGEP2(
  845. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  846. &stack_bound_offset, 1, "stack_bound_addr"))) {
  847. aot_set_last_error("llvm build in bounds gep failed");
  848. return false;
  849. }
  850. if (!(func_ctx->native_stack_bound =
  851. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, stack_bound_addr,
  852. "native_stack_bound"))) {
  853. aot_set_last_error("llvm build load failed");
  854. return false;
  855. }
  856. return true;
  857. }
  858. static bool
  859. create_native_stack_top_min(const AOTCompContext *comp_ctx,
  860. AOTFuncContext *func_ctx)
  861. {
  862. LLVMValueRef offset = I32_NINE;
  863. if (!(func_ctx->native_stack_top_min_addr = LLVMBuildInBoundsGEP2(
  864. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1,
  865. "native_stack_top_min_addr"))) {
  866. aot_set_last_error("llvm build in bounds gep failed");
  867. return false;
  868. }
  869. return true;
  870. }
  871. static bool
  872. create_aux_stack_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  873. {
  874. LLVMValueRef aux_stack_bound_offset = I32_SIX, aux_stack_bound_addr;
  875. LLVMValueRef aux_stack_bottom_offset = I32_SEVEN, aux_stack_bottom_addr;
  876. /* Get aux stack boundary address */
  877. if (!(aux_stack_bound_addr = LLVMBuildInBoundsGEP2(
  878. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  879. &aux_stack_bound_offset, 1, "aux_stack_bound_addr"))) {
  880. aot_set_last_error("llvm build in bounds gep failed");
  881. return false;
  882. }
  883. if (!(aux_stack_bound_addr =
  884. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bound_addr,
  885. INTPTR_T_PTR_TYPE, "aux_stack_bound_ptr"))) {
  886. aot_set_last_error("llvm build bit cast failed");
  887. return false;
  888. }
  889. if (!(func_ctx->aux_stack_bound =
  890. LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE,
  891. aux_stack_bound_addr, "aux_stack_bound_intptr"))) {
  892. aot_set_last_error("llvm build load failed");
  893. return false;
  894. }
  895. if (!(func_ctx->aux_stack_bound =
  896. LLVMBuildZExt(comp_ctx->builder, func_ctx->aux_stack_bound,
  897. I64_TYPE, "aux_stack_bound_i64"))) {
  898. aot_set_last_error("llvm build truncOrBitCast failed.");
  899. return false;
  900. }
  901. /* Get aux stack bottom address */
  902. if (!(aux_stack_bottom_addr = LLVMBuildInBoundsGEP2(
  903. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  904. &aux_stack_bottom_offset, 1, "aux_stack_bottom_addr"))) {
  905. aot_set_last_error("llvm build in bounds gep failed");
  906. return false;
  907. }
  908. if (!(aux_stack_bottom_addr =
  909. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bottom_addr,
  910. INTPTR_T_PTR_TYPE, "aux_stack_bottom_ptr"))) {
  911. aot_set_last_error("llvm build bit cast failed");
  912. return false;
  913. }
  914. if (!(func_ctx->aux_stack_bottom =
  915. LLVMBuildLoad2(comp_ctx->builder, INTPTR_T_TYPE,
  916. aux_stack_bottom_addr, "aux_stack_bottom"))) {
  917. aot_set_last_error("llvm build load failed");
  918. return false;
  919. }
  920. if (!(func_ctx->aux_stack_bottom =
  921. LLVMBuildZExt(comp_ctx->builder, func_ctx->aux_stack_bottom,
  922. I64_TYPE, "aux_stack_bottom_i64"))) {
  923. aot_set_last_error("llvm build truncOrBitCast failed.");
  924. return false;
  925. }
  926. return true;
  927. }
  928. static bool
  929. create_aux_stack_frame(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  930. {
  931. LLVMValueRef wasm_stack_top_bound_ptr, offset;
  932. offset = I32_ONE;
  933. if (!(func_ctx->cur_frame_ptr = LLVMBuildInBoundsGEP2(
  934. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1,
  935. "cur_frame_ptr"))) {
  936. aot_set_last_error("llvm build in bounds gep failed");
  937. return false;
  938. }
  939. if (!(func_ctx->cur_frame =
  940. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  941. func_ctx->cur_frame_ptr, "cur_frame"))) {
  942. aot_set_last_error("llvm build load failed");
  943. return false;
  944. }
  945. /* Get exec_env->wasm_stack.top_boundary and its address */
  946. offset = I32_TEN;
  947. if (!(wasm_stack_top_bound_ptr = LLVMBuildInBoundsGEP2(
  948. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1,
  949. "wasm_stack_top_bound_ptr"))
  950. || !(func_ctx->wasm_stack_top_bound = LLVMBuildLoad2(
  951. comp_ctx->builder, INT8_PTR_TYPE, wasm_stack_top_bound_ptr,
  952. "wasm_stack_top_bound"))) {
  953. aot_set_last_error("load wasm_stack.top_boundary failed");
  954. return false;
  955. }
  956. offset = I32_ELEVEN;
  957. if (!(func_ctx->wasm_stack_top_ptr = LLVMBuildInBoundsGEP2(
  958. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1,
  959. "wasm_stack_top_ptr"))) {
  960. aot_set_last_error("llvm build inbounds gep failed");
  961. return false;
  962. }
  963. return true;
  964. }
  965. static bool
  966. create_native_symbol(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  967. {
  968. LLVMValueRef native_symbol_offset = I32_EIGHT, native_symbol_addr;
  969. if (!(native_symbol_addr = LLVMBuildInBoundsGEP2(
  970. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  971. &native_symbol_offset, 1, "native_symbol_addr"))) {
  972. aot_set_last_error("llvm build in bounds gep failed");
  973. return false;
  974. }
  975. if (!(func_ctx->native_symbol =
  976. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  977. native_symbol_addr, "native_symbol_tmp"))) {
  978. aot_set_last_error("llvm build bit cast failed");
  979. return false;
  980. }
  981. if (!(func_ctx->native_symbol =
  982. LLVMBuildBitCast(comp_ctx->builder, func_ctx->native_symbol,
  983. comp_ctx->exec_env_type, "native_symbol"))) {
  984. aot_set_last_error("llvm build bit cast failed");
  985. return false;
  986. }
  987. return true;
  988. }
  989. static bool
  990. create_local_variables(const AOTCompData *comp_data,
  991. const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  992. const AOTFunc *func)
  993. {
  994. AOTFuncType *aot_func_type =
  995. (AOTFuncType *)comp_data->types[func->func_type_index];
  996. char local_name[32];
  997. uint32 i, j = 1;
  998. for (i = 0; i < aot_func_type->param_count; i++, j++) {
  999. snprintf(local_name, sizeof(local_name), "l%d", i);
  1000. func_ctx->locals[i] =
  1001. LLVMBuildAlloca(comp_ctx->builder,
  1002. TO_LLVM_TYPE(aot_func_type->types[i]), local_name);
  1003. if (!func_ctx->locals[i]) {
  1004. aot_set_last_error("llvm build alloca failed.");
  1005. return false;
  1006. }
  1007. if (!LLVMBuildStore(comp_ctx->builder, LLVMGetParam(func_ctx->func, j),
  1008. func_ctx->locals[i])) {
  1009. aot_set_last_error("llvm build store failed.");
  1010. return false;
  1011. }
  1012. }
  1013. for (i = 0; i < func->local_count; i++) {
  1014. LLVMTypeRef local_type;
  1015. LLVMValueRef local_value = NULL;
  1016. snprintf(local_name, sizeof(local_name), "l%d",
  1017. aot_func_type->param_count + i);
  1018. local_type = TO_LLVM_TYPE(func->local_types_wp[i]);
  1019. func_ctx->locals[aot_func_type->param_count + i] =
  1020. LLVMBuildAlloca(comp_ctx->builder, local_type, local_name);
  1021. if (!func_ctx->locals[aot_func_type->param_count + i]) {
  1022. aot_set_last_error("llvm build alloca failed.");
  1023. return false;
  1024. }
  1025. switch (func->local_types_wp[i]) {
  1026. case VALUE_TYPE_I32:
  1027. local_value = I32_ZERO;
  1028. break;
  1029. case VALUE_TYPE_I64:
  1030. local_value = I64_ZERO;
  1031. break;
  1032. case VALUE_TYPE_F32:
  1033. local_value = F32_ZERO;
  1034. break;
  1035. case VALUE_TYPE_F64:
  1036. local_value = F64_ZERO;
  1037. break;
  1038. case VALUE_TYPE_V128:
  1039. local_value = V128_i64x2_ZERO;
  1040. break;
  1041. case VALUE_TYPE_FUNCREF:
  1042. case VALUE_TYPE_EXTERNREF:
  1043. if (!comp_ctx->enable_gc)
  1044. local_value = REF_NULL;
  1045. else
  1046. local_value = GC_REF_NULL;
  1047. break;
  1048. #if WASM_ENABLE_GC != 0
  1049. case REF_TYPE_NULLFUNCREF:
  1050. case REF_TYPE_NULLEXTERNREF:
  1051. case REF_TYPE_NULLREF:
  1052. /* case REF_TYPE_FUNCREF: */
  1053. /* case REF_TYPE_EXTERNREF: */
  1054. case REF_TYPE_ANYREF:
  1055. case REF_TYPE_EQREF:
  1056. case REF_TYPE_HT_NULLABLE:
  1057. case REF_TYPE_HT_NON_NULLABLE:
  1058. case REF_TYPE_I31REF:
  1059. case REF_TYPE_STRUCTREF:
  1060. case REF_TYPE_ARRAYREF:
  1061. #if WASM_ENABLE_STRINGREF != 0
  1062. case REF_TYPE_STRINGREF:
  1063. case REF_TYPE_STRINGVIEWWTF8:
  1064. case REF_TYPE_STRINGVIEWWTF16:
  1065. case REF_TYPE_STRINGVIEWITER:
  1066. #endif
  1067. local_value = GC_REF_NULL;
  1068. break;
  1069. #endif
  1070. default:
  1071. bh_assert(0);
  1072. break;
  1073. }
  1074. if (!LLVMBuildStore(comp_ctx->builder, local_value,
  1075. func_ctx->locals[aot_func_type->param_count + i])) {
  1076. aot_set_last_error("llvm build store failed.");
  1077. return false;
  1078. }
  1079. }
  1080. return true;
  1081. }
  1082. static bool
  1083. create_memory_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  1084. LLVMTypeRef int8_ptr_type, uint32 func_index)
  1085. {
  1086. LLVMValueRef offset, mem_info_base;
  1087. uint32 memory_count;
  1088. WASMModule *module = comp_ctx->comp_data->wasm_module;
  1089. WASMFunction *func = module->functions[func_index];
  1090. LLVMTypeRef bound_check_type;
  1091. bool mem_space_unchanged =
  1092. (!func->has_op_memory_grow && !func->has_op_func_call)
  1093. || (!module->possible_memory_grow);
  1094. #if WASM_ENABLE_SHARED_MEMORY != 0
  1095. bool is_shared_memory;
  1096. #endif
  1097. func_ctx->mem_space_unchanged = mem_space_unchanged;
  1098. memory_count = module->memory_count + module->import_memory_count;
  1099. /* If the module doesn't have memory, reserve
  1100. one mem_info space with empty content */
  1101. if (memory_count == 0)
  1102. memory_count = 1;
  1103. if (!(func_ctx->mem_info =
  1104. wasm_runtime_malloc(sizeof(AOTMemInfo) * memory_count))) {
  1105. return false;
  1106. }
  1107. memset(func_ctx->mem_info, 0, sizeof(AOTMemInfo));
  1108. /* Currently we only create memory info for memory 0 */
  1109. /* Load memory base address */
  1110. #if WASM_ENABLE_SHARED_MEMORY != 0
  1111. is_shared_memory =
  1112. comp_ctx->comp_data->memories[0].flags & 0x02 ? true : false;
  1113. if (is_shared_memory) {
  1114. LLVMValueRef shared_mem_addr;
  1115. offset = I32_CONST(offsetof(AOTModuleInstance, memories));
  1116. if (!offset) {
  1117. aot_set_last_error("create llvm const failed.");
  1118. return false;
  1119. }
  1120. /* aot_inst->memories */
  1121. if (!(shared_mem_addr = LLVMBuildInBoundsGEP2(
  1122. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1123. "shared_mem_addr_offset"))) {
  1124. aot_set_last_error("llvm build in bounds gep failed");
  1125. return false;
  1126. }
  1127. if (!(shared_mem_addr =
  1128. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  1129. int8_ptr_type, "shared_mem_addr_ptr"))) {
  1130. aot_set_last_error("llvm build bit cast failed");
  1131. return false;
  1132. }
  1133. /* aot_inst->memories[0] */
  1134. if (!(shared_mem_addr =
  1135. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  1136. shared_mem_addr, "shared_mem_addr"))) {
  1137. aot_set_last_error("llvm build load failed");
  1138. return false;
  1139. }
  1140. if (!(shared_mem_addr =
  1141. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  1142. int8_ptr_type, "shared_mem_addr_ptr"))) {
  1143. aot_set_last_error("llvm build bit cast failed");
  1144. return false;
  1145. }
  1146. if (!(shared_mem_addr =
  1147. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  1148. shared_mem_addr, "shared_mem_addr"))) {
  1149. aot_set_last_error("llvm build load failed");
  1150. return false;
  1151. }
  1152. /* memories[0]->memory_data */
  1153. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data));
  1154. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildInBoundsGEP2(
  1155. comp_ctx->builder, INT8_TYPE, shared_mem_addr, &offset, 1,
  1156. "mem_base_addr_offset"))) {
  1157. aot_set_last_error("llvm build in bounds gep failed");
  1158. return false;
  1159. }
  1160. /* memories[0]->cur_page_count */
  1161. offset = I32_CONST(offsetof(AOTMemoryInstance, cur_page_count));
  1162. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  1163. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE,
  1164. shared_mem_addr, &offset, 1,
  1165. "mem_cur_page_offset"))) {
  1166. aot_set_last_error("llvm build in bounds gep failed");
  1167. return false;
  1168. }
  1169. /* memories[0]->memory_data_size */
  1170. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data_size));
  1171. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildInBoundsGEP2(
  1172. comp_ctx->builder, INT8_TYPE, shared_mem_addr, &offset, 1,
  1173. "mem_data_size_offset"))) {
  1174. aot_set_last_error("llvm build in bounds gep failed");
  1175. return false;
  1176. }
  1177. }
  1178. else
  1179. #endif
  1180. {
  1181. uint32 offset_of_global_table_data;
  1182. if (comp_ctx->is_jit_mode)
  1183. offset_of_global_table_data =
  1184. offsetof(WASMModuleInstance, global_table_data);
  1185. else
  1186. offset_of_global_table_data =
  1187. offsetof(AOTModuleInstance, global_table_data);
  1188. offset = I32_CONST(offset_of_global_table_data
  1189. + offsetof(AOTMemoryInstance, memory_data));
  1190. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildInBoundsGEP2(
  1191. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1192. "mem_base_addr_offset"))) {
  1193. aot_set_last_error("llvm build in bounds gep failed");
  1194. return false;
  1195. }
  1196. offset = I32_CONST(offset_of_global_table_data
  1197. + offsetof(AOTMemoryInstance, cur_page_count));
  1198. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  1199. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE,
  1200. func_ctx->aot_inst, &offset, 1,
  1201. "mem_cur_page_offset"))) {
  1202. aot_set_last_error("llvm build in bounds gep failed");
  1203. return false;
  1204. }
  1205. offset = I32_CONST(offset_of_global_table_data
  1206. + offsetof(AOTMemoryInstance, memory_data_size));
  1207. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildInBoundsGEP2(
  1208. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1209. "mem_data_size_offset"))) {
  1210. aot_set_last_error("llvm build in bounds gep failed");
  1211. return false;
  1212. }
  1213. }
  1214. /* Store mem info base address before cast */
  1215. mem_info_base = func_ctx->mem_info[0].mem_base_addr;
  1216. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildBitCast(
  1217. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  1218. int8_ptr_type, "mem_base_addr_ptr"))) {
  1219. aot_set_last_error("llvm build bit cast failed");
  1220. return false;
  1221. }
  1222. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr = LLVMBuildBitCast(
  1223. comp_ctx->builder, func_ctx->mem_info[0].mem_cur_page_count_addr,
  1224. INT32_PTR_TYPE, "mem_cur_page_ptr"))) {
  1225. aot_set_last_error("llvm build bit cast failed");
  1226. return false;
  1227. }
  1228. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildBitCast(
  1229. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  1230. INT64_PTR_TYPE, "mem_data_size_ptr"))) {
  1231. aot_set_last_error("llvm build bit cast failed");
  1232. return false;
  1233. }
  1234. if (mem_space_unchanged) {
  1235. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad2(
  1236. comp_ctx->builder, OPQ_PTR_TYPE,
  1237. func_ctx->mem_info[0].mem_base_addr, "mem_base_addr"))) {
  1238. aot_set_last_error("llvm build load failed");
  1239. return false;
  1240. }
  1241. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  1242. LLVMBuildLoad2(comp_ctx->builder, I32_TYPE,
  1243. func_ctx->mem_info[0].mem_cur_page_count_addr,
  1244. "mem_cur_page_count"))) {
  1245. aot_set_last_error("llvm build load failed");
  1246. return false;
  1247. }
  1248. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildLoad2(
  1249. comp_ctx->builder, I64_TYPE,
  1250. func_ctx->mem_info[0].mem_data_size_addr, "mem_data_size"))) {
  1251. aot_set_last_error("llvm build load failed");
  1252. return false;
  1253. }
  1254. }
  1255. #if WASM_ENABLE_SHARED_MEMORY != 0
  1256. else if (is_shared_memory) {
  1257. /* The base address for shared memory will never changed,
  1258. we can load the value here */
  1259. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad2(
  1260. comp_ctx->builder, OPQ_PTR_TYPE,
  1261. func_ctx->mem_info[0].mem_base_addr, "mem_base_addr"))) {
  1262. aot_set_last_error("llvm build load failed");
  1263. return false;
  1264. }
  1265. }
  1266. #endif
  1267. bound_check_type = (comp_ctx->pointer_size == sizeof(uint64))
  1268. ? INT64_PTR_TYPE
  1269. : INT32_PTR_TYPE;
  1270. /* Load memory bound check constants */
  1271. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_1byte)
  1272. - offsetof(AOTMemoryInstance, memory_data));
  1273. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  1274. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1275. &offset, 1, "bound_check_1byte_offset"))) {
  1276. aot_set_last_error("llvm build in bounds gep failed");
  1277. return false;
  1278. }
  1279. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildBitCast(
  1280. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_1byte,
  1281. bound_check_type, "bound_check_1byte_ptr"))) {
  1282. aot_set_last_error("llvm build bit cast failed");
  1283. return false;
  1284. }
  1285. if (mem_space_unchanged) {
  1286. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildLoad2(
  1287. comp_ctx->builder,
  1288. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1289. : I32_TYPE,
  1290. func_ctx->mem_info[0].mem_bound_check_1byte,
  1291. "bound_check_1byte"))) {
  1292. aot_set_last_error("llvm build load failed");
  1293. return false;
  1294. }
  1295. }
  1296. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_2bytes)
  1297. - offsetof(AOTMemoryInstance, memory_data));
  1298. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  1299. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1300. &offset, 1, "bound_check_2bytes_offset"))) {
  1301. aot_set_last_error("llvm build in bounds gep failed");
  1302. return false;
  1303. }
  1304. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildBitCast(
  1305. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_2bytes,
  1306. bound_check_type, "bound_check_2bytes_ptr"))) {
  1307. aot_set_last_error("llvm build bit cast failed");
  1308. return false;
  1309. }
  1310. if (mem_space_unchanged) {
  1311. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildLoad2(
  1312. comp_ctx->builder,
  1313. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1314. : I32_TYPE,
  1315. func_ctx->mem_info[0].mem_bound_check_2bytes,
  1316. "bound_check_2bytes"))) {
  1317. aot_set_last_error("llvm build load failed");
  1318. return false;
  1319. }
  1320. }
  1321. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_4bytes)
  1322. - offsetof(AOTMemoryInstance, memory_data));
  1323. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  1324. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1325. &offset, 1, "bound_check_4bytes_offset"))) {
  1326. aot_set_last_error("llvm build in bounds gep failed");
  1327. return false;
  1328. }
  1329. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildBitCast(
  1330. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_4bytes,
  1331. bound_check_type, "bound_check_4bytes_ptr"))) {
  1332. aot_set_last_error("llvm build bit cast failed");
  1333. return false;
  1334. }
  1335. if (mem_space_unchanged) {
  1336. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildLoad2(
  1337. comp_ctx->builder,
  1338. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1339. : I32_TYPE,
  1340. func_ctx->mem_info[0].mem_bound_check_4bytes,
  1341. "bound_check_4bytes"))) {
  1342. aot_set_last_error("llvm build load failed");
  1343. return false;
  1344. }
  1345. }
  1346. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_8bytes)
  1347. - offsetof(AOTMemoryInstance, memory_data));
  1348. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  1349. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1350. &offset, 1, "bound_check_8bytes_offset"))) {
  1351. aot_set_last_error("llvm build in bounds gep failed");
  1352. return false;
  1353. }
  1354. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildBitCast(
  1355. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_8bytes,
  1356. bound_check_type, "bound_check_8bytes_ptr"))) {
  1357. aot_set_last_error("llvm build bit cast failed");
  1358. return false;
  1359. }
  1360. if (mem_space_unchanged) {
  1361. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildLoad2(
  1362. comp_ctx->builder,
  1363. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1364. : I32_TYPE,
  1365. func_ctx->mem_info[0].mem_bound_check_8bytes,
  1366. "bound_check_8bytes"))) {
  1367. aot_set_last_error("llvm build load failed");
  1368. return false;
  1369. }
  1370. }
  1371. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_16bytes)
  1372. - offsetof(AOTMemoryInstance, memory_data));
  1373. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildInBoundsGEP2(
  1374. comp_ctx->builder, INT8_TYPE, mem_info_base, &offset, 1,
  1375. "bound_check_16bytes_offset"))) {
  1376. aot_set_last_error("llvm build in bounds gep failed");
  1377. return false;
  1378. }
  1379. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildBitCast(
  1380. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_16bytes,
  1381. bound_check_type, "bound_check_16bytes_ptr"))) {
  1382. aot_set_last_error("llvm build bit cast failed");
  1383. return false;
  1384. }
  1385. if (mem_space_unchanged) {
  1386. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildLoad2(
  1387. comp_ctx->builder,
  1388. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1389. : I32_TYPE,
  1390. func_ctx->mem_info[0].mem_bound_check_16bytes,
  1391. "bound_check_16bytes"))) {
  1392. aot_set_last_error("llvm build load failed");
  1393. return false;
  1394. }
  1395. }
  1396. return true;
  1397. }
  1398. #define BUILD_IS_NOT_NULL(value, res, name) \
  1399. do { \
  1400. if (!(res = LLVMBuildIsNotNull(comp_ctx->builder, value, name))) { \
  1401. aot_set_last_error("llvm build is not null failed."); \
  1402. goto fail; \
  1403. } \
  1404. } while (0)
  1405. #define get_module_extra_field_offset(field) \
  1406. do { \
  1407. offset_u32 = get_module_inst_extra_offset(comp_ctx); \
  1408. if (comp_ctx->is_jit_mode) \
  1409. offset_u32 += offsetof(WASMModuleInstanceExtra, field); \
  1410. else \
  1411. offset_u32 += offsetof(AOTModuleInstanceExtra, field); \
  1412. } while (0)
  1413. #define LOAD_MODULE_EXTRA_FIELD_AND_ALLOCA(field, type) \
  1414. do { \
  1415. get_module_extra_field_offset(field); \
  1416. offset = I32_CONST(offset_u32); \
  1417. CHECK_LLVM_CONST(offset); \
  1418. if (!(field_p = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, \
  1419. func_ctx->aot_inst, &offset, 1, \
  1420. #field "_p"))) { \
  1421. aot_set_last_error("llvm build inbounds gep failed"); \
  1422. goto fail; \
  1423. } \
  1424. if (!(load_val = \
  1425. LLVMBuildLoad2(comp_ctx->builder, type, field_p, #field))) { \
  1426. aot_set_last_error("llvm build load failed"); \
  1427. goto fail; \
  1428. } \
  1429. if (!(func_ctx->field = \
  1430. LLVMBuildAlloca(comp_ctx->builder, type, #field))) { \
  1431. aot_set_last_error("llvm build alloca failed"); \
  1432. goto fail; \
  1433. } \
  1434. if (!LLVMBuildStore(comp_ctx->builder, load_val, func_ctx->field)) { \
  1435. aot_set_last_error("llvm build store failed"); \
  1436. goto fail; \
  1437. } \
  1438. } while (0)
  1439. static bool
  1440. create_shared_heap_info(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  1441. {
  1442. #if WASM_ENABLE_SHARED_HEAP != 0
  1443. LLVMValueRef offset, field_p, load_val, shared_heap_head_p,
  1444. shared_heap_head, cmp, field_p_or_default, shared_heap_head_start_off,
  1445. shared_heap_head_start_off_minus_one;
  1446. LLVMTypeRef shared_heap_offset_type;
  1447. uint32 offset_u32;
  1448. #if WASM_ENABLE_MEMORY64 == 0
  1449. bool is_memory64 = false;
  1450. #else
  1451. bool is_memory64 = IS_MEMORY64;
  1452. #endif
  1453. shared_heap_offset_type =
  1454. comp_ctx->pointer_size == sizeof(uint64) ? I64_TYPE : I32_TYPE;
  1455. /* shared_heap_base_addr_adj, shared_heap_start_off, and
  1456. * shared_heap_end_off can be updated later, use local variable to
  1457. * represent them */
  1458. LOAD_MODULE_EXTRA_FIELD_AND_ALLOCA(shared_heap_base_addr_adj,
  1459. INT8_PTR_TYPE);
  1460. LOAD_MODULE_EXTRA_FIELD_AND_ALLOCA(shared_heap_start_off,
  1461. shared_heap_offset_type);
  1462. LOAD_MODULE_EXTRA_FIELD_AND_ALLOCA(shared_heap_end_off,
  1463. shared_heap_offset_type);
  1464. /* Shared Heap head start off won't be updated, no need to alloca */
  1465. get_module_extra_field_offset(shared_heap);
  1466. offset = I32_CONST(offset_u32);
  1467. CHECK_LLVM_CONST(offset);
  1468. if (!(shared_heap_head_p = LLVMBuildInBoundsGEP2(
  1469. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1470. "shared_heap_head_p"))) {
  1471. aot_set_last_error("llvm build inbounds gep failed");
  1472. goto fail;
  1473. }
  1474. if (!(shared_heap_head =
  1475. LLVMBuildLoad2(comp_ctx->builder, INT8_PTR_TYPE,
  1476. shared_heap_head_p, "shared_heap_head"))) {
  1477. aot_set_last_error("llvm build load failed");
  1478. goto fail;
  1479. }
  1480. BUILD_IS_NOT_NULL(shared_heap_head, cmp, "has_shared_heap");
  1481. if (is_memory64) {
  1482. offset_u32 = offsetof(WASMSharedHeap, start_off_mem64);
  1483. }
  1484. else {
  1485. offset_u32 = offsetof(WASMSharedHeap, start_off_mem32);
  1486. }
  1487. offset = I32_CONST(offset_u32);
  1488. CHECK_LLVM_CONST(offset);
  1489. if (!(field_p = LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE,
  1490. shared_heap_head, &offset, 1,
  1491. "head_start_off_p"))) {
  1492. aot_set_last_error("llvm build inbounds gep failed");
  1493. goto fail;
  1494. }
  1495. /* Select a valid shared heap head ptr or safe alloca ptr stores
  1496. * shared_heap_start_off(UINT32_MAX/UINT64_MAX) */
  1497. if (!(field_p_or_default = LLVMBuildSelect(comp_ctx->builder, cmp, field_p,
  1498. func_ctx->shared_heap_start_off,
  1499. "ptr_or_default"))) {
  1500. aot_set_last_error("llvm build select failed");
  1501. goto fail;
  1502. }
  1503. if (!(shared_heap_head_start_off = LLVMBuildLoad2(
  1504. comp_ctx->builder, shared_heap_offset_type, field_p_or_default,
  1505. "shared_heap_head_start_off"))) {
  1506. aot_set_last_error("llvm build load failed");
  1507. goto fail;
  1508. }
  1509. if (!(shared_heap_head_start_off_minus_one = LLVMBuildAdd(
  1510. comp_ctx->builder, shared_heap_head_start_off,
  1511. comp_ctx->pointer_size == sizeof(uint64) ? I64_NEG_ONE
  1512. : I32_NEG_ONE,
  1513. "head_start_off_minus_one"))) {
  1514. aot_set_last_error("llvm build load failed");
  1515. goto fail;
  1516. }
  1517. /* if there is attached shared heap(s), the value will be valid start_off-1,
  1518. * otherwise it will be UINT32_MAX/UINT64_MAX, so during the bounds checks,
  1519. * when has attached shared heap:
  1520. * offset > start_off - 1 => offset >= start_off
  1521. * when no attached shared heap:
  1522. * offset > UINT32_MAX/UINT64_MAX is always false
  1523. * */
  1524. if (!(func_ctx->shared_heap_head_start_off = LLVMBuildSelect(
  1525. comp_ctx->builder, cmp, shared_heap_head_start_off_minus_one,
  1526. shared_heap_head_start_off, "head_start_off"))) {
  1527. aot_set_last_error("llvm build select failed");
  1528. goto fail;
  1529. }
  1530. return true;
  1531. fail:
  1532. return false;
  1533. #else /* else of WASM_ENABLE_SHARED_HEAP != 0 */
  1534. return true;
  1535. #endif /* end of WASM_ENABLE_SHARED_HEAP != 0 */
  1536. }
  1537. static bool
  1538. create_cur_exception(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  1539. {
  1540. LLVMValueRef offset;
  1541. offset = I32_CONST(offsetof(AOTModuleInstance, cur_exception));
  1542. func_ctx->cur_exception =
  1543. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1544. &offset, 1, "cur_exception");
  1545. if (!func_ctx->cur_exception) {
  1546. aot_set_last_error("llvm build in bounds gep failed.");
  1547. return false;
  1548. }
  1549. return true;
  1550. }
  1551. static bool
  1552. create_func_type_indexes(const AOTCompContext *comp_ctx,
  1553. AOTFuncContext *func_ctx)
  1554. {
  1555. LLVMValueRef offset, func_type_indexes_ptr;
  1556. LLVMTypeRef int32_ptr_type;
  1557. offset = I32_CONST(offsetof(AOTModuleInstance, func_type_indexes));
  1558. func_type_indexes_ptr =
  1559. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1560. &offset, 1, "func_type_indexes_ptr");
  1561. if (!func_type_indexes_ptr) {
  1562. aot_set_last_error("llvm build add failed.");
  1563. return false;
  1564. }
  1565. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  1566. aot_set_last_error("llvm get pointer type failed.");
  1567. return false;
  1568. }
  1569. func_ctx->func_type_indexes =
  1570. LLVMBuildBitCast(comp_ctx->builder, func_type_indexes_ptr,
  1571. int32_ptr_type, "func_type_indexes_tmp");
  1572. if (!func_ctx->func_type_indexes) {
  1573. aot_set_last_error("llvm build bit cast failed.");
  1574. return false;
  1575. }
  1576. func_ctx->func_type_indexes =
  1577. LLVMBuildLoad2(comp_ctx->builder, INT32_PTR_TYPE,
  1578. func_ctx->func_type_indexes, "func_type_indexes");
  1579. if (!func_ctx->func_type_indexes) {
  1580. aot_set_last_error("llvm build load failed.");
  1581. return false;
  1582. }
  1583. return true;
  1584. }
  1585. static bool
  1586. create_func_ptrs(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  1587. {
  1588. LLVMValueRef offset;
  1589. offset = I32_CONST(offsetof(AOTModuleInstance, func_ptrs));
  1590. func_ctx->func_ptrs =
  1591. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1592. &offset, 1, "func_ptrs_offset");
  1593. if (!func_ctx->func_ptrs) {
  1594. aot_set_last_error("llvm build in bounds gep failed.");
  1595. return false;
  1596. }
  1597. func_ctx->func_ptrs =
  1598. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  1599. comp_ctx->exec_env_type, "func_ptrs_tmp");
  1600. if (!func_ctx->func_ptrs) {
  1601. aot_set_last_error("llvm build bit cast failed.");
  1602. return false;
  1603. }
  1604. func_ctx->func_ptrs = LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  1605. func_ctx->func_ptrs, "func_ptrs_ptr");
  1606. if (!func_ctx->func_ptrs) {
  1607. aot_set_last_error("llvm build load failed.");
  1608. return false;
  1609. }
  1610. func_ctx->func_ptrs =
  1611. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  1612. comp_ctx->exec_env_type, "func_ptrs");
  1613. if (!func_ctx->func_ptrs) {
  1614. aot_set_last_error("llvm build bit cast failed.");
  1615. return false;
  1616. }
  1617. return true;
  1618. }
  1619. const char *aot_stack_sizes_name = AOT_STACK_SIZES_NAME;
  1620. const char *aot_stack_sizes_alias_name = AOT_STACK_SIZES_ALIAS_NAME;
  1621. const char *aot_stack_sizes_section_name = AOT_STACK_SIZES_SECTION_NAME;
  1622. static bool
  1623. aot_create_stack_sizes(const AOTCompData *comp_data, AOTCompContext *comp_ctx)
  1624. {
  1625. LLVMValueRef stack_sizes, *values, array, alias;
  1626. LLVMTypeRef stack_sizes_type;
  1627. #if LLVM_VERSION_MAJOR <= 13
  1628. LLVMTypeRef alias_type;
  1629. #endif
  1630. uint64 size;
  1631. uint32 i;
  1632. stack_sizes_type = LLVMArrayType(I32_TYPE, comp_data->func_count);
  1633. if (!stack_sizes_type) {
  1634. aot_set_last_error("failed to create stack_sizes type.");
  1635. return false;
  1636. }
  1637. stack_sizes =
  1638. LLVMAddGlobal(comp_ctx->module, stack_sizes_type, aot_stack_sizes_name);
  1639. if (!stack_sizes) {
  1640. aot_set_last_error("failed to create stack_sizes global.");
  1641. return false;
  1642. }
  1643. size = sizeof(LLVMValueRef) * comp_data->func_count;
  1644. if (size >= UINT32_MAX || !(values = wasm_runtime_malloc((uint32)size))) {
  1645. aot_set_last_error("allocate memory failed.");
  1646. return false;
  1647. }
  1648. for (i = 0; i < comp_data->func_count; i++) {
  1649. /*
  1650. * This value is a placeholder, which will be replaced
  1651. * after the corresponding functions are compiled.
  1652. *
  1653. * Don't use zeros because LLVM can optimize them to
  1654. * zeroinitializer.
  1655. */
  1656. values[i] = I32_NEG_ONE;
  1657. }
  1658. array = LLVMConstArray(I32_TYPE, values, comp_data->func_count);
  1659. wasm_runtime_free(values);
  1660. if (!array) {
  1661. aot_set_last_error("failed to create stack_sizes initializer.");
  1662. return false;
  1663. }
  1664. LLVMSetInitializer(stack_sizes, array);
  1665. /*
  1666. * create an alias so that aot_resolve_stack_sizes can find it.
  1667. */
  1668. #if LLVM_VERSION_MAJOR > 13
  1669. alias = LLVMAddAlias2(comp_ctx->module, stack_sizes_type, 0, stack_sizes,
  1670. aot_stack_sizes_alias_name);
  1671. #else
  1672. alias_type = LLVMPointerType(stack_sizes_type, 0);
  1673. if (!alias_type) {
  1674. aot_set_last_error("failed to create alias type.");
  1675. return false;
  1676. }
  1677. alias = LLVMAddAlias(comp_ctx->module, alias_type, stack_sizes,
  1678. aot_stack_sizes_alias_name);
  1679. #endif
  1680. if (!alias) {
  1681. aot_set_last_error("failed to create stack_sizes alias.");
  1682. return false;
  1683. }
  1684. /*
  1685. * make the original symbol internal. we mainly use this version to
  1686. * avoid creating extra relocations in the precheck functions.
  1687. */
  1688. LLVMSetLinkage(stack_sizes, LLVMInternalLinkage);
  1689. /*
  1690. * for AOT, place it into a dedicated section for the convenience
  1691. * of the AOT file generation and symbol resolutions.
  1692. *
  1693. * for JIT, it doesn't matter.
  1694. */
  1695. if (!comp_ctx->is_jit_mode) {
  1696. LLVMSetSection(stack_sizes, aot_stack_sizes_section_name);
  1697. }
  1698. comp_ctx->stack_sizes_type = stack_sizes_type;
  1699. comp_ctx->stack_sizes = stack_sizes;
  1700. return true;
  1701. }
  1702. /**
  1703. * Create function compiler context
  1704. */
  1705. static AOTFuncContext *
  1706. aot_create_func_context(const AOTCompData *comp_data, AOTCompContext *comp_ctx,
  1707. AOTFunc *func, uint32 func_index)
  1708. {
  1709. AOTFuncContext *func_ctx;
  1710. AOTFuncType *aot_func_type =
  1711. (AOTFuncType *)comp_data->types[func->func_type_index];
  1712. WASMModule *module = comp_ctx->comp_data->wasm_module;
  1713. WASMFunction *wasm_func = module->functions[func_index];
  1714. AOTBlock *aot_block;
  1715. LLVMTypeRef int8_ptr_type;
  1716. uint64 size;
  1717. /* Allocate memory for the function context */
  1718. size = offsetof(AOTFuncContext, locals)
  1719. + sizeof(LLVMValueRef)
  1720. * ((uint64)aot_func_type->param_count + func->local_count);
  1721. if (size >= UINT32_MAX || !(func_ctx = wasm_runtime_malloc((uint32)size))) {
  1722. aot_set_last_error("allocate memory failed.");
  1723. return NULL;
  1724. }
  1725. memset(func_ctx, 0, (uint32)size);
  1726. func_ctx->aot_func = func;
  1727. func_ctx->module = comp_ctx->module;
  1728. /* Add LLVM function */
  1729. if (!(func_ctx->func = aot_add_llvm_func(
  1730. comp_ctx, func_ctx->module, aot_func_type, func_index,
  1731. &func_ctx->func_type, &func_ctx->precheck_func))) {
  1732. goto fail;
  1733. }
  1734. /* Create function's first AOTBlock */
  1735. if (!(aot_block =
  1736. aot_create_func_block(comp_ctx, func_ctx, func, aot_func_type))) {
  1737. goto fail;
  1738. }
  1739. #if WASM_ENABLE_DEBUG_AOT != 0
  1740. func_ctx->debug_func = dwarf_gen_func_info(comp_ctx, func_ctx);
  1741. #endif
  1742. aot_block_stack_push(&func_ctx->block_stack, aot_block);
  1743. /* Add local variables */
  1744. LLVMPositionBuilderAtEnd(comp_ctx->builder, aot_block->llvm_entry_block);
  1745. if (!create_basic_func_context(comp_ctx, func_ctx)) {
  1746. goto fail;
  1747. }
  1748. /* Get argv buffer address */
  1749. if (wasm_func->has_op_func_call && !create_argv_buf(comp_ctx, func_ctx)) {
  1750. goto fail;
  1751. }
  1752. /* Get auxiliary stack info */
  1753. if (wasm_func->has_op_set_global_aux_stack
  1754. && !create_aux_stack_info(comp_ctx, func_ctx)) {
  1755. goto fail;
  1756. }
  1757. if (comp_ctx->aux_stack_frame_type
  1758. && !create_aux_stack_frame(comp_ctx, func_ctx)) {
  1759. goto fail;
  1760. }
  1761. /* Create local variables */
  1762. if (!create_local_variables(comp_data, comp_ctx, func_ctx, func)) {
  1763. goto fail;
  1764. }
  1765. if (!(int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0))) {
  1766. aot_set_last_error("llvm add pointer type failed.");
  1767. goto fail;
  1768. }
  1769. /* Create base addr, end addr, data size of mem, heap */
  1770. if (wasm_func->has_memory_operations
  1771. && !create_memory_info(comp_ctx, func_ctx, int8_ptr_type, func_index)) {
  1772. goto fail;
  1773. }
  1774. /* Load current exception */
  1775. if (!create_cur_exception(comp_ctx, func_ctx)) {
  1776. goto fail;
  1777. }
  1778. /* Load function type indexes */
  1779. if (wasm_func->has_op_call_indirect
  1780. && !create_func_type_indexes(comp_ctx, func_ctx)) {
  1781. goto fail;
  1782. }
  1783. /* Load function pointers */
  1784. if (!create_func_ptrs(comp_ctx, func_ctx)) {
  1785. goto fail;
  1786. }
  1787. /* Load shared heap, shared heap start off mem32 or mem64 */
  1788. if ((comp_ctx->enable_shared_heap || comp_ctx->enable_shared_chain)
  1789. && !create_shared_heap_info(comp_ctx, func_ctx)) {
  1790. goto fail;
  1791. }
  1792. #if WASM_ENABLE_BRANCH_HINTS != 0
  1793. func_ctx->function_hints =
  1794. comp_ctx->comp_data->function_hints
  1795. ? comp_ctx->comp_data->function_hints[func_index]
  1796. : NULL;
  1797. #endif
  1798. return func_ctx;
  1799. fail:
  1800. if (func_ctx->mem_info)
  1801. wasm_runtime_free(func_ctx->mem_info);
  1802. aot_block_stack_destroy(comp_ctx, &func_ctx->block_stack);
  1803. wasm_runtime_free(func_ctx);
  1804. return NULL;
  1805. }
  1806. static void
  1807. aot_destroy_func_contexts(AOTCompContext *comp_ctx, AOTFuncContext **func_ctxes,
  1808. uint32 count)
  1809. {
  1810. uint32 i;
  1811. for (i = 0; i < count; i++)
  1812. if (func_ctxes[i]) {
  1813. if (func_ctxes[i]->mem_info)
  1814. wasm_runtime_free(func_ctxes[i]->mem_info);
  1815. aot_block_stack_destroy(comp_ctx, &func_ctxes[i]->block_stack);
  1816. aot_checked_addr_list_destroy(func_ctxes[i]);
  1817. wasm_runtime_free(func_ctxes[i]);
  1818. }
  1819. wasm_runtime_free(func_ctxes);
  1820. }
  1821. /**
  1822. * Create function compiler contexts
  1823. */
  1824. static AOTFuncContext **
  1825. aot_create_func_contexts(const AOTCompData *comp_data, AOTCompContext *comp_ctx)
  1826. {
  1827. AOTFuncContext **func_ctxes;
  1828. uint64 size;
  1829. uint32 i;
  1830. if ((comp_ctx->enable_stack_bound_check
  1831. || comp_ctx->enable_stack_estimation)
  1832. && !aot_create_stack_sizes(comp_data, comp_ctx))
  1833. return NULL;
  1834. /* Allocate memory */
  1835. size = sizeof(AOTFuncContext *) * (uint64)comp_data->func_count;
  1836. if (size >= UINT32_MAX
  1837. || !(func_ctxes = wasm_runtime_malloc((uint32)size))) {
  1838. aot_set_last_error("allocate memory failed.");
  1839. return NULL;
  1840. }
  1841. memset(func_ctxes, 0, size);
  1842. /* Create each function context */
  1843. for (i = 0; i < comp_data->func_count; i++) {
  1844. AOTFunc *func = comp_data->funcs[i];
  1845. if (!(func_ctxes[i] =
  1846. aot_create_func_context(comp_data, comp_ctx, func, i))) {
  1847. aot_destroy_func_contexts(comp_ctx, func_ctxes,
  1848. comp_data->func_count);
  1849. return NULL;
  1850. }
  1851. }
  1852. return func_ctxes;
  1853. }
  1854. static bool
  1855. aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context,
  1856. int pointer_size)
  1857. {
  1858. basic_types->int1_type = LLVMInt1TypeInContext(context);
  1859. basic_types->int8_type = LLVMInt8TypeInContext(context);
  1860. basic_types->int16_type = LLVMInt16TypeInContext(context);
  1861. basic_types->int32_type = LLVMInt32TypeInContext(context);
  1862. basic_types->int64_type = LLVMInt64TypeInContext(context);
  1863. basic_types->float32_type = LLVMFloatTypeInContext(context);
  1864. basic_types->float64_type = LLVMDoubleTypeInContext(context);
  1865. basic_types->void_type = LLVMVoidTypeInContext(context);
  1866. basic_types->meta_data_type = LLVMMetadataTypeInContext(context);
  1867. basic_types->int8_ptr_type = LLVMPointerType(basic_types->int8_type, 0);
  1868. if (basic_types->int8_ptr_type) {
  1869. basic_types->int8_pptr_type =
  1870. LLVMPointerType(basic_types->int8_ptr_type, 0);
  1871. }
  1872. basic_types->int16_ptr_type = LLVMPointerType(basic_types->int16_type, 0);
  1873. basic_types->int32_ptr_type = LLVMPointerType(basic_types->int32_type, 0);
  1874. basic_types->int64_ptr_type = LLVMPointerType(basic_types->int64_type, 0);
  1875. basic_types->float32_ptr_type =
  1876. LLVMPointerType(basic_types->float32_type, 0);
  1877. basic_types->float64_ptr_type =
  1878. LLVMPointerType(basic_types->float64_type, 0);
  1879. basic_types->i8x16_vec_type = LLVMVectorType(basic_types->int8_type, 16);
  1880. basic_types->i16x8_vec_type = LLVMVectorType(basic_types->int16_type, 8);
  1881. basic_types->i32x4_vec_type = LLVMVectorType(basic_types->int32_type, 4);
  1882. basic_types->i64x2_vec_type = LLVMVectorType(basic_types->int64_type, 2);
  1883. basic_types->f32x4_vec_type = LLVMVectorType(basic_types->float32_type, 4);
  1884. basic_types->f64x2_vec_type = LLVMVectorType(basic_types->float64_type, 2);
  1885. basic_types->v128_type = basic_types->i64x2_vec_type;
  1886. basic_types->v128_ptr_type = LLVMPointerType(basic_types->v128_type, 0);
  1887. basic_types->int8_ptr_type_gs =
  1888. LLVMPointerType(basic_types->int8_type, 256);
  1889. basic_types->int16_ptr_type_gs =
  1890. LLVMPointerType(basic_types->int16_type, 256);
  1891. basic_types->int32_ptr_type_gs =
  1892. LLVMPointerType(basic_types->int32_type, 256);
  1893. basic_types->int64_ptr_type_gs =
  1894. LLVMPointerType(basic_types->int64_type, 256);
  1895. basic_types->float32_ptr_type_gs =
  1896. LLVMPointerType(basic_types->float32_type, 256);
  1897. basic_types->float64_ptr_type_gs =
  1898. LLVMPointerType(basic_types->float64_type, 256);
  1899. basic_types->v128_ptr_type_gs =
  1900. LLVMPointerType(basic_types->v128_type, 256);
  1901. if (!basic_types->int8_ptr_type_gs || !basic_types->int16_ptr_type_gs
  1902. || !basic_types->int32_ptr_type_gs || !basic_types->int64_ptr_type_gs
  1903. || !basic_types->float32_ptr_type_gs
  1904. || !basic_types->float64_ptr_type_gs
  1905. || !basic_types->v128_ptr_type_gs) {
  1906. return false;
  1907. }
  1908. basic_types->i1x2_vec_type = LLVMVectorType(basic_types->int1_type, 2);
  1909. basic_types->funcref_type = LLVMInt32TypeInContext(context);
  1910. basic_types->externref_type = LLVMInt32TypeInContext(context);
  1911. if (pointer_size == 4) {
  1912. basic_types->intptr_t_type = basic_types->int32_type;
  1913. basic_types->intptr_t_ptr_type = basic_types->int32_ptr_type;
  1914. basic_types->size_t_type = basic_types->int32_type;
  1915. }
  1916. else {
  1917. basic_types->intptr_t_type = basic_types->int64_type;
  1918. basic_types->intptr_t_ptr_type = basic_types->int64_ptr_type;
  1919. basic_types->size_t_type = basic_types->int64_type;
  1920. }
  1921. basic_types->gc_ref_type = basic_types->int8_ptr_type;
  1922. basic_types->gc_ref_ptr_type = basic_types->int8_pptr_type;
  1923. return (basic_types->int8_ptr_type && basic_types->int8_pptr_type
  1924. && basic_types->int16_ptr_type && basic_types->int32_ptr_type
  1925. && basic_types->int64_ptr_type && basic_types->intptr_t_type
  1926. && basic_types->intptr_t_ptr_type && basic_types->float32_ptr_type
  1927. && basic_types->float64_ptr_type && basic_types->i8x16_vec_type
  1928. && basic_types->i16x8_vec_type && basic_types->i32x4_vec_type
  1929. && basic_types->i64x2_vec_type && basic_types->f32x4_vec_type
  1930. && basic_types->f64x2_vec_type && basic_types->i1x2_vec_type
  1931. && basic_types->meta_data_type && basic_types->funcref_type
  1932. && basic_types->externref_type && basic_types->gc_ref_type
  1933. && basic_types->gc_ref_ptr_type)
  1934. ? true
  1935. : false;
  1936. }
  1937. static bool
  1938. aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx)
  1939. {
  1940. #define CREATE_I1_CONST(name, value) \
  1941. if (!(consts->i1_##name = \
  1942. LLVMConstInt(comp_ctx->basic_types.int1_type, value, true))) \
  1943. return false;
  1944. CREATE_I1_CONST(zero, 0)
  1945. CREATE_I1_CONST(one, 1)
  1946. #undef CREATE_I1_CONST
  1947. if (!(consts->i8_zero = I8_CONST(0)))
  1948. return false;
  1949. if (!(consts->i8_one = I8_CONST(1)))
  1950. return false;
  1951. if (!(consts->f32_zero = F32_CONST(0)))
  1952. return false;
  1953. if (!(consts->f64_zero = F64_CONST(0)))
  1954. return false;
  1955. #define CREATE_I32_CONST(name, value) \
  1956. if (!(consts->i32_##name = LLVMConstInt(I32_TYPE, value, true))) \
  1957. return false;
  1958. CREATE_I32_CONST(min, (uint32)INT32_MIN)
  1959. CREATE_I32_CONST(neg_one, (uint32)-1)
  1960. CREATE_I32_CONST(zero, 0)
  1961. CREATE_I32_CONST(one, 1)
  1962. CREATE_I32_CONST(two, 2)
  1963. CREATE_I32_CONST(three, 3)
  1964. CREATE_I32_CONST(four, 4)
  1965. CREATE_I32_CONST(five, 5)
  1966. CREATE_I32_CONST(six, 6)
  1967. CREATE_I32_CONST(seven, 7)
  1968. CREATE_I32_CONST(eight, 8)
  1969. CREATE_I32_CONST(nine, 9)
  1970. CREATE_I32_CONST(ten, 10)
  1971. CREATE_I32_CONST(eleven, 11)
  1972. CREATE_I32_CONST(twelve, 12)
  1973. CREATE_I32_CONST(thirteen, 13)
  1974. CREATE_I32_CONST(fourteen, 14)
  1975. CREATE_I32_CONST(fifteen, 15)
  1976. CREATE_I32_CONST(31, 31)
  1977. CREATE_I32_CONST(32, 32)
  1978. #undef CREATE_I32_CONST
  1979. #define CREATE_I64_CONST(name, value) \
  1980. if (!(consts->i64_##name = LLVMConstInt(I64_TYPE, value, true))) \
  1981. return false;
  1982. CREATE_I64_CONST(min, (uint64)INT64_MIN)
  1983. CREATE_I64_CONST(neg_one, (uint64)-1)
  1984. CREATE_I64_CONST(zero, 0)
  1985. CREATE_I64_CONST(63, 63)
  1986. CREATE_I64_CONST(64, 64)
  1987. #undef CREATE_I64_CONST
  1988. #define CREATE_V128_CONST(name, type) \
  1989. if (!(consts->name##_vec_zero = LLVMConstNull(type))) \
  1990. return false; \
  1991. if (!(consts->name##_undef = LLVMGetUndef(type))) \
  1992. return false;
  1993. CREATE_V128_CONST(i8x16, V128_i8x16_TYPE)
  1994. CREATE_V128_CONST(i16x8, V128_i16x8_TYPE)
  1995. CREATE_V128_CONST(i32x4, V128_i32x4_TYPE)
  1996. CREATE_V128_CONST(i64x2, V128_i64x2_TYPE)
  1997. CREATE_V128_CONST(f32x4, V128_f32x4_TYPE)
  1998. CREATE_V128_CONST(f64x2, V128_f64x2_TYPE)
  1999. #undef CREATE_V128_CONST
  2000. #define CREATE_VEC_ZERO_MASK(slot) \
  2001. { \
  2002. LLVMTypeRef type = LLVMVectorType(I32_TYPE, slot); \
  2003. if (!type || !(consts->i32x##slot##_zero = LLVMConstNull(type))) \
  2004. return false; \
  2005. }
  2006. CREATE_VEC_ZERO_MASK(16)
  2007. CREATE_VEC_ZERO_MASK(8)
  2008. CREATE_VEC_ZERO_MASK(4)
  2009. CREATE_VEC_ZERO_MASK(2)
  2010. #undef CREATE_VEC_ZERO_MASK
  2011. if (!(consts->gc_ref_null =
  2012. LLVMConstNull(comp_ctx->basic_types.gc_ref_type)))
  2013. return false;
  2014. if (!(consts->i8_ptr_null =
  2015. LLVMConstNull(comp_ctx->basic_types.int8_ptr_type)))
  2016. return false;
  2017. return true;
  2018. }
  2019. typedef struct ArchItem {
  2020. char *arch;
  2021. bool support_eb;
  2022. } ArchItem;
  2023. /* clang-format off */
  2024. static ArchItem valid_archs[] = {
  2025. { "x86_64", false },
  2026. { "i386", false },
  2027. { "xtensa", false },
  2028. { "mips", true },
  2029. { "mipsel", false },
  2030. { "aarch64v8", false },
  2031. { "aarch64v8.1", false },
  2032. { "aarch64v8.2", false },
  2033. { "aarch64v8.3", false },
  2034. { "aarch64v8.4", false },
  2035. { "aarch64v8.5", false },
  2036. { "aarch64_bev8", false }, /* big endian */
  2037. { "aarch64_bev8.1", false },
  2038. { "aarch64_bev8.2", false },
  2039. { "aarch64_bev8.3", false },
  2040. { "aarch64_bev8.4", false },
  2041. { "aarch64_bev8.5", false },
  2042. { "armv4", true },
  2043. { "armv4t", true },
  2044. { "armv5t", true },
  2045. { "armv5te", true },
  2046. { "armv5tej", true },
  2047. { "armv6", true },
  2048. { "armv6kz", true },
  2049. { "armv6t2", true },
  2050. { "armv6k", true },
  2051. { "armv7", true },
  2052. { "armv6m", true },
  2053. { "armv6sm", true },
  2054. { "armv7em", true },
  2055. { "armv8a", true },
  2056. { "armv8r", true },
  2057. { "armv8m.base", true },
  2058. { "armv8m.main", true },
  2059. { "armv8.1m.main", true },
  2060. { "thumbv4", true },
  2061. { "thumbv4t", true },
  2062. { "thumbv5t", true },
  2063. { "thumbv5te", true },
  2064. { "thumbv5tej", true },
  2065. { "thumbv6", true },
  2066. { "thumbv6kz", true },
  2067. { "thumbv6t2", true },
  2068. { "thumbv6k", true },
  2069. { "thumbv7", true },
  2070. { "thumbv6m", true },
  2071. { "thumbv6sm", true },
  2072. { "thumbv7em", true },
  2073. { "thumbv8a", true },
  2074. { "thumbv8r", true },
  2075. { "thumbv8m.base", true },
  2076. { "thumbv8m.main", true },
  2077. { "thumbv8.1m.main", true },
  2078. { "riscv32", true },
  2079. { "riscv64", true },
  2080. { "arc", true }
  2081. };
  2082. static const char *valid_abis[] = {
  2083. "gnu",
  2084. "eabi",
  2085. "eabihf",
  2086. "gnueabihf",
  2087. "msvc",
  2088. "ilp32",
  2089. "ilp32f",
  2090. "ilp32d",
  2091. "lp64",
  2092. "lp64f",
  2093. "lp64d"
  2094. };
  2095. /* clang-format on */
  2096. static void
  2097. print_supported_targets()
  2098. {
  2099. uint32 i;
  2100. const char *target_name;
  2101. os_printf("Supported targets:\n");
  2102. /* over the list of all available targets */
  2103. for (LLVMTargetRef target = LLVMGetFirstTarget(); target != NULL;
  2104. target = LLVMGetNextTarget(target)) {
  2105. target_name = LLVMGetTargetName(target);
  2106. /* Skip mipsel, aarch64_be since prefix mips, aarch64 will cover them */
  2107. if (strcmp(target_name, "mipsel") == 0)
  2108. continue;
  2109. else if (strcmp(target_name, "aarch64_be") == 0)
  2110. continue;
  2111. if (strcmp(target_name, "x86-64") == 0)
  2112. os_printf(" x86_64\n");
  2113. else if (strcmp(target_name, "x86") == 0)
  2114. os_printf(" i386\n");
  2115. else {
  2116. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  2117. /* If target_name is prefix for valid_archs[i].arch */
  2118. if ((strncmp(target_name, valid_archs[i].arch,
  2119. strlen(target_name))
  2120. == 0))
  2121. os_printf(" %s\n", valid_archs[i].arch);
  2122. }
  2123. }
  2124. }
  2125. }
  2126. static void
  2127. print_supported_abis()
  2128. {
  2129. uint32 i;
  2130. os_printf("Supported ABI: ");
  2131. for (i = 0; i < sizeof(valid_abis) / sizeof(const char *); i++)
  2132. os_printf("%s ", valid_abis[i]);
  2133. os_printf("\n");
  2134. }
  2135. static bool
  2136. check_target_arch(const char *target_arch)
  2137. {
  2138. uint32 i;
  2139. char *arch;
  2140. bool support_eb;
  2141. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  2142. arch = valid_archs[i].arch;
  2143. support_eb = valid_archs[i].support_eb;
  2144. if (!strncmp(target_arch, arch, strlen(arch))
  2145. && ((support_eb
  2146. && (!strcmp(target_arch + strlen(arch), "eb")
  2147. || !strcmp(target_arch + strlen(arch), "")))
  2148. || (!support_eb && !strcmp(target_arch + strlen(arch), "")))) {
  2149. return true;
  2150. }
  2151. }
  2152. return false;
  2153. }
  2154. static bool
  2155. check_target_abi(const char *target_abi)
  2156. {
  2157. uint32 i;
  2158. for (i = 0; i < sizeof(valid_abis) / sizeof(char *); i++) {
  2159. if (!strcmp(target_abi, valid_abis[i]))
  2160. return true;
  2161. }
  2162. return false;
  2163. }
  2164. static void
  2165. get_target_arch_from_triple(const char *triple, char *arch_buf, uint32 buf_size)
  2166. {
  2167. uint32 i = 0;
  2168. while (*triple != '-' && *triple != '\0' && i < buf_size - 1)
  2169. arch_buf[i++] = *triple++;
  2170. /* Make sure buffer is long enough */
  2171. bh_assert(*triple == '-' || *triple == '\0');
  2172. }
  2173. static bool
  2174. is_baremetal_target(const char *target, const char *cpu, const char *abi)
  2175. {
  2176. /* TODO: support more baremetal targets */
  2177. if (target) {
  2178. /* If target is thumbxxx, then it is baremetal target */
  2179. if (!strncmp(target, "thumb", strlen("thumb")))
  2180. return true;
  2181. }
  2182. return false;
  2183. }
  2184. void
  2185. aot_handle_llvm_errmsg(const char *string, LLVMErrorRef err)
  2186. {
  2187. char *err_msg = LLVMGetErrorMessage(err);
  2188. aot_set_last_error_v("%s: %s", string, err_msg);
  2189. LLVMDisposeErrorMessage(err_msg);
  2190. }
  2191. static bool
  2192. create_target_machine_detect_host(AOTCompContext *comp_ctx)
  2193. {
  2194. char *triple = NULL;
  2195. LLVMTargetRef target = NULL;
  2196. char *err_msg = NULL;
  2197. char *cpu = NULL;
  2198. char *features = NULL;
  2199. LLVMTargetMachineRef target_machine = NULL;
  2200. bool ret = false;
  2201. triple = LLVMGetDefaultTargetTriple();
  2202. if (triple == NULL) {
  2203. aot_set_last_error("failed to get default target triple.");
  2204. goto fail;
  2205. }
  2206. if (LLVMGetTargetFromTriple(triple, &target, &err_msg) != 0) {
  2207. aot_set_last_error_v("failed to get llvm target from triple %s.",
  2208. err_msg);
  2209. LLVMDisposeMessage(err_msg);
  2210. goto fail;
  2211. }
  2212. if (!LLVMTargetHasJIT(target)) {
  2213. aot_set_last_error("unsupported JIT on this platform.");
  2214. goto fail;
  2215. }
  2216. cpu = LLVMGetHostCPUName();
  2217. if (cpu == NULL) {
  2218. aot_set_last_error("failed to get host cpu information.");
  2219. goto fail;
  2220. }
  2221. features = LLVMGetHostCPUFeatures();
  2222. if (features == NULL) {
  2223. aot_set_last_error("failed to get host cpu features.");
  2224. goto fail;
  2225. }
  2226. LOG_VERBOSE("LLVM ORCJIT detected CPU \"%s\", with features \"%s\"\n", cpu,
  2227. features);
  2228. /* create TargetMachine */
  2229. target_machine = LLVMCreateTargetMachine(
  2230. target, triple, cpu, features, LLVMCodeGenLevelDefault,
  2231. LLVMRelocDefault, LLVMCodeModelJITDefault);
  2232. if (!target_machine) {
  2233. aot_set_last_error("failed to create target machine.");
  2234. goto fail;
  2235. }
  2236. comp_ctx->target_machine = target_machine;
  2237. /* Save target arch */
  2238. get_target_arch_from_triple(triple, comp_ctx->target_arch,
  2239. sizeof(comp_ctx->target_arch));
  2240. ret = true;
  2241. fail:
  2242. if (triple)
  2243. LLVMDisposeMessage(triple);
  2244. if (features)
  2245. LLVMDisposeMessage(features);
  2246. if (cpu)
  2247. LLVMDisposeMessage(cpu);
  2248. return ret;
  2249. }
  2250. static void
  2251. jit_stack_size_callback(void *user_data, const char *name, size_t namelen,
  2252. size_t stack_size)
  2253. {
  2254. AOTCompContext *comp_ctx = user_data;
  2255. /*
  2256. * Note: the longest name we care is
  2257. * something like "aot_func_internal#4294967295".
  2258. */
  2259. char buf[64];
  2260. uint32 func_idx;
  2261. const AOTFuncContext *func_ctx;
  2262. bool musttail;
  2263. unsigned int stack_consumption_to_call_wrapped_func;
  2264. unsigned int call_size;
  2265. int ret;
  2266. bh_assert(comp_ctx != NULL);
  2267. bh_assert(comp_ctx->jit_stack_sizes != NULL);
  2268. if (namelen >= sizeof(buf)) {
  2269. LOG_DEBUG("too long name: %.*s", (int)namelen, name);
  2270. return;
  2271. }
  2272. /* ensure NUL termination */
  2273. bh_memcpy_s(buf, (uint32)sizeof(buf), name, (uint32)namelen);
  2274. buf[namelen] = 0;
  2275. ret = sscanf(buf, AOT_FUNC_INTERNAL_PREFIX "%" SCNu32, &func_idx);
  2276. if (ret != 1) {
  2277. return;
  2278. }
  2279. bh_assert(func_idx < comp_ctx->func_ctx_count);
  2280. func_ctx = comp_ctx->func_ctxes[func_idx];
  2281. call_size = func_ctx->stack_consumption_for_func_call;
  2282. musttail = aot_target_precheck_can_use_musttail(comp_ctx);
  2283. stack_consumption_to_call_wrapped_func =
  2284. musttail ? 0
  2285. : aot_estimate_stack_usage_for_function_call(
  2286. comp_ctx, func_ctx->aot_func->func_type);
  2287. LOG_VERBOSE("func %.*s stack %u + %zu + %u", (int)namelen, name,
  2288. stack_consumption_to_call_wrapped_func, stack_size, call_size);
  2289. /* Note: -1 == AOT_NEG_ONE from aot_create_stack_sizes */
  2290. bh_assert(comp_ctx->jit_stack_sizes[func_idx] == (uint32)-1);
  2291. comp_ctx->jit_stack_sizes[func_idx] = (uint32)stack_size + call_size;
  2292. }
  2293. static bool
  2294. orc_jit_create(AOTCompContext *comp_ctx)
  2295. {
  2296. LLVMErrorRef err;
  2297. LLVMOrcLLLazyJITRef orc_jit = NULL;
  2298. LLVMOrcLLLazyJITBuilderRef builder = NULL;
  2299. LLVMOrcJITTargetMachineBuilderRef jtmb = NULL;
  2300. bool ret = false;
  2301. builder = LLVMOrcCreateLLLazyJITBuilder();
  2302. if (builder == NULL) {
  2303. aot_set_last_error("failed to create jit builder.");
  2304. goto fail;
  2305. }
  2306. if (comp_ctx->enable_stack_bound_check || comp_ctx->enable_stack_estimation)
  2307. LLVMOrcLLJITBuilderSetCompileFunctionCreatorWithStackSizesCallback(
  2308. builder, jit_stack_size_callback, comp_ctx);
  2309. err = LLVMOrcJITTargetMachineBuilderDetectHost(&jtmb);
  2310. if (err != LLVMErrorSuccess) {
  2311. aot_handle_llvm_errmsg(
  2312. "quited to create LLVMOrcJITTargetMachineBuilderRef", err);
  2313. goto fail;
  2314. }
  2315. LLVMOrcLLLazyJITBuilderSetNumCompileThreads(
  2316. builder, WASM_ORC_JIT_COMPILE_THREAD_NUM);
  2317. /* Ownership transfer:
  2318. LLVMOrcJITTargetMachineBuilderRef -> LLVMOrcLLJITBuilderRef */
  2319. LLVMOrcLLLazyJITBuilderSetJITTargetMachineBuilder(builder, jtmb);
  2320. err = LLVMOrcCreateLLLazyJIT(&orc_jit, builder);
  2321. if (err != LLVMErrorSuccess) {
  2322. aot_handle_llvm_errmsg("quited to create llvm lazy orcjit instance",
  2323. err);
  2324. goto fail;
  2325. }
  2326. /* Ownership transfer: LLVMOrcLLJITBuilderRef -> LLVMOrcLLJITRef */
  2327. builder = NULL;
  2328. #if WASM_ENABLE_LINUX_PERF != 0
  2329. if (wasm_runtime_get_linux_perf()) {
  2330. LOG_DEBUG("Enable linux perf support in JIT");
  2331. LLVMOrcObjectLayerRef obj_linking_layer =
  2332. (LLVMOrcObjectLayerRef)LLVMOrcLLLazyJITGetObjLinkingLayer(orc_jit);
  2333. LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener(
  2334. obj_linking_layer, LLVMCreatePerfJITEventListener());
  2335. }
  2336. #endif
  2337. /* Ownership transfer: local -> AOTCompContext */
  2338. comp_ctx->orc_jit = orc_jit;
  2339. orc_jit = NULL;
  2340. ret = true;
  2341. fail:
  2342. if (builder)
  2343. LLVMOrcDisposeLLLazyJITBuilder(builder);
  2344. if (orc_jit)
  2345. LLVMOrcDisposeLLLazyJIT(orc_jit);
  2346. return ret;
  2347. }
  2348. bool
  2349. aot_compiler_init(void)
  2350. {
  2351. /* Initialize LLVM environment */
  2352. #if LLVM_VERSION_MAJOR < 17
  2353. LLVMInitializeCore(LLVMGetGlobalPassRegistry());
  2354. #endif
  2355. /* fuzzing only use host targets for simple */
  2356. #if WASM_ENABLE_WAMR_COMPILER != 0 && WASM_ENABLE_FUZZ_TEST == 0
  2357. /* Init environment of all targets for AOT compiler */
  2358. LLVMInitializeAllTargetInfos();
  2359. LLVMInitializeAllTargets();
  2360. LLVMInitializeAllTargetMCs();
  2361. LLVMInitializeAllAsmPrinters();
  2362. #else
  2363. /* Init environment of native for JIT compiler */
  2364. LLVMInitializeNativeTarget();
  2365. LLVMInitializeNativeTarget();
  2366. LLVMInitializeNativeAsmPrinter();
  2367. #endif
  2368. return true;
  2369. }
  2370. void
  2371. aot_compiler_destroy(void)
  2372. {
  2373. LLVMShutdown();
  2374. }
  2375. AOTCompContext *
  2376. aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option)
  2377. {
  2378. AOTCompContext *comp_ctx, *ret = NULL;
  2379. LLVMTargetRef target;
  2380. char *triple = NULL, *triple_norm, *arch, *abi;
  2381. char *cpu = NULL, *features, buf[128];
  2382. char *triple_norm_new = NULL, *cpu_new = NULL;
  2383. char *err = NULL, *fp_round = "round.tonearest",
  2384. *fp_exce = "fpexcept.strict";
  2385. char triple_buf[128] = { 0 }, features_buf[128] = { 0 };
  2386. uint32 opt_level, size_level, i;
  2387. LLVMCodeModel code_model;
  2388. LLVMTargetDataRef target_data_ref;
  2389. /* Allocate memory */
  2390. if (!(comp_ctx = wasm_runtime_malloc(sizeof(AOTCompContext)))) {
  2391. aot_set_last_error("allocate memory failed.");
  2392. return NULL;
  2393. }
  2394. memset(comp_ctx, 0, sizeof(AOTCompContext));
  2395. comp_ctx->comp_data = comp_data;
  2396. /* Create LLVM context, module and builder */
  2397. comp_ctx->orc_thread_safe_context = LLVMOrcCreateNewThreadSafeContext();
  2398. if (!comp_ctx->orc_thread_safe_context) {
  2399. aot_set_last_error("create LLVM ThreadSafeContext failed.");
  2400. goto fail;
  2401. }
  2402. /* Get a reference to the underlying LLVMContext, note:
  2403. different from non LAZY JIT mode, no need to dispose this context,
  2404. if will be disposed when the thread safe context is disposed */
  2405. if (!(comp_ctx->context = LLVMOrcThreadSafeContextGetContext(
  2406. comp_ctx->orc_thread_safe_context))) {
  2407. aot_set_last_error("get context from LLVM ThreadSafeContext failed.");
  2408. goto fail;
  2409. }
  2410. if (!(comp_ctx->builder = LLVMCreateBuilderInContext(comp_ctx->context))) {
  2411. aot_set_last_error("create LLVM builder failed.");
  2412. goto fail;
  2413. }
  2414. /* Create LLVM module for each jit function, note:
  2415. different from non ORC JIT mode, no need to dispose it,
  2416. it will be disposed when the thread safe context is disposed */
  2417. if (!(comp_ctx->module = LLVMModuleCreateWithNameInContext(
  2418. "WASM Module", comp_ctx->context))) {
  2419. aot_set_last_error("create LLVM module failed.");
  2420. goto fail;
  2421. }
  2422. #if LLVM_VERSION_MAJOR >= 19
  2423. LLVMSetIsNewDbgInfoFormat(comp_ctx->module, true);
  2424. #endif
  2425. #if WASM_ENABLE_LINUX_PERF != 0
  2426. if (wasm_runtime_get_linux_perf()) {
  2427. /* FramePointerKind.All */
  2428. LLVMMetadataRef val =
  2429. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32Type(), 2, false));
  2430. const char *key = "frame-pointer";
  2431. LLVMAddModuleFlag(comp_ctx->module, LLVMModuleFlagBehaviorWarning, key,
  2432. strlen(key), val);
  2433. comp_ctx->emit_frame_pointer = true;
  2434. }
  2435. #endif
  2436. if (BH_LIST_ERROR == bh_list_init(&comp_ctx->native_symbols)) {
  2437. goto fail;
  2438. }
  2439. #if WASM_ENABLE_DEBUG_AOT != 0
  2440. if (!(comp_ctx->debug_builder = LLVMCreateDIBuilder(comp_ctx->module))) {
  2441. aot_set_last_error("create LLVM Debug Infor builder failed.");
  2442. goto fail;
  2443. }
  2444. LLVMAddModuleFlag(
  2445. comp_ctx->module, LLVMModuleFlagBehaviorWarning, "Debug Info Version",
  2446. strlen("Debug Info Version"),
  2447. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32Type(), 3, false)));
  2448. comp_ctx->debug_file = dwarf_gen_file_info(comp_ctx);
  2449. if (!comp_ctx->debug_file) {
  2450. aot_set_last_error("dwarf generate file info failed");
  2451. goto fail;
  2452. }
  2453. comp_ctx->debug_comp_unit = dwarf_gen_comp_unit_info(comp_ctx);
  2454. if (!comp_ctx->debug_comp_unit) {
  2455. aot_set_last_error("dwarf generate compile unit info failed");
  2456. goto fail;
  2457. }
  2458. #endif
  2459. if (option->enable_bulk_memory)
  2460. comp_ctx->enable_bulk_memory = true;
  2461. if (option->enable_bulk_memory_opt)
  2462. comp_ctx->enable_bulk_memory_opt = true;
  2463. if (option->enable_thread_mgr)
  2464. comp_ctx->enable_thread_mgr = true;
  2465. if (option->enable_tail_call)
  2466. comp_ctx->enable_tail_call = true;
  2467. if (option->enable_ref_types)
  2468. comp_ctx->enable_ref_types = true;
  2469. if (option->enable_call_indirect_overlong)
  2470. comp_ctx->enable_call_indirect_overlong = true;
  2471. comp_ctx->aux_stack_frame_type = option->aux_stack_frame_type;
  2472. comp_ctx->call_stack_features = option->call_stack_features;
  2473. if (option->enable_perf_profiling)
  2474. comp_ctx->enable_perf_profiling = true;
  2475. if (option->enable_memory_profiling)
  2476. comp_ctx->enable_memory_profiling = true;
  2477. if (option->enable_aux_stack_check)
  2478. comp_ctx->enable_aux_stack_check = true;
  2479. if (option->is_indirect_mode) {
  2480. comp_ctx->is_indirect_mode = true;
  2481. /* avoid LUT relocations ("switch-table") */
  2482. comp_ctx->disable_llvm_jump_tables = true;
  2483. }
  2484. if (option->disable_llvm_intrinsics)
  2485. comp_ctx->disable_llvm_intrinsics = true;
  2486. if (option->disable_llvm_jump_tables)
  2487. comp_ctx->disable_llvm_jump_tables = true;
  2488. if (option->disable_llvm_lto)
  2489. comp_ctx->disable_llvm_lto = true;
  2490. if (option->enable_llvm_pgo)
  2491. comp_ctx->enable_llvm_pgo = true;
  2492. if (option->use_prof_file)
  2493. comp_ctx->use_prof_file = option->use_prof_file;
  2494. if (option->enable_stack_estimation)
  2495. comp_ctx->enable_stack_estimation = true;
  2496. if (option->quick_invoke_c_api_import)
  2497. comp_ctx->quick_invoke_c_api_import = true;
  2498. if (option->llvm_passes)
  2499. comp_ctx->llvm_passes = option->llvm_passes;
  2500. if (option->builtin_intrinsics)
  2501. comp_ctx->builtin_intrinsics = option->builtin_intrinsics;
  2502. if (option->enable_gc)
  2503. comp_ctx->enable_gc = true;
  2504. if (option->enable_shared_heap)
  2505. comp_ctx->enable_shared_heap = true;
  2506. if (option->enable_shared_chain)
  2507. comp_ctx->enable_shared_chain = true;
  2508. if (option->enable_extended_const)
  2509. comp_ctx->enable_extended_const = true;
  2510. comp_ctx->opt_level = option->opt_level;
  2511. comp_ctx->size_level = option->size_level;
  2512. comp_ctx->custom_sections_wp = option->custom_sections;
  2513. comp_ctx->custom_sections_count = option->custom_sections_count;
  2514. if (option->is_jit_mode) {
  2515. comp_ctx->is_jit_mode = true;
  2516. #ifndef OS_ENABLE_HW_BOUND_CHECK
  2517. comp_ctx->enable_bound_check = true;
  2518. /* Always enable stack boundary check if `bounds-checks`
  2519. is enabled */
  2520. comp_ctx->enable_stack_bound_check = true;
  2521. #else
  2522. comp_ctx->enable_bound_check = false;
  2523. /* When `bounds-checks` is disabled, we set stack boundary
  2524. check status according to the compilation option */
  2525. #if WASM_DISABLE_STACK_HW_BOUND_CHECK != 0
  2526. /* Native stack overflow check with hardware trap is disabled,
  2527. we need to enable the check by LLVM JITed/AOTed code */
  2528. comp_ctx->enable_stack_bound_check = true;
  2529. #else
  2530. /* Native stack overflow check with hardware trap is enabled,
  2531. no need to enable the check by LLVM JITed/AOTed code */
  2532. comp_ctx->enable_stack_bound_check = false;
  2533. #endif
  2534. #endif
  2535. /* Create TargetMachine */
  2536. if (!create_target_machine_detect_host(comp_ctx))
  2537. goto fail;
  2538. /* Create LLJIT Instance */
  2539. if (!orc_jit_create(comp_ctx))
  2540. goto fail;
  2541. }
  2542. else {
  2543. /* Create LLVM target machine */
  2544. if (!option->target_arch || !strstr(option->target_arch, "-")) {
  2545. /* Retrieve the target triple based on user input */
  2546. triple = NULL;
  2547. arch = option->target_arch;
  2548. abi = option->target_abi;
  2549. cpu = option->target_cpu;
  2550. features = option->cpu_features;
  2551. }
  2552. else {
  2553. /* Form a target triple */
  2554. triple = option->target_arch;
  2555. arch = NULL;
  2556. abi = NULL;
  2557. cpu = NULL;
  2558. features = NULL;
  2559. }
  2560. opt_level = option->opt_level;
  2561. size_level = option->size_level;
  2562. /* verify external llc compiler */
  2563. comp_ctx->external_llc_compiler = getenv("WAMRC_LLC_COMPILER");
  2564. if (comp_ctx->external_llc_compiler) {
  2565. if (access(comp_ctx->external_llc_compiler, X_OK) != 0) {
  2566. LOG_WARNING("WAMRC_LLC_COMPILER [%s] not found, fallback to "
  2567. "default pipeline",
  2568. comp_ctx->external_llc_compiler);
  2569. comp_ctx->external_llc_compiler = NULL;
  2570. }
  2571. else {
  2572. comp_ctx->llc_compiler_flags = getenv("WAMRC_LLC_FLAGS");
  2573. LOG_VERBOSE("Using external LLC compiler [%s]",
  2574. comp_ctx->external_llc_compiler);
  2575. }
  2576. }
  2577. /* verify external asm compiler */
  2578. if (!comp_ctx->external_llc_compiler) {
  2579. comp_ctx->external_asm_compiler = getenv("WAMRC_ASM_COMPILER");
  2580. if (comp_ctx->external_asm_compiler) {
  2581. if (access(comp_ctx->external_asm_compiler, X_OK) != 0) {
  2582. LOG_WARNING(
  2583. "WAMRC_ASM_COMPILER [%s] not found, fallback to "
  2584. "default pipeline",
  2585. comp_ctx->external_asm_compiler);
  2586. comp_ctx->external_asm_compiler = NULL;
  2587. }
  2588. else {
  2589. comp_ctx->asm_compiler_flags = getenv("WAMRC_ASM_FLAGS");
  2590. LOG_VERBOSE("Using external ASM compiler [%s]",
  2591. comp_ctx->external_asm_compiler);
  2592. }
  2593. }
  2594. }
  2595. if (arch) {
  2596. /* Add default sub-arch if not specified */
  2597. if (!strcmp(arch, "arm"))
  2598. arch = "armv4";
  2599. else if (!strcmp(arch, "armeb"))
  2600. arch = "armv4eb";
  2601. else if (!strcmp(arch, "thumb"))
  2602. arch = "thumbv4t";
  2603. else if (!strcmp(arch, "thumbeb"))
  2604. arch = "thumbv4teb";
  2605. else if (!strcmp(arch, "aarch64"))
  2606. arch = "aarch64v8";
  2607. else if (!strcmp(arch, "aarch64_be"))
  2608. arch = "aarch64_bev8";
  2609. }
  2610. /* Check target arch */
  2611. if (arch && !check_target_arch(arch)) {
  2612. if (!strcmp(arch, "help"))
  2613. print_supported_targets();
  2614. else
  2615. aot_set_last_error(
  2616. "Invalid target. "
  2617. "Use --target=help to list all supported targets");
  2618. goto fail;
  2619. }
  2620. /* Check target ABI */
  2621. if (abi && !check_target_abi(abi)) {
  2622. if (!strcmp(abi, "help"))
  2623. print_supported_abis();
  2624. else
  2625. aot_set_last_error(
  2626. "Invalid target ABI. "
  2627. "Use --target-abi=help to list all supported ABI");
  2628. goto fail;
  2629. }
  2630. /* Set default abi for riscv target */
  2631. if (arch && !strncmp(arch, "riscv", 5) && !abi) {
  2632. if (!strcmp(arch, "riscv64"))
  2633. abi = "lp64d";
  2634. else
  2635. abi = "ilp32d";
  2636. }
  2637. #if defined(__APPLE__) || defined(__MACH__)
  2638. if (!abi) {
  2639. /* On MacOS platform, set abi to "gnu" to avoid generating
  2640. object file of Mach-O binary format which is unsupported */
  2641. abi = "gnu";
  2642. if (!arch && !cpu && !features) {
  2643. /* Get CPU name of the host machine to avoid checking
  2644. SIMD capability failed */
  2645. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  2646. aot_set_last_error("llvm get host cpu name failed.");
  2647. goto fail;
  2648. }
  2649. }
  2650. }
  2651. #endif
  2652. if (abi) {
  2653. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  2654. const char *vendor_sys;
  2655. char *arch1 = arch, default_arch[32] = { 0 };
  2656. if (!arch1) {
  2657. char *default_triple = LLVMGetDefaultTargetTriple();
  2658. if (!default_triple) {
  2659. aot_set_last_error(
  2660. "llvm get default target triple failed.");
  2661. goto fail;
  2662. }
  2663. vendor_sys = strstr(default_triple, "-");
  2664. bh_assert(vendor_sys);
  2665. bh_memcpy_s(default_arch, sizeof(default_arch), default_triple,
  2666. (uint32)(vendor_sys - default_triple));
  2667. /**
  2668. * On Mac M[1-9]+ LLVM will report arm64 as the
  2669. * architecture, for the purposes of wamr this is the
  2670. * same as aarch64v8 so we'll normalize it here.
  2671. */
  2672. if (!strcmp(default_arch, "arm64")) {
  2673. bh_strcpy_s(default_arch, sizeof(default_arch),
  2674. "aarch64v8");
  2675. }
  2676. arch1 = default_arch;
  2677. LLVMDisposeMessage(default_triple);
  2678. }
  2679. /**
  2680. * Set <vendor>-<sys> according to abi to generate the object file
  2681. * with the correct file format which might be different from the
  2682. * default object file format of the host, e.g., generating AOT file
  2683. * for Windows/MacOS under Linux host, or generating AOT file for
  2684. * Linux/MacOS under Windows host.
  2685. */
  2686. if (!strcmp(abi, "msvc")) {
  2687. if (!strcmp(arch1, "i386"))
  2688. vendor_sys = "-pc-win32-";
  2689. else
  2690. vendor_sys = "-pc-windows-";
  2691. }
  2692. else {
  2693. if (is_baremetal_target(arch, cpu, abi))
  2694. vendor_sys = "-unknown-none-";
  2695. else
  2696. vendor_sys = "-pc-linux-";
  2697. }
  2698. bh_assert(strlen(arch1) + strlen(vendor_sys) + strlen(abi)
  2699. < sizeof(triple_buf));
  2700. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch1,
  2701. (uint32)strlen(arch1));
  2702. bh_memcpy_s(triple_buf + strlen(arch1),
  2703. (uint32)(sizeof(triple_buf) - strlen(arch1)),
  2704. vendor_sys, (uint32)strlen(vendor_sys));
  2705. bh_memcpy_s(triple_buf + strlen(arch1) + strlen(vendor_sys),
  2706. (uint32)(sizeof(triple_buf) - strlen(arch1)
  2707. - strlen(vendor_sys)),
  2708. abi, (uint32)strlen(abi));
  2709. triple = triple_buf;
  2710. }
  2711. else if (arch) {
  2712. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  2713. const char *vendor_sys;
  2714. char *default_triple = LLVMGetDefaultTargetTriple();
  2715. if (!default_triple) {
  2716. aot_set_last_error("llvm get default target triple failed.");
  2717. goto fail;
  2718. }
  2719. if (strstr(default_triple, "windows")) {
  2720. vendor_sys = "-pc-windows-";
  2721. if (!abi)
  2722. abi = "msvc";
  2723. }
  2724. else if (strstr(default_triple, "win32")) {
  2725. vendor_sys = "-pc-win32-";
  2726. if (!abi)
  2727. abi = "msvc";
  2728. }
  2729. else if (is_baremetal_target(arch, cpu, abi)) {
  2730. vendor_sys = "-unknown-none-";
  2731. if (!abi)
  2732. abi = "gnu";
  2733. }
  2734. else {
  2735. vendor_sys = "-pc-linux-";
  2736. if (!abi)
  2737. abi = "gnu";
  2738. }
  2739. LLVMDisposeMessage(default_triple);
  2740. bh_assert(strlen(arch) + strlen(vendor_sys) + strlen(abi)
  2741. < sizeof(triple_buf));
  2742. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch,
  2743. (uint32)strlen(arch));
  2744. bh_memcpy_s(triple_buf + strlen(arch),
  2745. (uint32)(sizeof(triple_buf) - strlen(arch)), vendor_sys,
  2746. (uint32)strlen(vendor_sys));
  2747. bh_memcpy_s(triple_buf + strlen(arch) + strlen(vendor_sys),
  2748. (uint32)(sizeof(triple_buf) - strlen(arch)
  2749. - strlen(vendor_sys)),
  2750. abi, (uint32)strlen(abi));
  2751. triple = triple_buf;
  2752. }
  2753. if (!cpu && features) {
  2754. aot_set_last_error("cpu isn't specified for cpu features.");
  2755. goto fail;
  2756. }
  2757. if (!triple && !cpu) {
  2758. /* Get a triple for the host machine */
  2759. if (!(triple_norm = triple_norm_new =
  2760. LLVMGetDefaultTargetTriple())) {
  2761. aot_set_last_error("llvm get default target triple failed.");
  2762. goto fail;
  2763. }
  2764. /* Get CPU name of the host machine */
  2765. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  2766. aot_set_last_error("llvm get host cpu name failed.");
  2767. goto fail;
  2768. }
  2769. }
  2770. else if (triple) {
  2771. /* Normalize a target triple */
  2772. if (!(triple_norm = triple_norm_new =
  2773. LLVMNormalizeTargetTriple(triple))) {
  2774. snprintf(buf, sizeof(buf),
  2775. "llvm normlalize target triple (%s) failed.", triple);
  2776. aot_set_last_error(buf);
  2777. goto fail;
  2778. }
  2779. LOG_VERBOSE("triple: %s => normailized: %s", triple, triple_norm);
  2780. if (!cpu)
  2781. cpu = "";
  2782. }
  2783. else {
  2784. /* triple is NULL, cpu isn't NULL */
  2785. snprintf(buf, sizeof(buf), "target isn't specified for cpu %s.",
  2786. cpu);
  2787. aot_set_last_error(buf);
  2788. goto fail;
  2789. }
  2790. /* Add module flag and cpu feature for riscv target */
  2791. if (arch && !strncmp(arch, "riscv", 5)) {
  2792. LLVMMetadataRef meta_target_abi;
  2793. if (!(meta_target_abi = LLVMMDStringInContext2(comp_ctx->context,
  2794. abi, strlen(abi)))) {
  2795. aot_set_last_error("create metadata string failed.");
  2796. goto fail;
  2797. }
  2798. LLVMAddModuleFlag(comp_ctx->module, LLVMModuleFlagBehaviorError,
  2799. "target-abi", strlen("target-abi"),
  2800. meta_target_abi);
  2801. if (!strcmp(abi, "lp64d") || !strcmp(abi, "ilp32d")) {
  2802. if (features && !strstr(features, "+d")) {
  2803. snprintf(features_buf, sizeof(features_buf), "%s%s",
  2804. features, ",+d");
  2805. features = features_buf;
  2806. }
  2807. else if (!features) {
  2808. features = "+d";
  2809. }
  2810. }
  2811. }
  2812. if (!features)
  2813. features = "";
  2814. /* Get target with triple, note that LLVMGetTargetFromTriple()
  2815. return 0 when success, but not true. */
  2816. if (LLVMGetTargetFromTriple(triple_norm, &target, &err) != 0) {
  2817. if (err) {
  2818. LLVMDisposeMessage(err);
  2819. err = NULL;
  2820. }
  2821. snprintf(buf, sizeof(buf),
  2822. "llvm get target from triple (%s) failed", triple_norm);
  2823. aot_set_last_error(buf);
  2824. goto fail;
  2825. }
  2826. /* Save target arch */
  2827. get_target_arch_from_triple(triple_norm, comp_ctx->target_arch,
  2828. sizeof(comp_ctx->target_arch));
  2829. if (option->bounds_checks == 1 || option->bounds_checks == 0) {
  2830. /* Set by the user */
  2831. comp_ctx->enable_bound_check =
  2832. (option->bounds_checks == 1) ? true : false;
  2833. }
  2834. else {
  2835. /* Unset by the user, use the default value */
  2836. if (strstr(comp_ctx->target_arch, "64")
  2837. && !option->is_sgx_platform) {
  2838. comp_ctx->enable_bound_check = false;
  2839. }
  2840. else {
  2841. comp_ctx->enable_bound_check = true;
  2842. }
  2843. }
  2844. if (option->stack_bounds_checks == 1
  2845. || option->stack_bounds_checks == 0) {
  2846. /* Set by the user */
  2847. comp_ctx->enable_stack_bound_check =
  2848. (option->stack_bounds_checks == 1) ? true : false;
  2849. }
  2850. else {
  2851. /* Unset by the user, use the default value, it will be the same
  2852. * value as the bound check */
  2853. comp_ctx->enable_stack_bound_check = comp_ctx->enable_bound_check;
  2854. }
  2855. if ((comp_ctx->enable_stack_bound_check
  2856. || comp_ctx->enable_stack_estimation)
  2857. && option->stack_usage_file == NULL) {
  2858. if (!aot_generate_tempfile_name(
  2859. "wamrc-su", "su", comp_ctx->stack_usage_temp_file,
  2860. sizeof(comp_ctx->stack_usage_temp_file)))
  2861. goto fail;
  2862. comp_ctx->stack_usage_file = comp_ctx->stack_usage_temp_file;
  2863. }
  2864. else {
  2865. comp_ctx->stack_usage_file = option->stack_usage_file;
  2866. }
  2867. os_printf("Create AoT compiler with:\n");
  2868. os_printf(" target: %s\n", comp_ctx->target_arch);
  2869. os_printf(" target cpu: %s\n", cpu);
  2870. os_printf(" target triple: %s\n", triple_norm);
  2871. os_printf(" cpu features: %s\n", features);
  2872. os_printf(" opt level: %d\n", opt_level);
  2873. os_printf(" size level: %d\n", size_level);
  2874. switch (option->output_format) {
  2875. case AOT_LLVMIR_UNOPT_FILE:
  2876. os_printf(" output format: unoptimized LLVM IR\n");
  2877. break;
  2878. case AOT_LLVMIR_OPT_FILE:
  2879. os_printf(" output format: optimized LLVM IR\n");
  2880. break;
  2881. case AOT_FORMAT_FILE:
  2882. os_printf(" output format: AoT file\n");
  2883. break;
  2884. case AOT_OBJECT_FILE:
  2885. os_printf(" output format: native object file\n");
  2886. break;
  2887. }
  2888. LLVMSetTarget(comp_ctx->module, triple_norm);
  2889. if (!LLVMTargetHasTargetMachine(target)) {
  2890. snprintf(buf, sizeof(buf),
  2891. "no target machine for this target (%s).", triple_norm);
  2892. aot_set_last_error(buf);
  2893. goto fail;
  2894. }
  2895. /* Report error if target isn't arc and hasn't asm backend.
  2896. For arc target, as it cannot emit to memory buffer of elf file
  2897. currently, we let it emit to assembly file instead, and then call
  2898. arc-gcc to compile
  2899. asm file to elf file, and read elf file to memory buffer. */
  2900. if (strncmp(comp_ctx->target_arch, "arc", 3)
  2901. && !LLVMTargetHasAsmBackend(target)) {
  2902. snprintf(buf, sizeof(buf), "no asm backend for this target (%s).",
  2903. LLVMGetTargetName(target));
  2904. aot_set_last_error(buf);
  2905. goto fail;
  2906. }
  2907. /* Set code model */
  2908. if (size_level == 0)
  2909. code_model = LLVMCodeModelLarge;
  2910. else if (size_level == 1)
  2911. code_model = LLVMCodeModelMedium;
  2912. else if (size_level == 2)
  2913. code_model = LLVMCodeModelKernel;
  2914. else
  2915. code_model = LLVMCodeModelSmall;
  2916. /* Create the target machine */
  2917. if (!(comp_ctx->target_machine = LLVMCreateTargetMachineWithOpts(
  2918. target, triple_norm, cpu, features, opt_level,
  2919. LLVMRelocStatic, code_model, false,
  2920. comp_ctx->stack_usage_file))) {
  2921. aot_set_last_error("create LLVM target machine failed.");
  2922. goto fail;
  2923. }
  2924. /* If only to create target machine for querying information, early stop
  2925. */
  2926. if ((arch && !strcmp(arch, "help")) || (abi && !strcmp(abi, "help"))
  2927. || (cpu && !strcmp(cpu, "help"))
  2928. || (features && !strcmp(features, "+help"))) {
  2929. LOG_DEBUG(
  2930. "create LLVM target machine only for printing help info.");
  2931. goto fail;
  2932. }
  2933. }
  2934. triple = LLVMGetTargetMachineTriple(comp_ctx->target_machine);
  2935. if (!triple) {
  2936. aot_set_last_error("get target machine triple failed.");
  2937. goto fail;
  2938. }
  2939. if (strstr(triple, "linux") && !strcmp(comp_ctx->target_arch, "x86_64")) {
  2940. if (option->segue_flags) {
  2941. if (option->segue_flags & (1 << 0))
  2942. comp_ctx->enable_segue_i32_load = true;
  2943. if (option->segue_flags & (1 << 1))
  2944. comp_ctx->enable_segue_i64_load = true;
  2945. if (option->segue_flags & (1 << 2))
  2946. comp_ctx->enable_segue_f32_load = true;
  2947. if (option->segue_flags & (1 << 3))
  2948. comp_ctx->enable_segue_f64_load = true;
  2949. if (option->segue_flags & (1 << 4))
  2950. comp_ctx->enable_segue_v128_load = true;
  2951. if (option->segue_flags & (1 << 8))
  2952. comp_ctx->enable_segue_i32_store = true;
  2953. if (option->segue_flags & (1 << 9))
  2954. comp_ctx->enable_segue_i64_store = true;
  2955. if (option->segue_flags & (1 << 10))
  2956. comp_ctx->enable_segue_f32_store = true;
  2957. if (option->segue_flags & (1 << 11))
  2958. comp_ctx->enable_segue_f64_store = true;
  2959. if (option->segue_flags & (1 << 12))
  2960. comp_ctx->enable_segue_v128_store = true;
  2961. }
  2962. }
  2963. LLVMDisposeMessage(triple);
  2964. #if WASM_ENABLE_WAMR_COMPILER != 0
  2965. WASMModule *wasm_module = (WASMModule *)comp_data->wasm_module;
  2966. bool is_memory64 = false;
  2967. /* TODO: multi-memories for now assuming the memory64 flag of a memory is
  2968. * consistent across multi-memories */
  2969. if (wasm_module->import_memory_count > 0)
  2970. is_memory64 = !!(wasm_module->import_memories[0].u.memory.mem_type.flags
  2971. & MEMORY64_FLAG);
  2972. else if (wasm_module->memory_count > 0)
  2973. is_memory64 = !!(wasm_module->memories[0].flags & MEMORY64_FLAG);
  2974. if (!(option->bounds_checks == 1 || option->bounds_checks == 0)
  2975. && is_memory64) {
  2976. /* For memory64, the boundary check default value is true */
  2977. comp_ctx->enable_bound_check = true;
  2978. }
  2979. /* Return error if SIMD is disabled by command line but SIMD instructions
  2980. * are used */
  2981. if (!option->enable_simd && wasm_module->is_simd_used) {
  2982. aot_set_last_error("SIMD is disabled by --disable-simd but SIMD "
  2983. "instructions are used in this module");
  2984. goto fail;
  2985. }
  2986. /* Return error if ref-types and GC are disabled by command line but
  2987. ref-types instructions are used */
  2988. if (!option->enable_call_indirect_overlong && !option->enable_gc
  2989. && wasm_module->is_ref_types_used) {
  2990. aot_set_last_error("ref-types instruction was found, "
  2991. "try removing --disable-ref-types option "
  2992. "or adding --enable-gc option.");
  2993. goto fail;
  2994. }
  2995. /* Disable features when they are not actually used */
  2996. if (!wasm_module->is_simd_used) {
  2997. option->enable_simd = comp_ctx->enable_simd = false;
  2998. }
  2999. if (!wasm_module->is_ref_types_used) {
  3000. option->enable_ref_types = comp_ctx->enable_ref_types = false;
  3001. option->enable_call_indirect_overlong =
  3002. comp_ctx->enable_call_indirect_overlong = false;
  3003. }
  3004. if (!wasm_module->is_bulk_memory_used) {
  3005. option->enable_bulk_memory = comp_ctx->enable_bulk_memory = false;
  3006. option->enable_bulk_memory_opt = comp_ctx->enable_bulk_memory_opt =
  3007. false;
  3008. }
  3009. #endif
  3010. if (option->enable_simd && strcmp(comp_ctx->target_arch, "x86_64") != 0
  3011. && strncmp(comp_ctx->target_arch, "aarch64", 7) != 0
  3012. && strcmp(comp_ctx->target_arch, "arc") != 0) {
  3013. /* Disable simd if it isn't supported by target arch */
  3014. option->enable_simd = false;
  3015. }
  3016. if (option->enable_simd) {
  3017. char *tmp;
  3018. bool check_simd_ret;
  3019. comp_ctx->enable_simd = true;
  3020. if (!(tmp = LLVMGetTargetMachineCPU(comp_ctx->target_machine))) {
  3021. aot_set_last_error("get CPU from Target Machine fail");
  3022. goto fail;
  3023. }
  3024. check_simd_ret =
  3025. aot_check_simd_compatibility(comp_ctx->target_arch, tmp);
  3026. LLVMDisposeMessage(tmp);
  3027. if (!check_simd_ret) {
  3028. aot_set_last_error("SIMD compatibility check failed, "
  3029. "try adding --cpu=<cpu> to specify a cpu "
  3030. "or adding --disable-simd to disable SIMD");
  3031. goto fail;
  3032. }
  3033. }
  3034. if (!(target_data_ref =
  3035. LLVMCreateTargetDataLayout(comp_ctx->target_machine))) {
  3036. aot_set_last_error("create LLVM target data layout failed.");
  3037. goto fail;
  3038. }
  3039. LLVMSetModuleDataLayout(comp_ctx->module, target_data_ref);
  3040. comp_ctx->pointer_size = LLVMPointerSize(target_data_ref);
  3041. LLVMDisposeTargetData(target_data_ref);
  3042. comp_ctx->optimize = true;
  3043. if (option->output_format == AOT_LLVMIR_UNOPT_FILE)
  3044. comp_ctx->optimize = false;
  3045. /* Create metadata for llvm float experimental constrained intrinsics */
  3046. if (!(comp_ctx->fp_rounding_mode = LLVMMDStringInContext(
  3047. comp_ctx->context, fp_round, (uint32)strlen(fp_round)))
  3048. || !(comp_ctx->fp_exception_behavior = LLVMMDStringInContext(
  3049. comp_ctx->context, fp_exce, (uint32)strlen(fp_exce)))) {
  3050. aot_set_last_error("create float llvm metadata failed.");
  3051. goto fail;
  3052. }
  3053. if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context,
  3054. comp_ctx->pointer_size)) {
  3055. aot_set_last_error("create LLVM basic types failed.");
  3056. goto fail;
  3057. }
  3058. if (!aot_create_llvm_consts(&comp_ctx->llvm_consts, comp_ctx)) {
  3059. aot_set_last_error("create LLVM const values failed.");
  3060. goto fail;
  3061. }
  3062. /* set exec_env data type to int8** */
  3063. comp_ctx->exec_env_type = comp_ctx->basic_types.int8_pptr_type;
  3064. /* set aot_inst data type to int8* */
  3065. comp_ctx->aot_inst_type = INT8_PTR_TYPE;
  3066. /* Create function context for each function */
  3067. comp_ctx->func_ctx_count = comp_data->func_count;
  3068. if (comp_data->func_count > 0
  3069. && !(comp_ctx->func_ctxes =
  3070. aot_create_func_contexts(comp_data, comp_ctx)))
  3071. goto fail;
  3072. if (cpu) {
  3073. uint32 len = (uint32)strlen(cpu) + 1;
  3074. if (!(comp_ctx->target_cpu = wasm_runtime_malloc(len))) {
  3075. aot_set_last_error("allocate memory failed");
  3076. goto fail;
  3077. }
  3078. bh_memcpy_s(comp_ctx->target_cpu, len, cpu, len);
  3079. }
  3080. if (comp_ctx->disable_llvm_intrinsics)
  3081. aot_intrinsic_fill_capability_flags(comp_ctx);
  3082. ret = comp_ctx;
  3083. fail:
  3084. if (triple_norm_new)
  3085. LLVMDisposeMessage(triple_norm_new);
  3086. if (cpu_new)
  3087. LLVMDisposeMessage(cpu_new);
  3088. if (!ret)
  3089. aot_destroy_comp_context(comp_ctx);
  3090. (void)i;
  3091. return ret;
  3092. }
  3093. void
  3094. aot_destroy_comp_context(AOTCompContext *comp_ctx)
  3095. {
  3096. if (!comp_ctx)
  3097. return;
  3098. if (comp_ctx->stack_usage_file == comp_ctx->stack_usage_temp_file) {
  3099. (void)unlink(comp_ctx->stack_usage_temp_file);
  3100. }
  3101. if (comp_ctx->target_machine)
  3102. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  3103. if (comp_ctx->builder)
  3104. LLVMDisposeBuilder(comp_ctx->builder);
  3105. #if WASM_ENABLE_DEBUG_AOT != 0
  3106. if (comp_ctx->debug_builder)
  3107. LLVMDisposeDIBuilder(comp_ctx->debug_builder);
  3108. #endif
  3109. if (comp_ctx->orc_thread_safe_context)
  3110. LLVMOrcDisposeThreadSafeContext(comp_ctx->orc_thread_safe_context);
  3111. /* Note: don't dispose comp_ctx->context and comp_ctx->module as
  3112. they are disposed when disposing the thread safe context */
  3113. /* Has to be the last one */
  3114. if (comp_ctx->orc_jit)
  3115. LLVMOrcDisposeLLLazyJIT(comp_ctx->orc_jit);
  3116. if (comp_ctx->func_ctxes)
  3117. aot_destroy_func_contexts(comp_ctx, comp_ctx->func_ctxes,
  3118. comp_ctx->func_ctx_count);
  3119. if (bh_list_length(&comp_ctx->native_symbols) > 0) {
  3120. AOTNativeSymbol *sym = bh_list_first_elem(&comp_ctx->native_symbols);
  3121. while (sym) {
  3122. AOTNativeSymbol *t = bh_list_elem_next(sym);
  3123. bh_list_remove(&comp_ctx->native_symbols, sym);
  3124. wasm_runtime_free(sym);
  3125. sym = t;
  3126. }
  3127. }
  3128. if (comp_ctx->target_cpu) {
  3129. wasm_runtime_free(comp_ctx->target_cpu);
  3130. }
  3131. if (comp_ctx->aot_frame) {
  3132. wasm_runtime_free(comp_ctx->aot_frame);
  3133. }
  3134. wasm_runtime_free(comp_ctx);
  3135. }
  3136. static bool
  3137. insert_native_symbol(AOTCompContext *comp_ctx, const char *symbol, int32 idx)
  3138. {
  3139. AOTNativeSymbol *sym = wasm_runtime_malloc(sizeof(AOTNativeSymbol));
  3140. int ret;
  3141. if (!sym) {
  3142. aot_set_last_error("alloc native symbol failed.");
  3143. return false;
  3144. }
  3145. memset(sym, 0, sizeof(AOTNativeSymbol));
  3146. bh_assert(strlen(symbol) <= sizeof(sym->symbol));
  3147. ret = snprintf(sym->symbol, sizeof(sym->symbol), "%s", symbol);
  3148. if (ret < 0 || ret + 1 > (int)sizeof(sym->symbol)) {
  3149. wasm_runtime_free(sym);
  3150. aot_set_last_error_v("symbol name too long: %s", symbol);
  3151. return false;
  3152. }
  3153. sym->index = idx;
  3154. if (BH_LIST_ERROR == bh_list_insert(&comp_ctx->native_symbols, sym)) {
  3155. wasm_runtime_free(sym);
  3156. aot_set_last_error("insert native symbol to list failed.");
  3157. return false;
  3158. }
  3159. return true;
  3160. }
  3161. int32
  3162. aot_get_native_symbol_index(AOTCompContext *comp_ctx, const char *symbol)
  3163. {
  3164. int32 idx = -1;
  3165. AOTNativeSymbol *sym = NULL;
  3166. sym = bh_list_first_elem(&comp_ctx->native_symbols);
  3167. /* Lookup an existing symbol record */
  3168. while (sym) {
  3169. if (strcmp(sym->symbol, symbol) == 0) {
  3170. idx = sym->index;
  3171. break;
  3172. }
  3173. sym = bh_list_elem_next(sym);
  3174. }
  3175. /* Given symbol is not exist in list, then we alloc a new index for it */
  3176. if (idx < 0) {
  3177. if (comp_ctx->pointer_size == sizeof(uint32)
  3178. && (!strncmp(symbol, "f64#", 4) || !strncmp(symbol, "i64#", 4))) {
  3179. idx = bh_list_length(&comp_ctx->native_symbols);
  3180. /* Add 4 bytes padding on 32-bit target to make sure that
  3181. the f64 const is stored on 8-byte aligned address */
  3182. if (idx & 1) {
  3183. if (!insert_native_symbol(comp_ctx, "__ignore", idx)) {
  3184. return -1;
  3185. }
  3186. }
  3187. }
  3188. idx = bh_list_length(&comp_ctx->native_symbols);
  3189. if (!insert_native_symbol(comp_ctx, symbol, idx)) {
  3190. return -1;
  3191. }
  3192. if (comp_ctx->pointer_size == sizeof(uint32)
  3193. && (!strncmp(symbol, "f64#", 4) || !strncmp(symbol, "i64#", 4))) {
  3194. /* f64 const occupies 2 pointer slots on 32-bit target */
  3195. if (!insert_native_symbol(comp_ctx, "__ignore", idx + 1)) {
  3196. return -1;
  3197. }
  3198. }
  3199. }
  3200. return idx;
  3201. }
  3202. void
  3203. aot_value_stack_push(const AOTCompContext *comp_ctx, AOTValueStack *stack,
  3204. AOTValue *value)
  3205. {
  3206. if (!stack->value_list_head)
  3207. stack->value_list_head = stack->value_list_end = value;
  3208. else {
  3209. stack->value_list_end->next = value;
  3210. value->prev = stack->value_list_end;
  3211. stack->value_list_end = value;
  3212. }
  3213. if (comp_ctx->aot_frame) {
  3214. switch (value->type) {
  3215. case VALUE_TYPE_I32:
  3216. case VALUE_TYPE_I1:
  3217. push_i32(comp_ctx->aot_frame, value);
  3218. break;
  3219. case VALUE_TYPE_I64:
  3220. push_i64(comp_ctx->aot_frame, value);
  3221. break;
  3222. case VALUE_TYPE_F32:
  3223. push_f32(comp_ctx->aot_frame, value);
  3224. break;
  3225. case VALUE_TYPE_F64:
  3226. push_f64(comp_ctx->aot_frame, value);
  3227. break;
  3228. case VALUE_TYPE_V128:
  3229. push_v128(comp_ctx->aot_frame, value);
  3230. break;
  3231. case VALUE_TYPE_FUNCREF:
  3232. case VALUE_TYPE_EXTERNREF:
  3233. push_ref(comp_ctx->aot_frame, value);
  3234. break;
  3235. #if WASM_ENABLE_GC != 0
  3236. case VALUE_TYPE_GC_REF:
  3237. bh_assert(comp_ctx->enable_gc);
  3238. push_gc_ref(comp_ctx->aot_frame, value);
  3239. break;
  3240. #endif
  3241. default:
  3242. bh_assert(0);
  3243. break;
  3244. }
  3245. }
  3246. }
  3247. AOTValue *
  3248. aot_value_stack_pop(const AOTCompContext *comp_ctx, AOTValueStack *stack)
  3249. {
  3250. AOTValue *value = stack->value_list_end;
  3251. bh_assert(stack->value_list_end);
  3252. if (stack->value_list_head == stack->value_list_end)
  3253. stack->value_list_head = stack->value_list_end = NULL;
  3254. else {
  3255. stack->value_list_end = stack->value_list_end->prev;
  3256. stack->value_list_end->next = NULL;
  3257. value->prev = NULL;
  3258. }
  3259. if (comp_ctx->aot_frame) {
  3260. bh_assert(value);
  3261. bh_assert(value->value == (comp_ctx->aot_frame->sp - 1)->value);
  3262. bh_assert(value->type == (comp_ctx->aot_frame->sp - 1)->type);
  3263. switch (value->type) {
  3264. case VALUE_TYPE_I32:
  3265. case VALUE_TYPE_I1:
  3266. pop_i32(comp_ctx->aot_frame);
  3267. break;
  3268. case VALUE_TYPE_I64:
  3269. pop_i64(comp_ctx->aot_frame);
  3270. break;
  3271. case VALUE_TYPE_F32:
  3272. pop_f32(comp_ctx->aot_frame);
  3273. break;
  3274. case VALUE_TYPE_F64:
  3275. pop_f64(comp_ctx->aot_frame);
  3276. break;
  3277. case VALUE_TYPE_V128:
  3278. pop_v128(comp_ctx->aot_frame);
  3279. break;
  3280. case VALUE_TYPE_FUNCREF:
  3281. case VALUE_TYPE_EXTERNREF:
  3282. pop_ref(comp_ctx->aot_frame);
  3283. break;
  3284. #if WASM_ENABLE_GC != 0
  3285. case VALUE_TYPE_GC_REF:
  3286. bh_assert(comp_ctx->enable_gc);
  3287. pop_gc_ref(comp_ctx->aot_frame);
  3288. break;
  3289. #endif
  3290. default:
  3291. bh_assert(0);
  3292. break;
  3293. }
  3294. }
  3295. return value;
  3296. }
  3297. void
  3298. aot_value_stack_destroy(AOTCompContext *comp_ctx, AOTValueStack *stack)
  3299. {
  3300. AOTValue *value = stack->value_list_head, *p;
  3301. while (value) {
  3302. p = value->next;
  3303. wasm_runtime_free(value);
  3304. value = p;
  3305. }
  3306. stack->value_list_head = NULL;
  3307. stack->value_list_end = NULL;
  3308. }
  3309. void
  3310. aot_block_stack_push(AOTBlockStack *stack, AOTBlock *block)
  3311. {
  3312. if (!stack->block_list_head)
  3313. stack->block_list_head = stack->block_list_end = block;
  3314. else {
  3315. stack->block_list_end->next = block;
  3316. block->prev = stack->block_list_end;
  3317. stack->block_list_end = block;
  3318. }
  3319. }
  3320. AOTBlock *
  3321. aot_block_stack_pop(AOTBlockStack *stack)
  3322. {
  3323. AOTBlock *block = stack->block_list_end;
  3324. bh_assert(stack->block_list_end);
  3325. if (stack->block_list_head == stack->block_list_end)
  3326. stack->block_list_head = stack->block_list_end = NULL;
  3327. else {
  3328. stack->block_list_end = stack->block_list_end->prev;
  3329. stack->block_list_end->next = NULL;
  3330. block->prev = NULL;
  3331. }
  3332. return block;
  3333. }
  3334. void
  3335. aot_block_stack_destroy(AOTCompContext *comp_ctx, AOTBlockStack *stack)
  3336. {
  3337. AOTBlock *block = stack->block_list_head, *p;
  3338. while (block) {
  3339. p = block->next;
  3340. aot_value_stack_destroy(comp_ctx, &block->value_stack);
  3341. aot_block_destroy(comp_ctx, block);
  3342. block = p;
  3343. }
  3344. stack->block_list_head = NULL;
  3345. stack->block_list_end = NULL;
  3346. }
  3347. void
  3348. aot_block_destroy(AOTCompContext *comp_ctx, AOTBlock *block)
  3349. {
  3350. aot_value_stack_destroy(comp_ctx, &block->value_stack);
  3351. if (block->param_types)
  3352. wasm_runtime_free(block->param_types);
  3353. if (block->param_phis)
  3354. wasm_runtime_free(block->param_phis);
  3355. if (block->else_param_phis)
  3356. wasm_runtime_free(block->else_param_phis);
  3357. if (block->result_types)
  3358. wasm_runtime_free(block->result_types);
  3359. if (block->result_phis)
  3360. wasm_runtime_free(block->result_phis);
  3361. wasm_runtime_free(block);
  3362. }
  3363. bool
  3364. aot_checked_addr_list_add(AOTFuncContext *func_ctx, uint32 local_idx,
  3365. uint64 offset, uint32 bytes)
  3366. {
  3367. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  3368. if (!(node = wasm_runtime_malloc(sizeof(AOTCheckedAddr)))) {
  3369. aot_set_last_error("allocate memory failed.");
  3370. return false;
  3371. }
  3372. node->local_idx = local_idx;
  3373. node->offset = offset;
  3374. node->bytes = bytes;
  3375. node->next = func_ctx->checked_addr_list;
  3376. func_ctx->checked_addr_list = node;
  3377. return true;
  3378. }
  3379. void
  3380. aot_checked_addr_list_del(AOTFuncContext *func_ctx, uint32 local_idx)
  3381. {
  3382. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  3383. AOTCheckedAddr *node_prev = NULL, *node_next;
  3384. while (node) {
  3385. node_next = node->next;
  3386. if (node->local_idx == local_idx) {
  3387. if (!node_prev)
  3388. func_ctx->checked_addr_list = node_next;
  3389. else
  3390. node_prev->next = node_next;
  3391. wasm_runtime_free(node);
  3392. }
  3393. else {
  3394. node_prev = node;
  3395. }
  3396. node = node_next;
  3397. }
  3398. }
  3399. bool
  3400. aot_checked_addr_list_find(AOTFuncContext *func_ctx, uint32 local_idx,
  3401. uint64 offset, uint32 bytes)
  3402. {
  3403. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  3404. while (node) {
  3405. if (node->local_idx == local_idx && node->offset == offset
  3406. && node->bytes >= bytes) {
  3407. return true;
  3408. }
  3409. node = node->next;
  3410. }
  3411. return false;
  3412. }
  3413. void
  3414. aot_checked_addr_list_destroy(AOTFuncContext *func_ctx)
  3415. {
  3416. AOTCheckedAddr *node = func_ctx->checked_addr_list, *node_next;
  3417. while (node) {
  3418. node_next = node->next;
  3419. wasm_runtime_free(node);
  3420. node = node_next;
  3421. }
  3422. func_ctx->checked_addr_list = NULL;
  3423. }
  3424. bool
  3425. aot_build_zero_function_ret(const AOTCompContext *comp_ctx,
  3426. AOTFuncContext *func_ctx, AOTFuncType *func_type)
  3427. {
  3428. LLVMValueRef ret = NULL;
  3429. if (func_type->result_count) {
  3430. switch (func_type->types[func_type->param_count]) {
  3431. case VALUE_TYPE_I32:
  3432. ret = LLVMBuildRet(comp_ctx->builder, I32_ZERO);
  3433. break;
  3434. case VALUE_TYPE_I64:
  3435. ret = LLVMBuildRet(comp_ctx->builder, I64_ZERO);
  3436. break;
  3437. case VALUE_TYPE_F32:
  3438. ret = LLVMBuildRet(comp_ctx->builder, F32_ZERO);
  3439. break;
  3440. case VALUE_TYPE_F64:
  3441. ret = LLVMBuildRet(comp_ctx->builder, F64_ZERO);
  3442. break;
  3443. case VALUE_TYPE_V128:
  3444. ret =
  3445. LLVMBuildRet(comp_ctx->builder, LLVM_CONST(i64x2_vec_zero));
  3446. break;
  3447. case VALUE_TYPE_FUNCREF:
  3448. case VALUE_TYPE_EXTERNREF:
  3449. if (comp_ctx->enable_ref_types)
  3450. ret = LLVMBuildRet(comp_ctx->builder, REF_NULL);
  3451. #if WASM_ENABLE_GC != 0
  3452. else if (comp_ctx->enable_gc)
  3453. ret = LLVMBuildRet(comp_ctx->builder, GC_REF_NULL);
  3454. #endif
  3455. else
  3456. bh_assert(0);
  3457. break;
  3458. #if WASM_ENABLE_GC != 0
  3459. case REF_TYPE_NULLFUNCREF:
  3460. case REF_TYPE_NULLEXTERNREF:
  3461. case REF_TYPE_NULLREF:
  3462. /* case REF_TYPE_FUNCREF: */
  3463. /* case REF_TYPE_EXTERNREF: */
  3464. case REF_TYPE_ANYREF:
  3465. case REF_TYPE_EQREF:
  3466. case REF_TYPE_HT_NULLABLE:
  3467. case REF_TYPE_HT_NON_NULLABLE:
  3468. case REF_TYPE_I31REF:
  3469. case REF_TYPE_STRUCTREF:
  3470. case REF_TYPE_ARRAYREF:
  3471. #if WASM_ENABLE_STRINGREF != 0
  3472. case REF_TYPE_STRINGREF:
  3473. case REF_TYPE_STRINGVIEWWTF8:
  3474. case REF_TYPE_STRINGVIEWWTF16:
  3475. case REF_TYPE_STRINGVIEWITER:
  3476. #endif
  3477. bh_assert(comp_ctx->enable_gc);
  3478. ret = LLVMBuildRet(comp_ctx->builder, GC_REF_NULL);
  3479. break;
  3480. #endif
  3481. default:
  3482. bh_assert(0);
  3483. }
  3484. }
  3485. else {
  3486. ret = LLVMBuildRetVoid(comp_ctx->builder);
  3487. }
  3488. if (!ret) {
  3489. aot_set_last_error("llvm build ret failed.");
  3490. return false;
  3491. }
  3492. #if WASM_ENABLE_DEBUG_AOT != 0
  3493. /* debug_func is NULL for precheck function */
  3494. if (func_ctx->debug_func != NULL) {
  3495. LLVMMetadataRef return_location =
  3496. dwarf_gen_func_ret_location(comp_ctx, func_ctx);
  3497. LLVMInstructionSetDebugLoc(ret, return_location);
  3498. }
  3499. #endif
  3500. return true;
  3501. }
  3502. static LLVMValueRef
  3503. __call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  3504. const AOTFuncContext *func_ctx, const char *name,
  3505. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  3506. int param_count, LLVMValueRef *param_values)
  3507. {
  3508. LLVMValueRef func, ret;
  3509. LLVMTypeRef func_type;
  3510. const char *symname;
  3511. int32 func_idx;
  3512. if (comp_ctx->disable_llvm_intrinsics
  3513. && aot_intrinsic_check_capability(comp_ctx, name)) {
  3514. if (func_ctx == NULL) {
  3515. aot_set_last_error_v("invalid func_ctx for intrinsic: %s", name);
  3516. return NULL;
  3517. }
  3518. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  3519. (uint32)param_count, false))) {
  3520. aot_set_last_error("create LLVM intrinsic function type failed.");
  3521. return NULL;
  3522. }
  3523. if (!(func_type = LLVMPointerType(func_type, 0))) {
  3524. aot_set_last_error(
  3525. "create LLVM intrinsic function pointer type failed.");
  3526. return NULL;
  3527. }
  3528. if (!(symname = aot_intrinsic_get_symbol(name))) {
  3529. aot_set_last_error_v("runtime intrinsic not implemented: %s\n",
  3530. name);
  3531. return NULL;
  3532. }
  3533. func_idx =
  3534. aot_get_native_symbol_index((AOTCompContext *)comp_ctx, symname);
  3535. if (func_idx < 0) {
  3536. aot_set_last_error_v("get runtime intrinsc index failed: %s\n",
  3537. name);
  3538. return NULL;
  3539. }
  3540. if (!(func = aot_get_func_from_table(comp_ctx, func_ctx->native_symbol,
  3541. func_type, func_idx))) {
  3542. aot_set_last_error_v("get runtime intrinsc failed: %s\n", name);
  3543. return NULL;
  3544. }
  3545. }
  3546. else {
  3547. /* Declare llvm intrinsic function if necessary */
  3548. if (!(func = LLVMGetNamedFunction(func_ctx->module, name))) {
  3549. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  3550. (uint32)param_count, false))) {
  3551. aot_set_last_error(
  3552. "create LLVM intrinsic function type failed.");
  3553. return NULL;
  3554. }
  3555. if (!(func = LLVMAddFunction(func_ctx->module, name, func_type))) {
  3556. aot_set_last_error("add LLVM intrinsic function failed.");
  3557. return NULL;
  3558. }
  3559. }
  3560. }
  3561. #if LLVM_VERSION_MAJOR >= 14
  3562. func_type =
  3563. LLVMFunctionType(ret_type, param_types, (uint32)param_count, false);
  3564. #endif
  3565. /* Call the LLVM intrinsic function */
  3566. if (!(ret = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values,
  3567. (uint32)param_count, "call"))) {
  3568. aot_set_last_error("llvm build intrinsic call failed.");
  3569. return NULL;
  3570. }
  3571. return ret;
  3572. }
  3573. LLVMValueRef
  3574. aot_call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  3575. const AOTFuncContext *func_ctx, const char *intrinsic,
  3576. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  3577. int param_count, ...)
  3578. {
  3579. LLVMValueRef *param_values, ret;
  3580. va_list argptr;
  3581. uint64 total_size;
  3582. int i = 0;
  3583. /* Create param values */
  3584. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  3585. if (total_size >= UINT32_MAX
  3586. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  3587. aot_set_last_error("allocate memory for param values failed.");
  3588. return false;
  3589. }
  3590. /* Load each param value */
  3591. va_start(argptr, param_count);
  3592. while (i < param_count)
  3593. param_values[i++] = va_arg(argptr, LLVMValueRef);
  3594. va_end(argptr);
  3595. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  3596. param_types, param_count, param_values);
  3597. wasm_runtime_free(param_values);
  3598. return ret;
  3599. }
  3600. LLVMValueRef
  3601. aot_call_llvm_intrinsic_v(const AOTCompContext *comp_ctx,
  3602. const AOTFuncContext *func_ctx, const char *intrinsic,
  3603. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  3604. int param_count, va_list param_value_list)
  3605. {
  3606. LLVMValueRef *param_values, ret;
  3607. uint64 total_size;
  3608. int i = 0;
  3609. /* Create param values */
  3610. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  3611. if (total_size >= UINT32_MAX
  3612. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  3613. aot_set_last_error("allocate memory for param values failed.");
  3614. return false;
  3615. }
  3616. /* Load each param value */
  3617. while (i < param_count)
  3618. param_values[i++] = va_arg(param_value_list, LLVMValueRef);
  3619. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  3620. param_types, param_count, param_values);
  3621. wasm_runtime_free(param_values);
  3622. return ret;
  3623. }
  3624. LLVMValueRef
  3625. aot_get_func_from_table(const AOTCompContext *comp_ctx, LLVMValueRef base,
  3626. LLVMTypeRef func_type, int32 index)
  3627. {
  3628. LLVMValueRef func;
  3629. LLVMValueRef func_addr;
  3630. if (!(func_addr = I32_CONST(index))) {
  3631. aot_set_last_error("construct function index failed.");
  3632. goto fail;
  3633. }
  3634. if (!(func_addr =
  3635. LLVMBuildInBoundsGEP2(comp_ctx->builder, OPQ_PTR_TYPE, base,
  3636. &func_addr, 1, "func_addr"))) {
  3637. aot_set_last_error("get function addr by index failed.");
  3638. goto fail;
  3639. }
  3640. func =
  3641. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, func_addr, "func_tmp");
  3642. if (func == NULL) {
  3643. aot_set_last_error("get function pointer failed.");
  3644. goto fail;
  3645. }
  3646. if (!(func =
  3647. LLVMBuildBitCast(comp_ctx->builder, func, func_type, "func"))) {
  3648. aot_set_last_error("cast function failed.");
  3649. goto fail;
  3650. }
  3651. return func;
  3652. fail:
  3653. return NULL;
  3654. }
  3655. LLVMValueRef
  3656. aot_load_const_from_table(AOTCompContext *comp_ctx, LLVMValueRef base,
  3657. const WASMValue *value, uint8 value_type)
  3658. {
  3659. LLVMValueRef const_index, const_addr, const_value;
  3660. LLVMTypeRef const_ptr_type, const_type;
  3661. char buf[128] = { 0 };
  3662. int32 index;
  3663. switch (value_type) {
  3664. case VALUE_TYPE_I32:
  3665. /* Store the raw int bits of i32 const as a hex string */
  3666. snprintf(buf, sizeof(buf), "i32#%08" PRIX32, value->i32);
  3667. const_ptr_type = INT32_PTR_TYPE;
  3668. const_type = I32_TYPE;
  3669. break;
  3670. case VALUE_TYPE_I64:
  3671. /* Store the raw int bits of i64 const as a hex string */
  3672. snprintf(buf, sizeof(buf), "i64#%016" PRIX64, value->i64);
  3673. const_ptr_type = INT64_PTR_TYPE;
  3674. const_type = I64_TYPE;
  3675. break;
  3676. case VALUE_TYPE_F32:
  3677. /* Store the raw int bits of f32 const as a hex string */
  3678. snprintf(buf, sizeof(buf), "f32#%08" PRIX32, value->i32);
  3679. const_ptr_type = F32_PTR_TYPE;
  3680. const_type = F32_TYPE;
  3681. break;
  3682. case VALUE_TYPE_F64:
  3683. /* Store the raw int bits of f64 const as a hex string */
  3684. snprintf(buf, sizeof(buf), "f64#%016" PRIX64, value->i64);
  3685. const_ptr_type = F64_PTR_TYPE;
  3686. const_type = F64_TYPE;
  3687. break;
  3688. default:
  3689. bh_assert(0);
  3690. return NULL;
  3691. }
  3692. /* Load f32/f64 const from exec_env->native_symbol[index] */
  3693. index = aot_get_native_symbol_index(comp_ctx, buf);
  3694. if (index < 0) {
  3695. return NULL;
  3696. }
  3697. if (!(const_index = I32_CONST(index))) {
  3698. aot_set_last_error("construct const index failed.");
  3699. return NULL;
  3700. }
  3701. if (!(const_addr =
  3702. LLVMBuildInBoundsGEP2(comp_ctx->builder, OPQ_PTR_TYPE, base,
  3703. &const_index, 1, "const_addr_tmp"))) {
  3704. aot_set_last_error("get const addr by index failed.");
  3705. return NULL;
  3706. }
  3707. if (!(const_addr = LLVMBuildBitCast(comp_ctx->builder, const_addr,
  3708. const_ptr_type, "const_addr"))) {
  3709. aot_set_last_error("cast const failed.");
  3710. return NULL;
  3711. }
  3712. if (!(const_value = LLVMBuildLoad2(comp_ctx->builder, const_type,
  3713. const_addr, "const_value"))) {
  3714. aot_set_last_error("load const failed.");
  3715. return NULL;
  3716. }
  3717. (void)const_type;
  3718. return const_value;
  3719. }
  3720. bool
  3721. aot_set_cond_br_weights(AOTCompContext *comp_ctx, LLVMValueRef cond_br,
  3722. int32 weights_true, int32 weights_false)
  3723. {
  3724. LLVMMetadataRef md_nodes[3], meta_data;
  3725. LLVMValueRef meta_data_as_value;
  3726. md_nodes[0] = LLVMMDStringInContext2(comp_ctx->context, "branch_weights",
  3727. strlen("branch_weights"));
  3728. md_nodes[1] = LLVMValueAsMetadata(I32_CONST(weights_true));
  3729. md_nodes[2] = LLVMValueAsMetadata(I32_CONST(weights_false));
  3730. meta_data = LLVMMDNodeInContext2(comp_ctx->context, md_nodes, 3);
  3731. meta_data_as_value = LLVMMetadataAsValue(comp_ctx->context, meta_data);
  3732. LLVMSetMetadata(cond_br, 2, meta_data_as_value);
  3733. return true;
  3734. }