llvm_backend_proc.cpp 118 KB

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