llvm_backend_proc.cpp 97 KB

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