llvm_backend_proc.cpp 112 KB

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