aot_llvm.c 120 KB

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