llvm_backend_proc.cpp 108 KB

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