llvm_backend_proc.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577
  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_procedure_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. lbBlock *prev_block = p->curr_block;
  595. p->curr_block = p->decl_block;
  596. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  597. p->curr_block = prev_block;
  598. }
  599. }
  600. }
  601. gb_internal void lb_end_procedure_body(lbProcedure *p) {
  602. lb_set_debug_position_to_procedure_begin(p);
  603. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  604. LLVMBuildBr(p->builder, p->entry_block->block);
  605. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  606. LLVMValueRef instr = nullptr;
  607. // Make sure there is a "ret void" at the end of a procedure with no return type
  608. if (p->type->Proc.result_count == 0) {
  609. instr = LLVMGetLastInstruction(p->curr_block->block);
  610. if (!lb_is_instr_terminating(instr)) {
  611. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  612. lb_set_debug_position_to_procedure_end(p);
  613. LLVMBuildRetVoid(p->builder);
  614. }
  615. }
  616. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  617. LLVMBasicBlockRef block = nullptr;
  618. // Make sure every block terminates, and if not, make it unreachable
  619. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  620. instr = LLVMGetLastInstruction(block);
  621. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  622. LLVMPositionBuilderAtEnd(p->builder, block);
  623. LLVMBuildUnreachable(p->builder);
  624. }
  625. }
  626. p->curr_block = nullptr;
  627. p->state_flags = 0;
  628. }
  629. gb_internal void lb_end_procedure(lbProcedure *p) {
  630. LLVMDisposeBuilder(p->builder);
  631. }
  632. gb_internal void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  633. GB_ASSERT(pd->body != nullptr);
  634. lbModule *m = p->module;
  635. auto *min_dep_set = &m->info->minimum_dependency_set;
  636. if (ptr_set_exists(min_dep_set, e) == false) {
  637. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  638. return;
  639. }
  640. // NOTE(bill): Generate a new name
  641. // parent.name-guid
  642. String original_name = e->token.string;
  643. String pd_name = original_name;
  644. if (e->Procedure.link_name.len > 0) {
  645. pd_name = e->Procedure.link_name;
  646. }
  647. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  648. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  649. i32 guid = cast(i32)p->children.count;
  650. name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  651. String name = make_string(cast(u8 *)name_text, name_len-1);
  652. e->Procedure.link_name = name;
  653. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  654. e->code_gen_procedure = nested_proc;
  655. lbValue value = {};
  656. value.value = nested_proc->value;
  657. value.type = nested_proc->type;
  658. lb_add_entity(m, e, value);
  659. array_add(&p->children, nested_proc);
  660. array_add(&m->procedures_to_generate, nested_proc);
  661. }
  662. gb_internal Array<lbValue> lb_value_to_array(lbProcedure *p, gbAllocator const &allocator, lbValue value) {
  663. Array<lbValue> array = {};
  664. Type *t = base_type(value.type);
  665. if (t == nullptr) {
  666. // Do nothing
  667. } else if (is_type_tuple(t)) {
  668. array = array_make<lbValue>(allocator, 0, t->Tuple.variables.count);
  669. lb_append_tuple_values(p, &array, value);
  670. } else {
  671. array = array_make<lbValue>(allocator, 1);
  672. array[0] = value;
  673. }
  674. return array;
  675. }
  676. 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) {
  677. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  678. unsigned arg_count = cast(unsigned)processed_args.count;
  679. if (return_ptr.value != nullptr) {
  680. arg_count += 1;
  681. }
  682. if (context_ptr.addr.value != nullptr) {
  683. arg_count += 1;
  684. }
  685. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  686. isize arg_index = 0;
  687. if (return_ptr.value != nullptr) {
  688. args[arg_index++] = return_ptr.value;
  689. }
  690. for_array(i, processed_args) {
  691. lbValue arg = processed_args[i];
  692. if (is_type_proc(arg.type)) {
  693. arg.value = LLVMBuildPointerCast(p->builder, arg.value, lb_type(p->module, arg.type), "");
  694. }
  695. args[arg_index++] = arg.value;
  696. }
  697. if (context_ptr.addr.value != nullptr) {
  698. LLVMValueRef cp = context_ptr.addr.value;
  699. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  700. args[arg_index++] = cp;
  701. }
  702. GB_ASSERT(arg_index == arg_count);
  703. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  704. GB_ASSERT(curr_block != p->decl_block->block);
  705. {
  706. Type *proc_type = base_type(value.type);
  707. GB_ASSERT(proc_type->kind == Type_Proc);
  708. LLVMTypeRef fnp = lb_type_internal_for_procedures_raw(p->module, proc_type);
  709. LLVMTypeRef ftp = LLVMPointerType(fnp, 0);
  710. LLVMValueRef fn = value.value;
  711. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  712. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  713. }
  714. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  715. lbFunctionType *ft = map_must_get(&p->module->function_type_map, base_type(value.type));
  716. {
  717. unsigned param_count = LLVMCountParamTypes(fnp);
  718. GB_ASSERT(arg_count >= param_count);
  719. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  720. LLVMGetParamTypes(fnp, param_types);
  721. for (unsigned i = 0; i < param_count; i++) {
  722. LLVMTypeRef param_type = param_types[i];
  723. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  724. if (LB_USE_NEW_PASS_SYSTEM &&
  725. arg_type != param_type) {
  726. LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  727. LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  728. if (arg_kind == param_kind &&
  729. arg_kind == LLVMPointerTypeKind) {
  730. // NOTE(bill): LLVM's newer `ptr` only type system seems to fail at times
  731. // I don't know why...
  732. args[i] = LLVMBuildPointerCast(p->builder, args[i], param_type, "");
  733. arg_type = param_type;
  734. continue;
  735. }
  736. }
  737. GB_ASSERT_MSG(
  738. arg_type == param_type,
  739. "Parameter types do not match: %s != %s, argument: %s\n\t%s",
  740. LLVMPrintTypeToString(arg_type),
  741. LLVMPrintTypeToString(param_type),
  742. LLVMPrintValueToString(args[i]),
  743. LLVMPrintTypeToString(fnp)
  744. );
  745. }
  746. }
  747. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  748. auto llvm_cc = lb_calling_convention_map[proc_type->Proc.calling_convention];
  749. LLVMSetInstructionCallConv(ret, llvm_cc);
  750. LLVMAttributeIndex param_offset = LLVMAttributeIndex_FirstArgIndex;
  751. if (return_ptr.value != nullptr) {
  752. param_offset += 1;
  753. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  754. }
  755. for_array(i, ft->args) {
  756. LLVMAttributeRef attribute = ft->args[i].attribute;
  757. if (attribute != nullptr) {
  758. LLVMAddCallSiteAttribute(ret, param_offset + cast(LLVMAttributeIndex)i, attribute);
  759. }
  760. }
  761. switch (inlining) {
  762. case ProcInlining_none:
  763. break;
  764. case ProcInlining_inline:
  765. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  766. break;
  767. case ProcInlining_no_inline:
  768. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  769. break;
  770. }
  771. lbValue res = {};
  772. res.value = ret;
  773. res.type = abi_rt;
  774. return res;
  775. }
  776. }
  777. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  778. AstPackage *pkg = m->info->runtime_package;
  779. Entity *e = scope_lookup_current(pkg->scope, name);
  780. return lb_find_procedure_value_from_entity(m, e);
  781. }
  782. gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  783. String name = make_string_c(c_name);
  784. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  785. return lb_emit_call(p, proc, args);
  786. }
  787. gb_internal lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  788. lbValue res = {};
  789. Type *t = val.type;
  790. if (is_type_complex(t)) {
  791. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  792. lbValue real = lb_emit_struct_ev(p, val, 0);
  793. lbValue imag = lb_emit_struct_ev(p, val, 1);
  794. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  795. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  796. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  797. } else if (is_type_quaternion(t)) {
  798. // @QuaternionLayout
  799. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  800. lbValue real = lb_emit_struct_ev(p, val, 3);
  801. lbValue imag = lb_emit_struct_ev(p, val, 0);
  802. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  803. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  804. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  805. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  806. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  807. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  808. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  809. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  810. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  811. } else if (is_type_array_like(t)) {
  812. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  813. Type *elem_type = base_array_type(t);
  814. i64 count = get_array_type_count(t);
  815. for (i64 i = 0; i < count; i++) {
  816. lbValue dst = lb_emit_array_epi(p, res, i);
  817. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  818. elem = lb_emit_conjugate(p, elem, elem_type);
  819. lb_emit_store(p, dst, elem);
  820. }
  821. } else if (is_type_matrix(t)) {
  822. Type *mt = base_type(t);
  823. GB_ASSERT(mt->kind == Type_Matrix);
  824. Type *elem_type = mt->Matrix.elem;
  825. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  826. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  827. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  828. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  829. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  830. elem = lb_emit_conjugate(p, elem, elem_type);
  831. lb_emit_store(p, dst, elem);
  832. }
  833. }
  834. }
  835. return lb_emit_load(p, res);
  836. }
  837. gb_internal lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining) {
  838. lbModule *m = p->module;
  839. Type *pt = base_type(value.type);
  840. GB_ASSERT(pt->kind == Type_Proc);
  841. Type *results = pt->Proc.results;
  842. lbAddr context_ptr = {};
  843. if (pt->Proc.calling_convention == ProcCC_Odin) {
  844. context_ptr = lb_find_or_generate_context_ptr(p);
  845. }
  846. defer (if (pt->Proc.diverging) {
  847. LLVMBuildUnreachable(p->builder);
  848. });
  849. bool is_c_vararg = pt->Proc.c_vararg;
  850. isize param_count = pt->Proc.param_count;
  851. if (is_c_vararg) {
  852. GB_ASSERT(param_count-1 <= args.count);
  853. param_count -= 1;
  854. } else {
  855. GB_ASSERT_MSG(param_count == args.count, "%td == %td (%s)", param_count, args.count, LLVMPrintValueToString(value.value));
  856. }
  857. lbValue result = {};
  858. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  859. {
  860. bool is_odin_cc = is_calling_convention_odin(pt->Proc.calling_convention);
  861. lbFunctionType *ft = lb_get_function_type(m, pt);
  862. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  863. bool split_returns = ft->multiple_return_original_type != nullptr;
  864. unsigned param_index = 0;
  865. for (isize i = 0; i < param_count; i++) {
  866. Entity *e = pt->Proc.params->Tuple.variables[i];
  867. if (e->kind != Entity_Variable) {
  868. continue;
  869. }
  870. GB_ASSERT(e->flags & EntityFlag_Param);
  871. Type *original_type = e->type;
  872. lbArgType *arg = &ft->args[param_index];
  873. if (arg->kind == lbArg_Ignore) {
  874. param_index += 1;
  875. continue;
  876. }
  877. lbValue x = lb_emit_conv(p, args[i], original_type);
  878. LLVMTypeRef xt = lb_type(p->module, x.type);
  879. if (arg->kind == lbArg_Direct) {
  880. LLVMTypeRef abi_type = arg->cast_type;
  881. if (!abi_type) {
  882. abi_type = arg->type;
  883. }
  884. if (xt == abi_type) {
  885. array_add(&processed_args, x);
  886. } else {
  887. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  888. array_add(&processed_args, x);
  889. }
  890. } else if (arg->kind == lbArg_Indirect) {
  891. lbValue ptr = {};
  892. if (arg->is_byval) {
  893. if (is_odin_cc) {
  894. if (are_types_identical(original_type, t_source_code_location)) {
  895. ptr = lb_address_from_load_or_generate_local(p, x);
  896. // } else {
  897. // ptr = lb_address_from_load_if_readonly_parameter(p, x);
  898. }
  899. }
  900. if (ptr.value == nullptr) {
  901. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  902. }
  903. } else if (is_odin_cc) {
  904. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  905. // i.e. `T const &` in C++
  906. if (LLVMIsConstant(x.value)) {
  907. // NOTE(bill): if the value is already constant, then just it as a global variable
  908. // and pass it by pointer
  909. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  910. lb_make_global_private_const(addr);
  911. ptr = addr.addr;
  912. } else {
  913. ptr = lb_address_from_load_or_generate_local(p, x);
  914. }
  915. } else {
  916. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  917. }
  918. array_add(&processed_args, ptr);
  919. }
  920. param_index += 1;
  921. }
  922. if (is_c_vararg) {
  923. for (isize i = processed_args.count; i < args.count; i++) {
  924. array_add(&processed_args, args[i]);
  925. }
  926. }
  927. if (inlining == ProcInlining_none) {
  928. inlining = p->inlining;
  929. }
  930. Type *rt = reduce_tuple_to_single_type(results);
  931. Type *original_rt = rt;
  932. if (split_returns) {
  933. GB_ASSERT(rt->kind == Type_Tuple);
  934. for (isize j = 0; j < rt->Tuple.variables.count-1; j++) {
  935. Type *partial_return_type = rt->Tuple.variables[j]->type;
  936. lbValue partial_return_ptr = lb_add_local(p, partial_return_type, nullptr, true, false).addr;
  937. array_add(&processed_args, partial_return_ptr);
  938. }
  939. rt = reduce_tuple_to_single_type(rt->Tuple.variables[rt->Tuple.variables.count-1]->type);
  940. }
  941. if (return_by_pointer) {
  942. lbValue return_ptr = lb_add_local_generated(p, rt, true).addr;
  943. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  944. result = lb_emit_load(p, return_ptr);
  945. } else if (rt != nullptr) {
  946. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  947. if (ft->ret.cast_type) {
  948. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  949. }
  950. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  951. result.type = rt;
  952. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  953. result.type = t_llvm_bool;
  954. }
  955. if (!is_type_tuple(rt)) {
  956. result = lb_emit_conv(p, result, rt);
  957. }
  958. } else {
  959. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  960. }
  961. if (original_rt != rt) {
  962. GB_ASSERT(split_returns);
  963. GB_ASSERT(is_type_tuple(original_rt));
  964. // IMPORTANT NOTE(bill, 2022-11-24)
  965. // result_ptr is a dummy value which is only used to reference a tuple
  966. // value for the "tuple-fix"
  967. //
  968. // The reason for the fake stack allocation is to have a unique pointer
  969. // for the value to be used as a key within the procedure itself
  970. lbValue result_ptr = lb_add_local_generated(p, original_rt, false).addr;
  971. isize ret_count = original_rt->Tuple.variables.count;
  972. auto tuple_fix_values = slice_make<lbValue>(permanent_allocator(), ret_count);
  973. auto tuple_geps = slice_make<lbValue>(permanent_allocator(), ret_count);
  974. isize offset = ft->original_arg_count;
  975. for (isize j = 0; j < ret_count-1; j++) {
  976. lbValue ret_arg_ptr = processed_args[offset + j];
  977. lbValue ret_arg = lb_emit_load(p, ret_arg_ptr);
  978. tuple_fix_values[j] = ret_arg;
  979. }
  980. tuple_fix_values[ret_count-1] = result;
  981. #if 0
  982. for (isize j = 0; j < ret_count; j++) {
  983. tuple_geps[j] = lb_emit_struct_ep(p, result_ptr, cast(i32)j);
  984. }
  985. for (isize j = 0; j < ret_count; j++) {
  986. lb_emit_store(p, tuple_geps[j], tuple_fix_values[j]);
  987. }
  988. #endif
  989. result = lb_emit_load(p, result_ptr);
  990. lbTupleFix tf = {tuple_fix_values};
  991. map_set(&p->tuple_fix_map, result_ptr.value, tf);
  992. map_set(&p->tuple_fix_map, result.value, tf);
  993. }
  994. }
  995. LLVMValueRef the_proc_value = value.value;
  996. if (LLVMIsAConstantExpr(the_proc_value)) {
  997. // NOTE(bill): it's a bit cast
  998. the_proc_value = LLVMGetOperand(the_proc_value, 0);
  999. }
  1000. Entity **found = map_get(&p->module->procedure_values, the_proc_value);
  1001. if (found != nullptr) {
  1002. Entity *e = *found;
  1003. if (e != nullptr && entity_has_deferred_procedure(e)) {
  1004. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  1005. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  1006. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  1007. bool by_ptr = false;
  1008. auto in_args = args;
  1009. Array<lbValue> result_as_args = {};
  1010. switch (kind) {
  1011. case DeferredProcedure_none:
  1012. break;
  1013. case DeferredProcedure_in_by_ptr:
  1014. by_ptr = true;
  1015. /*fallthrough*/
  1016. case DeferredProcedure_in:
  1017. result_as_args = array_clone(heap_allocator(), in_args);
  1018. break;
  1019. case DeferredProcedure_out_by_ptr:
  1020. by_ptr = true;
  1021. /*fallthrough*/
  1022. case DeferredProcedure_out:
  1023. result_as_args = lb_value_to_array(p, heap_allocator(), result);
  1024. break;
  1025. case DeferredProcedure_in_out_by_ptr:
  1026. by_ptr = true;
  1027. /*fallthrough*/
  1028. case DeferredProcedure_in_out:
  1029. {
  1030. auto out_args = lb_value_to_array(p, heap_allocator(), result);
  1031. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  1032. array_copy(&result_as_args, in_args, 0);
  1033. array_copy(&result_as_args, out_args, in_args.count);
  1034. }
  1035. break;
  1036. }
  1037. if (by_ptr) {
  1038. for_array(i, result_as_args) {
  1039. lbValue arg_ptr = lb_address_from_load_or_generate_local(p, result_as_args[i]);
  1040. result_as_args[i] = arg_ptr;
  1041. }
  1042. }
  1043. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  1044. }
  1045. }
  1046. return result;
  1047. }
  1048. gb_internal LLVMValueRef llvm_splat_int(i64 count, LLVMTypeRef type, i64 value, bool is_signed=false) {
  1049. LLVMValueRef v = LLVMConstInt(type, value, is_signed);
  1050. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1051. for (i64 i = 0; i < count; i++) {
  1052. values[i] = v;
  1053. }
  1054. return LLVMConstVector(values, cast(unsigned)count);
  1055. }
  1056. gb_internal lbValue lb_build_builtin_simd_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId builtin_id) {
  1057. ast_node(ce, CallExpr, expr);
  1058. lbModule *m = p->module;
  1059. lbValue res = {};
  1060. res.type = tv.type;
  1061. lbValue arg0 = {}; if (ce->args.count > 0) arg0 = lb_build_expr(p, ce->args[0]);
  1062. lbValue arg1 = {}; if (ce->args.count > 1) arg1 = lb_build_expr(p, ce->args[1]);
  1063. lbValue arg2 = {}; if (ce->args.count > 2) arg2 = lb_build_expr(p, ce->args[2]);
  1064. Type *elem = base_array_type(arg0.type);
  1065. bool is_float = is_type_float(elem);
  1066. bool is_signed = !is_type_unsigned(elem);
  1067. LLVMOpcode op_code = cast(LLVMOpcode)0;
  1068. switch (builtin_id) {
  1069. case BuiltinProc_simd_add:
  1070. case BuiltinProc_simd_sub:
  1071. case BuiltinProc_simd_mul:
  1072. case BuiltinProc_simd_div:
  1073. case BuiltinProc_simd_rem:
  1074. if (is_float) {
  1075. switch (builtin_id) {
  1076. case BuiltinProc_simd_add: op_code = LLVMFAdd; break;
  1077. case BuiltinProc_simd_sub: op_code = LLVMFSub; break;
  1078. case BuiltinProc_simd_mul: op_code = LLVMFMul; break;
  1079. case BuiltinProc_simd_div: op_code = LLVMFDiv; break;
  1080. }
  1081. } else {
  1082. switch (builtin_id) {
  1083. case BuiltinProc_simd_add: op_code = LLVMAdd; break;
  1084. case BuiltinProc_simd_sub: op_code = LLVMSub; break;
  1085. case BuiltinProc_simd_mul: op_code = LLVMMul; break;
  1086. case BuiltinProc_simd_div:
  1087. if (is_signed) {
  1088. op_code = LLVMSDiv;
  1089. } else {
  1090. op_code = LLVMUDiv;
  1091. }
  1092. break;
  1093. case BuiltinProc_simd_rem:
  1094. if (is_signed) {
  1095. op_code = LLVMSRem;
  1096. } else {
  1097. op_code = LLVMURem;
  1098. }
  1099. break;
  1100. }
  1101. }
  1102. if (op_code) {
  1103. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1104. return res;
  1105. }
  1106. break;
  1107. case BuiltinProc_simd_shl: // Odin logic
  1108. case BuiltinProc_simd_shr: // Odin logic
  1109. case BuiltinProc_simd_shl_masked: // C logic
  1110. case BuiltinProc_simd_shr_masked: // C logic
  1111. {
  1112. i64 sz = type_size_of(elem);
  1113. GB_ASSERT(arg0.type->kind == Type_SimdVector);
  1114. i64 count = arg0.type->SimdVector.count;
  1115. Type *elem1 = base_array_type(arg1.type);
  1116. bool is_masked = false;
  1117. switch (builtin_id) {
  1118. case BuiltinProc_simd_shl: op_code = LLVMShl; is_masked = false; break;
  1119. case BuiltinProc_simd_shr: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = false; break;
  1120. case BuiltinProc_simd_shl_masked: op_code = LLVMShl; is_masked = true; break;
  1121. case BuiltinProc_simd_shr_masked: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = true; break;
  1122. }
  1123. if (op_code) {
  1124. LLVMValueRef bits = llvm_splat_int(count, lb_type(m, elem1), sz*8 - 1);
  1125. if (is_masked) {
  1126. // C logic
  1127. LLVMValueRef shift = LLVMBuildAnd(p->builder, arg1.value, bits, "");
  1128. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, shift, "");
  1129. } else {
  1130. // Odin logic
  1131. LLVMValueRef zero = lb_const_nil(m, arg1.type).value;
  1132. LLVMValueRef mask = LLVMBuildICmp(p->builder, LLVMIntULE, arg1.value, bits, "");
  1133. LLVMValueRef shift = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1134. res.value = LLVMBuildSelect(p->builder, mask, shift, zero, "");
  1135. }
  1136. return res;
  1137. }
  1138. }
  1139. break;
  1140. case BuiltinProc_simd_bit_and:
  1141. case BuiltinProc_simd_bit_or:
  1142. case BuiltinProc_simd_bit_xor:
  1143. case BuiltinProc_simd_bit_and_not:
  1144. switch (builtin_id) {
  1145. case BuiltinProc_simd_bit_and: op_code = LLVMAnd; break;
  1146. case BuiltinProc_simd_bit_or: op_code = LLVMOr; break;
  1147. case BuiltinProc_simd_bit_xor: op_code = LLVMXor; break;
  1148. case BuiltinProc_simd_bit_and_not:
  1149. op_code = LLVMAnd;
  1150. arg1.value = LLVMBuildNot(p->builder, arg1.value, "");
  1151. break;
  1152. }
  1153. if (op_code) {
  1154. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1155. return res;
  1156. }
  1157. break;
  1158. case BuiltinProc_simd_neg:
  1159. if (is_float) {
  1160. res.value = LLVMBuildFNeg(p->builder, arg0.value, "");
  1161. } else {
  1162. res.value = LLVMBuildNeg(p->builder, arg0.value, "");
  1163. }
  1164. return res;
  1165. case BuiltinProc_simd_abs:
  1166. if (is_float) {
  1167. LLVMValueRef pos = arg0.value;
  1168. LLVMValueRef neg = LLVMBuildFNeg(p->builder, pos, "");
  1169. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, pos, neg, "");
  1170. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1171. } else {
  1172. LLVMValueRef pos = arg0.value;
  1173. LLVMValueRef neg = LLVMBuildNeg(p->builder, pos, "");
  1174. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, pos, neg, "");
  1175. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1176. }
  1177. return res;
  1178. case BuiltinProc_simd_min:
  1179. if (is_float) {
  1180. return lb_emit_min(p, res.type, arg0, arg1);
  1181. } else {
  1182. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSLT : LLVMIntULT, arg0.value, arg1.value, "");
  1183. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1184. }
  1185. return res;
  1186. case BuiltinProc_simd_max:
  1187. if (is_float) {
  1188. return lb_emit_max(p, res.type, arg0, arg1);
  1189. } else {
  1190. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, arg0.value, arg1.value, "");
  1191. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1192. }
  1193. return res;
  1194. case BuiltinProc_simd_lanes_eq:
  1195. case BuiltinProc_simd_lanes_ne:
  1196. case BuiltinProc_simd_lanes_lt:
  1197. case BuiltinProc_simd_lanes_le:
  1198. case BuiltinProc_simd_lanes_gt:
  1199. case BuiltinProc_simd_lanes_ge:
  1200. if (is_float) {
  1201. LLVMRealPredicate pred = cast(LLVMRealPredicate)0;
  1202. switch (builtin_id) {
  1203. case BuiltinProc_simd_lanes_eq: pred = LLVMRealOEQ; break;
  1204. case BuiltinProc_simd_lanes_ne: pred = LLVMRealONE; break;
  1205. case BuiltinProc_simd_lanes_lt: pred = LLVMRealOLT; break;
  1206. case BuiltinProc_simd_lanes_le: pred = LLVMRealOLE; break;
  1207. case BuiltinProc_simd_lanes_gt: pred = LLVMRealOGT; break;
  1208. case BuiltinProc_simd_lanes_ge: pred = LLVMRealOGE; break;
  1209. }
  1210. if (pred) {
  1211. res.value = LLVMBuildFCmp(p->builder, pred, arg0.value, arg1.value, "");
  1212. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1213. return res;
  1214. }
  1215. } else {
  1216. LLVMIntPredicate pred = cast(LLVMIntPredicate)0;
  1217. switch (builtin_id) {
  1218. case BuiltinProc_simd_lanes_eq: pred = LLVMIntEQ; break;
  1219. case BuiltinProc_simd_lanes_ne: pred = LLVMIntNE; break;
  1220. case BuiltinProc_simd_lanes_lt: pred = is_signed ? LLVMIntSLT :LLVMIntULT; break;
  1221. case BuiltinProc_simd_lanes_le: pred = is_signed ? LLVMIntSLE :LLVMIntULE; break;
  1222. case BuiltinProc_simd_lanes_gt: pred = is_signed ? LLVMIntSGT :LLVMIntUGT; break;
  1223. case BuiltinProc_simd_lanes_ge: pred = is_signed ? LLVMIntSGE :LLVMIntUGE; break;
  1224. }
  1225. if (pred) {
  1226. res.value = LLVMBuildICmp(p->builder, pred, arg0.value, arg1.value, "");
  1227. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1228. return res;
  1229. }
  1230. }
  1231. break;
  1232. case BuiltinProc_simd_extract:
  1233. res.value = LLVMBuildExtractElement(p->builder, arg0.value, arg1.value, "");
  1234. return res;
  1235. case BuiltinProc_simd_replace:
  1236. res.value = LLVMBuildInsertElement(p->builder, arg0.value, arg2.value, arg1.value, "");
  1237. return res;
  1238. case BuiltinProc_simd_reduce_add_ordered:
  1239. case BuiltinProc_simd_reduce_mul_ordered:
  1240. {
  1241. LLVMTypeRef llvm_elem = lb_type(m, elem);
  1242. LLVMValueRef args[2] = {};
  1243. isize args_count = 0;
  1244. char const *name = nullptr;
  1245. switch (builtin_id) {
  1246. case BuiltinProc_simd_reduce_add_ordered:
  1247. if (is_float) {
  1248. name = "llvm.vector.reduce.fadd";
  1249. args[args_count++] = LLVMConstReal(llvm_elem, 0.0);
  1250. } else {
  1251. name = "llvm.vector.reduce.add";
  1252. }
  1253. break;
  1254. case BuiltinProc_simd_reduce_mul_ordered:
  1255. if (is_float) {
  1256. name = "llvm.vector.reduce.fmul";
  1257. args[args_count++] = LLVMConstReal(llvm_elem, 1.0);
  1258. } else {
  1259. name = "llvm.vector.reduce.mul";
  1260. }
  1261. break;
  1262. }
  1263. args[args_count++] = arg0.value;
  1264. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1265. res.value = lb_call_intrinsic(p, name, args, cast(unsigned)args_count, types, gb_count_of(types));
  1266. return res;
  1267. }
  1268. case BuiltinProc_simd_reduce_min:
  1269. case BuiltinProc_simd_reduce_max:
  1270. case BuiltinProc_simd_reduce_and:
  1271. case BuiltinProc_simd_reduce_or:
  1272. case BuiltinProc_simd_reduce_xor:
  1273. {
  1274. char const *name = nullptr;
  1275. switch (builtin_id) {
  1276. case BuiltinProc_simd_reduce_min:
  1277. if (is_float) {
  1278. name = "llvm.vector.reduce.fmin";
  1279. } else if (is_signed) {
  1280. name = "llvm.vector.reduce.smin";
  1281. } else {
  1282. name = "llvm.vector.reduce.umin";
  1283. }
  1284. break;
  1285. case BuiltinProc_simd_reduce_max:
  1286. if (is_float) {
  1287. name = "llvm.vector.reduce.fmax";
  1288. } else if (is_signed) {
  1289. name = "llvm.vector.reduce.smax";
  1290. } else {
  1291. name = "llvm.vector.reduce.umax";
  1292. }
  1293. break;
  1294. case BuiltinProc_simd_reduce_and: name = "llvm.vector.reduce.and"; break;
  1295. case BuiltinProc_simd_reduce_or: name = "llvm.vector.reduce.or"; break;
  1296. case BuiltinProc_simd_reduce_xor: name = "llvm.vector.reduce.xor"; break;
  1297. }
  1298. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1299. LLVMValueRef args[1] = { arg0.value };
  1300. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1301. return res;
  1302. }
  1303. case BuiltinProc_simd_shuffle:
  1304. {
  1305. Type *vt = arg0.type;
  1306. GB_ASSERT(vt->kind == Type_SimdVector);
  1307. i64 indices_count = ce->args.count-2;
  1308. i64 max_count = vt->SimdVector.count*2;
  1309. GB_ASSERT(indices_count <= max_count);
  1310. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, indices_count);
  1311. for (isize i = 0; i < indices_count; i++) {
  1312. lbValue idx = lb_build_expr(p, ce->args[i+2]);
  1313. GB_ASSERT(LLVMIsConstant(idx.value));
  1314. values[i] = idx.value;
  1315. }
  1316. LLVMValueRef indices = LLVMConstVector(values, cast(unsigned)indices_count);
  1317. res.value = LLVMBuildShuffleVector(p->builder, arg0.value, arg1.value, indices, "");
  1318. return res;
  1319. }
  1320. case BuiltinProc_simd_select:
  1321. {
  1322. LLVMValueRef cond = arg0.value;
  1323. LLVMValueRef x = lb_build_expr(p, ce->args[1]).value;
  1324. LLVMValueRef y = lb_build_expr(p, ce->args[2]).value;
  1325. cond = LLVMBuildICmp(p->builder, LLVMIntNE, cond, LLVMConstNull(LLVMTypeOf(cond)), "");
  1326. res.value = LLVMBuildSelect(p->builder, cond, x, y, "");
  1327. return res;
  1328. }
  1329. case BuiltinProc_simd_ceil:
  1330. case BuiltinProc_simd_floor:
  1331. case BuiltinProc_simd_trunc:
  1332. case BuiltinProc_simd_nearest:
  1333. {
  1334. char const *name = nullptr;
  1335. switch (builtin_id) {
  1336. case BuiltinProc_simd_ceil: name = "llvm.ceil"; break;
  1337. case BuiltinProc_simd_floor: name = "llvm.floor"; break;
  1338. case BuiltinProc_simd_trunc: name = "llvm.trunc"; break;
  1339. case BuiltinProc_simd_nearest: name = "llvm.nearbyint"; break;
  1340. }
  1341. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1342. LLVMValueRef args[1] = { arg0.value };
  1343. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1344. return res;
  1345. }
  1346. case BuiltinProc_simd_lanes_reverse:
  1347. {
  1348. i64 count = get_array_type_count(arg0.type);
  1349. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1350. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1351. for (i64 i = 0; i < count; i++) {
  1352. values[i] = LLVMConstInt(llvm_u32, count-1-i, false);
  1353. }
  1354. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1355. LLVMValueRef v = arg0.value;
  1356. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1357. return res;
  1358. }
  1359. case BuiltinProc_simd_lanes_rotate_left:
  1360. case BuiltinProc_simd_lanes_rotate_right:
  1361. {
  1362. i64 count = get_array_type_count(arg0.type);
  1363. GB_ASSERT(is_power_of_two(count));
  1364. BigInt bi_count = {};
  1365. big_int_from_i64(&bi_count, count);
  1366. TypeAndValue const &tv = ce->args[1]->tav;
  1367. ExactValue val = exact_value_to_integer(tv.value);
  1368. GB_ASSERT(val.kind == ExactValue_Integer);
  1369. BigInt *bi = &val.value_integer;
  1370. if (builtin_id == BuiltinProc_simd_lanes_rotate_right) {
  1371. big_int_neg(bi, bi);
  1372. }
  1373. big_int_rem(bi, bi, &bi_count);
  1374. big_int_dealloc(&bi_count);
  1375. i64 left = big_int_to_i64(bi);
  1376. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1377. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1378. for (i64 i = 0; i < count; i++) {
  1379. u64 idx = cast(u64)(i+left) & cast(u64)(count-1);
  1380. values[i] = LLVMConstInt(llvm_u32, idx, false);
  1381. }
  1382. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1383. LLVMValueRef v = arg0.value;
  1384. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1385. return res;
  1386. }
  1387. case BuiltinProc_simd_add_sat:
  1388. case BuiltinProc_simd_sub_sat:
  1389. {
  1390. char const *name = nullptr;
  1391. switch (builtin_id) {
  1392. case BuiltinProc_simd_add_sat: name = is_signed ? "llvm.sadd.sat" : "llvm.uadd.sat"; break;
  1393. case BuiltinProc_simd_sub_sat: name = is_signed ? "llvm.ssub.sat" : "llvm.usub.sat"; break;
  1394. }
  1395. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1396. LLVMValueRef args[2] = { arg0.value, arg1.value };
  1397. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1398. return res;
  1399. }
  1400. case BuiltinProc_simd_clamp:
  1401. {
  1402. LLVMValueRef v = arg0.value;
  1403. LLVMValueRef min = arg1.value;
  1404. LLVMValueRef max = arg2.value;
  1405. if (is_float) {
  1406. v = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOLT, v, min, ""), min, v, "");
  1407. res.value = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOGT, v, max, ""), max, v, "");
  1408. } else if (is_signed) {
  1409. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSLT, v, min, ""), min, v, "");
  1410. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSGT, v, max, ""), max, v, "");
  1411. } else {
  1412. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntULT, v, min, ""), min, v, "");
  1413. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntUGT, v, max, ""), max, v, "");
  1414. }
  1415. return res;
  1416. }
  1417. case BuiltinProc_simd_to_bits:
  1418. {
  1419. res.value = LLVMBuildBitCast(p->builder, arg0.value, lb_type(m, tv.type), "");
  1420. return res;
  1421. }
  1422. }
  1423. GB_PANIC("Unhandled simd intrinsic: '%.*s'", LIT(builtin_procs[builtin_id].name));
  1424. return {};
  1425. }
  1426. gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  1427. ast_node(ce, CallExpr, expr);
  1428. if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {
  1429. return lb_build_builtin_simd_proc(p, expr, tv, id);
  1430. }
  1431. switch (id) {
  1432. case BuiltinProc_DIRECTIVE: {
  1433. ast_node(bd, BasicDirective, ce->proc);
  1434. String name = bd->name.string;
  1435. if (name == "location") {
  1436. String procedure = p->entity->token.string;
  1437. TokenPos pos = ast_token(ce->proc).pos;
  1438. if (ce->args.count > 0) {
  1439. Ast *ident = unselector_expr(ce->args[0]);
  1440. GB_ASSERT(ident->kind == Ast_Ident);
  1441. Entity *e = entity_of_node(ident);
  1442. GB_ASSERT(e != nullptr);
  1443. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  1444. procedure = e->parent_proc_decl->entity->token.string;
  1445. } else {
  1446. procedure = str_lit("");
  1447. }
  1448. pos = e->token.pos;
  1449. }
  1450. return lb_emit_source_code_location_as_global(p, procedure, pos);
  1451. } else if (name == "load_directory") {
  1452. lbModule *m = p->module;
  1453. TEMPORARY_ALLOCATOR_GUARD();
  1454. LoadDirectoryCache *cache = map_must_get(&m->info->load_directory_map, expr);
  1455. isize count = cache->files.count;
  1456. LLVMValueRef *elements = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1457. for_array(i, cache->files) {
  1458. LoadFileCache *file = cache->files[i];
  1459. String file_name = filename_without_directory(file->path);
  1460. LLVMValueRef values[2] = {};
  1461. values[0] = lb_const_string(m, file_name).value;
  1462. values[1] = lb_const_string(m, file->data).value;
  1463. LLVMValueRef element = llvm_const_named_struct(m, t_load_directory_file, values, gb_count_of(values));
  1464. elements[i] = element;
  1465. }
  1466. LLVMValueRef backing_array = llvm_const_array(lb_type(m, t_load_directory_file), elements, count);
  1467. Type *array_type = alloc_type_array(t_load_directory_file, count);
  1468. lbAddr backing_array_addr = lb_add_global_generated(m, array_type, {backing_array, array_type}, nullptr);
  1469. lb_make_global_private_const(backing_array_addr);
  1470. LLVMValueRef backing_array_ptr = backing_array_addr.addr.value;
  1471. backing_array_ptr = LLVMConstPointerCast(backing_array_ptr, lb_type(m, t_load_directory_file_ptr));
  1472. LLVMValueRef const_slice = llvm_const_slice_internal(m, backing_array_ptr, LLVMConstInt(lb_type(m, t_int), count, false));
  1473. lbAddr addr = lb_add_global_generated(p->module, tv.type, {const_slice, t_load_directory_file_slice}, nullptr);
  1474. lb_make_global_private_const(addr);
  1475. return lb_addr_load(p, addr);
  1476. } else {
  1477. GB_PANIC("UNKNOWN DIRECTIVE: %.*s", LIT(name));
  1478. }
  1479. }
  1480. case BuiltinProc_type_info_of: {
  1481. Ast *arg = ce->args[0];
  1482. TypeAndValue tav = type_and_value_of_expr(arg);
  1483. if (tav.mode == Addressing_Type) {
  1484. Type *t = default_type(type_of_expr(arg));
  1485. return lb_type_info(p, t);
  1486. }
  1487. GB_ASSERT(is_type_typeid(tav.type));
  1488. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1489. args[0] = lb_build_expr(p, arg);
  1490. return lb_emit_runtime_call(p, "__type_info_of", args);
  1491. }
  1492. case BuiltinProc_typeid_of: {
  1493. Ast *arg = ce->args[0];
  1494. TypeAndValue tav = type_and_value_of_expr(arg);
  1495. GB_ASSERT(tav.mode == Addressing_Type);
  1496. Type *t = default_type(type_of_expr(arg));
  1497. return lb_typeid(p->module, t);
  1498. }
  1499. case BuiltinProc_len: {
  1500. lbValue v = lb_build_expr(p, ce->args[0]);
  1501. Type *t = base_type(v.type);
  1502. if (is_type_pointer(t)) {
  1503. v = lb_emit_load(p, v);
  1504. t = type_deref(t);
  1505. }
  1506. if (is_type_cstring(t)) {
  1507. return lb_cstring_len(p, v);
  1508. } else if (is_type_string(t)) {
  1509. return lb_string_len(p, v);
  1510. } else if (is_type_array(t)) {
  1511. GB_PANIC("Array lengths are constant");
  1512. } else if (is_type_slice(t)) {
  1513. return lb_slice_len(p, v);
  1514. } else if (is_type_dynamic_array(t)) {
  1515. return lb_dynamic_array_len(p, v);
  1516. } else if (is_type_map(t)) {
  1517. return lb_map_len(p, v);
  1518. } else if (is_type_soa_struct(t)) {
  1519. return lb_soa_struct_len(p, v);
  1520. }
  1521. GB_PANIC("Unreachable");
  1522. break;
  1523. }
  1524. case BuiltinProc_cap: {
  1525. lbValue v = lb_build_expr(p, ce->args[0]);
  1526. Type *t = base_type(v.type);
  1527. if (is_type_pointer(t)) {
  1528. v = lb_emit_load(p, v);
  1529. t = type_deref(t);
  1530. }
  1531. if (is_type_string(t)) {
  1532. GB_PANIC("Unreachable");
  1533. } else if (is_type_array(t)) {
  1534. GB_PANIC("Array lengths are constant");
  1535. } else if (is_type_slice(t)) {
  1536. return lb_slice_len(p, v);
  1537. } else if (is_type_dynamic_array(t)) {
  1538. return lb_dynamic_array_cap(p, v);
  1539. } else if (is_type_map(t)) {
  1540. return lb_map_cap(p, v);
  1541. } else if (is_type_soa_struct(t)) {
  1542. return lb_soa_struct_cap(p, v);
  1543. }
  1544. GB_PANIC("Unreachable");
  1545. break;
  1546. }
  1547. case BuiltinProc_swizzle: {
  1548. isize index_count = ce->args.count-1;
  1549. if (is_type_simd_vector(tv.type)) {
  1550. lbValue vec = lb_build_expr(p, ce->args[0]);
  1551. if (index_count == 0) {
  1552. return vec;
  1553. }
  1554. unsigned mask_len = cast(unsigned)index_count;
  1555. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1556. for (isize i = 1; i < ce->args.count; i++) {
  1557. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  1558. GB_ASSERT(is_type_integer(tv.type));
  1559. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  1560. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  1561. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  1562. }
  1563. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1564. LLVMValueRef v1 = vec.value;
  1565. LLVMValueRef v2 = vec.value;
  1566. lbValue res = {};
  1567. res.type = tv.type;
  1568. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1569. return res;
  1570. }
  1571. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  1572. return lb_addr_load(p, addr);
  1573. }
  1574. case BuiltinProc_complex: {
  1575. lbValue real = lb_build_expr(p, ce->args[0]);
  1576. lbValue imag = lb_build_expr(p, ce->args[1]);
  1577. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1578. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1579. Type *ft = base_complex_elem_type(tv.type);
  1580. real = lb_emit_conv(p, real, ft);
  1581. imag = lb_emit_conv(p, imag, ft);
  1582. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  1583. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  1584. return lb_emit_load(p, dst);
  1585. }
  1586. case BuiltinProc_quaternion: {
  1587. lbValue xyzw[4] = {};
  1588. for (i32 i = 0; i < 4; i++) {
  1589. ast_node(f, FieldValue, ce->args[i]);
  1590. GB_ASSERT(f->field->kind == Ast_Ident);
  1591. String name = f->field->Ident.token.string;
  1592. i32 index = -1;
  1593. // @QuaternionLayout
  1594. if (name == "x" || name == "imag") {
  1595. index = 0;
  1596. } else if (name == "y" || name == "jmag") {
  1597. index = 1;
  1598. } else if (name == "z" || name == "kmag") {
  1599. index = 2;
  1600. } else if (name == "w" || name == "real") {
  1601. index = 3;
  1602. }
  1603. GB_ASSERT(index >= 0);
  1604. xyzw[index] = lb_build_expr(p, f->value);
  1605. }
  1606. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1607. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1608. Type *ft = base_complex_elem_type(tv.type);
  1609. xyzw[0] = lb_emit_conv(p, xyzw[0], ft);
  1610. xyzw[1] = lb_emit_conv(p, xyzw[1], ft);
  1611. xyzw[2] = lb_emit_conv(p, xyzw[2], ft);
  1612. xyzw[3] = lb_emit_conv(p, xyzw[3], ft);
  1613. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), xyzw[0]);
  1614. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), xyzw[1]);
  1615. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), xyzw[2]);
  1616. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), xyzw[3]);
  1617. return lb_emit_load(p, dst);
  1618. }
  1619. case BuiltinProc_real: {
  1620. lbValue val = lb_build_expr(p, ce->args[0]);
  1621. if (is_type_complex(val.type)) {
  1622. lbValue real = lb_emit_struct_ev(p, val, 0);
  1623. return lb_emit_conv(p, real, tv.type);
  1624. } else if (is_type_quaternion(val.type)) {
  1625. // @QuaternionLayout
  1626. lbValue real = lb_emit_struct_ev(p, val, 3);
  1627. return lb_emit_conv(p, real, tv.type);
  1628. }
  1629. GB_PANIC("invalid type for real");
  1630. return {};
  1631. }
  1632. case BuiltinProc_imag: {
  1633. lbValue val = lb_build_expr(p, ce->args[0]);
  1634. if (is_type_complex(val.type)) {
  1635. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1636. return lb_emit_conv(p, imag, tv.type);
  1637. } else if (is_type_quaternion(val.type)) {
  1638. // @QuaternionLayout
  1639. lbValue imag = lb_emit_struct_ev(p, val, 0);
  1640. return lb_emit_conv(p, imag, tv.type);
  1641. }
  1642. GB_PANIC("invalid type for imag");
  1643. return {};
  1644. }
  1645. case BuiltinProc_jmag: {
  1646. lbValue val = lb_build_expr(p, ce->args[0]);
  1647. if (is_type_quaternion(val.type)) {
  1648. // @QuaternionLayout
  1649. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1650. return lb_emit_conv(p, imag, tv.type);
  1651. }
  1652. GB_PANIC("invalid type for jmag");
  1653. return {};
  1654. }
  1655. case BuiltinProc_kmag: {
  1656. lbValue val = lb_build_expr(p, ce->args[0]);
  1657. if (is_type_quaternion(val.type)) {
  1658. // @QuaternionLayout
  1659. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1660. return lb_emit_conv(p, imag, tv.type);
  1661. }
  1662. GB_PANIC("invalid type for kmag");
  1663. return {};
  1664. }
  1665. case BuiltinProc_conj: {
  1666. lbValue val = lb_build_expr(p, ce->args[0]);
  1667. return lb_emit_conjugate(p, val, tv.type);
  1668. }
  1669. case BuiltinProc_expand_values: {
  1670. lbValue val = lb_build_expr(p, ce->args[0]);
  1671. Type *t = base_type(val.type);
  1672. if (!is_type_tuple(tv.type)) {
  1673. if (t->kind == Type_Struct) {
  1674. GB_ASSERT(t->Struct.fields.count == 1);
  1675. return lb_emit_struct_ev(p, val, 0);
  1676. } else if (t->kind == Type_Array) {
  1677. GB_ASSERT(t->Array.count == 1);
  1678. return lb_emit_struct_ev(p, val, 0);
  1679. } else {
  1680. GB_PANIC("Unknown type of expand_values");
  1681. }
  1682. }
  1683. GB_ASSERT(is_type_tuple(tv.type));
  1684. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1685. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1686. if (t->kind == Type_Struct) {
  1687. for_array(src_index, t->Struct.fields) {
  1688. Entity *field = t->Struct.fields[src_index];
  1689. i32 field_index = field->Variable.field_index;
  1690. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1691. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1692. lb_emit_store(p, ep, f);
  1693. }
  1694. } else if (is_type_array_like(t)) {
  1695. // TODO(bill): Clean-up this code
  1696. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1697. i32 n = cast(i32)get_array_type_count(t);
  1698. for (i32 i = 0; i < n; i++) {
  1699. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1700. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1701. lb_emit_store(p, ep, f);
  1702. }
  1703. } else {
  1704. GB_PANIC("Unknown type of expand_values");
  1705. }
  1706. return lb_emit_load(p, tuple);
  1707. }
  1708. case BuiltinProc_min: {
  1709. Type *t = type_of_expr(expr);
  1710. if (ce->args.count == 2) {
  1711. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1712. } else {
  1713. lbValue x = lb_build_expr(p, ce->args[0]);
  1714. for (isize i = 1; i < ce->args.count; i++) {
  1715. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1716. }
  1717. return x;
  1718. }
  1719. }
  1720. case BuiltinProc_max: {
  1721. Type *t = type_of_expr(expr);
  1722. if (ce->args.count == 2) {
  1723. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1724. } else {
  1725. lbValue x = lb_build_expr(p, ce->args[0]);
  1726. for (isize i = 1; i < ce->args.count; i++) {
  1727. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1728. }
  1729. return x;
  1730. }
  1731. }
  1732. case BuiltinProc_abs: {
  1733. lbValue x = lb_build_expr(p, ce->args[0]);
  1734. Type *t = x.type;
  1735. if (is_type_unsigned(t)) {
  1736. return x;
  1737. }
  1738. if (is_type_quaternion(t)) {
  1739. i64 sz = 8*type_size_of(t);
  1740. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1741. args[0] = x;
  1742. switch (sz) {
  1743. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1744. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1745. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1746. }
  1747. GB_PANIC("Unknown complex type");
  1748. } else if (is_type_complex(t)) {
  1749. i64 sz = 8*type_size_of(t);
  1750. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1751. args[0] = x;
  1752. switch (sz) {
  1753. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1754. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1755. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1756. }
  1757. GB_PANIC("Unknown complex type");
  1758. }
  1759. lbValue zero = lb_const_nil(p->module, t);
  1760. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1761. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1762. return lb_emit_select(p, cond, neg, x);
  1763. }
  1764. case BuiltinProc_clamp:
  1765. return lb_emit_clamp(p, type_of_expr(expr),
  1766. lb_build_expr(p, ce->args[0]),
  1767. lb_build_expr(p, ce->args[1]),
  1768. lb_build_expr(p, ce->args[2]));
  1769. case BuiltinProc_soa_zip:
  1770. return lb_soa_zip(p, ce, tv);
  1771. case BuiltinProc_soa_unzip:
  1772. return lb_soa_unzip(p, ce, tv);
  1773. case BuiltinProc_transpose:
  1774. {
  1775. lbValue m = lb_build_expr(p, ce->args[0]);
  1776. return lb_emit_matrix_tranpose(p, m, tv.type);
  1777. }
  1778. case BuiltinProc_outer_product:
  1779. {
  1780. lbValue a = lb_build_expr(p, ce->args[0]);
  1781. lbValue b = lb_build_expr(p, ce->args[1]);
  1782. return lb_emit_outer_product(p, a, b, tv.type);
  1783. }
  1784. case BuiltinProc_hadamard_product:
  1785. {
  1786. lbValue a = lb_build_expr(p, ce->args[0]);
  1787. lbValue b = lb_build_expr(p, ce->args[1]);
  1788. if (is_type_array(tv.type)) {
  1789. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1790. }
  1791. GB_ASSERT(is_type_matrix(tv.type));
  1792. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1793. }
  1794. case BuiltinProc_matrix_flatten:
  1795. {
  1796. lbValue m = lb_build_expr(p, ce->args[0]);
  1797. return lb_emit_matrix_flatten(p, m, tv.type);
  1798. }
  1799. case BuiltinProc_unreachable:
  1800. lb_emit_unreachable(p);
  1801. return {};
  1802. case BuiltinProc_raw_data:
  1803. {
  1804. lbValue x = lb_build_expr(p, ce->args[0]);
  1805. Type *t = base_type(x.type);
  1806. lbValue res = {};
  1807. switch (t->kind) {
  1808. case Type_Slice:
  1809. res = lb_slice_elem(p, x);
  1810. res = lb_emit_conv(p, res, tv.type);
  1811. break;
  1812. case Type_DynamicArray:
  1813. res = lb_dynamic_array_elem(p, x);
  1814. res = lb_emit_conv(p, res, tv.type);
  1815. break;
  1816. case Type_Basic:
  1817. if (t->Basic.kind == Basic_string) {
  1818. res = lb_string_elem(p, x);
  1819. res = lb_emit_conv(p, res, tv.type);
  1820. } else if (t->Basic.kind == Basic_cstring) {
  1821. res = lb_emit_conv(p, x, tv.type);
  1822. }
  1823. break;
  1824. case Type_Pointer:
  1825. case Type_MultiPointer:
  1826. res = lb_emit_conv(p, x, tv.type);
  1827. break;
  1828. }
  1829. GB_ASSERT(res.value != nullptr);
  1830. return res;
  1831. }
  1832. // "Intrinsics"
  1833. case BuiltinProc_alloca:
  1834. {
  1835. lbValue sz = lb_build_expr(p, ce->args[0]);
  1836. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1837. lbValue res = {};
  1838. res.type = alloc_type_multi_pointer(t_u8);
  1839. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1840. LLVMSetAlignment(res.value, cast(unsigned)al);
  1841. return res;
  1842. }
  1843. case BuiltinProc_cpu_relax:
  1844. if (build_context.metrics.arch == TargetArch_i386 ||
  1845. build_context.metrics.arch == TargetArch_amd64) {
  1846. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1847. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1848. GB_ASSERT(the_asm != nullptr);
  1849. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1850. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1851. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1852. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1853. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1854. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1855. GB_ASSERT(the_asm != nullptr);
  1856. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1857. } else {
  1858. // NOTE: default to something to prevent optimization
  1859. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1860. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1861. GB_ASSERT(the_asm != nullptr);
  1862. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1863. }
  1864. return {};
  1865. case BuiltinProc_debug_trap:
  1866. case BuiltinProc_trap:
  1867. {
  1868. char const *name = nullptr;
  1869. switch (id) {
  1870. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1871. case BuiltinProc_trap: name = "llvm.trap"; break;
  1872. }
  1873. lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1874. if (id == BuiltinProc_trap) {
  1875. LLVMBuildUnreachable(p->builder);
  1876. }
  1877. return {};
  1878. }
  1879. case BuiltinProc_read_cycle_counter:
  1880. {
  1881. lbValue res = {};
  1882. res.type = tv.type;
  1883. if (build_context.metrics.arch == TargetArch_arm64) {
  1884. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1885. bool has_side_effects = false;
  1886. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs $0, cntvct_el0"), str_lit("=r"), has_side_effects);
  1887. GB_ASSERT(the_asm != nullptr);
  1888. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1889. } else {
  1890. char const *name = "llvm.readcyclecounter";
  1891. res.value = lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1892. }
  1893. return res;
  1894. }
  1895. case BuiltinProc_count_trailing_zeros:
  1896. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1897. case BuiltinProc_count_leading_zeros:
  1898. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1899. case BuiltinProc_count_ones:
  1900. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1901. case BuiltinProc_count_zeros:
  1902. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1903. case BuiltinProc_reverse_bits:
  1904. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1905. case BuiltinProc_byte_swap:
  1906. {
  1907. lbValue x = lb_build_expr(p, ce->args[0]);
  1908. x = lb_emit_conv(p, x, tv.type);
  1909. return lb_emit_byte_swap(p, x, tv.type);
  1910. }
  1911. case BuiltinProc_overflow_add:
  1912. case BuiltinProc_overflow_sub:
  1913. case BuiltinProc_overflow_mul:
  1914. {
  1915. Type *main_type = tv.type;
  1916. Type *type = main_type;
  1917. if (is_type_tuple(main_type)) {
  1918. type = main_type->Tuple.variables[0]->type;
  1919. }
  1920. lbValue x = lb_build_expr(p, ce->args[0]);
  1921. lbValue y = lb_build_expr(p, ce->args[1]);
  1922. x = lb_emit_conv(p, x, type);
  1923. y = lb_emit_conv(p, y, type);
  1924. char const *name = nullptr;
  1925. if (is_type_unsigned(type)) {
  1926. switch (id) {
  1927. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1928. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1929. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1930. }
  1931. } else {
  1932. switch (id) {
  1933. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1934. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1935. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1936. }
  1937. }
  1938. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1939. LLVMValueRef args[2] = { x.value, y.value };
  1940. lbValue res = {};
  1941. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1942. if (is_type_tuple(main_type)) {
  1943. Type *res_type = nullptr;
  1944. gbAllocator a = permanent_allocator();
  1945. res_type = alloc_type_tuple();
  1946. slice_init(&res_type->Tuple.variables, a, 2);
  1947. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1948. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1949. res.type = res_type;
  1950. } else {
  1951. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1952. res.type = type;
  1953. }
  1954. return res;
  1955. }
  1956. case BuiltinProc_sqrt:
  1957. {
  1958. Type *type = tv.type;
  1959. lbValue x = lb_build_expr(p, ce->args[0]);
  1960. x = lb_emit_conv(p, x, type);
  1961. char const *name = "llvm.sqrt";
  1962. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1963. LLVMValueRef args[1] = { x.value };
  1964. lbValue res = {};
  1965. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1966. res.type = type;
  1967. return res;
  1968. }
  1969. case BuiltinProc_fused_mul_add:
  1970. {
  1971. Type *type = tv.type;
  1972. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), type);
  1973. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), type);
  1974. lbValue z = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), type);
  1975. char const *name = "llvm.fma";
  1976. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1977. LLVMValueRef args[3] = { x.value, y.value, z.value };
  1978. lbValue res = {};
  1979. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1980. res.type = type;
  1981. return res;
  1982. }
  1983. case BuiltinProc_mem_copy:
  1984. {
  1985. lbValue dst = lb_build_expr(p, ce->args[0]);
  1986. lbValue src = lb_build_expr(p, ce->args[1]);
  1987. lbValue len = lb_build_expr(p, ce->args[2]);
  1988. lb_mem_copy_overlapping(p, dst, src, len, false);
  1989. return {};
  1990. }
  1991. case BuiltinProc_mem_copy_non_overlapping:
  1992. {
  1993. lbValue dst = lb_build_expr(p, ce->args[0]);
  1994. lbValue src = lb_build_expr(p, ce->args[1]);
  1995. lbValue len = lb_build_expr(p, ce->args[2]);
  1996. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  1997. return {};
  1998. }
  1999. case BuiltinProc_mem_zero:
  2000. {
  2001. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2002. lbValue len = lb_build_expr(p, ce->args[1]);
  2003. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2004. len = lb_emit_conv(p, len, t_int);
  2005. unsigned alignment = 1;
  2006. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  2007. return {};
  2008. }
  2009. case BuiltinProc_mem_zero_volatile:
  2010. {
  2011. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2012. lbValue len = lb_build_expr(p, ce->args[1]);
  2013. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2014. len = lb_emit_conv(p, len, t_int);
  2015. unsigned alignment = 1;
  2016. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  2017. return {};
  2018. }
  2019. case BuiltinProc_ptr_offset:
  2020. {
  2021. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2022. lbValue len = lb_build_expr(p, ce->args[1]);
  2023. len = lb_emit_conv(p, len, t_int);
  2024. return lb_emit_ptr_offset(p, ptr, len);
  2025. }
  2026. case BuiltinProc_ptr_sub:
  2027. {
  2028. Type *elem0 = type_deref(type_of_expr(ce->args[0]));
  2029. Type *elem1 = type_deref(type_of_expr(ce->args[1]));
  2030. GB_ASSERT(are_types_identical(elem0, elem1));
  2031. Type *elem = elem0;
  2032. lbValue ptr0 = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr);
  2033. lbValue ptr1 = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr);
  2034. ptr0 = lb_emit_conv(p, ptr0, t_int);
  2035. ptr1 = lb_emit_conv(p, ptr1, t_int);
  2036. lbValue diff = lb_emit_arith(p, Token_Sub, ptr0, ptr1, t_int);
  2037. return lb_emit_arith(p, Token_Quo, diff, lb_const_int(p->module, t_int, type_size_of(elem)), t_int);
  2038. }
  2039. // TODO(bill): Which is correct?
  2040. case BuiltinProc_atomic_thread_fence:
  2041. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  2042. return {};
  2043. case BuiltinProc_atomic_signal_fence:
  2044. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  2045. return {};
  2046. case BuiltinProc_volatile_store:
  2047. case BuiltinProc_non_temporal_store:
  2048. case BuiltinProc_atomic_store:
  2049. case BuiltinProc_atomic_store_explicit: {
  2050. lbValue dst = lb_build_expr(p, ce->args[0]);
  2051. lbValue val = lb_build_expr(p, ce->args[1]);
  2052. val = lb_emit_conv(p, val, type_deref(dst.type));
  2053. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  2054. switch (id) {
  2055. case BuiltinProc_non_temporal_store:
  2056. {
  2057. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2058. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2059. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2060. }
  2061. break;
  2062. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  2063. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2064. case BuiltinProc_atomic_store_explicit:
  2065. {
  2066. auto ordering = llvm_atomic_ordering_from_odin(ce->args[2]);
  2067. LLVMSetOrdering(instr, ordering);
  2068. if (ordering == LLVMAtomicOrderingUnordered) {
  2069. LLVMSetVolatile(instr, true);
  2070. }
  2071. }
  2072. break;
  2073. }
  2074. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2075. return {};
  2076. }
  2077. case BuiltinProc_volatile_load:
  2078. case BuiltinProc_non_temporal_load:
  2079. case BuiltinProc_atomic_load:
  2080. case BuiltinProc_atomic_load_explicit: {
  2081. lbValue dst = lb_build_expr(p, ce->args[0]);
  2082. LLVMValueRef instr = LLVMBuildLoad2(p->builder, lb_type(p->module, type_deref(dst.type)), dst.value, "");
  2083. switch (id) {
  2084. case BuiltinProc_non_temporal_load:
  2085. {
  2086. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2087. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2088. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2089. }
  2090. break;
  2091. break;
  2092. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  2093. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2094. case BuiltinProc_atomic_load_explicit:
  2095. {
  2096. auto ordering = llvm_atomic_ordering_from_odin(ce->args[1]);
  2097. LLVMSetOrdering(instr, ordering);
  2098. if (ordering == LLVMAtomicOrderingUnordered) {
  2099. LLVMSetVolatile(instr, true);
  2100. }
  2101. }
  2102. break;
  2103. }
  2104. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2105. lbValue res = {};
  2106. res.value = instr;
  2107. res.type = type_deref(dst.type);
  2108. return res;
  2109. }
  2110. case BuiltinProc_unaligned_store:
  2111. {
  2112. lbValue dst = lb_build_expr(p, ce->args[0]);
  2113. lbValue src = lb_build_expr(p, ce->args[1]);
  2114. Type *t = type_deref(dst.type);
  2115. if (is_type_simd_vector(t)) {
  2116. LLVMValueRef store = LLVMBuildStore(p->builder, src.value, dst.value);
  2117. LLVMSetAlignment(store, 1);
  2118. } else {
  2119. src = lb_address_from_load_or_generate_local(p, src);
  2120. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2121. }
  2122. return {};
  2123. }
  2124. case BuiltinProc_unaligned_load:
  2125. {
  2126. lbValue src = lb_build_expr(p, ce->args[0]);
  2127. Type *t = type_deref(src.type);
  2128. if (is_type_simd_vector(t)) {
  2129. lbValue res = {};
  2130. res.type = t;
  2131. res.value = LLVMBuildLoad2(p->builder, lb_type(p->module, t), src.value, "");
  2132. LLVMSetAlignment(res.value, 1);
  2133. return res;
  2134. } else {
  2135. lbAddr dst = lb_add_local_generated(p, t, false);
  2136. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2137. return lb_addr_load(p, dst);
  2138. }
  2139. }
  2140. case BuiltinProc_atomic_add:
  2141. case BuiltinProc_atomic_sub:
  2142. case BuiltinProc_atomic_and:
  2143. case BuiltinProc_atomic_nand:
  2144. case BuiltinProc_atomic_or:
  2145. case BuiltinProc_atomic_xor:
  2146. case BuiltinProc_atomic_exchange:
  2147. case BuiltinProc_atomic_add_explicit:
  2148. case BuiltinProc_atomic_sub_explicit:
  2149. case BuiltinProc_atomic_and_explicit:
  2150. case BuiltinProc_atomic_nand_explicit:
  2151. case BuiltinProc_atomic_or_explicit:
  2152. case BuiltinProc_atomic_xor_explicit:
  2153. case BuiltinProc_atomic_exchange_explicit: {
  2154. lbValue dst = lb_build_expr(p, ce->args[0]);
  2155. lbValue val = lb_build_expr(p, ce->args[1]);
  2156. val = lb_emit_conv(p, val, type_deref(dst.type));
  2157. LLVMAtomicRMWBinOp op = {};
  2158. LLVMAtomicOrdering ordering = {};
  2159. switch (id) {
  2160. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2161. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2162. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2163. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2164. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2165. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2166. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2167. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2168. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2169. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2170. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2171. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2172. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2173. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2174. }
  2175. lbValue res = {};
  2176. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  2177. res.type = tv.type;
  2178. if (ordering == LLVMAtomicOrderingUnordered) {
  2179. LLVMSetVolatile(res.value, true);
  2180. }
  2181. return res;
  2182. }
  2183. case BuiltinProc_atomic_compare_exchange_strong:
  2184. case BuiltinProc_atomic_compare_exchange_weak:
  2185. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  2186. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  2187. lbValue address = lb_build_expr(p, ce->args[0]);
  2188. Type *elem = type_deref(address.type);
  2189. lbValue old_value = lb_build_expr(p, ce->args[1]);
  2190. lbValue new_value = lb_build_expr(p, ce->args[2]);
  2191. old_value = lb_emit_conv(p, old_value, elem);
  2192. new_value = lb_emit_conv(p, new_value, elem);
  2193. LLVMAtomicOrdering success_ordering = {};
  2194. LLVMAtomicOrdering failure_ordering = {};
  2195. LLVMBool weak = false;
  2196. switch (id) {
  2197. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  2198. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  2199. 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;
  2200. 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;
  2201. }
  2202. LLVMBool single_threaded = false;
  2203. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  2204. p->builder, address.value,
  2205. old_value.value, new_value.value,
  2206. success_ordering,
  2207. failure_ordering,
  2208. single_threaded
  2209. );
  2210. LLVMSetWeak(value, weak);
  2211. if (success_ordering == LLVMAtomicOrderingUnordered || failure_ordering == LLVMAtomicOrderingUnordered) {
  2212. LLVMSetVolatile(value, true);
  2213. }
  2214. if (is_type_tuple(tv.type)) {
  2215. Type *fix_typed = alloc_type_tuple();
  2216. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  2217. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  2218. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2219. lbValue res = {};
  2220. res.value = value;
  2221. res.type = fix_typed;
  2222. return res;
  2223. } else {
  2224. lbValue res = {};
  2225. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  2226. res.type = tv.type;
  2227. return res;
  2228. }
  2229. }
  2230. case BuiltinProc_type_equal_proc:
  2231. return lb_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  2232. case BuiltinProc_type_hasher_proc:
  2233. return lb_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  2234. case BuiltinProc_type_map_info:
  2235. return lb_gen_map_info_ptr(p->module, ce->args[0]->tav.type);
  2236. case BuiltinProc_type_map_cell_info:
  2237. return lb_gen_map_cell_info_ptr(p->module, ce->args[0]->tav.type);
  2238. case BuiltinProc_fixed_point_mul:
  2239. case BuiltinProc_fixed_point_div:
  2240. case BuiltinProc_fixed_point_mul_sat:
  2241. case BuiltinProc_fixed_point_div_sat:
  2242. {
  2243. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  2244. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  2245. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  2246. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  2247. char const *name = nullptr;
  2248. if (is_type_unsigned(tv.type)) {
  2249. switch (id) {
  2250. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  2251. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  2252. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  2253. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  2254. }
  2255. } else {
  2256. switch (id) {
  2257. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  2258. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  2259. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  2260. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  2261. }
  2262. }
  2263. GB_ASSERT(name != nullptr);
  2264. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  2265. lbValue res = {};
  2266. LLVMValueRef args[3] = {
  2267. x.value,
  2268. y.value,
  2269. scale.value };
  2270. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2271. res.type = platform_type;
  2272. return lb_emit_conv(p, res, tv.type);
  2273. }
  2274. case BuiltinProc_expect:
  2275. {
  2276. Type *t = default_type(tv.type);
  2277. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  2278. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  2279. char const *name = "llvm.expect";
  2280. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  2281. lbValue res = {};
  2282. LLVMValueRef args[2] = { x.value, y.value };
  2283. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2284. res.type = t;
  2285. return lb_emit_conv(p, res, t);
  2286. }
  2287. case BuiltinProc_prefetch_read_instruction:
  2288. case BuiltinProc_prefetch_read_data:
  2289. case BuiltinProc_prefetch_write_instruction:
  2290. case BuiltinProc_prefetch_write_data:
  2291. {
  2292. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  2293. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  2294. unsigned long long rw = 0;
  2295. unsigned long long cache = 0;
  2296. switch (id) {
  2297. case BuiltinProc_prefetch_read_instruction:
  2298. rw = 0;
  2299. cache = 0;
  2300. break;
  2301. case BuiltinProc_prefetch_read_data:
  2302. rw = 0;
  2303. cache = 1;
  2304. break;
  2305. case BuiltinProc_prefetch_write_instruction:
  2306. rw = 1;
  2307. cache = 0;
  2308. break;
  2309. case BuiltinProc_prefetch_write_data:
  2310. rw = 1;
  2311. cache = 1;
  2312. break;
  2313. }
  2314. char const *name = "llvm.prefetch";
  2315. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  2316. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  2317. LLVMValueRef args[4] = {};
  2318. args[0] = ptr.value;
  2319. args[1] = LLVMConstInt(llvm_i32, rw, false);
  2320. args[2] = LLVMConstInt(llvm_i32, locality, false);
  2321. args[3] = LLVMConstInt(llvm_i32, cache, false);
  2322. lbValue res = {};
  2323. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2324. res.type = nullptr;
  2325. return res;
  2326. }
  2327. case BuiltinProc___entry_point:
  2328. if (p->module->info->entry_point) {
  2329. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  2330. GB_ASSERT(entry_point.value != nullptr);
  2331. lb_emit_call(p, entry_point, {});
  2332. }
  2333. return {};
  2334. case BuiltinProc_syscall:
  2335. {
  2336. unsigned arg_count = cast(unsigned)ce->args.count;
  2337. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2338. for_array(i, ce->args) {
  2339. lbValue arg = lb_build_expr(p, ce->args[i]);
  2340. arg = lb_emit_conv(p, arg, t_uintptr);
  2341. args[i] = arg.value;
  2342. }
  2343. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2344. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2345. for (unsigned i = 0; i < arg_count; i++) {
  2346. llvm_arg_types[i] = llvm_uintptr;
  2347. }
  2348. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  2349. LLVMValueRef inline_asm = nullptr;
  2350. switch (build_context.metrics.arch) {
  2351. case TargetArch_amd64:
  2352. {
  2353. GB_ASSERT(arg_count <= 7);
  2354. char asm_string[] = "syscall";
  2355. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  2356. for (unsigned i = 0; i < arg_count; i++) {
  2357. constraints = gb_string_appendc(constraints, ",{");
  2358. static char const *regs[] = {
  2359. "rax",
  2360. "rdi",
  2361. "rsi",
  2362. "rdx",
  2363. "r10",
  2364. "r8",
  2365. "r9"
  2366. };
  2367. constraints = gb_string_appendc(constraints, regs[i]);
  2368. constraints = gb_string_appendc(constraints, "}");
  2369. }
  2370. // The SYSCALL instruction stores the address of the
  2371. // following instruction into RCX, and RFLAGS in R11.
  2372. //
  2373. // RSP is not saved, but at least on Linux it appears
  2374. // that the kernel system-call handler does the right
  2375. // thing.
  2376. //
  2377. // Some but not all system calls will additionally
  2378. // clobber memory.
  2379. //
  2380. // TODO:
  2381. // * Figure out what Darwin does.
  2382. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  2383. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2384. }
  2385. break;
  2386. case TargetArch_i386:
  2387. {
  2388. GB_ASSERT(arg_count <= 7);
  2389. char asm_string[] = "int $$0x80";
  2390. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  2391. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  2392. constraints = gb_string_appendc(constraints, ",{");
  2393. static char const *regs[] = {
  2394. "eax",
  2395. "ebx",
  2396. "ecx",
  2397. "edx",
  2398. "esi",
  2399. "edi",
  2400. "ebp",
  2401. };
  2402. constraints = gb_string_appendc(constraints, regs[i]);
  2403. constraints = gb_string_appendc(constraints, "}");
  2404. }
  2405. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2406. }
  2407. break;
  2408. case TargetArch_arm64:
  2409. {
  2410. GB_ASSERT(arg_count <= 7);
  2411. if(build_context.metrics.os == TargetOs_darwin) {
  2412. char asm_string[] = "svc #0x80";
  2413. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2414. for (unsigned i = 0; i < arg_count; i++) {
  2415. constraints = gb_string_appendc(constraints, ",{");
  2416. static char const *regs[] = {
  2417. "x16",
  2418. "x0",
  2419. "x1",
  2420. "x2",
  2421. "x3",
  2422. "x4",
  2423. "x5",
  2424. };
  2425. constraints = gb_string_appendc(constraints, regs[i]);
  2426. constraints = gb_string_appendc(constraints, "}");
  2427. }
  2428. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2429. } else {
  2430. char asm_string[] = "svc #0";
  2431. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2432. for (unsigned i = 0; i < arg_count; i++) {
  2433. constraints = gb_string_appendc(constraints, ",{");
  2434. static char const *regs[] = {
  2435. "x8",
  2436. "x0",
  2437. "x1",
  2438. "x2",
  2439. "x3",
  2440. "x4",
  2441. "x5",
  2442. };
  2443. constraints = gb_string_appendc(constraints, regs[i]);
  2444. constraints = gb_string_appendc(constraints, "}");
  2445. }
  2446. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2447. }
  2448. }
  2449. break;
  2450. case TargetArch_arm32:
  2451. {
  2452. GB_ASSERT(arg_count <= 7);
  2453. char asm_string[] = "svc #0";
  2454. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  2455. for (unsigned i = 0; i < arg_count; i++) {
  2456. constraints = gb_string_appendc(constraints, ",{");
  2457. static char const *regs[] = {
  2458. "r7",
  2459. "r0",
  2460. "r1",
  2461. "r2",
  2462. "r3",
  2463. "r4",
  2464. "r5",
  2465. "r6",
  2466. };
  2467. constraints = gb_string_appendc(constraints, regs[i]);
  2468. constraints = gb_string_appendc(constraints, "}");
  2469. }
  2470. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2471. }
  2472. break;
  2473. default:
  2474. GB_PANIC("Unsupported platform");
  2475. }
  2476. lbValue res = {};
  2477. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2478. res.type = t_uintptr;
  2479. return res;
  2480. }
  2481. case BuiltinProc_syscall_bsd:
  2482. {
  2483. // This is a BSD-style syscall where errors are indicated by a high
  2484. // Carry Flag and a positive return value, allowing the kernel to
  2485. // return any value that fits into a machine word.
  2486. //
  2487. // This is unlike Linux, where errors are indicated by a negative
  2488. // return value, limiting what can be expressed in one result.
  2489. unsigned arg_count = cast(unsigned)ce->args.count;
  2490. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2491. for_array(i, ce->args) {
  2492. lbValue arg = lb_build_expr(p, ce->args[i]);
  2493. arg = lb_emit_conv(p, arg, t_uintptr);
  2494. args[i] = arg.value;
  2495. }
  2496. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2497. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2498. for (unsigned i = 0; i < arg_count; i++) {
  2499. llvm_arg_types[i] = llvm_uintptr;
  2500. }
  2501. LLVMTypeRef *results = gb_alloc_array(permanent_allocator(), LLVMTypeRef, 2);
  2502. results[0] = lb_type(p->module, t_uintptr);
  2503. results[1] = lb_type(p->module, t_bool);
  2504. LLVMTypeRef llvm_results = LLVMStructTypeInContext(p->module->ctx, results, 2, false);
  2505. LLVMTypeRef func_type = LLVMFunctionType(llvm_results, llvm_arg_types, arg_count, false);
  2506. LLVMValueRef inline_asm = nullptr;
  2507. switch (build_context.metrics.arch) {
  2508. case TargetArch_amd64:
  2509. {
  2510. GB_ASSERT(arg_count <= 7);
  2511. char asm_string[] = "syscall; setnb %cl";
  2512. // Using CL as an output; RCX doesn't need to get clobbered later.
  2513. gbString constraints = gb_string_make(heap_allocator(), "={rax},={cl}");
  2514. for (unsigned i = 0; i < arg_count; i++) {
  2515. constraints = gb_string_appendc(constraints, ",{");
  2516. static char const *regs[] = {
  2517. "rax",
  2518. "rdi",
  2519. "rsi",
  2520. "rdx",
  2521. "r10",
  2522. "r8",
  2523. "r9",
  2524. };
  2525. constraints = gb_string_appendc(constraints, regs[i]);
  2526. constraints = gb_string_appendc(constraints, "}");
  2527. }
  2528. // NOTE(Feoramund): If you're experiencing instability
  2529. // regarding syscalls during optimized builds, it is
  2530. // possible that the ABI has changed for your platform,
  2531. // or I've missed a register clobber.
  2532. //
  2533. // Documentation on this topic is sparse, but I was able to
  2534. // determine what registers were being clobbered by adding
  2535. // dummy values to them, setting a breakpoint after the
  2536. // syscall, and checking the state of the registers afterwards.
  2537. //
  2538. // Be advised that manually stepping through a debugger may
  2539. // cause the kernel to not return via sysret, which will
  2540. // preserve register state that normally would've been
  2541. // otherwise clobbered.
  2542. //
  2543. // It is also possible that some syscalls clobber different registers.
  2544. if (build_context.metrics.os == TargetOs_freebsd) {
  2545. // As a fix for CVE-2019-5595, FreeBSD started
  2546. // clobbering R8, R9, and R10, instead of restoring
  2547. // them.
  2548. //
  2549. // More info here:
  2550. //
  2551. // https://www.freebsd.org/security/advisories/FreeBSD-SA-19:01.syscall.asc
  2552. // https://github.com/freebsd/freebsd-src/blob/098dbd7ff7f3da9dda03802cdb2d8755f816eada/sys/amd64/amd64/exception.S#L605
  2553. // https://stackoverflow.com/q/66878250
  2554. constraints = gb_string_appendc(constraints, ",~{r8},~{r9},~{r10}");
  2555. }
  2556. // Both FreeBSD and NetBSD might clobber RDX.
  2557. //
  2558. // For NetBSD, it was clobbered during a call to sysctl.
  2559. //
  2560. // For FreeBSD, it's listed as "return value 2" in their
  2561. // AMD64 assembly, so there's no guarantee that it will persist.
  2562. constraints = gb_string_appendc(constraints, ",~{rdx},~{r11},~{cc},~{memory}");
  2563. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2564. }
  2565. break;
  2566. case TargetArch_arm64:
  2567. {
  2568. GB_ASSERT(arg_count <= 7);
  2569. char asm_string[] = "svc #0; cset x8, cc";
  2570. gbString constraints = gb_string_make(heap_allocator(), "={x0},={x8}");
  2571. for (unsigned i = 0; i < arg_count; i++) {
  2572. constraints = gb_string_appendc(constraints, ",{");
  2573. static char const *regs[] = {
  2574. "x8",
  2575. "x0",
  2576. "x1",
  2577. "x2",
  2578. "x3",
  2579. "x4",
  2580. "x5",
  2581. };
  2582. constraints = gb_string_appendc(constraints, regs[i]);
  2583. constraints = gb_string_appendc(constraints, "}");
  2584. }
  2585. // FreeBSD clobbered x1 on a call to sysctl.
  2586. constraints = gb_string_appendc(constraints, ",~{x1},~{cc},~{memory}");
  2587. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2588. }
  2589. break;
  2590. default:
  2591. GB_PANIC("Unsupported platform");
  2592. }
  2593. lbValue res = {};
  2594. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2595. res.type = make_optional_ok_type(t_uintptr, true);
  2596. return res;
  2597. }
  2598. case BuiltinProc_objc_send:
  2599. return lb_handle_objc_send(p, expr);
  2600. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  2601. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  2602. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  2603. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  2604. case BuiltinProc_constant_utf16_cstring:
  2605. {
  2606. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  2607. if (r < 0x10000 || r > 0x10ffff) {
  2608. *r1 = 0xfffd;
  2609. *r2 = 0xfffd;
  2610. } else {
  2611. r -= 0x10000;
  2612. *r1 = 0xd800 + ((r>>10)&0x3ff);
  2613. *r2 = 0xdc00 + (r&0x3ff);
  2614. }
  2615. };
  2616. lbModule *m = p->module;
  2617. auto tav = type_and_value_of_expr(ce->args[0]);
  2618. GB_ASSERT(tav.value.kind == ExactValue_String);
  2619. String value = tav.value.value_string;
  2620. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  2621. isize max_len = value.len*2 + 1;
  2622. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  2623. isize n = 0;
  2624. while (value.len > 0) {
  2625. Rune r = 0;
  2626. isize w = gb_utf8_decode(value.text, value.len, &r);
  2627. value.text += w;
  2628. value.len -= w;
  2629. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  2630. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  2631. } else if (0x10000 <= r && r <= 0x10ffff) {
  2632. u16 r1, r2;
  2633. encode_surrogate_pair(r, &r1, &r2);
  2634. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  2635. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  2636. } else {
  2637. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  2638. }
  2639. }
  2640. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  2641. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  2642. char *name = nullptr;
  2643. {
  2644. isize max_len = 7+8+1;
  2645. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2646. u32 id = m->gen->global_array_index.fetch_add(1);
  2647. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2648. len -= 1;
  2649. }
  2650. LLVMTypeRef type = LLVMTypeOf(array);
  2651. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2652. LLVMSetInitializer(global_data, array);
  2653. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  2654. LLVMValueRef indices[] = {
  2655. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2656. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2657. };
  2658. lbValue res = {};
  2659. res.type = tv.type;
  2660. res.value = LLVMBuildInBoundsGEP2(p->builder, type, global_data, indices, gb_count_of(indices), "");
  2661. return res;
  2662. }
  2663. case BuiltinProc_wasm_memory_grow:
  2664. {
  2665. char const *name = "llvm.wasm.memory.grow";
  2666. LLVMTypeRef types[1] = {
  2667. lb_type(p->module, t_i32),
  2668. };
  2669. LLVMValueRef args[2] = {};
  2670. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2671. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  2672. lbValue res = {};
  2673. res.type = t_i32;
  2674. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2675. return lb_emit_conv(p, res, tv.type);
  2676. }
  2677. case BuiltinProc_wasm_memory_size:
  2678. {
  2679. char const *name = "llvm.wasm.memory.size";
  2680. LLVMTypeRef types[1] = {
  2681. lb_type(p->module, t_i32),
  2682. };
  2683. LLVMValueRef args[1] = {};
  2684. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2685. lbValue res = {};
  2686. res.type = t_i32;
  2687. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2688. return lb_emit_conv(p, res, tv.type);
  2689. }
  2690. case BuiltinProc_wasm_memory_atomic_wait32:
  2691. {
  2692. char const *name = "llvm.wasm.memory.atomic.wait32";
  2693. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2694. LLVMValueRef args[3] = {};
  2695. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  2696. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2697. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  2698. lbValue res = {};
  2699. res.type = tv.type;
  2700. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2701. return res;
  2702. }
  2703. case BuiltinProc_wasm_memory_atomic_notify32:
  2704. {
  2705. char const *name = "llvm.wasm.memory.atomic.notify";
  2706. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2707. LLVMValueRef args[2] = {
  2708. lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value,
  2709. lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value
  2710. };
  2711. lbValue res = {};
  2712. res.type = tv.type;
  2713. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2714. return res;
  2715. }
  2716. case BuiltinProc_x86_cpuid:
  2717. {
  2718. Type *param_types[2] = {t_u32, t_u32};
  2719. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), tv.type, false, ProcCC_None);
  2720. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2721. LLVMValueRef the_asm = llvm_get_inline_asm(
  2722. func_type,
  2723. str_lit("cpuid"),
  2724. str_lit("={ax},={bx},={cx},={dx},{ax},{cx}"),
  2725. true
  2726. );
  2727. GB_ASSERT(the_asm != nullptr);
  2728. LLVMValueRef args[2] = {};
  2729. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2730. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2731. lbValue res = {};
  2732. res.type = tv.type;
  2733. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2734. return res;
  2735. }
  2736. case BuiltinProc_x86_xgetbv:
  2737. {
  2738. Type *type = alloc_type_proc_from_types(&t_u32, 1, tv.type, false, ProcCC_None);
  2739. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2740. LLVMValueRef the_asm = llvm_get_inline_asm(
  2741. func_type,
  2742. str_lit("xgetbv"),
  2743. str_lit("={ax},={dx},{cx}"),
  2744. true
  2745. );
  2746. GB_ASSERT(the_asm != nullptr);
  2747. LLVMValueRef args[1] = {};
  2748. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2749. lbValue res = {};
  2750. res.type = tv.type;
  2751. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2752. return res;
  2753. }
  2754. case BuiltinProc_valgrind_client_request:
  2755. {
  2756. lbValue args[7] = {};
  2757. for (isize i = 0; i < 7; i++) {
  2758. args[i] = lb_emit_conv(p, lb_build_expr(p, ce->args[i]), t_uintptr);
  2759. }
  2760. if (!build_context.ODIN_VALGRIND_SUPPORT) {
  2761. return args[0];
  2762. }
  2763. lbValue array = lb_generate_local_array(p, t_uintptr, 6, false);
  2764. for (isize i = 0; i < 6; i++) {
  2765. lbValue gep = lb_emit_array_epi(p, array, i);
  2766. lb_emit_store(p, gep, args[i+1]);
  2767. }
  2768. switch (build_context.metrics.arch) {
  2769. case TargetArch_amd64:
  2770. {
  2771. Type *param_types[2] = {};
  2772. param_types[0] = t_uintptr;
  2773. param_types[1] = array.type;
  2774. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), t_uintptr, false, ProcCC_None);
  2775. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2776. LLVMValueRef the_asm = llvm_get_inline_asm(
  2777. func_type,
  2778. str_lit("rolq $$3, %rdi; rolq $$13, %rdi\n rolq $$61, %rdi; rolq $$51, %rdi\n xchgq %rbx, %rbx"),
  2779. str_lit("={rdx},{rdx},{rax},~{cc},~{memory}"),
  2780. true
  2781. );
  2782. LLVMValueRef asm_args[2] = {};
  2783. asm_args[0] = args[0].value;
  2784. asm_args[1] = array.value;
  2785. lbValue res = {};
  2786. res.type = t_uintptr;
  2787. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, asm_args, gb_count_of(asm_args), "");
  2788. return res;
  2789. }
  2790. break;
  2791. default:
  2792. GB_PANIC("Unsupported architecture: %.*s", LIT(target_arch_names[build_context.metrics.arch]));
  2793. break;
  2794. }
  2795. }
  2796. }
  2797. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  2798. return {};
  2799. }
  2800. gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  2801. switch (param_value.kind) {
  2802. case ParameterValue_Constant:
  2803. if (is_type_constant_type(parameter_type)) {
  2804. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  2805. return res;
  2806. } else {
  2807. ExactValue ev = param_value.value;
  2808. lbValue arg = {};
  2809. Type *type = type_of_expr(param_value.original_ast_expr);
  2810. if (type != nullptr) {
  2811. arg = lb_const_value(p->module, type, ev);
  2812. } else {
  2813. arg = lb_const_value(p->module, parameter_type, param_value.value);
  2814. }
  2815. return lb_emit_conv(p, arg, parameter_type);
  2816. }
  2817. case ParameterValue_Nil:
  2818. return lb_const_nil(p->module, parameter_type);
  2819. case ParameterValue_Location:
  2820. {
  2821. String proc_name = {};
  2822. if (p->entity != nullptr) {
  2823. proc_name = p->entity->token.string;
  2824. }
  2825. return lb_emit_source_code_location_as_global(p, proc_name, pos);
  2826. }
  2827. case ParameterValue_Value:
  2828. return lb_build_expr(p, param_value.ast_value);
  2829. }
  2830. return lb_const_nil(p->module, parameter_type);
  2831. }
  2832. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  2833. gb_internal lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  2834. expr = unparen_expr(expr);
  2835. ast_node(ce, CallExpr, expr);
  2836. lbValue res = lb_build_call_expr_internal(p, expr);
  2837. if (ce->optional_ok_one) {
  2838. GB_ASSERT(is_type_tuple(res.type));
  2839. GB_ASSERT(res.type->Tuple.variables.count == 2);
  2840. return lb_emit_struct_ev(p, res, 0);
  2841. }
  2842. return res;
  2843. }
  2844. gb_internal void lb_add_values_to_array(lbProcedure *p, Array<lbValue> *args, lbValue value) {
  2845. if (is_type_tuple(value.type)) {
  2846. for_array(i, value.type->Tuple.variables) {
  2847. lbValue sub_value = lb_emit_struct_ev(p, value, cast(i32)i);
  2848. array_add(args, sub_value);
  2849. }
  2850. } else {
  2851. array_add(args, value);
  2852. }
  2853. }
  2854. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  2855. lbModule *m = p->module;
  2856. TypeAndValue tv = type_and_value_of_expr(expr);
  2857. ast_node(ce, CallExpr, expr);
  2858. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  2859. AddressingMode proc_mode = proc_tv.mode;
  2860. if (proc_mode == Addressing_Type) {
  2861. GB_ASSERT(ce->args.count == 1);
  2862. lbValue x = lb_build_expr(p, ce->args[0]);
  2863. lbValue y = lb_emit_conv(p, x, tv.type);
  2864. return y;
  2865. }
  2866. Ast *proc_expr = unparen_expr(ce->proc);
  2867. if (proc_mode == Addressing_Builtin) {
  2868. Entity *e = entity_of_node(proc_expr);
  2869. BuiltinProcId id = BuiltinProc_Invalid;
  2870. if (e != nullptr) {
  2871. id = cast(BuiltinProcId)e->Builtin.id;
  2872. } else {
  2873. id = BuiltinProc_DIRECTIVE;
  2874. }
  2875. return lb_build_builtin_proc(p, expr, tv, id);
  2876. }
  2877. // NOTE(bill): Regular call
  2878. lbValue value = {};
  2879. Entity *proc_entity = entity_of_node(proc_expr);
  2880. if (proc_entity != nullptr) {
  2881. if (proc_entity->flags & EntityFlag_Disabled) {
  2882. GB_ASSERT(tv.type == nullptr);
  2883. return {};
  2884. }
  2885. }
  2886. if (proc_expr->tav.mode == Addressing_Constant) {
  2887. ExactValue v = proc_expr->tav.value;
  2888. switch (v.kind) {
  2889. case ExactValue_Integer:
  2890. {
  2891. u64 u = big_int_to_u64(&v.value_integer);
  2892. lbValue x = {};
  2893. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2894. x.type = t_uintptr;
  2895. x = lb_emit_conv(p, x, t_rawptr);
  2896. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2897. break;
  2898. }
  2899. case ExactValue_Pointer:
  2900. {
  2901. u64 u = cast(u64)v.value_pointer;
  2902. lbValue x = {};
  2903. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2904. x.type = t_uintptr;
  2905. x = lb_emit_conv(p, x, t_rawptr);
  2906. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2907. break;
  2908. }
  2909. }
  2910. }
  2911. if (value.value == nullptr) {
  2912. value = lb_build_expr(p, proc_expr);
  2913. }
  2914. GB_ASSERT(value.value != nullptr);
  2915. Type *proc_type_ = base_type(value.type);
  2916. GB_ASSERT(proc_type_->kind == Type_Proc);
  2917. TypeProc *pt = &proc_type_->Proc;
  2918. GB_ASSERT(ce->split_args != nullptr);
  2919. auto args = array_make<lbValue>(permanent_allocator(), 0, pt->param_count);
  2920. bool vari_expand = (ce->ellipsis.pos.line != 0);
  2921. bool is_c_vararg = pt->c_vararg;
  2922. for_array(i, ce->split_args->positional) {
  2923. Entity *e = pt->params->Tuple.variables[i];
  2924. if (e->kind == Entity_TypeName) {
  2925. array_add(&args, lb_const_nil(p->module, e->type));
  2926. continue;
  2927. } else if (e->kind == Entity_Constant) {
  2928. array_add(&args, lb_const_value(p->module, e->type, e->Constant.value));
  2929. continue;
  2930. }
  2931. GB_ASSERT(e->kind == Entity_Variable);
  2932. if (pt->variadic && pt->variadic_index == i) {
  2933. lbValue variadic_args = lb_const_nil(p->module, e->type);
  2934. auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count);
  2935. if (variadic.count != 0) {
  2936. // variadic call argument generation
  2937. Type *slice_type = e->type;
  2938. GB_ASSERT(slice_type->kind == Type_Slice);
  2939. if (is_c_vararg) {
  2940. GB_ASSERT(!vari_expand);
  2941. Type *elem_type = slice_type->Slice.elem;
  2942. for (Ast *var_arg : variadic) {
  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. break;
  2954. } else if (vari_expand) {
  2955. GB_ASSERT(variadic.count == 1);
  2956. variadic_args = lb_build_expr(p, variadic[0]);
  2957. variadic_args = lb_emit_conv(p, variadic_args, slice_type);
  2958. } else {
  2959. Type *elem_type = slice_type->Slice.elem;
  2960. auto var_args = array_make<lbValue>(heap_allocator(), 0, variadic.count);
  2961. defer (array_free(&var_args));
  2962. for (Ast *var_arg : variadic) {
  2963. lbValue v = lb_build_expr(p, var_arg);
  2964. lb_add_values_to_array(p, &var_args, v);
  2965. }
  2966. isize slice_len = var_args.count;
  2967. if (slice_len > 0) {
  2968. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  2969. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  2970. for (isize i = 0; i < var_args.count; i++) {
  2971. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)i);
  2972. lbValue var_arg = var_args[i];
  2973. var_arg = lb_emit_conv(p, var_arg, elem_type);
  2974. lb_emit_store(p, addr, var_arg);
  2975. }
  2976. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  2977. lbValue len = lb_const_int(p->module, t_int, slice_len);
  2978. lb_fill_slice(p, slice, base_elem, len);
  2979. variadic_args = lb_addr_load(p, slice);
  2980. }
  2981. }
  2982. }
  2983. array_add(&args, variadic_args);
  2984. break;
  2985. } else {
  2986. lbValue value = lb_build_expr(p, ce->split_args->positional[i]);
  2987. lb_add_values_to_array(p, &args, value);
  2988. }
  2989. }
  2990. if (!is_c_vararg) {
  2991. array_resize(&args, pt->param_count);
  2992. }
  2993. for (Ast *arg : ce->split_args->named) {
  2994. ast_node(fv, FieldValue, arg);
  2995. GB_ASSERT(fv->field->kind == Ast_Ident);
  2996. String name = fv->field->Ident.token.string;
  2997. gb_unused(name);
  2998. isize param_index = lookup_procedure_parameter(pt, name);
  2999. GB_ASSERT(param_index >= 0);
  3000. Entity *e = pt->params->Tuple.variables[param_index];
  3001. if (e->kind == Entity_TypeName) {
  3002. lbValue value = lb_const_nil(p->module, e->type);
  3003. args[param_index] = value;
  3004. } else if (is_c_vararg && pt->variadic && pt->variadic_index == param_index) {
  3005. GB_ASSERT(param_index == pt->param_count-1);
  3006. Type *slice_type = e->type;
  3007. GB_ASSERT(slice_type->kind == Type_Slice);
  3008. Type *elem_type = slice_type->Slice.elem;
  3009. if (fv->value->kind == Ast_CompoundLit) {
  3010. ast_node(literal, CompoundLit, fv->value);
  3011. for (Ast *var_arg : literal->elems) {
  3012. lbValue arg = lb_build_expr(p, var_arg);
  3013. if (is_type_any(elem_type)) {
  3014. if (is_type_untyped_nil(arg.type)) {
  3015. arg = lb_const_nil(p->module, t_rawptr);
  3016. }
  3017. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(default_type(arg.type))));
  3018. } else {
  3019. array_add(&args, lb_emit_conv(p, arg, c_vararg_promote_type(elem_type)));
  3020. }
  3021. }
  3022. } else {
  3023. lbValue value = lb_build_expr(p, fv->value);
  3024. GB_ASSERT(!is_type_tuple(value.type));
  3025. array_add(&args, lb_emit_conv(p, value, c_vararg_promote_type(value.type)));
  3026. }
  3027. } else {
  3028. lbValue value = lb_build_expr(p, fv->value);
  3029. GB_ASSERT(!is_type_tuple(value.type));
  3030. args[param_index] = value;
  3031. }
  3032. }
  3033. TokenPos pos = ast_token(ce->proc).pos;
  3034. if (pt->params != nullptr) {
  3035. isize min_count = pt->params->Tuple.variables.count;
  3036. if (is_c_vararg) {
  3037. min_count -= 1;
  3038. }
  3039. GB_ASSERT(args.count >= min_count);
  3040. for_array(arg_index, pt->params->Tuple.variables) {
  3041. Entity *e = pt->params->Tuple.variables[arg_index];
  3042. if (pt->variadic && arg_index == pt->variadic_index) {
  3043. if (!is_c_vararg && args[arg_index].value == 0) {
  3044. args[arg_index] = lb_const_nil(p->module, e->type);
  3045. }
  3046. continue;
  3047. }
  3048. lbValue arg = args[arg_index];
  3049. if (arg.value == nullptr && arg.type == nullptr) {
  3050. switch (e->kind) {
  3051. case Entity_TypeName:
  3052. args[arg_index] = lb_const_nil(p->module, e->type);
  3053. break;
  3054. case Entity_Variable:
  3055. args[arg_index] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  3056. break;
  3057. case Entity_Constant:
  3058. args[arg_index] = lb_const_value(p->module, e->type, e->Constant.value);
  3059. break;
  3060. default:
  3061. GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind]));
  3062. }
  3063. } else {
  3064. args[arg_index] = lb_emit_conv(p, arg, e->type);
  3065. }
  3066. }
  3067. }
  3068. isize final_count = is_c_vararg ? args.count : pt->param_count;
  3069. auto call_args = array_slice(args, 0, final_count);
  3070. return lb_emit_call(p, value, call_args, ce->inlining);
  3071. }