llvm_backend_proc.cpp 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. gb_internal LLVMValueRef lb_call_intrinsic(lbProcedure *p, const char *name, LLVMValueRef* args, unsigned arg_count, LLVMTypeRef* types, unsigned type_count) {
  2. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  4. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, type_count);
  5. LLVMTypeRef call_type = LLVMIntrinsicGetType(p->module->ctx, id, types, type_count);
  6. return LLVMBuildCall2(p->builder, call_type, ip, args, arg_count, "");
  7. }
  8. gb_internal void lb_mem_copy_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  9. dst = lb_emit_conv(p, dst, t_rawptr);
  10. src = lb_emit_conv(p, src, t_rawptr);
  11. len = lb_emit_conv(p, len, t_int);
  12. char const *name = "llvm.memmove";
  13. if (LLVMIsConstant(len.value)) {
  14. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  15. if (const_len <= 4*build_context.int_size) {
  16. name = "llvm.memmove.inline";
  17. }
  18. }
  19. LLVMTypeRef types[3] = {
  20. lb_type(p->module, t_rawptr),
  21. lb_type(p->module, t_rawptr),
  22. lb_type(p->module, t_int)
  23. };
  24. LLVMValueRef args[4] = {
  25. dst.value,
  26. src.value,
  27. len.value,
  28. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile)
  29. };
  30. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  31. }
  32. gb_internal void lb_mem_copy_non_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  33. dst = lb_emit_conv(p, dst, t_rawptr);
  34. src = lb_emit_conv(p, src, t_rawptr);
  35. len = lb_emit_conv(p, len, t_int);
  36. char const *name = "llvm.memcpy";
  37. if (LLVMIsConstant(len.value)) {
  38. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  39. if (const_len <= 4*build_context.int_size) {
  40. name = "llvm.memcpy.inline";
  41. }
  42. }
  43. LLVMTypeRef types[3] = {
  44. lb_type(p->module, t_rawptr),
  45. lb_type(p->module, t_rawptr),
  46. lb_type(p->module, t_int)
  47. };
  48. LLVMValueRef args[4] = {
  49. dst.value,
  50. src.value,
  51. len.value,
  52. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile) };
  53. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  54. }
  55. gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  56. GB_ASSERT(entity != nullptr);
  57. GB_ASSERT(entity->kind == Entity_Procedure);
  58. if (!entity->Procedure.is_foreign) {
  59. if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  60. GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false));
  61. }
  62. }
  63. String link_name = {};
  64. if (ignore_body) {
  65. lbModule *other_module = lb_module_of_entity(m->gen, entity);
  66. link_name = lb_get_entity_name(other_module, entity);
  67. } else {
  68. link_name = lb_get_entity_name(m, entity);
  69. }
  70. {
  71. StringHashKey key = string_hash_string(link_name);
  72. lbValue *found = string_map_get(&m->members, key);
  73. if (found) {
  74. lb_add_entity(m, entity, *found);
  75. return string_map_must_get(&m->procedures, key);
  76. }
  77. }
  78. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  79. p->module = m;
  80. entity->code_gen_module = m;
  81. entity->code_gen_procedure = p;
  82. p->entity = entity;
  83. p->name = link_name;
  84. DeclInfo *decl = entity->decl_info;
  85. ast_node(pl, ProcLit, decl->proc_lit);
  86. Type *pt = base_type(entity->type);
  87. GB_ASSERT(pt->kind == Type_Proc);
  88. p->type = entity->type;
  89. p->type_expr = decl->type_expr;
  90. p->body = pl->body;
  91. p->inlining = pl->inlining;
  92. p->is_foreign = entity->Procedure.is_foreign;
  93. p->is_export = entity->Procedure.is_export;
  94. p->is_entry_point = false;
  95. gbAllocator a = heap_allocator();
  96. p->children.allocator = a;
  97. p->defer_stmts.allocator = a;
  98. p->blocks.allocator = a;
  99. p->branch_blocks.allocator = a;
  100. p->context_stack.allocator = a;
  101. p->scope_stack.allocator = a;
  102. // map_init(&p->selector_values, 0);
  103. // map_init(&p->selector_addr, 0);
  104. // map_init(&p->tuple_fix_map, 0);
  105. if (p->is_foreign) {
  106. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  107. }
  108. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  109. {
  110. TEMPORARY_ALLOCATOR_GUARD();
  111. char *c_link_name = alloc_cstring(temporary_allocator(), p->name);
  112. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  113. }
  114. lb_ensure_abi_function_type(m, p);
  115. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  116. if (pt->Proc.diverging) {
  117. lb_add_attribute_to_proc(m, p->value, "noreturn");
  118. }
  119. if (pt->Proc.calling_convention == ProcCC_Naked) {
  120. lb_add_attribute_to_proc(m, p->value, "naked");
  121. }
  122. if (!entity->Procedure.is_foreign && build_context.disable_red_zone) {
  123. lb_add_attribute_to_proc(m, p->value, "noredzone");
  124. }
  125. switch (p->inlining) {
  126. case ProcInlining_inline:
  127. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  128. break;
  129. case ProcInlining_no_inline:
  130. lb_add_attribute_to_proc(m, p->value, "noinline");
  131. break;
  132. }
  133. switch (entity->Procedure.optimization_mode) {
  134. case ProcedureOptimizationMode_None:
  135. break;
  136. case ProcedureOptimizationMode_Minimal:
  137. lb_add_attribute_to_proc(m, p->value, "optnone");
  138. lb_add_attribute_to_proc(m, p->value, "noinline");
  139. break;
  140. case ProcedureOptimizationMode_Size:
  141. lb_add_attribute_to_proc(m, p->value, "optsize");
  142. break;
  143. case ProcedureOptimizationMode_Speed:
  144. // TODO(bill): handle this correctly
  145. lb_add_attribute_to_proc(m, p->value, "optsize");
  146. break;
  147. }
  148. if (pt->Proc.enable_target_feature.len != 0) {
  149. gbString feature_str = gb_string_make(temporary_allocator(), "");
  150. String_Iterator it = {pt->Proc.enable_target_feature, 0};
  151. bool first = true;
  152. for (;;) {
  153. String str = string_split_iterator(&it, ',');
  154. if (str == "") break;
  155. if (!first) {
  156. feature_str = gb_string_appendc(feature_str, ",");
  157. }
  158. first = false;
  159. feature_str = gb_string_appendc(feature_str, "+");
  160. feature_str = gb_string_append_length(feature_str, str.text, str.len);
  161. }
  162. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("target-features"), make_string_c(feature_str));
  163. }
  164. if (entity->flags & EntityFlag_Cold) {
  165. lb_add_attribute_to_proc(m, p->value, "cold");
  166. }
  167. if (p->is_export) {
  168. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  169. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  170. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  171. lb_set_wasm_export_attributes(p->value, p->name);
  172. } else if (!p->is_foreign) {
  173. if (USE_SEPARATE_MODULES) {
  174. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  175. } else {
  176. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  177. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  178. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  179. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  180. GB_ASSERT(entity->kind == Entity_Procedure);
  181. String link_name = entity->Procedure.link_name;
  182. if (entity->flags & EntityFlag_CustomLinkName &&
  183. link_name != "") {
  184. if (string_starts_with(link_name, str_lit("__"))) {
  185. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  186. } else {
  187. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  188. }
  189. }
  190. }
  191. }
  192. }
  193. lb_set_linkage_from_entity_flags(p->module, p->value, entity->flags);
  194. if (p->is_foreign) {
  195. lb_set_wasm_import_attributes(p->value, entity, p->name);
  196. }
  197. // NOTE(bill): offset==0 is the return value
  198. isize offset = 1;
  199. if (pt->Proc.return_by_pointer) {
  200. offset = 2;
  201. }
  202. isize parameter_index = 0;
  203. if (pt->Proc.param_count) {
  204. TypeTuple *params = &pt->Proc.params->Tuple;
  205. for (isize i = 0; i < pt->Proc.param_count; i++) {
  206. Entity *e = params->variables[i];
  207. if (e->kind != Entity_Variable) {
  208. continue;
  209. }
  210. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  211. continue;
  212. }
  213. if (e->flags&EntityFlag_NoAlias) {
  214. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  215. }
  216. parameter_index += 1;
  217. }
  218. }
  219. if (ignore_body) {
  220. p->body = nullptr;
  221. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  222. }
  223. if (m->debug_builder) { // Debug Information
  224. Type *bt = base_type(p->type);
  225. unsigned line = cast(unsigned)entity->token.pos.line;
  226. LLVMMetadataRef scope = nullptr;
  227. LLVMMetadataRef file = nullptr;
  228. LLVMMetadataRef type = nullptr;
  229. scope = p->module->debug_compile_unit;
  230. type = lb_debug_type_internal_proc(m, bt);
  231. Ast *ident = entity->identifier.load();
  232. if (entity->file != nullptr) {
  233. file = lb_get_llvm_metadata(m, entity->file);
  234. scope = file;
  235. } else if (ident != nullptr && ident->file_id != 0) {
  236. file = lb_get_llvm_metadata(m, ident->file());
  237. scope = file;
  238. } else if (entity->scope != nullptr) {
  239. file = lb_get_llvm_metadata(m, entity->scope->file);
  240. scope = file;
  241. }
  242. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  243. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  244. LLVMBool is_local_to_unit = false;
  245. LLVMBool is_definition = p->body != nullptr;
  246. unsigned scope_line = line;
  247. u32 flags = LLVMDIFlagStaticMember;
  248. LLVMBool is_optimized = false;
  249. if (bt->Proc.diverging) {
  250. flags |= LLVMDIFlagNoReturn;
  251. }
  252. if (p->body == nullptr) {
  253. flags |= LLVMDIFlagPrototyped;
  254. is_optimized = false;
  255. }
  256. if (p->body != nullptr) {
  257. // String debug_name = entity->token.string.text;
  258. String debug_name = p->name;
  259. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  260. cast(char const *)debug_name.text, debug_name.len,
  261. cast(char const *)p->name.text, p->name.len,
  262. file, line, type,
  263. is_local_to_unit, is_definition,
  264. scope_line, cast(LLVMDIFlags)flags, is_optimized
  265. );
  266. GB_ASSERT(p->debug_info != nullptr);
  267. LLVMSetSubprogram(p->value, p->debug_info);
  268. lb_set_llvm_metadata(m, p, p->debug_info);
  269. }
  270. }
  271. if (p->body && entity->pkg && ((entity->pkg->kind == Package_Normal) || (entity->pkg->kind == Package_Init))) {
  272. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  273. lb_add_attribute_to_proc(m, p->value, "sanitize_address");
  274. }
  275. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  276. lb_add_attribute_to_proc(m, p->value, "sanitize_memory");
  277. }
  278. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  279. lb_add_attribute_to_proc(m, p->value, "sanitize_thread");
  280. }
  281. }
  282. if (p->body && entity->Procedure.has_instrumentation) {
  283. Entity *instrumentation_enter = m->info->instrumentation_enter_entity;
  284. Entity *instrumentation_exit = m->info->instrumentation_exit_entity;
  285. if (instrumentation_enter && instrumentation_exit) {
  286. String enter = lb_get_entity_name(m, instrumentation_enter);
  287. String exit = lb_get_entity_name(m, instrumentation_exit);
  288. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("instrument-function-entry"), enter);
  289. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("instrument-function-exit"), exit);
  290. }
  291. }
  292. lbValue proc_value = {p->value, p->type};
  293. lb_add_entity(m, entity, proc_value);
  294. lb_add_member(m, p->name, proc_value);
  295. lb_add_procedure_value(m, p);
  296. return p;
  297. }
  298. gb_internal lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  299. {
  300. lbValue *found = string_map_get(&m->members, link_name);
  301. GB_ASSERT_MSG(found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name));
  302. }
  303. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  304. p->module = m;
  305. p->name = link_name;
  306. p->type = type;
  307. p->type_expr = nullptr;
  308. p->body = nullptr;
  309. p->tags = 0;
  310. p->inlining = ProcInlining_none;
  311. p->is_foreign = false;
  312. p->is_export = false;
  313. p->is_entry_point = false;
  314. gbAllocator a = permanent_allocator();
  315. p->children.allocator = a;
  316. p->defer_stmts.allocator = a;
  317. p->blocks.allocator = a;
  318. p->branch_blocks.allocator = a;
  319. p->context_stack.allocator = a;
  320. map_init(&p->tuple_fix_map, 0);
  321. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  322. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  323. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  324. Type *pt = p->type;
  325. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  326. if (!is_arch_wasm()) {
  327. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  328. }
  329. LLVMSetFunctionCallConv(p->value, cc_kind);
  330. lbValue proc_value = {p->value, p->type};
  331. lb_add_member(m, p->name, proc_value);
  332. lb_add_procedure_value(m, p);
  333. // NOTE(bill): offset==0 is the return value
  334. isize offset = 1;
  335. if (pt->Proc.return_by_pointer) {
  336. lb_add_proc_attribute_at_index(p, 1, "sret");
  337. lb_add_proc_attribute_at_index(p, 1, "noalias");
  338. offset = 2;
  339. }
  340. isize parameter_index = 0;
  341. if (pt->Proc.calling_convention == ProcCC_Odin) {
  342. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  343. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  344. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  345. }
  346. return p;
  347. }
  348. // gb_internal lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  349. // lbParamPasskind kind = lbParamPass_Value;
  350. // if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  351. // if (is_type_pointer(abi_type)) {
  352. // GB_ASSERT(e->kind == Entity_Variable);
  353. // Type *av = core_type(type_deref(abi_type));
  354. // if (are_types_identical(av, core_type(e->type))) {
  355. // kind = lbParamPass_Pointer;
  356. // if (e->flags&EntityFlag_Value) {
  357. // kind = lbParamPass_ConstRef;
  358. // }
  359. // } else {
  360. // kind = lbParamPass_BitCast;
  361. // }
  362. // } else if (is_type_integer(abi_type)) {
  363. // kind = lbParamPass_Integer;
  364. // } else if (abi_type == t_llvm_bool) {
  365. // kind = lbParamPass_Value;
  366. // } else if (is_type_boolean(abi_type)) {
  367. // kind = lbParamPass_Integer;
  368. // } else if (is_type_simd_vector(abi_type)) {
  369. // kind = lbParamPass_BitCast;
  370. // } else if (is_type_float(abi_type)) {
  371. // kind = lbParamPass_BitCast;
  372. // } else if (is_type_tuple(abi_type)) {
  373. // kind = lbParamPass_Tuple;
  374. // } else if (is_type_proc(abi_type)) {
  375. // kind = lbParamPass_Value;
  376. // } else {
  377. // GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  378. // }
  379. // }
  380. // if (kind_) *kind_ = kind;
  381. // lbValue res = {};
  382. // res.value = LLVMGetParam(p->value, cast(unsigned)index);
  383. // res.type = abi_type;
  384. // return res;
  385. // }
  386. gb_internal void lb_start_block(lbProcedure *p, lbBlock *b) {
  387. GB_ASSERT(b != nullptr);
  388. if (!b->appended) {
  389. b->appended = true;
  390. LLVMAppendExistingBasicBlock(p->value, b->block);
  391. }
  392. LLVMPositionBuilderAtEnd(p->builder, b->block);
  393. p->curr_block = b;
  394. }
  395. gb_internal void lb_set_debug_position_to_procedure_begin(lbProcedure *p) {
  396. if (p->debug_info == nullptr) {
  397. return;
  398. }
  399. TokenPos pos = {};
  400. if (p->body != nullptr) {
  401. pos = ast_token(p->body).pos;
  402. } else if (p->type_expr != nullptr) {
  403. pos = ast_token(p->type_expr).pos;
  404. } else if (p->entity != nullptr) {
  405. pos = p->entity->token.pos;
  406. }
  407. if (pos.file_id != 0) {
  408. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  409. }
  410. }
  411. gb_internal void lb_set_debug_position_to_procedure_end(lbProcedure *p) {
  412. if (p->debug_info == nullptr) {
  413. return;
  414. }
  415. TokenPos pos = {};
  416. if (p->body != nullptr) {
  417. pos = ast_end_token(p->body).pos;
  418. } else if (p->type_expr != nullptr) {
  419. pos = ast_end_token(p->type_expr).pos;
  420. } else if (p->entity != nullptr) {
  421. pos = p->entity->token.pos;
  422. }
  423. if (pos.file_id != 0) {
  424. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  425. }
  426. }
  427. gb_internal void lb_begin_procedure_body(lbProcedure *p) {
  428. DeclInfo *decl = decl_info_of_entity(p->entity);
  429. if (decl != nullptr) {
  430. for_array(i, decl->labels) {
  431. BlockLabel bl = decl->labels[i];
  432. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  433. array_add(&p->branch_blocks, bb);
  434. }
  435. }
  436. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  437. p->decl_block = lb_create_block(p, "decls", true);
  438. p->entry_block = lb_create_block(p, "entry", true);
  439. lb_start_block(p, p->entry_block);
  440. map_init(&p->direct_parameters);
  441. GB_ASSERT(p->type != nullptr);
  442. lb_ensure_abi_function_type(p->module, p);
  443. {
  444. lbFunctionType *ft = p->abi_function_type;
  445. unsigned param_offset = 0;
  446. lbValue return_ptr_value = {};
  447. if (ft->ret.kind == lbArg_Indirect) {
  448. // NOTE(bill): this must be parameter 0
  449. String name = str_lit("agg.result");
  450. if (ft->multiple_return_original_type &&
  451. p->type->Proc.has_named_results) {
  452. auto const &variables = p->type->Proc.results->Tuple.variables;
  453. Entity *e = variables[variables.count-1];
  454. if (!is_blank_ident(e->token)) {
  455. name = e->token.string;
  456. }
  457. }
  458. Type *return_ptr_type = reduce_tuple_to_single_type(p->type->Proc.results);
  459. bool split_returns = ft->multiple_return_original_type != nullptr;
  460. if (split_returns) {
  461. GB_ASSERT(is_type_tuple(return_ptr_type));
  462. auto const &variables = return_ptr_type->Tuple.variables;
  463. return_ptr_type = variables[variables.count-1]->type;
  464. }
  465. Type *ptr_type = alloc_type_pointer(return_ptr_type);
  466. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  467. e->flags |= EntityFlag_NoAlias;
  468. return_ptr_value.value = LLVMGetParam(p->value, 0);
  469. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  470. return_ptr_value.type = ptr_type;
  471. p->return_ptr = lb_addr(return_ptr_value);
  472. lb_add_entity(p->module, e, return_ptr_value);
  473. param_offset += 1;
  474. }
  475. if (p->type->Proc.params != nullptr) {
  476. TypeTuple *params = &p->type->Proc.params->Tuple;
  477. unsigned raw_input_parameters_count = LLVMCountParams(p->value);
  478. p->raw_input_parameters = array_make<LLVMValueRef>(permanent_allocator(), raw_input_parameters_count);
  479. LLVMGetParams(p->value, p->raw_input_parameters.data);
  480. unsigned param_index = 0;
  481. for_array(i, params->variables) {
  482. Entity *e = params->variables[i];
  483. if (e->kind != Entity_Variable) {
  484. continue;
  485. }
  486. lbArgType *arg_type = &ft->args[param_index];
  487. defer (param_index += 1);
  488. if (arg_type->kind == lbArg_Ignore) {
  489. // Even though it is an ignored argument, it might still be referenced in the
  490. // body.
  491. lbValue dummy = lb_add_local_generated(p, e->type, false).addr;
  492. lb_add_entity(p->module, e, dummy);
  493. } else if (arg_type->kind == lbArg_Direct) {
  494. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  495. LLVMTypeRef param_type = lb_type(p->module, e->type);
  496. LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index);
  497. LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type);
  498. lbValue param = {};
  499. param.value = value;
  500. param.type = e->type;
  501. map_set(&p->direct_parameters, e, param);
  502. lbValue ptr = lb_address_from_load_or_generate_local(p, param);
  503. GB_ASSERT(LLVMIsAAllocaInst(ptr.value));
  504. lb_add_entity(p->module, e, ptr);
  505. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->curr_block);
  506. }
  507. } else if (arg_type->kind == lbArg_Indirect) {
  508. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  509. lbValue ptr = {};
  510. ptr.value = LLVMGetParam(p->value, param_offset+param_index);
  511. ptr.type = alloc_type_pointer(e->type);
  512. lb_add_entity(p->module, e, ptr);
  513. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block);
  514. }
  515. }
  516. }
  517. }
  518. if (p->type->Proc.has_named_results) {
  519. GB_ASSERT(p->type->Proc.result_count > 0);
  520. TypeTuple *results = &p->type->Proc.results->Tuple;
  521. for_array(i, results->variables) {
  522. Entity *e = results->variables[i];
  523. GB_ASSERT(e->kind == Entity_Variable);
  524. if (e->token.string != "") {
  525. GB_ASSERT(!is_blank_ident(e->token));
  526. lbAddr res = {};
  527. if (p->entity && p->entity->decl_info &&
  528. p->entity->decl_info->defer_use_checked &&
  529. p->entity->decl_info->defer_used == 0) {
  530. // NOTE(bill): this is a bodge to get around the issue of the problem BELOW
  531. // We check to see if we ever use a defer statement ever within a procedure and if it
  532. // if it never happens, see if you can possibly do take the return value pointer
  533. //
  534. // NOTE(bill): this could be buggy in that I have missed a case where `defer` was used
  535. //
  536. // TODO(bill): This could be optimized to check to see where a `defer` only uses
  537. // the variable in question
  538. bool has_return_ptr = p->return_ptr.addr.value != nullptr;
  539. lbValue ptr = {};
  540. if (ft->multiple_return_original_type != nullptr) {
  541. isize the_offset = -1;
  542. if (i+1 < results->variables.count) {
  543. the_offset = cast(isize)param_offset + ft->original_arg_count + i;
  544. } else if (has_return_ptr) {
  545. GB_ASSERT(i+1 == results->variables.count);
  546. the_offset = 0;
  547. }
  548. if (the_offset >= 0) {
  549. lbValue ptr = {};
  550. ptr.value = LLVMGetParam(p->value, cast(unsigned)the_offset);
  551. ptr.type = alloc_type_pointer(e->type);
  552. }
  553. } else if (has_return_ptr) {
  554. lbValue ptr = p->return_ptr.addr;
  555. if (results->variables.count > 1) {
  556. ptr = lb_emit_tuple_ep(p, ptr, cast(i32)i);
  557. }
  558. GB_ASSERT(is_type_pointer(ptr.type));
  559. GB_ASSERT(are_types_identical(type_deref(ptr.type), e->type));
  560. }
  561. if (ptr.value != nullptr) {
  562. lb_add_entity(p->module, e, ptr);
  563. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  564. // NOTE(bill): no need to zero on the callee side as it is zeroed on the caller side
  565. res = lb_addr(ptr);
  566. }
  567. }
  568. if (res.addr.type == nullptr) {
  569. // NOTE(bill): Don't even bother trying to optimize this with the return ptr value
  570. // This will violate the defer rules if you do:
  571. // foo :: proc() -> (x, y: T) {
  572. // defer x = ... // defer is executed after the `defer`
  573. // return // the values returned should be zeroed
  574. // }
  575. // NOTE(bill): REALLY, don't even bother.
  576. //
  577. // IMPORTANT NOTE(bill): REALLY, don't even bother!!!!!!
  578. res = lb_add_local(p, e->type, e);
  579. }
  580. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  581. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  582. lb_addr_store(p, res, c);
  583. }
  584. }
  585. }
  586. }
  587. }
  588. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  589. lb_push_context_onto_stack_from_implicit_parameter(p);
  590. }
  591. lb_set_debug_position_to_procedure_begin(p);
  592. if (p->debug_info != nullptr) {
  593. if (p->context_stack.count != 0) {
  594. p->curr_block = p->decl_block;
  595. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  596. }
  597. }
  598. lb_start_block(p, p->entry_block);
  599. }
  600. gb_internal void lb_end_procedure_body(lbProcedure *p) {
  601. lb_set_debug_position_to_procedure_begin(p);
  602. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  603. LLVMBuildBr(p->builder, p->entry_block->block);
  604. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  605. LLVMValueRef instr = nullptr;
  606. // Make sure there is a "ret void" at the end of a procedure with no return type
  607. if (p->type->Proc.result_count == 0) {
  608. instr = LLVMGetLastInstruction(p->curr_block->block);
  609. if (!lb_is_instr_terminating(instr)) {
  610. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  611. lb_set_debug_position_to_procedure_end(p);
  612. LLVMBuildRetVoid(p->builder);
  613. }
  614. }
  615. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  616. LLVMBasicBlockRef block = nullptr;
  617. // Make sure every block terminates, and if not, make it unreachable
  618. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  619. instr = LLVMGetLastInstruction(block);
  620. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  621. LLVMPositionBuilderAtEnd(p->builder, block);
  622. LLVMBuildUnreachable(p->builder);
  623. }
  624. }
  625. p->curr_block = nullptr;
  626. p->state_flags = 0;
  627. }
  628. gb_internal void lb_end_procedure(lbProcedure *p) {
  629. LLVMDisposeBuilder(p->builder);
  630. }
  631. gb_internal void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  632. GB_ASSERT(pd->body != nullptr);
  633. lbModule *m = p->module;
  634. auto *min_dep_set = &m->info->minimum_dependency_set;
  635. if (ptr_set_exists(min_dep_set, e) == false) {
  636. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  637. return;
  638. }
  639. // NOTE(bill): Generate a new name
  640. // parent.name-guid
  641. String original_name = e->token.string;
  642. String pd_name = original_name;
  643. if (e->Procedure.link_name.len > 0) {
  644. pd_name = e->Procedure.link_name;
  645. }
  646. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  647. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  648. i32 guid = cast(i32)p->children.count;
  649. name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  650. String name = make_string(cast(u8 *)name_text, name_len-1);
  651. e->Procedure.link_name = name;
  652. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  653. e->code_gen_procedure = nested_proc;
  654. lbValue value = {};
  655. value.value = nested_proc->value;
  656. value.type = nested_proc->type;
  657. lb_add_entity(m, e, value);
  658. array_add(&p->children, nested_proc);
  659. array_add(&m->procedures_to_generate, nested_proc);
  660. }
  661. gb_internal Array<lbValue> lb_value_to_array(lbProcedure *p, gbAllocator const &allocator, lbValue value) {
  662. Array<lbValue> array = {};
  663. Type *t = base_type(value.type);
  664. if (t == nullptr) {
  665. // Do nothing
  666. } else if (is_type_tuple(t)) {
  667. array = array_make<lbValue>(allocator, 0, t->Tuple.variables.count);
  668. lb_append_tuple_values(p, &array, value);
  669. } else {
  670. array = array_make<lbValue>(allocator, 1);
  671. array[0] = value;
  672. }
  673. return array;
  674. }
  675. gb_internal lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  676. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  677. unsigned arg_count = cast(unsigned)processed_args.count;
  678. if (return_ptr.value != nullptr) {
  679. arg_count += 1;
  680. }
  681. if (context_ptr.addr.value != nullptr) {
  682. arg_count += 1;
  683. }
  684. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  685. isize arg_index = 0;
  686. if (return_ptr.value != nullptr) {
  687. args[arg_index++] = return_ptr.value;
  688. }
  689. for_array(i, processed_args) {
  690. lbValue arg = processed_args[i];
  691. if (is_type_proc(arg.type)) {
  692. arg.value = LLVMBuildPointerCast(p->builder, arg.value, lb_type(p->module, arg.type), "");
  693. }
  694. args[arg_index++] = arg.value;
  695. }
  696. if (context_ptr.addr.value != nullptr) {
  697. LLVMValueRef cp = context_ptr.addr.value;
  698. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  699. args[arg_index++] = cp;
  700. }
  701. GB_ASSERT(arg_index == arg_count);
  702. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  703. GB_ASSERT(curr_block != p->decl_block->block);
  704. {
  705. Type *proc_type = base_type(value.type);
  706. GB_ASSERT(proc_type->kind == Type_Proc);
  707. LLVMTypeRef fnp = lb_type_internal_for_procedures_raw(p->module, proc_type);
  708. LLVMTypeRef ftp = LLVMPointerType(fnp, 0);
  709. LLVMValueRef fn = value.value;
  710. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  711. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  712. }
  713. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  714. lbFunctionType *ft = map_must_get(&p->module->function_type_map, base_type(value.type));
  715. {
  716. unsigned param_count = LLVMCountParamTypes(fnp);
  717. GB_ASSERT(arg_count >= param_count);
  718. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  719. LLVMGetParamTypes(fnp, param_types);
  720. for (unsigned i = 0; i < param_count; i++) {
  721. LLVMTypeRef param_type = param_types[i];
  722. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  723. if (LB_USE_NEW_PASS_SYSTEM &&
  724. arg_type != param_type) {
  725. LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  726. LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  727. if (arg_kind == param_kind &&
  728. arg_kind == LLVMPointerTypeKind) {
  729. // NOTE(bill): LLVM's newer `ptr` only type system seems to fail at times
  730. // I don't know why...
  731. args[i] = LLVMBuildPointerCast(p->builder, args[i], param_type, "");
  732. arg_type = param_type;
  733. continue;
  734. }
  735. }
  736. GB_ASSERT_MSG(
  737. arg_type == param_type,
  738. "Parameter types do not match: %s != %s, argument: %s\n\t%s",
  739. LLVMPrintTypeToString(arg_type),
  740. LLVMPrintTypeToString(param_type),
  741. LLVMPrintValueToString(args[i]),
  742. LLVMPrintTypeToString(fnp)
  743. );
  744. }
  745. }
  746. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  747. auto llvm_cc = lb_calling_convention_map[proc_type->Proc.calling_convention];
  748. LLVMSetInstructionCallConv(ret, llvm_cc);
  749. LLVMAttributeIndex param_offset = LLVMAttributeIndex_FirstArgIndex;
  750. if (return_ptr.value != nullptr) {
  751. param_offset += 1;
  752. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  753. }
  754. for_array(i, ft->args) {
  755. LLVMAttributeRef attribute = ft->args[i].attribute;
  756. if (attribute != nullptr) {
  757. LLVMAddCallSiteAttribute(ret, param_offset + cast(LLVMAttributeIndex)i, attribute);
  758. }
  759. }
  760. switch (inlining) {
  761. case ProcInlining_none:
  762. break;
  763. case ProcInlining_inline:
  764. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  765. break;
  766. case ProcInlining_no_inline:
  767. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  768. break;
  769. }
  770. lbValue res = {};
  771. res.value = ret;
  772. res.type = abi_rt;
  773. return res;
  774. }
  775. }
  776. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  777. AstPackage *pkg = m->info->runtime_package;
  778. Entity *e = scope_lookup_current(pkg->scope, name);
  779. return lb_find_procedure_value_from_entity(m, e);
  780. }
  781. gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  782. String name = make_string_c(c_name);
  783. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  784. return lb_emit_call(p, proc, args);
  785. }
  786. gb_internal lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  787. lbValue res = {};
  788. Type *t = val.type;
  789. if (is_type_complex(t)) {
  790. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  791. lbValue real = lb_emit_struct_ev(p, val, 0);
  792. lbValue imag = lb_emit_struct_ev(p, val, 1);
  793. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  794. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  795. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  796. } else if (is_type_quaternion(t)) {
  797. // @QuaternionLayout
  798. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  799. lbValue real = lb_emit_struct_ev(p, val, 3);
  800. lbValue imag = lb_emit_struct_ev(p, val, 0);
  801. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  802. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  803. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  804. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  805. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  806. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  807. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  808. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  809. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  810. } else if (is_type_array_like(t)) {
  811. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  812. Type *elem_type = base_array_type(t);
  813. i64 count = get_array_type_count(t);
  814. for (i64 i = 0; i < count; i++) {
  815. lbValue dst = lb_emit_array_epi(p, res, i);
  816. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  817. elem = lb_emit_conjugate(p, elem, elem_type);
  818. lb_emit_store(p, dst, elem);
  819. }
  820. } else if (is_type_matrix(t)) {
  821. Type *mt = base_type(t);
  822. GB_ASSERT(mt->kind == Type_Matrix);
  823. Type *elem_type = mt->Matrix.elem;
  824. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  825. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  826. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  827. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  828. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  829. elem = lb_emit_conjugate(p, elem, elem_type);
  830. lb_emit_store(p, dst, elem);
  831. }
  832. }
  833. }
  834. return lb_emit_load(p, res);
  835. }
  836. gb_internal lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining) {
  837. lbModule *m = p->module;
  838. Type *pt = base_type(value.type);
  839. GB_ASSERT(pt->kind == Type_Proc);
  840. Type *results = pt->Proc.results;
  841. lbAddr context_ptr = {};
  842. if (pt->Proc.calling_convention == ProcCC_Odin) {
  843. context_ptr = lb_find_or_generate_context_ptr(p);
  844. }
  845. defer (if (pt->Proc.diverging) {
  846. LLVMBuildUnreachable(p->builder);
  847. });
  848. bool is_c_vararg = pt->Proc.c_vararg;
  849. isize param_count = pt->Proc.param_count;
  850. if (is_c_vararg) {
  851. GB_ASSERT(param_count-1 <= args.count);
  852. param_count -= 1;
  853. } else {
  854. GB_ASSERT_MSG(param_count == args.count, "%td == %td (%s)", param_count, args.count, LLVMPrintValueToString(value.value));
  855. }
  856. lbValue result = {};
  857. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  858. {
  859. bool is_odin_cc = is_calling_convention_odin(pt->Proc.calling_convention);
  860. lbFunctionType *ft = lb_get_function_type(m, pt);
  861. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  862. bool split_returns = ft->multiple_return_original_type != nullptr;
  863. unsigned param_index = 0;
  864. for (isize i = 0; i < param_count; i++) {
  865. Entity *e = pt->Proc.params->Tuple.variables[i];
  866. if (e->kind != Entity_Variable) {
  867. continue;
  868. }
  869. GB_ASSERT(e->flags & EntityFlag_Param);
  870. Type *original_type = e->type;
  871. lbArgType *arg = &ft->args[param_index];
  872. if (arg->kind == lbArg_Ignore) {
  873. param_index += 1;
  874. continue;
  875. }
  876. lbValue x = lb_emit_conv(p, args[i], original_type);
  877. LLVMTypeRef xt = lb_type(p->module, x.type);
  878. if (arg->kind == lbArg_Direct) {
  879. LLVMTypeRef abi_type = arg->cast_type;
  880. if (!abi_type) {
  881. abi_type = arg->type;
  882. }
  883. if (xt == abi_type) {
  884. array_add(&processed_args, x);
  885. } else {
  886. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  887. array_add(&processed_args, x);
  888. }
  889. } else if (arg->kind == lbArg_Indirect) {
  890. lbValue ptr = {};
  891. if (arg->is_byval) {
  892. if (is_odin_cc) {
  893. if (are_types_identical(original_type, t_source_code_location)) {
  894. ptr = lb_address_from_load_or_generate_local(p, x);
  895. // } else {
  896. // ptr = lb_address_from_load_if_readonly_parameter(p, x);
  897. }
  898. }
  899. if (ptr.value == nullptr) {
  900. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  901. }
  902. } else if (is_odin_cc) {
  903. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  904. // i.e. `T const &` in C++
  905. if (LLVMIsConstant(x.value)) {
  906. // NOTE(bill): if the value is already constant, then just it as a global variable
  907. // and pass it by pointer
  908. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  909. lb_make_global_private_const(addr);
  910. ptr = addr.addr;
  911. } else {
  912. ptr = lb_address_from_load_or_generate_local(p, x);
  913. }
  914. } else {
  915. if (LLVMIsConstant(x.value)) {
  916. // NOTE(bill): if the value is already constant, then just it as a global variable
  917. // and pass it by pointer
  918. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  919. lb_make_global_private_const(addr);
  920. ptr = addr.addr;
  921. } else {
  922. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  923. }
  924. }
  925. array_add(&processed_args, ptr);
  926. }
  927. param_index += 1;
  928. }
  929. if (is_c_vararg) {
  930. for (isize i = processed_args.count; i < args.count; i++) {
  931. array_add(&processed_args, args[i]);
  932. }
  933. }
  934. if (inlining == ProcInlining_none) {
  935. inlining = p->inlining;
  936. }
  937. Type *rt = reduce_tuple_to_single_type(results);
  938. Type *original_rt = rt;
  939. if (split_returns) {
  940. GB_ASSERT(rt->kind == Type_Tuple);
  941. for (isize j = 0; j < rt->Tuple.variables.count-1; j++) {
  942. Type *partial_return_type = rt->Tuple.variables[j]->type;
  943. lbValue partial_return_ptr = lb_add_local(p, partial_return_type, nullptr, true, false).addr;
  944. array_add(&processed_args, partial_return_ptr);
  945. }
  946. rt = reduce_tuple_to_single_type(rt->Tuple.variables[rt->Tuple.variables.count-1]->type);
  947. }
  948. if (return_by_pointer) {
  949. lbValue return_ptr = lb_add_local_generated(p, rt, true).addr;
  950. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  951. result = lb_emit_load(p, return_ptr);
  952. } else if (rt != nullptr) {
  953. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  954. if (ft->ret.cast_type) {
  955. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  956. }
  957. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  958. result.type = rt;
  959. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  960. result.type = t_llvm_bool;
  961. }
  962. if (!is_type_tuple(rt)) {
  963. result = lb_emit_conv(p, result, rt);
  964. }
  965. } else {
  966. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  967. }
  968. if (original_rt != rt) {
  969. GB_ASSERT(split_returns);
  970. GB_ASSERT(is_type_tuple(original_rt));
  971. // IMPORTANT NOTE(bill, 2022-11-24)
  972. // result_ptr is a dummy value which is only used to reference a tuple
  973. // value for the "tuple-fix"
  974. //
  975. // The reason for the fake stack allocation is to have a unique pointer
  976. // for the value to be used as a key within the procedure itself
  977. lbValue result_ptr = lb_add_local_generated(p, original_rt, false).addr;
  978. isize ret_count = original_rt->Tuple.variables.count;
  979. auto tuple_fix_values = slice_make<lbValue>(permanent_allocator(), ret_count);
  980. auto tuple_geps = slice_make<lbValue>(permanent_allocator(), ret_count);
  981. isize offset = ft->original_arg_count;
  982. for (isize j = 0; j < ret_count-1; j++) {
  983. lbValue ret_arg_ptr = processed_args[offset + j];
  984. lbValue ret_arg = lb_emit_load(p, ret_arg_ptr);
  985. tuple_fix_values[j] = ret_arg;
  986. }
  987. tuple_fix_values[ret_count-1] = result;
  988. #if 0
  989. for (isize j = 0; j < ret_count; j++) {
  990. tuple_geps[j] = lb_emit_struct_ep(p, result_ptr, cast(i32)j);
  991. }
  992. for (isize j = 0; j < ret_count; j++) {
  993. lb_emit_store(p, tuple_geps[j], tuple_fix_values[j]);
  994. }
  995. #endif
  996. result = lb_emit_load(p, result_ptr);
  997. lbTupleFix tf = {tuple_fix_values};
  998. map_set(&p->tuple_fix_map, result_ptr.value, tf);
  999. map_set(&p->tuple_fix_map, result.value, tf);
  1000. }
  1001. }
  1002. LLVMValueRef the_proc_value = value.value;
  1003. if (LLVMIsAConstantExpr(the_proc_value)) {
  1004. // NOTE(bill): it's a bit cast
  1005. the_proc_value = LLVMGetOperand(the_proc_value, 0);
  1006. }
  1007. Entity **found = map_get(&p->module->procedure_values, the_proc_value);
  1008. if (found != nullptr) {
  1009. Entity *e = *found;
  1010. if (e != nullptr && entity_has_deferred_procedure(e)) {
  1011. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  1012. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  1013. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  1014. bool by_ptr = false;
  1015. auto in_args = args;
  1016. Array<lbValue> result_as_args = {};
  1017. switch (kind) {
  1018. case DeferredProcedure_none:
  1019. break;
  1020. case DeferredProcedure_in_by_ptr:
  1021. by_ptr = true;
  1022. /*fallthrough*/
  1023. case DeferredProcedure_in:
  1024. result_as_args = array_clone(heap_allocator(), in_args);
  1025. break;
  1026. case DeferredProcedure_out_by_ptr:
  1027. by_ptr = true;
  1028. /*fallthrough*/
  1029. case DeferredProcedure_out:
  1030. result_as_args = lb_value_to_array(p, heap_allocator(), result);
  1031. break;
  1032. case DeferredProcedure_in_out_by_ptr:
  1033. by_ptr = true;
  1034. /*fallthrough*/
  1035. case DeferredProcedure_in_out:
  1036. {
  1037. auto out_args = lb_value_to_array(p, heap_allocator(), result);
  1038. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  1039. array_copy(&result_as_args, in_args, 0);
  1040. array_copy(&result_as_args, out_args, in_args.count);
  1041. }
  1042. break;
  1043. }
  1044. if (by_ptr) {
  1045. for_array(i, result_as_args) {
  1046. lbValue arg_ptr = lb_address_from_load_or_generate_local(p, result_as_args[i]);
  1047. result_as_args[i] = arg_ptr;
  1048. }
  1049. }
  1050. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  1051. }
  1052. }
  1053. return result;
  1054. }
  1055. gb_internal LLVMValueRef llvm_splat_int(i64 count, LLVMTypeRef type, i64 value, bool is_signed=false) {
  1056. LLVMValueRef v = LLVMConstInt(type, value, is_signed);
  1057. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1058. for (i64 i = 0; i < count; i++) {
  1059. values[i] = v;
  1060. }
  1061. return LLVMConstVector(values, cast(unsigned)count);
  1062. }
  1063. gb_internal lbValue lb_build_builtin_simd_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId builtin_id) {
  1064. ast_node(ce, CallExpr, expr);
  1065. lbModule *m = p->module;
  1066. lbValue res = {};
  1067. res.type = tv.type;
  1068. lbValue arg0 = {}; if (ce->args.count > 0) arg0 = lb_build_expr(p, ce->args[0]);
  1069. lbValue arg1 = {}; if (ce->args.count > 1) arg1 = lb_build_expr(p, ce->args[1]);
  1070. lbValue arg2 = {}; if (ce->args.count > 2) arg2 = lb_build_expr(p, ce->args[2]);
  1071. Type *elem = base_array_type(arg0.type);
  1072. bool is_float = is_type_float(elem);
  1073. bool is_signed = !is_type_unsigned(elem);
  1074. LLVMOpcode op_code = cast(LLVMOpcode)0;
  1075. switch (builtin_id) {
  1076. case BuiltinProc_simd_add:
  1077. case BuiltinProc_simd_sub:
  1078. case BuiltinProc_simd_mul:
  1079. case BuiltinProc_simd_div:
  1080. case BuiltinProc_simd_rem:
  1081. if (is_float) {
  1082. switch (builtin_id) {
  1083. case BuiltinProc_simd_add: op_code = LLVMFAdd; break;
  1084. case BuiltinProc_simd_sub: op_code = LLVMFSub; break;
  1085. case BuiltinProc_simd_mul: op_code = LLVMFMul; break;
  1086. case BuiltinProc_simd_div: op_code = LLVMFDiv; break;
  1087. }
  1088. } else {
  1089. switch (builtin_id) {
  1090. case BuiltinProc_simd_add: op_code = LLVMAdd; break;
  1091. case BuiltinProc_simd_sub: op_code = LLVMSub; break;
  1092. case BuiltinProc_simd_mul: op_code = LLVMMul; break;
  1093. case BuiltinProc_simd_div:
  1094. if (is_signed) {
  1095. op_code = LLVMSDiv;
  1096. } else {
  1097. op_code = LLVMUDiv;
  1098. }
  1099. break;
  1100. case BuiltinProc_simd_rem:
  1101. if (is_signed) {
  1102. op_code = LLVMSRem;
  1103. } else {
  1104. op_code = LLVMURem;
  1105. }
  1106. break;
  1107. }
  1108. }
  1109. if (op_code) {
  1110. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1111. return res;
  1112. }
  1113. break;
  1114. case BuiltinProc_simd_shl: // Odin logic
  1115. case BuiltinProc_simd_shr: // Odin logic
  1116. case BuiltinProc_simd_shl_masked: // C logic
  1117. case BuiltinProc_simd_shr_masked: // C logic
  1118. {
  1119. i64 sz = type_size_of(elem);
  1120. GB_ASSERT(arg0.type->kind == Type_SimdVector);
  1121. i64 count = arg0.type->SimdVector.count;
  1122. Type *elem1 = base_array_type(arg1.type);
  1123. bool is_masked = false;
  1124. switch (builtin_id) {
  1125. case BuiltinProc_simd_shl: op_code = LLVMShl; is_masked = false; break;
  1126. case BuiltinProc_simd_shr: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = false; break;
  1127. case BuiltinProc_simd_shl_masked: op_code = LLVMShl; is_masked = true; break;
  1128. case BuiltinProc_simd_shr_masked: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = true; break;
  1129. }
  1130. if (op_code) {
  1131. LLVMValueRef bits = llvm_splat_int(count, lb_type(m, elem1), sz*8 - 1);
  1132. if (is_masked) {
  1133. // C logic
  1134. LLVMValueRef shift = LLVMBuildAnd(p->builder, arg1.value, bits, "");
  1135. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, shift, "");
  1136. } else {
  1137. // Odin logic
  1138. LLVMValueRef zero = lb_const_nil(m, arg1.type).value;
  1139. LLVMValueRef mask = LLVMBuildICmp(p->builder, LLVMIntULE, arg1.value, bits, "");
  1140. LLVMValueRef shift = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1141. res.value = LLVMBuildSelect(p->builder, mask, shift, zero, "");
  1142. }
  1143. return res;
  1144. }
  1145. }
  1146. break;
  1147. case BuiltinProc_simd_bit_and:
  1148. case BuiltinProc_simd_bit_or:
  1149. case BuiltinProc_simd_bit_xor:
  1150. case BuiltinProc_simd_bit_and_not:
  1151. switch (builtin_id) {
  1152. case BuiltinProc_simd_bit_and: op_code = LLVMAnd; break;
  1153. case BuiltinProc_simd_bit_or: op_code = LLVMOr; break;
  1154. case BuiltinProc_simd_bit_xor: op_code = LLVMXor; break;
  1155. case BuiltinProc_simd_bit_and_not:
  1156. op_code = LLVMAnd;
  1157. arg1.value = LLVMBuildNot(p->builder, arg1.value, "");
  1158. break;
  1159. }
  1160. if (op_code) {
  1161. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1162. return res;
  1163. }
  1164. break;
  1165. case BuiltinProc_simd_neg:
  1166. if (is_float) {
  1167. res.value = LLVMBuildFNeg(p->builder, arg0.value, "");
  1168. } else {
  1169. res.value = LLVMBuildNeg(p->builder, arg0.value, "");
  1170. }
  1171. return res;
  1172. case BuiltinProc_simd_abs:
  1173. if (is_float) {
  1174. LLVMValueRef pos = arg0.value;
  1175. LLVMValueRef neg = LLVMBuildFNeg(p->builder, pos, "");
  1176. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, pos, neg, "");
  1177. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1178. } else {
  1179. LLVMValueRef pos = arg0.value;
  1180. LLVMValueRef neg = LLVMBuildNeg(p->builder, pos, "");
  1181. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, pos, neg, "");
  1182. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1183. }
  1184. return res;
  1185. case BuiltinProc_simd_min:
  1186. if (is_float) {
  1187. return lb_emit_min(p, res.type, arg0, arg1);
  1188. } else {
  1189. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSLT : LLVMIntULT, arg0.value, arg1.value, "");
  1190. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1191. }
  1192. return res;
  1193. case BuiltinProc_simd_max:
  1194. if (is_float) {
  1195. return lb_emit_max(p, res.type, arg0, arg1);
  1196. } else {
  1197. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, arg0.value, arg1.value, "");
  1198. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1199. }
  1200. return res;
  1201. case BuiltinProc_simd_lanes_eq:
  1202. case BuiltinProc_simd_lanes_ne:
  1203. case BuiltinProc_simd_lanes_lt:
  1204. case BuiltinProc_simd_lanes_le:
  1205. case BuiltinProc_simd_lanes_gt:
  1206. case BuiltinProc_simd_lanes_ge:
  1207. if (is_float) {
  1208. LLVMRealPredicate pred = cast(LLVMRealPredicate)0;
  1209. switch (builtin_id) {
  1210. case BuiltinProc_simd_lanes_eq: pred = LLVMRealOEQ; break;
  1211. case BuiltinProc_simd_lanes_ne: pred = LLVMRealONE; break;
  1212. case BuiltinProc_simd_lanes_lt: pred = LLVMRealOLT; break;
  1213. case BuiltinProc_simd_lanes_le: pred = LLVMRealOLE; break;
  1214. case BuiltinProc_simd_lanes_gt: pred = LLVMRealOGT; break;
  1215. case BuiltinProc_simd_lanes_ge: pred = LLVMRealOGE; break;
  1216. }
  1217. if (pred) {
  1218. res.value = LLVMBuildFCmp(p->builder, pred, arg0.value, arg1.value, "");
  1219. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1220. return res;
  1221. }
  1222. } else {
  1223. LLVMIntPredicate pred = cast(LLVMIntPredicate)0;
  1224. switch (builtin_id) {
  1225. case BuiltinProc_simd_lanes_eq: pred = LLVMIntEQ; break;
  1226. case BuiltinProc_simd_lanes_ne: pred = LLVMIntNE; break;
  1227. case BuiltinProc_simd_lanes_lt: pred = is_signed ? LLVMIntSLT :LLVMIntULT; break;
  1228. case BuiltinProc_simd_lanes_le: pred = is_signed ? LLVMIntSLE :LLVMIntULE; break;
  1229. case BuiltinProc_simd_lanes_gt: pred = is_signed ? LLVMIntSGT :LLVMIntUGT; break;
  1230. case BuiltinProc_simd_lanes_ge: pred = is_signed ? LLVMIntSGE :LLVMIntUGE; break;
  1231. }
  1232. if (pred) {
  1233. res.value = LLVMBuildICmp(p->builder, pred, arg0.value, arg1.value, "");
  1234. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1235. return res;
  1236. }
  1237. }
  1238. break;
  1239. case BuiltinProc_simd_extract:
  1240. res.value = LLVMBuildExtractElement(p->builder, arg0.value, arg1.value, "");
  1241. return res;
  1242. case BuiltinProc_simd_replace:
  1243. res.value = LLVMBuildInsertElement(p->builder, arg0.value, arg2.value, arg1.value, "");
  1244. return res;
  1245. case BuiltinProc_simd_reduce_add_ordered:
  1246. case BuiltinProc_simd_reduce_mul_ordered:
  1247. {
  1248. LLVMTypeRef llvm_elem = lb_type(m, elem);
  1249. LLVMValueRef args[2] = {};
  1250. isize args_count = 0;
  1251. char const *name = nullptr;
  1252. switch (builtin_id) {
  1253. case BuiltinProc_simd_reduce_add_ordered:
  1254. if (is_float) {
  1255. name = "llvm.vector.reduce.fadd";
  1256. args[args_count++] = LLVMConstReal(llvm_elem, 0.0);
  1257. } else {
  1258. name = "llvm.vector.reduce.add";
  1259. }
  1260. break;
  1261. case BuiltinProc_simd_reduce_mul_ordered:
  1262. if (is_float) {
  1263. name = "llvm.vector.reduce.fmul";
  1264. args[args_count++] = LLVMConstReal(llvm_elem, 1.0);
  1265. } else {
  1266. name = "llvm.vector.reduce.mul";
  1267. }
  1268. break;
  1269. }
  1270. args[args_count++] = arg0.value;
  1271. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1272. res.value = lb_call_intrinsic(p, name, args, cast(unsigned)args_count, types, gb_count_of(types));
  1273. return res;
  1274. }
  1275. case BuiltinProc_simd_reduce_min:
  1276. case BuiltinProc_simd_reduce_max:
  1277. case BuiltinProc_simd_reduce_and:
  1278. case BuiltinProc_simd_reduce_or:
  1279. case BuiltinProc_simd_reduce_xor:
  1280. {
  1281. char const *name = nullptr;
  1282. switch (builtin_id) {
  1283. case BuiltinProc_simd_reduce_min:
  1284. if (is_float) {
  1285. name = "llvm.vector.reduce.fmin";
  1286. } else if (is_signed) {
  1287. name = "llvm.vector.reduce.smin";
  1288. } else {
  1289. name = "llvm.vector.reduce.umin";
  1290. }
  1291. break;
  1292. case BuiltinProc_simd_reduce_max:
  1293. if (is_float) {
  1294. name = "llvm.vector.reduce.fmax";
  1295. } else if (is_signed) {
  1296. name = "llvm.vector.reduce.smax";
  1297. } else {
  1298. name = "llvm.vector.reduce.umax";
  1299. }
  1300. break;
  1301. case BuiltinProc_simd_reduce_and: name = "llvm.vector.reduce.and"; break;
  1302. case BuiltinProc_simd_reduce_or: name = "llvm.vector.reduce.or"; break;
  1303. case BuiltinProc_simd_reduce_xor: name = "llvm.vector.reduce.xor"; break;
  1304. }
  1305. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1306. LLVMValueRef args[1] = { arg0.value };
  1307. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1308. return res;
  1309. }
  1310. case BuiltinProc_simd_shuffle:
  1311. {
  1312. Type *vt = arg0.type;
  1313. GB_ASSERT(vt->kind == Type_SimdVector);
  1314. i64 indices_count = ce->args.count-2;
  1315. i64 max_count = vt->SimdVector.count*2;
  1316. GB_ASSERT(indices_count <= max_count);
  1317. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, indices_count);
  1318. for (isize i = 0; i < indices_count; i++) {
  1319. lbValue idx = lb_build_expr(p, ce->args[i+2]);
  1320. GB_ASSERT(LLVMIsConstant(idx.value));
  1321. values[i] = idx.value;
  1322. }
  1323. LLVMValueRef indices = LLVMConstVector(values, cast(unsigned)indices_count);
  1324. res.value = LLVMBuildShuffleVector(p->builder, arg0.value, arg1.value, indices, "");
  1325. return res;
  1326. }
  1327. case BuiltinProc_simd_select:
  1328. {
  1329. LLVMValueRef cond = arg0.value;
  1330. LLVMValueRef x = lb_build_expr(p, ce->args[1]).value;
  1331. LLVMValueRef y = lb_build_expr(p, ce->args[2]).value;
  1332. cond = LLVMBuildICmp(p->builder, LLVMIntNE, cond, LLVMConstNull(LLVMTypeOf(cond)), "");
  1333. res.value = LLVMBuildSelect(p->builder, cond, x, y, "");
  1334. return res;
  1335. }
  1336. case BuiltinProc_simd_ceil:
  1337. case BuiltinProc_simd_floor:
  1338. case BuiltinProc_simd_trunc:
  1339. case BuiltinProc_simd_nearest:
  1340. {
  1341. char const *name = nullptr;
  1342. switch (builtin_id) {
  1343. case BuiltinProc_simd_ceil: name = "llvm.ceil"; break;
  1344. case BuiltinProc_simd_floor: name = "llvm.floor"; break;
  1345. case BuiltinProc_simd_trunc: name = "llvm.trunc"; break;
  1346. case BuiltinProc_simd_nearest: name = "llvm.nearbyint"; break;
  1347. }
  1348. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1349. LLVMValueRef args[1] = { arg0.value };
  1350. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1351. return res;
  1352. }
  1353. case BuiltinProc_simd_lanes_reverse:
  1354. {
  1355. i64 count = get_array_type_count(arg0.type);
  1356. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1357. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1358. for (i64 i = 0; i < count; i++) {
  1359. values[i] = LLVMConstInt(llvm_u32, count-1-i, false);
  1360. }
  1361. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1362. LLVMValueRef v = arg0.value;
  1363. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1364. return res;
  1365. }
  1366. case BuiltinProc_simd_lanes_rotate_left:
  1367. case BuiltinProc_simd_lanes_rotate_right:
  1368. {
  1369. i64 count = get_array_type_count(arg0.type);
  1370. GB_ASSERT(is_power_of_two(count));
  1371. BigInt bi_count = {};
  1372. big_int_from_i64(&bi_count, count);
  1373. TypeAndValue const &tv = ce->args[1]->tav;
  1374. ExactValue val = exact_value_to_integer(tv.value);
  1375. GB_ASSERT(val.kind == ExactValue_Integer);
  1376. BigInt *bi = &val.value_integer;
  1377. if (builtin_id == BuiltinProc_simd_lanes_rotate_right) {
  1378. big_int_neg(bi, bi);
  1379. }
  1380. big_int_rem(bi, bi, &bi_count);
  1381. big_int_dealloc(&bi_count);
  1382. i64 left = big_int_to_i64(bi);
  1383. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1384. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1385. for (i64 i = 0; i < count; i++) {
  1386. u64 idx = cast(u64)(i+left) & cast(u64)(count-1);
  1387. values[i] = LLVMConstInt(llvm_u32, idx, false);
  1388. }
  1389. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1390. LLVMValueRef v = arg0.value;
  1391. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1392. return res;
  1393. }
  1394. case BuiltinProc_simd_add_sat:
  1395. case BuiltinProc_simd_sub_sat:
  1396. {
  1397. char const *name = nullptr;
  1398. switch (builtin_id) {
  1399. case BuiltinProc_simd_add_sat: name = is_signed ? "llvm.sadd.sat" : "llvm.uadd.sat"; break;
  1400. case BuiltinProc_simd_sub_sat: name = is_signed ? "llvm.ssub.sat" : "llvm.usub.sat"; break;
  1401. }
  1402. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1403. LLVMValueRef args[2] = { arg0.value, arg1.value };
  1404. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1405. return res;
  1406. }
  1407. case BuiltinProc_simd_clamp:
  1408. {
  1409. LLVMValueRef v = arg0.value;
  1410. LLVMValueRef min = arg1.value;
  1411. LLVMValueRef max = arg2.value;
  1412. if (is_float) {
  1413. v = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOLT, v, min, ""), min, v, "");
  1414. res.value = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOGT, v, max, ""), max, v, "");
  1415. } else if (is_signed) {
  1416. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSLT, v, min, ""), min, v, "");
  1417. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSGT, v, max, ""), max, v, "");
  1418. } else {
  1419. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntULT, v, min, ""), min, v, "");
  1420. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntUGT, v, max, ""), max, v, "");
  1421. }
  1422. return res;
  1423. }
  1424. case BuiltinProc_simd_to_bits:
  1425. {
  1426. res.value = LLVMBuildBitCast(p->builder, arg0.value, lb_type(m, tv.type), "");
  1427. return res;
  1428. }
  1429. }
  1430. GB_PANIC("Unhandled simd intrinsic: '%.*s'", LIT(builtin_procs[builtin_id].name));
  1431. return {};
  1432. }
  1433. gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  1434. ast_node(ce, CallExpr, expr);
  1435. if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {
  1436. return lb_build_builtin_simd_proc(p, expr, tv, id);
  1437. }
  1438. switch (id) {
  1439. case BuiltinProc_DIRECTIVE: {
  1440. ast_node(bd, BasicDirective, ce->proc);
  1441. String name = bd->name.string;
  1442. if (name == "location") {
  1443. String procedure = p->entity->token.string;
  1444. TokenPos pos = ast_token(ce->proc).pos;
  1445. if (ce->args.count > 0) {
  1446. Ast *ident = unselector_expr(ce->args[0]);
  1447. GB_ASSERT(ident->kind == Ast_Ident);
  1448. Entity *e = entity_of_node(ident);
  1449. GB_ASSERT(e != nullptr);
  1450. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  1451. procedure = e->parent_proc_decl->entity->token.string;
  1452. } else {
  1453. procedure = str_lit("");
  1454. }
  1455. pos = e->token.pos;
  1456. }
  1457. return lb_emit_source_code_location_as_global(p, procedure, pos);
  1458. } else if (name == "load_directory") {
  1459. lbModule *m = p->module;
  1460. TEMPORARY_ALLOCATOR_GUARD();
  1461. LoadDirectoryCache *cache = map_must_get(&m->info->load_directory_map, expr);
  1462. isize count = cache->files.count;
  1463. LLVMValueRef *elements = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1464. for_array(i, cache->files) {
  1465. LoadFileCache *file = cache->files[i];
  1466. String file_name = filename_without_directory(file->path);
  1467. LLVMValueRef values[2] = {};
  1468. values[0] = lb_const_string(m, file_name).value;
  1469. values[1] = lb_const_string(m, file->data).value;
  1470. LLVMValueRef element = llvm_const_named_struct(m, t_load_directory_file, values, gb_count_of(values));
  1471. elements[i] = element;
  1472. }
  1473. LLVMValueRef backing_array = llvm_const_array(lb_type(m, t_load_directory_file), elements, count);
  1474. Type *array_type = alloc_type_array(t_load_directory_file, count);
  1475. lbAddr backing_array_addr = lb_add_global_generated(m, array_type, {backing_array, array_type}, nullptr);
  1476. lb_make_global_private_const(backing_array_addr);
  1477. LLVMValueRef backing_array_ptr = backing_array_addr.addr.value;
  1478. backing_array_ptr = LLVMConstPointerCast(backing_array_ptr, lb_type(m, t_load_directory_file_ptr));
  1479. LLVMValueRef const_slice = llvm_const_slice_internal(m, backing_array_ptr, LLVMConstInt(lb_type(m, t_int), count, false));
  1480. lbAddr addr = lb_add_global_generated(p->module, tv.type, {const_slice, t_load_directory_file_slice}, nullptr);
  1481. lb_make_global_private_const(addr);
  1482. return lb_addr_load(p, addr);
  1483. } else {
  1484. GB_PANIC("UNKNOWN DIRECTIVE: %.*s", LIT(name));
  1485. }
  1486. }
  1487. case BuiltinProc_type_info_of: {
  1488. Ast *arg = ce->args[0];
  1489. TypeAndValue tav = type_and_value_of_expr(arg);
  1490. if (tav.mode == Addressing_Type) {
  1491. Type *t = default_type(type_of_expr(arg));
  1492. return lb_type_info(p, t);
  1493. }
  1494. GB_ASSERT(is_type_typeid(tav.type));
  1495. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1496. args[0] = lb_build_expr(p, arg);
  1497. return lb_emit_runtime_call(p, "__type_info_of", args);
  1498. }
  1499. case BuiltinProc_typeid_of: {
  1500. Ast *arg = ce->args[0];
  1501. TypeAndValue tav = type_and_value_of_expr(arg);
  1502. GB_ASSERT(tav.mode == Addressing_Type);
  1503. Type *t = default_type(type_of_expr(arg));
  1504. return lb_typeid(p->module, t);
  1505. }
  1506. case BuiltinProc_len: {
  1507. lbValue v = lb_build_expr(p, ce->args[0]);
  1508. Type *t = base_type(v.type);
  1509. if (is_type_pointer(t)) {
  1510. v = lb_emit_load(p, v);
  1511. t = type_deref(t);
  1512. }
  1513. if (is_type_cstring(t)) {
  1514. return lb_cstring_len(p, v);
  1515. } else if (is_type_string(t)) {
  1516. return lb_string_len(p, v);
  1517. } else if (is_type_array(t)) {
  1518. GB_PANIC("Array lengths are constant");
  1519. } else if (is_type_slice(t)) {
  1520. return lb_slice_len(p, v);
  1521. } else if (is_type_dynamic_array(t)) {
  1522. return lb_dynamic_array_len(p, v);
  1523. } else if (is_type_map(t)) {
  1524. return lb_map_len(p, v);
  1525. } else if (is_type_soa_struct(t)) {
  1526. return lb_soa_struct_len(p, v);
  1527. }
  1528. GB_PANIC("Unreachable");
  1529. break;
  1530. }
  1531. case BuiltinProc_cap: {
  1532. lbValue v = lb_build_expr(p, ce->args[0]);
  1533. Type *t = base_type(v.type);
  1534. if (is_type_pointer(t)) {
  1535. v = lb_emit_load(p, v);
  1536. t = type_deref(t);
  1537. }
  1538. if (is_type_string(t)) {
  1539. GB_PANIC("Unreachable");
  1540. } else if (is_type_array(t)) {
  1541. GB_PANIC("Array lengths are constant");
  1542. } else if (is_type_slice(t)) {
  1543. return lb_slice_len(p, v);
  1544. } else if (is_type_dynamic_array(t)) {
  1545. return lb_dynamic_array_cap(p, v);
  1546. } else if (is_type_map(t)) {
  1547. return lb_map_cap(p, v);
  1548. } else if (is_type_soa_struct(t)) {
  1549. return lb_soa_struct_cap(p, v);
  1550. }
  1551. GB_PANIC("Unreachable");
  1552. break;
  1553. }
  1554. case BuiltinProc_swizzle: {
  1555. isize index_count = ce->args.count-1;
  1556. if (is_type_simd_vector(tv.type)) {
  1557. lbValue vec = lb_build_expr(p, ce->args[0]);
  1558. if (index_count == 0) {
  1559. return vec;
  1560. }
  1561. unsigned mask_len = cast(unsigned)index_count;
  1562. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1563. for (isize i = 1; i < ce->args.count; i++) {
  1564. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  1565. GB_ASSERT(is_type_integer(tv.type));
  1566. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  1567. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  1568. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  1569. }
  1570. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1571. LLVMValueRef v1 = vec.value;
  1572. LLVMValueRef v2 = vec.value;
  1573. lbValue res = {};
  1574. res.type = tv.type;
  1575. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1576. return res;
  1577. }
  1578. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  1579. return lb_addr_load(p, addr);
  1580. }
  1581. case BuiltinProc_complex: {
  1582. lbValue real = lb_build_expr(p, ce->args[0]);
  1583. lbValue imag = lb_build_expr(p, ce->args[1]);
  1584. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1585. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1586. Type *ft = base_complex_elem_type(tv.type);
  1587. real = lb_emit_conv(p, real, ft);
  1588. imag = lb_emit_conv(p, imag, ft);
  1589. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  1590. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  1591. return lb_emit_load(p, dst);
  1592. }
  1593. case BuiltinProc_quaternion: {
  1594. lbValue xyzw[4] = {};
  1595. for (i32 i = 0; i < 4; i++) {
  1596. ast_node(f, FieldValue, ce->args[i]);
  1597. GB_ASSERT(f->field->kind == Ast_Ident);
  1598. String name = f->field->Ident.token.string;
  1599. i32 index = -1;
  1600. // @QuaternionLayout
  1601. if (name == "x" || name == "imag") {
  1602. index = 0;
  1603. } else if (name == "y" || name == "jmag") {
  1604. index = 1;
  1605. } else if (name == "z" || name == "kmag") {
  1606. index = 2;
  1607. } else if (name == "w" || name == "real") {
  1608. index = 3;
  1609. }
  1610. GB_ASSERT(index >= 0);
  1611. xyzw[index] = lb_build_expr(p, f->value);
  1612. }
  1613. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1614. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1615. Type *ft = base_complex_elem_type(tv.type);
  1616. xyzw[0] = lb_emit_conv(p, xyzw[0], ft);
  1617. xyzw[1] = lb_emit_conv(p, xyzw[1], ft);
  1618. xyzw[2] = lb_emit_conv(p, xyzw[2], ft);
  1619. xyzw[3] = lb_emit_conv(p, xyzw[3], ft);
  1620. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), xyzw[0]);
  1621. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), xyzw[1]);
  1622. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), xyzw[2]);
  1623. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), xyzw[3]);
  1624. return lb_emit_load(p, dst);
  1625. }
  1626. case BuiltinProc_real: {
  1627. lbValue val = lb_build_expr(p, ce->args[0]);
  1628. if (is_type_complex(val.type)) {
  1629. lbValue real = lb_emit_struct_ev(p, val, 0);
  1630. return lb_emit_conv(p, real, tv.type);
  1631. } else if (is_type_quaternion(val.type)) {
  1632. // @QuaternionLayout
  1633. lbValue real = lb_emit_struct_ev(p, val, 3);
  1634. return lb_emit_conv(p, real, tv.type);
  1635. }
  1636. GB_PANIC("invalid type for real");
  1637. return {};
  1638. }
  1639. case BuiltinProc_imag: {
  1640. lbValue val = lb_build_expr(p, ce->args[0]);
  1641. if (is_type_complex(val.type)) {
  1642. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1643. return lb_emit_conv(p, imag, tv.type);
  1644. } else if (is_type_quaternion(val.type)) {
  1645. // @QuaternionLayout
  1646. lbValue imag = lb_emit_struct_ev(p, val, 0);
  1647. return lb_emit_conv(p, imag, tv.type);
  1648. }
  1649. GB_PANIC("invalid type for imag");
  1650. return {};
  1651. }
  1652. case BuiltinProc_jmag: {
  1653. lbValue val = lb_build_expr(p, ce->args[0]);
  1654. if (is_type_quaternion(val.type)) {
  1655. // @QuaternionLayout
  1656. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1657. return lb_emit_conv(p, imag, tv.type);
  1658. }
  1659. GB_PANIC("invalid type for jmag");
  1660. return {};
  1661. }
  1662. case BuiltinProc_kmag: {
  1663. lbValue val = lb_build_expr(p, ce->args[0]);
  1664. if (is_type_quaternion(val.type)) {
  1665. // @QuaternionLayout
  1666. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1667. return lb_emit_conv(p, imag, tv.type);
  1668. }
  1669. GB_PANIC("invalid type for kmag");
  1670. return {};
  1671. }
  1672. case BuiltinProc_conj: {
  1673. lbValue val = lb_build_expr(p, ce->args[0]);
  1674. return lb_emit_conjugate(p, val, tv.type);
  1675. }
  1676. case BuiltinProc_expand_values: {
  1677. lbValue val = lb_build_expr(p, ce->args[0]);
  1678. Type *t = base_type(val.type);
  1679. if (!is_type_tuple(tv.type)) {
  1680. if (t->kind == Type_Struct) {
  1681. GB_ASSERT(t->Struct.fields.count == 1);
  1682. return lb_emit_struct_ev(p, val, 0);
  1683. } else if (t->kind == Type_Array) {
  1684. GB_ASSERT(t->Array.count == 1);
  1685. return lb_emit_struct_ev(p, val, 0);
  1686. } else {
  1687. GB_PANIC("Unknown type of expand_values");
  1688. }
  1689. }
  1690. GB_ASSERT(is_type_tuple(tv.type));
  1691. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1692. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1693. if (t->kind == Type_Struct) {
  1694. for_array(src_index, t->Struct.fields) {
  1695. Entity *field = t->Struct.fields[src_index];
  1696. i32 field_index = field->Variable.field_index;
  1697. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1698. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1699. lb_emit_store(p, ep, f);
  1700. }
  1701. } else if (is_type_array_like(t)) {
  1702. // TODO(bill): Clean-up this code
  1703. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1704. i32 n = cast(i32)get_array_type_count(t);
  1705. for (i32 i = 0; i < n; i++) {
  1706. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1707. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1708. lb_emit_store(p, ep, f);
  1709. }
  1710. } else {
  1711. GB_PANIC("Unknown type of expand_values");
  1712. }
  1713. return lb_emit_load(p, tuple);
  1714. }
  1715. case BuiltinProc_min: {
  1716. Type *t = type_of_expr(expr);
  1717. if (ce->args.count == 2) {
  1718. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1719. } else {
  1720. lbValue x = lb_build_expr(p, ce->args[0]);
  1721. for (isize i = 1; i < ce->args.count; i++) {
  1722. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1723. }
  1724. return x;
  1725. }
  1726. }
  1727. case BuiltinProc_max: {
  1728. Type *t = type_of_expr(expr);
  1729. if (ce->args.count == 2) {
  1730. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1731. } else {
  1732. lbValue x = lb_build_expr(p, ce->args[0]);
  1733. for (isize i = 1; i < ce->args.count; i++) {
  1734. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1735. }
  1736. return x;
  1737. }
  1738. }
  1739. case BuiltinProc_abs: {
  1740. lbValue x = lb_build_expr(p, ce->args[0]);
  1741. Type *t = x.type;
  1742. if (is_type_unsigned(t)) {
  1743. return x;
  1744. }
  1745. if (is_type_quaternion(t)) {
  1746. i64 sz = 8*type_size_of(t);
  1747. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1748. args[0] = x;
  1749. switch (sz) {
  1750. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1751. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1752. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1753. }
  1754. GB_PANIC("Unknown complex type");
  1755. } else if (is_type_complex(t)) {
  1756. i64 sz = 8*type_size_of(t);
  1757. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1758. args[0] = x;
  1759. switch (sz) {
  1760. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1761. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1762. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1763. }
  1764. GB_PANIC("Unknown complex type");
  1765. }
  1766. lbValue zero = lb_const_nil(p->module, t);
  1767. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1768. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1769. return lb_emit_select(p, cond, neg, x);
  1770. }
  1771. case BuiltinProc_clamp:
  1772. return lb_emit_clamp(p, type_of_expr(expr),
  1773. lb_build_expr(p, ce->args[0]),
  1774. lb_build_expr(p, ce->args[1]),
  1775. lb_build_expr(p, ce->args[2]));
  1776. case BuiltinProc_soa_zip:
  1777. return lb_soa_zip(p, ce, tv);
  1778. case BuiltinProc_soa_unzip:
  1779. return lb_soa_unzip(p, ce, tv);
  1780. case BuiltinProc_transpose:
  1781. {
  1782. lbValue m = lb_build_expr(p, ce->args[0]);
  1783. return lb_emit_matrix_tranpose(p, m, tv.type);
  1784. }
  1785. case BuiltinProc_outer_product:
  1786. {
  1787. lbValue a = lb_build_expr(p, ce->args[0]);
  1788. lbValue b = lb_build_expr(p, ce->args[1]);
  1789. return lb_emit_outer_product(p, a, b, tv.type);
  1790. }
  1791. case BuiltinProc_hadamard_product:
  1792. {
  1793. lbValue a = lb_build_expr(p, ce->args[0]);
  1794. lbValue b = lb_build_expr(p, ce->args[1]);
  1795. if (is_type_array(tv.type)) {
  1796. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1797. }
  1798. GB_ASSERT(is_type_matrix(tv.type));
  1799. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1800. }
  1801. case BuiltinProc_matrix_flatten:
  1802. {
  1803. lbValue m = lb_build_expr(p, ce->args[0]);
  1804. return lb_emit_matrix_flatten(p, m, tv.type);
  1805. }
  1806. case BuiltinProc_unreachable:
  1807. lb_emit_unreachable(p);
  1808. return {};
  1809. case BuiltinProc_raw_data:
  1810. {
  1811. lbValue x = lb_build_expr(p, ce->args[0]);
  1812. Type *t = base_type(x.type);
  1813. lbValue res = {};
  1814. switch (t->kind) {
  1815. case Type_Slice:
  1816. res = lb_slice_elem(p, x);
  1817. res = lb_emit_conv(p, res, tv.type);
  1818. break;
  1819. case Type_DynamicArray:
  1820. res = lb_dynamic_array_elem(p, x);
  1821. res = lb_emit_conv(p, res, tv.type);
  1822. break;
  1823. case Type_Basic:
  1824. if (t->Basic.kind == Basic_string) {
  1825. res = lb_string_elem(p, x);
  1826. res = lb_emit_conv(p, res, tv.type);
  1827. } else if (t->Basic.kind == Basic_cstring) {
  1828. res = lb_emit_conv(p, x, tv.type);
  1829. }
  1830. break;
  1831. case Type_Pointer:
  1832. case Type_MultiPointer:
  1833. res = lb_emit_conv(p, x, tv.type);
  1834. break;
  1835. }
  1836. GB_ASSERT(res.value != nullptr);
  1837. return res;
  1838. }
  1839. // "Intrinsics"
  1840. case BuiltinProc_alloca:
  1841. {
  1842. lbValue sz = lb_build_expr(p, ce->args[0]);
  1843. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1844. lbValue res = {};
  1845. res.type = alloc_type_multi_pointer(t_u8);
  1846. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1847. LLVMSetAlignment(res.value, cast(unsigned)al);
  1848. return res;
  1849. }
  1850. case BuiltinProc_cpu_relax:
  1851. if (build_context.metrics.arch == TargetArch_i386 ||
  1852. build_context.metrics.arch == TargetArch_amd64) {
  1853. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1854. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1855. GB_ASSERT(the_asm != nullptr);
  1856. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1857. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1858. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1859. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1860. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1861. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1862. GB_ASSERT(the_asm != nullptr);
  1863. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1864. } else {
  1865. // NOTE: default to something to prevent optimization
  1866. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1867. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1868. GB_ASSERT(the_asm != nullptr);
  1869. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1870. }
  1871. return {};
  1872. case BuiltinProc_debug_trap:
  1873. case BuiltinProc_trap:
  1874. {
  1875. char const *name = nullptr;
  1876. switch (id) {
  1877. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1878. case BuiltinProc_trap: name = "llvm.trap"; break;
  1879. }
  1880. lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1881. if (id == BuiltinProc_trap) {
  1882. LLVMBuildUnreachable(p->builder);
  1883. }
  1884. return {};
  1885. }
  1886. case BuiltinProc_read_cycle_counter:
  1887. {
  1888. lbValue res = {};
  1889. res.type = tv.type;
  1890. if (build_context.metrics.arch == TargetArch_arm64) {
  1891. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1892. bool has_side_effects = false;
  1893. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs $0, cntvct_el0"), str_lit("=r"), has_side_effects);
  1894. GB_ASSERT(the_asm != nullptr);
  1895. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1896. } else {
  1897. char const *name = "llvm.readcyclecounter";
  1898. res.value = lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1899. }
  1900. return res;
  1901. }
  1902. case BuiltinProc_count_trailing_zeros:
  1903. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1904. case BuiltinProc_count_leading_zeros:
  1905. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1906. case BuiltinProc_count_ones:
  1907. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1908. case BuiltinProc_count_zeros:
  1909. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1910. case BuiltinProc_reverse_bits:
  1911. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1912. case BuiltinProc_byte_swap:
  1913. {
  1914. lbValue x = lb_build_expr(p, ce->args[0]);
  1915. x = lb_emit_conv(p, x, tv.type);
  1916. return lb_emit_byte_swap(p, x, tv.type);
  1917. }
  1918. case BuiltinProc_overflow_add:
  1919. case BuiltinProc_overflow_sub:
  1920. case BuiltinProc_overflow_mul:
  1921. {
  1922. Type *main_type = tv.type;
  1923. Type *type = main_type;
  1924. if (is_type_tuple(main_type)) {
  1925. type = main_type->Tuple.variables[0]->type;
  1926. }
  1927. lbValue x = lb_build_expr(p, ce->args[0]);
  1928. lbValue y = lb_build_expr(p, ce->args[1]);
  1929. x = lb_emit_conv(p, x, type);
  1930. y = lb_emit_conv(p, y, type);
  1931. char const *name = nullptr;
  1932. if (is_type_unsigned(type)) {
  1933. switch (id) {
  1934. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1935. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1936. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1937. }
  1938. } else {
  1939. switch (id) {
  1940. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1941. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1942. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1943. }
  1944. }
  1945. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1946. LLVMValueRef args[2] = { x.value, y.value };
  1947. lbValue res = {};
  1948. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1949. if (is_type_tuple(main_type)) {
  1950. Type *res_type = nullptr;
  1951. gbAllocator a = permanent_allocator();
  1952. res_type = alloc_type_tuple();
  1953. slice_init(&res_type->Tuple.variables, a, 2);
  1954. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1955. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1956. res.type = res_type;
  1957. } else {
  1958. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1959. res.type = type;
  1960. }
  1961. return res;
  1962. }
  1963. case BuiltinProc_sqrt:
  1964. {
  1965. Type *type = tv.type;
  1966. lbValue x = lb_build_expr(p, ce->args[0]);
  1967. x = lb_emit_conv(p, x, type);
  1968. char const *name = "llvm.sqrt";
  1969. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1970. LLVMValueRef args[1] = { x.value };
  1971. lbValue res = {};
  1972. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1973. res.type = type;
  1974. return res;
  1975. }
  1976. case BuiltinProc_fused_mul_add:
  1977. {
  1978. Type *type = tv.type;
  1979. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), type);
  1980. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), type);
  1981. lbValue z = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), type);
  1982. char const *name = "llvm.fma";
  1983. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1984. LLVMValueRef args[3] = { x.value, y.value, z.value };
  1985. lbValue res = {};
  1986. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1987. res.type = type;
  1988. return res;
  1989. }
  1990. case BuiltinProc_mem_copy:
  1991. {
  1992. lbValue dst = lb_build_expr(p, ce->args[0]);
  1993. lbValue src = lb_build_expr(p, ce->args[1]);
  1994. lbValue len = lb_build_expr(p, ce->args[2]);
  1995. lb_mem_copy_overlapping(p, dst, src, len, false);
  1996. return {};
  1997. }
  1998. case BuiltinProc_mem_copy_non_overlapping:
  1999. {
  2000. lbValue dst = lb_build_expr(p, ce->args[0]);
  2001. lbValue src = lb_build_expr(p, ce->args[1]);
  2002. lbValue len = lb_build_expr(p, ce->args[2]);
  2003. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  2004. return {};
  2005. }
  2006. case BuiltinProc_mem_zero:
  2007. {
  2008. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2009. lbValue len = lb_build_expr(p, ce->args[1]);
  2010. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2011. len = lb_emit_conv(p, len, t_int);
  2012. unsigned alignment = 1;
  2013. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  2014. return {};
  2015. }
  2016. case BuiltinProc_mem_zero_volatile:
  2017. {
  2018. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2019. lbValue len = lb_build_expr(p, ce->args[1]);
  2020. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2021. len = lb_emit_conv(p, len, t_int);
  2022. unsigned alignment = 1;
  2023. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  2024. return {};
  2025. }
  2026. case BuiltinProc_ptr_offset:
  2027. {
  2028. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2029. lbValue len = lb_build_expr(p, ce->args[1]);
  2030. len = lb_emit_conv(p, len, t_int);
  2031. return lb_emit_ptr_offset(p, ptr, len);
  2032. }
  2033. case BuiltinProc_ptr_sub:
  2034. {
  2035. Type *elem0 = type_deref(type_of_expr(ce->args[0]));
  2036. Type *elem1 = type_deref(type_of_expr(ce->args[1]));
  2037. GB_ASSERT(are_types_identical(elem0, elem1));
  2038. Type *elem = elem0;
  2039. lbValue ptr0 = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr);
  2040. lbValue ptr1 = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr);
  2041. ptr0 = lb_emit_conv(p, ptr0, t_int);
  2042. ptr1 = lb_emit_conv(p, ptr1, t_int);
  2043. lbValue diff = lb_emit_arith(p, Token_Sub, ptr0, ptr1, t_int);
  2044. return lb_emit_arith(p, Token_Quo, diff, lb_const_int(p->module, t_int, type_size_of(elem)), t_int);
  2045. }
  2046. // TODO(bill): Which is correct?
  2047. case BuiltinProc_atomic_thread_fence:
  2048. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  2049. return {};
  2050. case BuiltinProc_atomic_signal_fence:
  2051. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  2052. return {};
  2053. case BuiltinProc_volatile_store:
  2054. case BuiltinProc_non_temporal_store:
  2055. case BuiltinProc_atomic_store:
  2056. case BuiltinProc_atomic_store_explicit: {
  2057. lbValue dst = lb_build_expr(p, ce->args[0]);
  2058. lbValue val = lb_build_expr(p, ce->args[1]);
  2059. val = lb_emit_conv(p, val, type_deref(dst.type));
  2060. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  2061. switch (id) {
  2062. case BuiltinProc_non_temporal_store:
  2063. {
  2064. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2065. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2066. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2067. }
  2068. break;
  2069. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  2070. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2071. case BuiltinProc_atomic_store_explicit:
  2072. {
  2073. auto ordering = llvm_atomic_ordering_from_odin(ce->args[2]);
  2074. LLVMSetOrdering(instr, ordering);
  2075. if (ordering == LLVMAtomicOrderingUnordered) {
  2076. LLVMSetVolatile(instr, true);
  2077. }
  2078. }
  2079. break;
  2080. }
  2081. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2082. return {};
  2083. }
  2084. case BuiltinProc_volatile_load:
  2085. case BuiltinProc_non_temporal_load:
  2086. case BuiltinProc_atomic_load:
  2087. case BuiltinProc_atomic_load_explicit: {
  2088. lbValue dst = lb_build_expr(p, ce->args[0]);
  2089. LLVMValueRef instr = LLVMBuildLoad2(p->builder, lb_type(p->module, type_deref(dst.type)), dst.value, "");
  2090. switch (id) {
  2091. case BuiltinProc_non_temporal_load:
  2092. {
  2093. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2094. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2095. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2096. }
  2097. break;
  2098. break;
  2099. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  2100. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2101. case BuiltinProc_atomic_load_explicit:
  2102. {
  2103. auto ordering = llvm_atomic_ordering_from_odin(ce->args[1]);
  2104. LLVMSetOrdering(instr, ordering);
  2105. if (ordering == LLVMAtomicOrderingUnordered) {
  2106. LLVMSetVolatile(instr, true);
  2107. }
  2108. }
  2109. break;
  2110. }
  2111. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2112. lbValue res = {};
  2113. res.value = instr;
  2114. res.type = type_deref(dst.type);
  2115. return res;
  2116. }
  2117. case BuiltinProc_unaligned_store:
  2118. {
  2119. lbValue dst = lb_build_expr(p, ce->args[0]);
  2120. lbValue src = lb_build_expr(p, ce->args[1]);
  2121. Type *t = type_deref(dst.type);
  2122. if (is_type_simd_vector(t)) {
  2123. LLVMValueRef store = LLVMBuildStore(p->builder, src.value, dst.value);
  2124. LLVMSetAlignment(store, 1);
  2125. } else {
  2126. src = lb_address_from_load_or_generate_local(p, src);
  2127. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2128. }
  2129. return {};
  2130. }
  2131. case BuiltinProc_unaligned_load:
  2132. {
  2133. lbValue src = lb_build_expr(p, ce->args[0]);
  2134. Type *t = type_deref(src.type);
  2135. if (is_type_simd_vector(t)) {
  2136. lbValue res = {};
  2137. res.type = t;
  2138. res.value = LLVMBuildLoad2(p->builder, lb_type(p->module, t), src.value, "");
  2139. LLVMSetAlignment(res.value, 1);
  2140. return res;
  2141. } else {
  2142. lbAddr dst = lb_add_local_generated(p, t, false);
  2143. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2144. return lb_addr_load(p, dst);
  2145. }
  2146. }
  2147. case BuiltinProc_atomic_add:
  2148. case BuiltinProc_atomic_sub:
  2149. case BuiltinProc_atomic_and:
  2150. case BuiltinProc_atomic_nand:
  2151. case BuiltinProc_atomic_or:
  2152. case BuiltinProc_atomic_xor:
  2153. case BuiltinProc_atomic_exchange:
  2154. case BuiltinProc_atomic_add_explicit:
  2155. case BuiltinProc_atomic_sub_explicit:
  2156. case BuiltinProc_atomic_and_explicit:
  2157. case BuiltinProc_atomic_nand_explicit:
  2158. case BuiltinProc_atomic_or_explicit:
  2159. case BuiltinProc_atomic_xor_explicit:
  2160. case BuiltinProc_atomic_exchange_explicit: {
  2161. lbValue dst = lb_build_expr(p, ce->args[0]);
  2162. lbValue val = lb_build_expr(p, ce->args[1]);
  2163. val = lb_emit_conv(p, val, type_deref(dst.type));
  2164. LLVMAtomicRMWBinOp op = {};
  2165. LLVMAtomicOrdering ordering = {};
  2166. switch (id) {
  2167. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2168. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2169. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2170. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2171. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2172. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2173. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2174. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2175. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2176. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2177. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2178. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2179. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2180. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2181. }
  2182. lbValue res = {};
  2183. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  2184. res.type = tv.type;
  2185. if (ordering == LLVMAtomicOrderingUnordered) {
  2186. LLVMSetVolatile(res.value, true);
  2187. }
  2188. return res;
  2189. }
  2190. case BuiltinProc_atomic_compare_exchange_strong:
  2191. case BuiltinProc_atomic_compare_exchange_weak:
  2192. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  2193. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  2194. lbValue address = lb_build_expr(p, ce->args[0]);
  2195. Type *elem = type_deref(address.type);
  2196. lbValue old_value = lb_build_expr(p, ce->args[1]);
  2197. lbValue new_value = lb_build_expr(p, ce->args[2]);
  2198. old_value = lb_emit_conv(p, old_value, elem);
  2199. new_value = lb_emit_conv(p, new_value, elem);
  2200. LLVMAtomicOrdering success_ordering = {};
  2201. LLVMAtomicOrdering failure_ordering = {};
  2202. LLVMBool weak = false;
  2203. switch (id) {
  2204. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  2205. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  2206. case BuiltinProc_atomic_compare_exchange_strong_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = false; break;
  2207. case BuiltinProc_atomic_compare_exchange_weak_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = true; break;
  2208. }
  2209. LLVMBool single_threaded = false;
  2210. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  2211. p->builder, address.value,
  2212. old_value.value, new_value.value,
  2213. success_ordering,
  2214. failure_ordering,
  2215. single_threaded
  2216. );
  2217. LLVMSetWeak(value, weak);
  2218. if (success_ordering == LLVMAtomicOrderingUnordered || failure_ordering == LLVMAtomicOrderingUnordered) {
  2219. LLVMSetVolatile(value, true);
  2220. }
  2221. if (is_type_tuple(tv.type)) {
  2222. Type *fix_typed = alloc_type_tuple();
  2223. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  2224. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  2225. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2226. lbValue res = {};
  2227. res.value = value;
  2228. res.type = fix_typed;
  2229. return res;
  2230. } else {
  2231. lbValue res = {};
  2232. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  2233. res.type = tv.type;
  2234. return res;
  2235. }
  2236. }
  2237. case BuiltinProc_type_equal_proc:
  2238. return lb_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  2239. case BuiltinProc_type_hasher_proc:
  2240. return lb_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  2241. case BuiltinProc_type_map_info:
  2242. return lb_gen_map_info_ptr(p->module, ce->args[0]->tav.type);
  2243. case BuiltinProc_type_map_cell_info:
  2244. return lb_gen_map_cell_info_ptr(p->module, ce->args[0]->tav.type);
  2245. case BuiltinProc_fixed_point_mul:
  2246. case BuiltinProc_fixed_point_div:
  2247. case BuiltinProc_fixed_point_mul_sat:
  2248. case BuiltinProc_fixed_point_div_sat:
  2249. {
  2250. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  2251. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  2252. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  2253. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  2254. char const *name = nullptr;
  2255. if (is_type_unsigned(tv.type)) {
  2256. switch (id) {
  2257. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  2258. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  2259. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  2260. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  2261. }
  2262. } else {
  2263. switch (id) {
  2264. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  2265. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  2266. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  2267. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  2268. }
  2269. }
  2270. GB_ASSERT(name != nullptr);
  2271. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  2272. lbValue res = {};
  2273. LLVMValueRef args[3] = {
  2274. x.value,
  2275. y.value,
  2276. scale.value };
  2277. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2278. res.type = platform_type;
  2279. return lb_emit_conv(p, res, tv.type);
  2280. }
  2281. case BuiltinProc_expect:
  2282. {
  2283. Type *t = default_type(tv.type);
  2284. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  2285. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  2286. char const *name = "llvm.expect";
  2287. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  2288. lbValue res = {};
  2289. LLVMValueRef args[2] = { x.value, y.value };
  2290. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2291. res.type = t;
  2292. return lb_emit_conv(p, res, t);
  2293. }
  2294. case BuiltinProc_prefetch_read_instruction:
  2295. case BuiltinProc_prefetch_read_data:
  2296. case BuiltinProc_prefetch_write_instruction:
  2297. case BuiltinProc_prefetch_write_data:
  2298. {
  2299. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  2300. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  2301. unsigned long long rw = 0;
  2302. unsigned long long cache = 0;
  2303. switch (id) {
  2304. case BuiltinProc_prefetch_read_instruction:
  2305. rw = 0;
  2306. cache = 0;
  2307. break;
  2308. case BuiltinProc_prefetch_read_data:
  2309. rw = 0;
  2310. cache = 1;
  2311. break;
  2312. case BuiltinProc_prefetch_write_instruction:
  2313. rw = 1;
  2314. cache = 0;
  2315. break;
  2316. case BuiltinProc_prefetch_write_data:
  2317. rw = 1;
  2318. cache = 1;
  2319. break;
  2320. }
  2321. char const *name = "llvm.prefetch";
  2322. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  2323. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  2324. LLVMValueRef args[4] = {};
  2325. args[0] = ptr.value;
  2326. args[1] = LLVMConstInt(llvm_i32, rw, false);
  2327. args[2] = LLVMConstInt(llvm_i32, locality, false);
  2328. args[3] = LLVMConstInt(llvm_i32, cache, false);
  2329. lbValue res = {};
  2330. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2331. res.type = nullptr;
  2332. return res;
  2333. }
  2334. case BuiltinProc___entry_point:
  2335. if (p->module->info->entry_point) {
  2336. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  2337. GB_ASSERT(entry_point.value != nullptr);
  2338. lb_emit_call(p, entry_point, {});
  2339. }
  2340. return {};
  2341. case BuiltinProc_syscall:
  2342. {
  2343. unsigned arg_count = cast(unsigned)ce->args.count;
  2344. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2345. for_array(i, ce->args) {
  2346. lbValue arg = lb_build_expr(p, ce->args[i]);
  2347. arg = lb_emit_conv(p, arg, t_uintptr);
  2348. args[i] = arg.value;
  2349. }
  2350. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2351. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2352. for (unsigned i = 0; i < arg_count; i++) {
  2353. llvm_arg_types[i] = llvm_uintptr;
  2354. }
  2355. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  2356. LLVMValueRef inline_asm = nullptr;
  2357. switch (build_context.metrics.arch) {
  2358. case TargetArch_amd64:
  2359. {
  2360. GB_ASSERT(arg_count <= 7);
  2361. // FreeBSD additionally clobbers r8, r9, r10, but they
  2362. // can also be used to pass in arguments, so this needs
  2363. // to be handled in two parts.
  2364. bool clobber_arg_regs[7] = {
  2365. false, false, false, false, false, false, false
  2366. };
  2367. if (build_context.metrics.os == TargetOs_freebsd) {
  2368. clobber_arg_regs[4] = true; // r10
  2369. clobber_arg_regs[5] = true; // r8
  2370. clobber_arg_regs[6] = true; // r9
  2371. }
  2372. char asm_string[] = "syscall";
  2373. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  2374. for (unsigned i = 0; i < arg_count; i++) {
  2375. if (!clobber_arg_regs[i]) {
  2376. constraints = gb_string_appendc(constraints, ",{");
  2377. } else {
  2378. constraints = gb_string_appendc(constraints, ",+{");
  2379. }
  2380. static char const *regs[] = {
  2381. "rax",
  2382. "rdi",
  2383. "rsi",
  2384. "rdx",
  2385. "r10",
  2386. "r8",
  2387. "r9"
  2388. };
  2389. constraints = gb_string_appendc(constraints, regs[i]);
  2390. constraints = gb_string_appendc(constraints, "}");
  2391. }
  2392. // The SYSCALL instruction stores the address of the
  2393. // following instruction into RCX, and RFLAGS in R11.
  2394. //
  2395. // RSP is not saved, but at least on Linux it appears
  2396. // that the kernel system-call handler does the right
  2397. // thing.
  2398. //
  2399. // Some but not all system calls will additionally
  2400. // clobber memory.
  2401. //
  2402. // As a fix for CVE-2019-5595, FreeBSD started
  2403. // clobbering R8, R9, and R10, instead of restoring
  2404. // them. Additionally unlike Linux, instead of
  2405. // returning negative errno, positive errno is
  2406. // returned and CF is set.
  2407. //
  2408. // TODO:
  2409. // * Figure out what Darwin does.
  2410. // * Add some extra handling to propagate CF back
  2411. // up to the caller on FreeBSD systems so that
  2412. // the caller knows that the return value is
  2413. // positive errno.
  2414. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  2415. if (build_context.metrics.os == TargetOs_freebsd) {
  2416. // Second half of dealing with FreeBSD's system
  2417. // call semantics. Explicitly clobber the registers
  2418. // that were not used to pass in arguments, and
  2419. // then clobber RFLAGS.
  2420. if (arg_count < 5) {
  2421. constraints = gb_string_appendc(constraints, ",~{r10}");
  2422. }
  2423. if (arg_count < 6) {
  2424. constraints = gb_string_appendc(constraints, ",~{r8}");
  2425. }
  2426. if (arg_count < 7) {
  2427. constraints = gb_string_appendc(constraints, ",~{r9}");
  2428. }
  2429. constraints = gb_string_appendc(constraints, ",~{cc}");
  2430. }
  2431. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2432. }
  2433. break;
  2434. case TargetArch_i386:
  2435. {
  2436. GB_ASSERT(arg_count <= 7);
  2437. char asm_string[] = "int $$0x80";
  2438. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  2439. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  2440. constraints = gb_string_appendc(constraints, ",{");
  2441. static char const *regs[] = {
  2442. "eax",
  2443. "ebx",
  2444. "ecx",
  2445. "edx",
  2446. "esi",
  2447. "edi",
  2448. "ebp",
  2449. };
  2450. constraints = gb_string_appendc(constraints, regs[i]);
  2451. constraints = gb_string_appendc(constraints, "}");
  2452. }
  2453. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2454. }
  2455. break;
  2456. case TargetArch_arm64:
  2457. {
  2458. GB_ASSERT(arg_count <= 7);
  2459. if(build_context.metrics.os == TargetOs_darwin) {
  2460. char asm_string[] = "svc #0x80";
  2461. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2462. for (unsigned i = 0; i < arg_count; i++) {
  2463. constraints = gb_string_appendc(constraints, ",{");
  2464. static char const *regs[] = {
  2465. "x16",
  2466. "x0",
  2467. "x1",
  2468. "x2",
  2469. "x3",
  2470. "x4",
  2471. "x5",
  2472. };
  2473. constraints = gb_string_appendc(constraints, regs[i]);
  2474. constraints = gb_string_appendc(constraints, "}");
  2475. }
  2476. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2477. } else {
  2478. char asm_string[] = "svc #0";
  2479. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2480. for (unsigned i = 0; i < arg_count; i++) {
  2481. constraints = gb_string_appendc(constraints, ",{");
  2482. static char const *regs[] = {
  2483. "x8",
  2484. "x0",
  2485. "x1",
  2486. "x2",
  2487. "x3",
  2488. "x4",
  2489. "x5",
  2490. };
  2491. constraints = gb_string_appendc(constraints, regs[i]);
  2492. constraints = gb_string_appendc(constraints, "}");
  2493. }
  2494. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2495. }
  2496. }
  2497. break;
  2498. case TargetArch_arm32:
  2499. {
  2500. GB_ASSERT(arg_count <= 7);
  2501. char asm_string[] = "svc #0";
  2502. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  2503. for (unsigned i = 0; i < arg_count; i++) {
  2504. constraints = gb_string_appendc(constraints, ",{");
  2505. static char const *regs[] = {
  2506. "r7",
  2507. "r0",
  2508. "r1",
  2509. "r2",
  2510. "r3",
  2511. "r4",
  2512. "r5",
  2513. "r6",
  2514. };
  2515. constraints = gb_string_appendc(constraints, regs[i]);
  2516. constraints = gb_string_appendc(constraints, "}");
  2517. }
  2518. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2519. }
  2520. break;
  2521. default:
  2522. GB_PANIC("Unsupported platform");
  2523. }
  2524. lbValue res = {};
  2525. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2526. res.type = t_uintptr;
  2527. return res;
  2528. }
  2529. case BuiltinProc_objc_send:
  2530. return lb_handle_objc_send(p, expr);
  2531. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  2532. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  2533. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  2534. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  2535. case BuiltinProc_constant_utf16_cstring:
  2536. {
  2537. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  2538. if (r < 0x10000 || r > 0x10ffff) {
  2539. *r1 = 0xfffd;
  2540. *r2 = 0xfffd;
  2541. } else {
  2542. r -= 0x10000;
  2543. *r1 = 0xd800 + ((r>>10)&0x3ff);
  2544. *r2 = 0xdc00 + (r&0x3ff);
  2545. }
  2546. };
  2547. lbModule *m = p->module;
  2548. auto tav = type_and_value_of_expr(ce->args[0]);
  2549. GB_ASSERT(tav.value.kind == ExactValue_String);
  2550. String value = tav.value.value_string;
  2551. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  2552. isize max_len = value.len*2 + 1;
  2553. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  2554. isize n = 0;
  2555. while (value.len > 0) {
  2556. Rune r = 0;
  2557. isize w = gb_utf8_decode(value.text, value.len, &r);
  2558. value.text += w;
  2559. value.len -= w;
  2560. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  2561. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  2562. } else if (0x10000 <= r && r <= 0x10ffff) {
  2563. u16 r1, r2;
  2564. encode_surrogate_pair(r, &r1, &r2);
  2565. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  2566. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  2567. } else {
  2568. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  2569. }
  2570. }
  2571. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  2572. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  2573. char *name = nullptr;
  2574. {
  2575. isize max_len = 7+8+1;
  2576. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2577. u32 id = m->gen->global_array_index.fetch_add(1);
  2578. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2579. len -= 1;
  2580. }
  2581. LLVMTypeRef type = LLVMTypeOf(array);
  2582. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2583. LLVMSetInitializer(global_data, array);
  2584. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  2585. LLVMValueRef indices[] = {
  2586. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2587. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2588. };
  2589. lbValue res = {};
  2590. res.type = tv.type;
  2591. res.value = LLVMBuildInBoundsGEP2(p->builder, type, global_data, indices, gb_count_of(indices), "");
  2592. return res;
  2593. }
  2594. case BuiltinProc_wasm_memory_grow:
  2595. {
  2596. char const *name = "llvm.wasm.memory.grow";
  2597. LLVMTypeRef types[1] = {
  2598. lb_type(p->module, t_i32),
  2599. };
  2600. LLVMValueRef args[2] = {};
  2601. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2602. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  2603. lbValue res = {};
  2604. res.type = t_i32;
  2605. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2606. return lb_emit_conv(p, res, tv.type);
  2607. }
  2608. case BuiltinProc_wasm_memory_size:
  2609. {
  2610. char const *name = "llvm.wasm.memory.size";
  2611. LLVMTypeRef types[1] = {
  2612. lb_type(p->module, t_i32),
  2613. };
  2614. LLVMValueRef args[1] = {};
  2615. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2616. lbValue res = {};
  2617. res.type = t_i32;
  2618. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2619. return lb_emit_conv(p, res, tv.type);
  2620. }
  2621. case BuiltinProc_wasm_memory_atomic_wait32:
  2622. {
  2623. char const *name = "llvm.wasm.memory.atomic.wait32";
  2624. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2625. LLVMValueRef args[3] = {};
  2626. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  2627. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2628. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  2629. lbValue res = {};
  2630. res.type = tv.type;
  2631. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2632. return res;
  2633. }
  2634. case BuiltinProc_wasm_memory_atomic_notify32:
  2635. {
  2636. char const *name = "llvm.wasm.memory.atomic.notify";
  2637. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2638. LLVMValueRef args[2] = {
  2639. lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value,
  2640. lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value
  2641. };
  2642. lbValue res = {};
  2643. res.type = tv.type;
  2644. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2645. return res;
  2646. }
  2647. case BuiltinProc_x86_cpuid:
  2648. {
  2649. Type *param_types[2] = {t_u32, t_u32};
  2650. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), tv.type, false, ProcCC_None);
  2651. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2652. LLVMValueRef the_asm = llvm_get_inline_asm(
  2653. func_type,
  2654. str_lit("cpuid"),
  2655. str_lit("={ax},={bx},={cx},={dx},{ax},{cx}"),
  2656. true
  2657. );
  2658. GB_ASSERT(the_asm != nullptr);
  2659. LLVMValueRef args[2] = {};
  2660. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2661. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2662. lbValue res = {};
  2663. res.type = tv.type;
  2664. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2665. return res;
  2666. }
  2667. case BuiltinProc_x86_xgetbv:
  2668. {
  2669. Type *type = alloc_type_proc_from_types(&t_u32, 1, tv.type, false, ProcCC_None);
  2670. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2671. LLVMValueRef the_asm = llvm_get_inline_asm(
  2672. func_type,
  2673. str_lit("xgetbv"),
  2674. str_lit("={ax},={dx},{cx}"),
  2675. true
  2676. );
  2677. GB_ASSERT(the_asm != nullptr);
  2678. LLVMValueRef args[1] = {};
  2679. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2680. lbValue res = {};
  2681. res.type = tv.type;
  2682. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2683. return res;
  2684. }
  2685. case BuiltinProc_valgrind_client_request:
  2686. {
  2687. lbValue args[7] = {};
  2688. for (isize i = 0; i < 7; i++) {
  2689. args[i] = lb_emit_conv(p, lb_build_expr(p, ce->args[i]), t_uintptr);
  2690. }
  2691. if (!build_context.ODIN_VALGRIND_SUPPORT) {
  2692. return args[0];
  2693. }
  2694. lbValue array = lb_generate_local_array(p, t_uintptr, 6, false);
  2695. for (isize i = 0; i < 6; i++) {
  2696. lbValue gep = lb_emit_array_epi(p, array, i);
  2697. lb_emit_store(p, gep, args[i+1]);
  2698. }
  2699. switch (build_context.metrics.arch) {
  2700. case TargetArch_amd64:
  2701. {
  2702. Type *param_types[2] = {};
  2703. param_types[0] = t_uintptr;
  2704. param_types[1] = array.type;
  2705. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), t_uintptr, false, ProcCC_None);
  2706. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2707. LLVMValueRef the_asm = llvm_get_inline_asm(
  2708. func_type,
  2709. str_lit("rolq $$3, %rdi; rolq $$13, %rdi\n rolq $$61, %rdi; rolq $$51, %rdi\n xchgq %rbx, %rbx"),
  2710. str_lit("={rdx},{rdx},{rax},~{cc},~{memory}"),
  2711. true
  2712. );
  2713. LLVMValueRef asm_args[2] = {};
  2714. asm_args[0] = args[0].value;
  2715. asm_args[1] = array.value;
  2716. lbValue res = {};
  2717. res.type = t_uintptr;
  2718. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, asm_args, gb_count_of(asm_args), "");
  2719. return res;
  2720. }
  2721. break;
  2722. default:
  2723. GB_PANIC("Unsupported architecture: %.*s", LIT(target_arch_names[build_context.metrics.arch]));
  2724. break;
  2725. }
  2726. }
  2727. }
  2728. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  2729. return {};
  2730. }
  2731. gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  2732. switch (param_value.kind) {
  2733. case ParameterValue_Constant:
  2734. if (is_type_constant_type(parameter_type)) {
  2735. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  2736. return res;
  2737. } else {
  2738. ExactValue ev = param_value.value;
  2739. lbValue arg = {};
  2740. Type *type = type_of_expr(param_value.original_ast_expr);
  2741. if (type != nullptr) {
  2742. arg = lb_const_value(p->module, type, ev);
  2743. } else {
  2744. arg = lb_const_value(p->module, parameter_type, param_value.value);
  2745. }
  2746. return lb_emit_conv(p, arg, parameter_type);
  2747. }
  2748. case ParameterValue_Nil:
  2749. return lb_const_nil(p->module, parameter_type);
  2750. case ParameterValue_Location:
  2751. {
  2752. String proc_name = {};
  2753. if (p->entity != nullptr) {
  2754. proc_name = p->entity->token.string;
  2755. }
  2756. return lb_emit_source_code_location_as_global(p, proc_name, pos);
  2757. }
  2758. case ParameterValue_Value:
  2759. return lb_build_expr(p, param_value.ast_value);
  2760. }
  2761. return lb_const_nil(p->module, parameter_type);
  2762. }
  2763. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  2764. gb_internal lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  2765. expr = unparen_expr(expr);
  2766. ast_node(ce, CallExpr, expr);
  2767. lbValue res = lb_build_call_expr_internal(p, expr);
  2768. if (ce->optional_ok_one) {
  2769. GB_ASSERT(is_type_tuple(res.type));
  2770. GB_ASSERT(res.type->Tuple.variables.count == 2);
  2771. return lb_emit_struct_ev(p, res, 0);
  2772. }
  2773. return res;
  2774. }
  2775. gb_internal void lb_add_values_to_array(lbProcedure *p, Array<lbValue> *args, lbValue value) {
  2776. if (is_type_tuple(value.type)) {
  2777. for_array(i, value.type->Tuple.variables) {
  2778. lbValue sub_value = lb_emit_struct_ev(p, value, cast(i32)i);
  2779. array_add(args, sub_value);
  2780. }
  2781. } else {
  2782. array_add(args, value);
  2783. }
  2784. }
  2785. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  2786. lbModule *m = p->module;
  2787. TypeAndValue tv = type_and_value_of_expr(expr);
  2788. ast_node(ce, CallExpr, expr);
  2789. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  2790. AddressingMode proc_mode = proc_tv.mode;
  2791. if (proc_mode == Addressing_Type) {
  2792. GB_ASSERT(ce->args.count == 1);
  2793. lbValue x = lb_build_expr(p, ce->args[0]);
  2794. lbValue y = lb_emit_conv(p, x, tv.type);
  2795. return y;
  2796. }
  2797. Ast *proc_expr = unparen_expr(ce->proc);
  2798. if (proc_mode == Addressing_Builtin) {
  2799. Entity *e = entity_of_node(proc_expr);
  2800. BuiltinProcId id = BuiltinProc_Invalid;
  2801. if (e != nullptr) {
  2802. id = cast(BuiltinProcId)e->Builtin.id;
  2803. } else {
  2804. id = BuiltinProc_DIRECTIVE;
  2805. }
  2806. return lb_build_builtin_proc(p, expr, tv, id);
  2807. }
  2808. // NOTE(bill): Regular call
  2809. lbValue value = {};
  2810. Entity *proc_entity = entity_of_node(proc_expr);
  2811. if (proc_entity != nullptr) {
  2812. if (proc_entity->flags & EntityFlag_Disabled) {
  2813. GB_ASSERT(tv.type == nullptr);
  2814. return {};
  2815. }
  2816. }
  2817. if (proc_expr->tav.mode == Addressing_Constant) {
  2818. ExactValue v = proc_expr->tav.value;
  2819. switch (v.kind) {
  2820. case ExactValue_Integer:
  2821. {
  2822. u64 u = big_int_to_u64(&v.value_integer);
  2823. lbValue x = {};
  2824. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2825. x.type = t_uintptr;
  2826. x = lb_emit_conv(p, x, t_rawptr);
  2827. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2828. break;
  2829. }
  2830. case ExactValue_Pointer:
  2831. {
  2832. u64 u = cast(u64)v.value_pointer;
  2833. lbValue x = {};
  2834. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2835. x.type = t_uintptr;
  2836. x = lb_emit_conv(p, x, t_rawptr);
  2837. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2838. break;
  2839. }
  2840. }
  2841. }
  2842. if (value.value == nullptr) {
  2843. value = lb_build_expr(p, proc_expr);
  2844. }
  2845. GB_ASSERT(value.value != nullptr);
  2846. Type *proc_type_ = base_type(value.type);
  2847. GB_ASSERT(proc_type_->kind == Type_Proc);
  2848. TypeProc *pt = &proc_type_->Proc;
  2849. GB_ASSERT(ce->split_args != nullptr);
  2850. auto args = array_make<lbValue>(permanent_allocator(), 0, pt->param_count);
  2851. bool vari_expand = (ce->ellipsis.pos.line != 0);
  2852. bool is_c_vararg = pt->c_vararg;
  2853. for_array(i, ce->split_args->positional) {
  2854. Entity *e = pt->params->Tuple.variables[i];
  2855. if (e->kind == Entity_TypeName) {
  2856. array_add(&args, lb_const_nil(p->module, e->type));
  2857. continue;
  2858. } else if (e->kind == Entity_Constant) {
  2859. array_add(&args, lb_const_value(p->module, e->type, e->Constant.value));
  2860. continue;
  2861. }
  2862. GB_ASSERT(e->kind == Entity_Variable);
  2863. if (pt->variadic && pt->variadic_index == i) {
  2864. lbValue variadic_args = lb_const_nil(p->module, e->type);
  2865. auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count);
  2866. if (variadic.count != 0) {
  2867. // variadic call argument generation
  2868. Type *slice_type = e->type;
  2869. GB_ASSERT(slice_type->kind == Type_Slice);
  2870. if (is_c_vararg) {
  2871. GB_ASSERT(!vari_expand);
  2872. Type *elem_type = slice_type->Slice.elem;
  2873. for (Ast *var_arg : variadic) {
  2874. lbValue arg = lb_build_expr(p, var_arg);
  2875. if (is_type_any(elem_type)) {
  2876. if (is_type_untyped_nil(arg.type)) {
  2877. arg = lb_const_nil(p->module, t_rawptr);
  2878. }
  2879. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(default_type(arg.type))));
  2880. } else {
  2881. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(elem_type)));
  2882. }
  2883. }
  2884. break;
  2885. } else if (vari_expand) {
  2886. GB_ASSERT(variadic.count == 1);
  2887. variadic_args = lb_build_expr(p, variadic[0]);
  2888. variadic_args = lb_emit_conv(p, variadic_args, slice_type);
  2889. } else {
  2890. Type *elem_type = slice_type->Slice.elem;
  2891. auto var_args = array_make<lbValue>(heap_allocator(), 0, variadic.count);
  2892. defer (array_free(&var_args));
  2893. for (Ast *var_arg : variadic) {
  2894. lbValue v = lb_build_expr(p, var_arg);
  2895. lb_add_values_to_array(p, &var_args, v);
  2896. }
  2897. isize slice_len = var_args.count;
  2898. if (slice_len > 0) {
  2899. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  2900. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  2901. for (isize i = 0; i < var_args.count; i++) {
  2902. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)i);
  2903. lbValue var_arg = var_args[i];
  2904. var_arg = lb_emit_conv(p, var_arg, elem_type);
  2905. lb_emit_store(p, addr, var_arg);
  2906. }
  2907. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  2908. lbValue len = lb_const_int(p->module, t_int, slice_len);
  2909. lb_fill_slice(p, slice, base_elem, len);
  2910. variadic_args = lb_addr_load(p, slice);
  2911. }
  2912. }
  2913. }
  2914. array_add(&args, variadic_args);
  2915. break;
  2916. } else {
  2917. lbValue value = lb_build_expr(p, ce->split_args->positional[i]);
  2918. lb_add_values_to_array(p, &args, value);
  2919. }
  2920. }
  2921. if (!is_c_vararg) {
  2922. array_resize(&args, pt->param_count);
  2923. }
  2924. for (Ast *arg : ce->split_args->named) {
  2925. ast_node(fv, FieldValue, arg);
  2926. GB_ASSERT(fv->field->kind == Ast_Ident);
  2927. String name = fv->field->Ident.token.string;
  2928. gb_unused(name);
  2929. isize param_index = lookup_procedure_parameter(pt, name);
  2930. GB_ASSERT(param_index >= 0);
  2931. Entity *e = pt->params->Tuple.variables[param_index];
  2932. if (e->kind == Entity_TypeName) {
  2933. lbValue value = lb_const_nil(p->module, e->type);
  2934. args[param_index] = value;
  2935. } else if (is_c_vararg && pt->variadic && pt->variadic_index == param_index) {
  2936. GB_ASSERT(param_index == pt->param_count-1);
  2937. Type *slice_type = e->type;
  2938. GB_ASSERT(slice_type->kind == Type_Slice);
  2939. Type *elem_type = slice_type->Slice.elem;
  2940. if (fv->value->kind == Ast_CompoundLit) {
  2941. ast_node(literal, CompoundLit, fv->value);
  2942. for (Ast *var_arg : literal->elems) {
  2943. lbValue arg = lb_build_expr(p, var_arg);
  2944. if (is_type_any(elem_type)) {
  2945. if (is_type_untyped_nil(arg.type)) {
  2946. arg = lb_const_nil(p->module, t_rawptr);
  2947. }
  2948. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(default_type(arg.type))));
  2949. } else {
  2950. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(elem_type)));
  2951. }
  2952. }
  2953. } else {
  2954. lbValue value = lb_build_expr(p, fv->value);
  2955. GB_ASSERT(!is_type_tuple(value.type));
  2956. array_add(&args, lb_emit_conv(p, value, c_vararg_promote_type(value.type)));
  2957. }
  2958. } else {
  2959. lbValue value = lb_build_expr(p, fv->value);
  2960. GB_ASSERT(!is_type_tuple(value.type));
  2961. args[param_index] = value;
  2962. }
  2963. }
  2964. TokenPos pos = ast_token(ce->proc).pos;
  2965. if (pt->params != nullptr) {
  2966. isize min_count = pt->params->Tuple.variables.count;
  2967. if (is_c_vararg) {
  2968. min_count -= 1;
  2969. }
  2970. GB_ASSERT(args.count >= min_count);
  2971. for_array(arg_index, pt->params->Tuple.variables) {
  2972. Entity *e = pt->params->Tuple.variables[arg_index];
  2973. if (pt->variadic && arg_index == pt->variadic_index) {
  2974. if (!is_c_vararg && args[arg_index].value == 0) {
  2975. args[arg_index] = lb_const_nil(p->module, e->type);
  2976. }
  2977. continue;
  2978. }
  2979. lbValue arg = args[arg_index];
  2980. if (arg.value == nullptr && arg.type == nullptr) {
  2981. switch (e->kind) {
  2982. case Entity_TypeName:
  2983. args[arg_index] = lb_const_nil(p->module, e->type);
  2984. break;
  2985. case Entity_Variable:
  2986. args[arg_index] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  2987. break;
  2988. case Entity_Constant:
  2989. args[arg_index] = lb_const_value(p->module, e->type, e->Constant.value);
  2990. break;
  2991. default:
  2992. GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind]));
  2993. }
  2994. } else {
  2995. args[arg_index] = lb_emit_conv(p, arg, e->type);
  2996. }
  2997. }
  2998. }
  2999. isize final_count = is_c_vararg ? args.count : pt->param_count;
  3000. auto call_args = array_slice(args, 0, final_count);
  3001. return lb_emit_call(p, value, call_args, ce->inlining);
  3002. }