llvm_backend_stmt.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  1. gb_internal void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2. if (vd == nullptr || vd->is_mutable) {
  3. return;
  4. }
  5. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  6. static i32 global_guid = 0;
  7. for (Ast *ident : vd->names) {
  8. GB_ASSERT(ident->kind == Ast_Ident);
  9. Entity *e = entity_of_node(ident);
  10. GB_ASSERT(e != nullptr);
  11. if (e->kind != Entity_TypeName) {
  12. continue;
  13. }
  14. bool polymorphic_struct = false;
  15. if (e->type != nullptr && e->kind == Entity_TypeName) {
  16. Type *bt = base_type(e->type);
  17. if (bt->kind == Type_Struct) {
  18. polymorphic_struct = bt->Struct.is_polymorphic;
  19. }
  20. }
  21. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  22. continue;
  23. }
  24. if (e->TypeName.ir_mangled_name.len != 0) {
  25. // NOTE(bill): Already set
  26. continue;
  27. }
  28. lb_set_nested_type_name_ir_mangled_name(e, p, p->module);
  29. }
  30. for_array(i, vd->names) {
  31. Ast *ident = vd->names[i];
  32. GB_ASSERT(ident->kind == Ast_Ident);
  33. Entity *e = entity_of_node(ident);
  34. GB_ASSERT(e != nullptr);
  35. if (e->kind != Entity_Procedure) {
  36. continue;
  37. }
  38. GB_ASSERT (vd->values[i] != nullptr);
  39. Ast *value = unparen_expr(vd->values[i]);
  40. if (value->kind != Ast_ProcLit) {
  41. continue; // It's an alias
  42. }
  43. DeclInfo *decl = decl_info_of_entity(e);
  44. ast_node(pl, ProcLit, decl->proc_lit);
  45. if (pl->body != nullptr) {
  46. GenProcsData *gpd = e->Procedure.gen_procs;
  47. if (gpd) {
  48. rw_mutex_shared_lock(&gpd->mutex);
  49. for (Entity *e : gpd->procs) {
  50. if (!ptr_set_exists(min_dep_set, e)) {
  51. continue;
  52. }
  53. DeclInfo *d = decl_info_of_entity(e);
  54. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  55. }
  56. rw_mutex_shared_unlock(&gpd->mutex);
  57. } else {
  58. lb_build_nested_proc(p, pl, e);
  59. }
  60. } else {
  61. // FFI - Foreign function interace
  62. String original_name = e->token.string;
  63. String name = original_name;
  64. if (e->Procedure.is_foreign) {
  65. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  66. }
  67. if (e->Procedure.link_name.len > 0) {
  68. name = e->Procedure.link_name;
  69. }
  70. lbValue *prev_value = string_map_get(&p->module->members, name);
  71. if (prev_value != nullptr) {
  72. // NOTE(bill): Don't do mutliple declarations in the IR
  73. return;
  74. }
  75. e->Procedure.link_name = name;
  76. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  77. lbValue value = {};
  78. value.value = nested_proc->value;
  79. value.type = nested_proc->type;
  80. array_add(&p->module->procedures_to_generate, nested_proc);
  81. array_add(&p->children, nested_proc);
  82. string_map_set(&p->module->members, name, value);
  83. }
  84. }
  85. }
  86. gb_internal void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  87. for (Ast *stmt : stmts) {
  88. switch (stmt->kind) {
  89. case_ast_node(vd, ValueDecl, stmt);
  90. lb_build_constant_value_decl(p, vd);
  91. case_end;
  92. case_ast_node(fb, ForeignBlockDecl, stmt);
  93. ast_node(block, BlockStmt, fb->body);
  94. lb_build_stmt_list(p, block->stmts);
  95. case_end;
  96. }
  97. }
  98. for (Ast *stmt : stmts) {
  99. lb_build_stmt(p, stmt);
  100. }
  101. }
  102. gb_internal lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  103. GB_ASSERT(ident->kind == Ast_Ident);
  104. Entity *e = entity_of_node(ident);
  105. GB_ASSERT(e->kind == Entity_Label);
  106. for (lbBranchBlocks const &b : p->branch_blocks) {
  107. if (b.label == e->Label.node) {
  108. return b;
  109. }
  110. }
  111. GB_PANIC("Unreachable");
  112. lbBranchBlocks empty = {};
  113. return empty;
  114. }
  115. gb_internal lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  116. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  117. tl->prev = p->target_list;
  118. tl->break_ = break_;
  119. tl->continue_ = continue_;
  120. tl->fallthrough_ = fallthrough_;
  121. p->target_list = tl;
  122. if (label != nullptr) { // Set label blocks
  123. GB_ASSERT(label->kind == Ast_Label);
  124. for (lbBranchBlocks &b : p->branch_blocks) {
  125. GB_ASSERT(b.label != nullptr && label != nullptr);
  126. GB_ASSERT(b.label->kind == Ast_Label);
  127. if (b.label == label) {
  128. b.break_ = break_;
  129. b.continue_ = continue_;
  130. return tl;
  131. }
  132. }
  133. GB_PANIC("Unreachable");
  134. }
  135. return tl;
  136. }
  137. gb_internal void lb_pop_target_list(lbProcedure *p) {
  138. p->target_list = p->target_list->prev;
  139. }
  140. gb_internal void lb_open_scope(lbProcedure *p, Scope *s) {
  141. lbModule *m = p->module;
  142. if (m->debug_builder) {
  143. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  144. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  145. Token token = ast_token(s->node);
  146. unsigned line = cast(unsigned)token.pos.line;
  147. unsigned column = cast(unsigned)token.pos.column;
  148. LLVMMetadataRef file = nullptr;
  149. AstFile *ast_file = s->node->file();
  150. if (ast_file != nullptr) {
  151. file = lb_get_llvm_metadata(m, ast_file);
  152. }
  153. LLVMMetadataRef scope = nullptr;
  154. if (p->scope_stack.count > 0) {
  155. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  156. }
  157. if (scope == nullptr) {
  158. scope = lb_get_llvm_metadata(m, p);
  159. }
  160. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  161. if (m->debug_builder) {
  162. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  163. file, line, column
  164. );
  165. lb_set_llvm_metadata(m, s, res);
  166. }
  167. }
  168. }
  169. p->scope_index += 1;
  170. array_add(&p->scope_stack, s);
  171. }
  172. gb_internal void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  173. lb_emit_defer_stmts(p, kind, block);
  174. GB_ASSERT(p->scope_index > 0);
  175. // NOTE(bill): Remove `context`s made in that scope
  176. while (p->context_stack.count > 0) {
  177. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  178. if (ctx->scope_index >= p->scope_index) {
  179. array_pop(&p->context_stack);
  180. } else {
  181. break;
  182. }
  183. }
  184. p->scope_index -= 1;
  185. array_pop(&p->scope_stack);
  186. }
  187. gb_internal void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  188. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  189. GB_ASSERT(is_type_boolean(tv.type));
  190. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  191. if (tv.value.value_bool) {
  192. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  193. } else if (ws->else_stmt) {
  194. switch (ws->else_stmt->kind) {
  195. case Ast_BlockStmt:
  196. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  197. break;
  198. case Ast_WhenStmt:
  199. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  200. break;
  201. default:
  202. GB_PANIC("Invalid 'else' statement in 'when' statement");
  203. break;
  204. }
  205. }
  206. }
  207. gb_internal void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  208. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_,
  209. bool is_reverse) {
  210. lbModule *m = p->module;
  211. lbValue count = {};
  212. Type *expr_type = base_type(type_deref(expr.type));
  213. switch (expr_type->kind) {
  214. case Type_Array:
  215. count = lb_const_int(m, t_int, expr_type->Array.count);
  216. break;
  217. }
  218. lbValue val = {};
  219. lbValue idx = {};
  220. lbBlock *loop = nullptr;
  221. lbBlock *done = nullptr;
  222. lbBlock *body = nullptr;
  223. lbAddr index = {};
  224. lbValue incr = {};
  225. lbValue cond = {};
  226. index = lb_add_local_generated(p, t_int, false);
  227. if (!is_reverse) {
  228. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  229. loop = lb_create_block(p, "for.index.loop");
  230. lb_emit_jump(p, loop);
  231. lb_start_block(p, loop);
  232. incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  233. lb_addr_store(p, index, incr);
  234. body = lb_create_block(p, "for.index.body");
  235. done = lb_create_block(p, "for.index.done");
  236. if (count.value == nullptr) {
  237. GB_ASSERT(count_ptr.value != nullptr);
  238. count = lb_emit_load(p, count_ptr);
  239. }
  240. cond = lb_emit_comp(p, Token_Lt, incr, count);
  241. } else {
  242. // NOTE(bill): REVERSED LOGIC
  243. if (count.value == nullptr) {
  244. GB_ASSERT(count_ptr.value != nullptr);
  245. count = lb_emit_load(p, count_ptr);
  246. }
  247. count = lb_emit_conv(p, count, t_int);
  248. lb_addr_store(p, index, count);
  249. loop = lb_create_block(p, "for.index.loop");
  250. lb_emit_jump(p, loop);
  251. lb_start_block(p, loop);
  252. incr = lb_emit_arith(p, Token_Sub, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  253. lb_addr_store(p, index, incr);
  254. body = lb_create_block(p, "for.index.body");
  255. done = lb_create_block(p, "for.index.done");
  256. cond = lb_emit_comp(p, Token_GtEq, incr, lb_const_int(m, t_int, 0));
  257. }
  258. lb_emit_if(p, cond, body, done);
  259. lb_start_block(p, body);
  260. idx = lb_addr_load(p, index);
  261. switch (expr_type->kind) {
  262. case Type_Array: {
  263. if (val_type != nullptr) {
  264. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  265. }
  266. break;
  267. }
  268. case Type_EnumeratedArray: {
  269. if (val_type != nullptr) {
  270. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  271. // NOTE(bill): Override the idx value for the enumeration
  272. Type *index_type = expr_type->EnumeratedArray.index;
  273. if (compare_exact_values(Token_NotEq, *expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  274. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, *expr_type->EnumeratedArray.min_value), index_type);
  275. }
  276. }
  277. break;
  278. }
  279. case Type_Slice: {
  280. if (val_type != nullptr) {
  281. lbValue elem = lb_slice_elem(p, expr);
  282. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  283. }
  284. break;
  285. }
  286. case Type_DynamicArray: {
  287. if (val_type != nullptr) {
  288. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  289. elem = lb_emit_load(p, elem);
  290. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  291. }
  292. break;
  293. }
  294. case Type_Struct: {
  295. GB_ASSERT(is_type_soa_struct(expr_type));
  296. break;
  297. }
  298. default:
  299. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  300. break;
  301. }
  302. if (val_) *val_ = val;
  303. if (idx_) *idx_ = idx;
  304. if (loop_) *loop_ = loop;
  305. if (done_) *done_ = done;
  306. }
  307. gb_internal lbValue lb_map_cell_index_static(lbProcedure *p, Type *type, lbValue cells_ptr, lbValue index) {
  308. i64 size, len;
  309. i64 elem_sz = type_size_of(type);
  310. map_cell_size_and_len(type, &size, &len);
  311. index = lb_emit_conv(p, index, t_uintptr);
  312. if (size == len*elem_sz) {
  313. lbValue elems_ptr = lb_emit_conv(p, cells_ptr, alloc_type_pointer(type));
  314. return lb_emit_ptr_offset(p, elems_ptr, index);
  315. }
  316. lbValue cell_index = {};
  317. lbValue data_index = {};
  318. lbValue size_const = lb_const_int(p->module, t_uintptr, size);
  319. lbValue len_const = lb_const_int(p->module, t_uintptr, len);
  320. if (is_power_of_two(len)) {
  321. u64 log2_len = floor_log2(cast(u64)len);
  322. cell_index = log2_len == 0 ? index : lb_emit_arith(p, Token_Shr, index, lb_const_int(p->module, t_uintptr, log2_len), t_uintptr);
  323. data_index = lb_emit_arith(p, Token_And, index, lb_const_int(p->module, t_uintptr, len-1), t_uintptr);
  324. } else {
  325. cell_index = lb_emit_arith(p, Token_Quo, index, len_const, t_uintptr);
  326. data_index = lb_emit_arith(p, Token_Mod, index, len_const, t_uintptr);
  327. }
  328. lbValue elems_ptr = lb_emit_conv(p, cells_ptr, t_uintptr);
  329. lbValue cell_offset = lb_emit_arith(p, Token_Mul, size_const, cell_index, t_uintptr);
  330. elems_ptr = lb_emit_arith(p, Token_Add, elems_ptr, cell_offset, t_uintptr);
  331. elems_ptr = lb_emit_conv(p, elems_ptr, alloc_type_pointer(type));
  332. return lb_emit_ptr_offset(p, elems_ptr, data_index);
  333. }
  334. gb_internal lbValue lb_map_hash_is_valid(lbProcedure *p, lbValue hash) {
  335. // N :: size_of(uintptr)*8 - 1
  336. // (hash != 0) & (hash>>N == 0)
  337. u64 top_bit_index = cast(u64)(type_size_of(t_uintptr)*8 - 1);
  338. lbValue shift_amount = lb_const_int(p->module, t_uintptr, top_bit_index);
  339. lbValue zero = lb_const_int(p->module, t_uintptr, 0);
  340. lbValue not_empty = lb_emit_comp(p, Token_NotEq, hash, zero);
  341. lbValue not_deleted = lb_emit_arith(p, Token_Shr, hash, shift_amount, t_uintptr);
  342. not_deleted = lb_emit_comp(p, Token_CmpEq, not_deleted, zero);
  343. return lb_emit_arith(p, Token_And, not_deleted, not_empty, t_uintptr);
  344. }
  345. gb_internal void lb_build_range_map(lbProcedure *p, lbValue expr, Type *val_type,
  346. lbValue *val_, lbValue *key_, lbBlock **loop_, lbBlock **done_) {
  347. lbModule *m = p->module;
  348. Type *type = base_type(type_deref(expr.type));
  349. GB_ASSERT(type->kind == Type_Map);
  350. lbValue idx = {};
  351. lbBlock *loop = nullptr;
  352. lbBlock *done = nullptr;
  353. lbBlock *body = nullptr;
  354. lbBlock *hash_check = nullptr;
  355. lbAddr index = lb_add_local_generated(p, t_int, false);
  356. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  357. loop = lb_create_block(p, "for.index.loop");
  358. lb_emit_jump(p, loop);
  359. lb_start_block(p, loop);
  360. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  361. lb_addr_store(p, index, incr);
  362. hash_check = lb_create_block(p, "for.index.hash_check");
  363. body = lb_create_block(p, "for.index.body");
  364. done = lb_create_block(p, "for.index.done");
  365. lbValue map_value = lb_emit_load(p, expr);
  366. lbValue capacity = lb_map_cap(p, map_value);
  367. lbValue cond = lb_emit_comp(p, Token_Lt, incr, capacity);
  368. lb_emit_if(p, cond, hash_check, done);
  369. lb_start_block(p, hash_check);
  370. idx = lb_addr_load(p, index);
  371. lbValue ks = lb_map_data_uintptr(p, map_value);
  372. lbValue vs = lb_emit_conv(p, lb_map_cell_index_static(p, type->Map.key, ks, capacity), alloc_type_pointer(type->Map.value));
  373. lbValue hs = lb_emit_conv(p, lb_map_cell_index_static(p, type->Map.value, vs, capacity), alloc_type_pointer(t_uintptr));
  374. // NOTE(bill): no need to use lb_map_cell_index_static for that hashes
  375. // since it will always be packed without padding into the cells
  376. lbValue hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, idx));
  377. lbValue hash_cond = lb_map_hash_is_valid(p, hash);
  378. lb_emit_if(p, hash_cond, body, loop);
  379. lb_start_block(p, body);
  380. lbValue key_ptr = lb_map_cell_index_static(p, type->Map.key, ks, idx);
  381. lbValue val_ptr = lb_map_cell_index_static(p, type->Map.value, vs, idx);
  382. lbValue key = lb_emit_load(p, key_ptr);
  383. lbValue val = lb_emit_load(p, val_ptr);
  384. if (val_) *val_ = val;
  385. if (key_) *key_ = key;
  386. if (loop_) *loop_ = loop;
  387. if (done_) *done_ = done;
  388. }
  389. gb_internal void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  390. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_,
  391. bool is_reverse) {
  392. lbModule *m = p->module;
  393. lbValue count = lb_const_int(m, t_int, 0);
  394. Type *expr_type = base_type(expr.type);
  395. switch (expr_type->kind) {
  396. case Type_Basic:
  397. count = lb_string_len(p, expr);
  398. break;
  399. default:
  400. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  401. break;
  402. }
  403. lbValue val = {};
  404. lbValue idx = {};
  405. lbBlock *loop = nullptr;
  406. lbBlock *done = nullptr;
  407. lbBlock *body = nullptr;
  408. loop = lb_create_block(p, "for.string.loop");
  409. body = lb_create_block(p, "for.string.body");
  410. done = lb_create_block(p, "for.string.done");
  411. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  412. lbValue offset = {};
  413. lbValue cond = {};
  414. if (!is_reverse) {
  415. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  416. lb_emit_jump(p, loop);
  417. lb_start_block(p, loop);
  418. offset = lb_addr_load(p, offset_);
  419. cond = lb_emit_comp(p, Token_Lt, offset, count);
  420. } else {
  421. // NOTE(bill): REVERSED LOGIC
  422. lb_addr_store(p, offset_, count);
  423. lb_emit_jump(p, loop);
  424. lb_start_block(p, loop);
  425. offset = lb_addr_load(p, offset_);
  426. cond = lb_emit_comp(p, Token_Gt, offset, lb_const_int(m, t_int, 0));
  427. }
  428. lb_emit_if(p, cond, body, done);
  429. lb_start_block(p, body);
  430. lbValue rune_and_len = {};
  431. if (!is_reverse) {
  432. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  433. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  434. auto args = array_make<lbValue>(permanent_allocator(), 1);
  435. args[0] = lb_emit_string(p, str_elem, str_len);
  436. rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  437. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  438. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  439. idx = offset;
  440. } else {
  441. // NOTE(bill): REVERSED LOGIC
  442. lbValue str_elem = lb_string_elem(p, expr);
  443. lbValue str_len = offset;
  444. auto args = array_make<lbValue>(permanent_allocator(), 1);
  445. args[0] = lb_emit_string(p, str_elem, str_len);
  446. rune_and_len = lb_emit_runtime_call(p, "string_decode_last_rune", args);
  447. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  448. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Sub, offset, len, t_int));
  449. idx = lb_addr_load(p, offset_);
  450. }
  451. if (val_type != nullptr) {
  452. val = lb_emit_struct_ev(p, rune_and_len, 0);
  453. }
  454. if (val_) *val_ = val;
  455. if (idx_) *idx_ = idx;
  456. if (loop_) *loop_ = loop;
  457. if (done_) *done_ = done;
  458. }
  459. gb_internal void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  460. AstRangeStmt *rs, Scope *scope) {
  461. bool ADD_EXTRA_WRAPPING_CHECK = true;
  462. lbModule *m = p->module;
  463. lb_open_scope(p, scope);
  464. Type *val0_type = nullptr;
  465. Type *val1_type = nullptr;
  466. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  467. val0_type = type_of_expr(rs->vals[0]);
  468. }
  469. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  470. val1_type = type_of_expr(rs->vals[1]);
  471. }
  472. TokenKind op = Token_Lt;
  473. switch (node->op.kind) {
  474. case Token_Ellipsis: op = Token_LtEq; break;
  475. case Token_RangeFull: op = Token_LtEq; break;
  476. case Token_RangeHalf: op = Token_Lt; break;
  477. default: GB_PANIC("Invalid interval operator"); break;
  478. }
  479. lbValue lower = lb_build_expr(p, node->left);
  480. lbValue upper = {}; // initialized each time in the loop
  481. lbAddr value;
  482. if (val0_type != nullptr) {
  483. Entity *e = entity_of_node(rs->vals[0]);
  484. value = lb_add_local(p, val0_type, e, false);
  485. } else {
  486. value = lb_add_local_generated(p, lower.type, false);
  487. }
  488. lb_addr_store(p, value, lower);
  489. lbAddr index;
  490. if (val1_type != nullptr) {
  491. Entity *e = entity_of_node(rs->vals[1]);
  492. index = lb_add_local(p, val1_type, e, false);
  493. } else {
  494. index = lb_add_local_generated(p, t_int, false);
  495. }
  496. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  497. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  498. lbBlock *body = lb_create_block(p, "for.interval.body");
  499. lbBlock *done = lb_create_block(p, "for.interval.done");
  500. lb_emit_jump(p, loop);
  501. lb_start_block(p, loop);
  502. upper = lb_build_expr(p, node->right);
  503. lbValue curr_value = lb_addr_load(p, value);
  504. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  505. lb_emit_if(p, cond, body, done);
  506. lb_start_block(p, body);
  507. lbValue val = lb_addr_load(p, value);
  508. lbValue idx = lb_addr_load(p, index);
  509. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  510. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], idx);
  511. {
  512. // NOTE: this check block will most likely be optimized out, and is here
  513. // to make this code easier to read
  514. lbBlock *check = nullptr;
  515. lbBlock *post = lb_create_block(p, "for.interval.post");
  516. lbBlock *continue_block = post;
  517. if (ADD_EXTRA_WRAPPING_CHECK &&
  518. op == Token_LtEq) {
  519. check = lb_create_block(p, "for.interval.check");
  520. continue_block = check;
  521. }
  522. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  523. lb_build_stmt(p, rs->body);
  524. lb_close_scope(p, lbDeferExit_Default, nullptr);
  525. lb_pop_target_list(p);
  526. if (check != nullptr) {
  527. lb_emit_jump(p, check);
  528. lb_start_block(p, check);
  529. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  530. lb_emit_if(p, check_cond, post, done);
  531. } else {
  532. lb_emit_jump(p, post);
  533. }
  534. lb_start_block(p, post);
  535. lb_emit_increment(p, value.addr);
  536. lb_emit_increment(p, index.addr);
  537. lb_emit_jump(p, loop);
  538. }
  539. lb_start_block(p, done);
  540. }
  541. gb_internal void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  542. lbModule *m = p->module;
  543. Type *t = enum_type;
  544. GB_ASSERT(is_type_enum(t));
  545. t = base_type(t);
  546. Type *core_elem = core_type(t);
  547. GB_ASSERT(t->kind == Type_Enum);
  548. i64 enum_count = t->Enum.fields.count;
  549. lbValue max_count = lb_const_int(m, t_int, enum_count);
  550. lbValue ti = lb_type_info(m, t);
  551. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  552. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  553. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  554. lbValue values_data = lb_slice_elem(p, values);
  555. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  556. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  557. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  558. lb_emit_jump(p, loop);
  559. lb_start_block(p, loop);
  560. lbBlock *body = lb_create_block(p, "for.enum.body");
  561. lbBlock *done = lb_create_block(p, "for.enum.done");
  562. lbValue offset = lb_addr_load(p, offset_);
  563. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  564. lb_emit_if(p, cond, body, done);
  565. lb_start_block(p, body);
  566. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  567. lb_emit_increment(p, offset_.addr);
  568. lbValue val = {};
  569. if (val_type != nullptr) {
  570. GB_ASSERT(are_types_identical(enum_type, val_type));
  571. if (is_type_integer(core_elem)) {
  572. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  573. val = lb_emit_conv(p, i, t);
  574. } else {
  575. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  576. }
  577. }
  578. if (val_) *val_ = val;
  579. if (idx_) *idx_ = offset;
  580. if (loop_) *loop_ = loop;
  581. if (done_) *done_ = done;
  582. }
  583. gb_internal void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  584. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  585. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  586. lb_emit_jump(p, loop);
  587. lb_start_block(p, loop);
  588. lbBlock *body = lb_create_block(p, "for.tuple.body");
  589. lbBlock *done = lb_create_block(p, "for.tuple.done");
  590. lbValue tuple_value = lb_build_expr(p, expr);
  591. Type *tuple = tuple_value.type;
  592. GB_ASSERT(tuple->kind == Type_Tuple);
  593. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  594. i32 cond_index = tuple_count-1;
  595. lbValue cond = lb_emit_tuple_ev(p, tuple_value, cond_index);
  596. lb_emit_if(p, cond, body, done);
  597. lb_start_block(p, body);
  598. if (val0_) *val0_ = lb_emit_tuple_ev(p, tuple_value, 0);
  599. if (val1_) *val1_ = lb_emit_tuple_ev(p, tuple_value, 1);
  600. if (loop_) *loop_ = loop;
  601. if (done_) *done_ = done;
  602. }
  603. gb_internal void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  604. Ast *expr = unparen_expr(rs->expr);
  605. TypeAndValue tav = type_and_value_of_expr(expr);
  606. lbBlock *loop = nullptr;
  607. lbBlock *body = nullptr;
  608. lbBlock *done = nullptr;
  609. bool is_reverse = rs->reverse;
  610. lb_open_scope(p, scope);
  611. Type *val_types[2] = {};
  612. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  613. val_types[0] = type_of_expr(rs->vals[0]);
  614. }
  615. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  616. val_types[1] = type_of_expr(rs->vals[1]);
  617. }
  618. lbAddr array = lb_build_addr(p, expr);
  619. if (is_type_pointer(lb_addr_type(array))) {
  620. array = lb_addr(lb_addr_load(p, array));
  621. }
  622. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  623. lbAddr index = lb_add_local_generated(p, t_int, false);
  624. lbValue incr = {};
  625. lbValue cond = {};
  626. if (!is_reverse) {
  627. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  628. loop = lb_create_block(p, "for.soa.loop");
  629. lb_emit_jump(p, loop);
  630. lb_start_block(p, loop);
  631. incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  632. lb_addr_store(p, index, incr);
  633. body = lb_create_block(p, "for.soa.body");
  634. done = lb_create_block(p, "for.soa.done");
  635. cond = lb_emit_comp(p, Token_Lt, incr, count);
  636. } else {
  637. // NOTE(bill): REVERSED LOGIC
  638. lb_addr_store(p, index, count);
  639. loop = lb_create_block(p, "for.soa.loop");
  640. lb_emit_jump(p, loop);
  641. lb_start_block(p, loop);
  642. incr = lb_emit_arith(p, Token_Sub, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  643. lb_addr_store(p, index, incr);
  644. body = lb_create_block(p, "for.soa.body");
  645. done = lb_create_block(p, "for.soa.done");
  646. cond = lb_emit_comp(p, Token_GtEq, incr, lb_const_int(p->module, t_int, 0));
  647. }
  648. lb_emit_if(p, cond, body, done);
  649. lb_start_block(p, body);
  650. if (val_types[0]) {
  651. Entity *e = entity_of_node(rs->vals[0]);
  652. if (e != nullptr) {
  653. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  654. map_set(&p->module->soa_values, e, soa_val);
  655. }
  656. }
  657. if (val_types[1]) {
  658. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  659. }
  660. lb_push_target_list(p, rs->label, done, loop, nullptr);
  661. lb_build_stmt(p, rs->body);
  662. lb_close_scope(p, lbDeferExit_Default, nullptr);
  663. lb_pop_target_list(p);
  664. lb_emit_jump(p, loop);
  665. lb_start_block(p, done);
  666. }
  667. gb_internal void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  668. Ast *expr = unparen_expr(rs->expr);
  669. if (is_ast_range(expr)) {
  670. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  671. return;
  672. }
  673. Type *expr_type = type_of_expr(expr);
  674. if (expr_type != nullptr) {
  675. Type *et = base_type(type_deref(expr_type));
  676. if (is_type_soa_struct(et)) {
  677. lb_build_range_stmt_struct_soa(p, rs, scope);
  678. return;
  679. }
  680. }
  681. lb_open_scope(p, scope);
  682. Type *val0_type = nullptr;
  683. Type *val1_type = nullptr;
  684. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  685. val0_type = type_of_expr(rs->vals[0]);
  686. }
  687. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  688. val1_type = type_of_expr(rs->vals[1]);
  689. }
  690. lbValue val = {};
  691. lbValue key = {};
  692. lbBlock *loop = nullptr;
  693. lbBlock *done = nullptr;
  694. bool is_map = false;
  695. TypeAndValue tav = type_and_value_of_expr(expr);
  696. if (tav.mode == Addressing_Type) {
  697. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  698. } else {
  699. Type *expr_type = type_of_expr(expr);
  700. Type *et = base_type(type_deref(expr_type));
  701. switch (et->kind) {
  702. case Type_Map: {
  703. is_map = true;
  704. lbValue map = lb_build_addr_ptr(p, expr);
  705. if (is_type_pointer(type_deref(map.type))) {
  706. map = lb_emit_load(p, map);
  707. }
  708. lb_build_range_map(p, map, val1_type, &val, &key, &loop, &done);
  709. break;
  710. }
  711. case Type_Array: {
  712. lbValue array = lb_build_addr_ptr(p, expr);
  713. if (is_type_pointer(type_deref(array.type))) {
  714. array = lb_emit_load(p, array);
  715. }
  716. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  717. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  718. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse);
  719. break;
  720. }
  721. case Type_EnumeratedArray: {
  722. lbValue array = lb_build_addr_ptr(p, expr);
  723. if (is_type_pointer(type_deref(array.type))) {
  724. array = lb_emit_load(p, array);
  725. }
  726. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  727. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  728. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse);
  729. break;
  730. }
  731. case Type_DynamicArray: {
  732. lbValue count_ptr = {};
  733. lbValue array = lb_build_addr_ptr(p, expr);
  734. if (is_type_pointer(type_deref(array.type))) {
  735. array = lb_emit_load(p, array);
  736. }
  737. count_ptr = lb_emit_struct_ep(p, array, 1);
  738. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse);
  739. break;
  740. }
  741. case Type_Slice: {
  742. lbValue count_ptr = {};
  743. lbValue slice = lb_build_expr(p, expr);
  744. if (is_type_pointer(slice.type)) {
  745. count_ptr = lb_emit_struct_ep(p, slice, 1);
  746. slice = lb_emit_load(p, slice);
  747. } else {
  748. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  749. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  750. }
  751. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse);
  752. break;
  753. }
  754. case Type_Basic: {
  755. lbValue string = lb_build_expr(p, expr);
  756. if (is_type_pointer(string.type)) {
  757. string = lb_emit_load(p, string);
  758. }
  759. if (is_type_untyped(expr_type)) {
  760. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  761. lb_addr_store(p, s, string);
  762. string = lb_addr_load(p, s);
  763. }
  764. Type *t = base_type(string.type);
  765. GB_ASSERT(!is_type_cstring(t));
  766. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done, rs->reverse);
  767. break;
  768. }
  769. case Type_Tuple:
  770. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  771. break;
  772. default:
  773. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  774. break;
  775. }
  776. }
  777. if (is_map) {
  778. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  779. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  780. } else {
  781. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  782. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  783. }
  784. lb_push_target_list(p, rs->label, done, loop, nullptr);
  785. lb_build_stmt(p, rs->body);
  786. lb_close_scope(p, lbDeferExit_Default, nullptr);
  787. lb_pop_target_list(p);
  788. lb_emit_jump(p, loop);
  789. lb_start_block(p, done);
  790. }
  791. gb_internal void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  792. lbModule *m = p->module;
  793. lb_open_scope(p, scope); // Open scope here
  794. Type *val0_type = nullptr;
  795. Type *val1_type = nullptr;
  796. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  797. val0_type = type_of_expr(rs->val0);
  798. }
  799. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  800. val1_type = type_of_expr(rs->val1);
  801. }
  802. if (val0_type != nullptr) {
  803. Entity *e = entity_of_node(rs->val0);
  804. lb_add_local(p, e->type, e, true);
  805. }
  806. if (val1_type != nullptr) {
  807. Entity *e = entity_of_node(rs->val1);
  808. lb_add_local(p, e->type, e, true);
  809. }
  810. lbValue val = {};
  811. lbValue key = {};
  812. Ast *expr = unparen_expr(rs->expr);
  813. TypeAndValue tav = type_and_value_of_expr(expr);
  814. if (is_ast_range(expr)) {
  815. lbAddr val0_addr = {};
  816. lbAddr val1_addr = {};
  817. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  818. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  819. TokenKind op = expr->BinaryExpr.op.kind;
  820. Ast *start_expr = expr->BinaryExpr.left;
  821. Ast *end_expr = expr->BinaryExpr.right;
  822. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  823. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  824. ExactValue start = start_expr->tav.value;
  825. ExactValue end = end_expr->tav.value;
  826. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  827. ExactValue index = exact_value_i64(0);
  828. for (ExactValue val = start;
  829. compare_exact_values(Token_LtEq, val, end);
  830. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  831. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  832. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  833. lb_build_stmt(p, rs->body);
  834. }
  835. } else { // ..< [start, end)
  836. ExactValue index = exact_value_i64(0);
  837. for (ExactValue val = start;
  838. compare_exact_values(Token_Lt, val, end);
  839. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  840. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  841. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  842. lb_build_stmt(p, rs->body);
  843. }
  844. }
  845. } else if (tav.mode == Addressing_Type) {
  846. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  847. Type *et = type_deref(tav.type);
  848. Type *bet = base_type(et);
  849. lbAddr val0_addr = {};
  850. lbAddr val1_addr = {};
  851. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  852. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  853. for_array(i, bet->Enum.fields) {
  854. Entity *field = bet->Enum.fields[i];
  855. GB_ASSERT(field->kind == Entity_Constant);
  856. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  857. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  858. lb_build_stmt(p, rs->body);
  859. }
  860. } else {
  861. lbAddr val0_addr = {};
  862. lbAddr val1_addr = {};
  863. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  864. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  865. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  866. Type *t = base_type(expr->tav.type);
  867. switch (t->kind) {
  868. case Type_Basic:
  869. GB_ASSERT(is_type_string(t));
  870. {
  871. ExactValue value = expr->tav.value;
  872. GB_ASSERT(value.kind == ExactValue_String);
  873. String str = value.value_string;
  874. Rune codepoint = 0;
  875. isize offset = 0;
  876. do {
  877. isize width = utf8_decode(str.text+offset, str.len-offset, &codepoint);
  878. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  879. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  880. lb_build_stmt(p, rs->body);
  881. offset += width;
  882. } while (offset < str.len);
  883. }
  884. break;
  885. case Type_Array:
  886. if (t->Array.count > 0) {
  887. lbValue val = lb_build_expr(p, expr);
  888. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  889. for (i64 i = 0; i < t->Array.count; i++) {
  890. if (val0_type) {
  891. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  892. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  893. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  894. }
  895. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  896. lb_build_stmt(p, rs->body);
  897. }
  898. }
  899. break;
  900. case Type_EnumeratedArray:
  901. if (t->EnumeratedArray.count > 0) {
  902. lbValue val = lb_build_expr(p, expr);
  903. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  904. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  905. if (val0_type) {
  906. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  907. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  908. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  909. }
  910. if (val1_type) {
  911. ExactValue idx = exact_value_add(exact_value_i64(i), *t->EnumeratedArray.min_value);
  912. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  913. }
  914. lb_build_stmt(p, rs->body);
  915. }
  916. }
  917. break;
  918. default:
  919. GB_PANIC("Invalid '#unroll for' type");
  920. break;
  921. }
  922. }
  923. lb_close_scope(p, lbDeferExit_Default, nullptr);
  924. }
  925. gb_internal bool lb_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss, bool *default_found_) {
  926. if (ss->tag == nullptr) {
  927. return false;
  928. }
  929. bool is_typeid = false;
  930. TypeAndValue tv = type_and_value_of_expr(ss->tag);
  931. if (is_type_integer(core_type(tv.type))) {
  932. // okay
  933. } else if (is_type_typeid(tv.type)) {
  934. // okay
  935. is_typeid = true;
  936. } else {
  937. return false;
  938. }
  939. ast_node(body, BlockStmt, ss->body);
  940. for (Ast *clause : body->stmts) {
  941. ast_node(cc, CaseClause, clause);
  942. if (cc->list.count == 0) {
  943. if (default_found_) *default_found_ = true;
  944. continue;
  945. }
  946. for (Ast *expr : cc->list) {
  947. expr = unparen_expr(expr);
  948. if (is_ast_range(expr)) {
  949. return false;
  950. }
  951. if (expr->tav.mode == Addressing_Type) {
  952. GB_ASSERT(is_typeid);
  953. continue;
  954. }
  955. tv = type_and_value_of_expr(expr);
  956. if (tv.mode != Addressing_Constant) {
  957. return false;
  958. }
  959. if (!is_type_integer(core_type(tv.type))) {
  960. return false;
  961. }
  962. }
  963. }
  964. return true;
  965. }
  966. gb_internal void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  967. lb_open_scope(p, scope);
  968. if (ss->init != nullptr) {
  969. lb_build_stmt(p, ss->init);
  970. }
  971. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  972. if (ss->tag != nullptr) {
  973. tag = lb_build_expr(p, ss->tag);
  974. }
  975. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  976. ast_node(body, BlockStmt, ss->body);
  977. isize case_count = body->stmts.count;
  978. Slice<Ast *> default_stmts = {};
  979. lbBlock *default_fall = nullptr;
  980. lbBlock *default_block = nullptr;
  981. lbBlock *fall = nullptr;
  982. bool default_found = false;
  983. bool is_trivial = lb_switch_stmt_can_be_trivial_jump_table(ss, &default_found);
  984. auto body_blocks = slice_make<lbBlock *>(permanent_allocator(), body->stmts.count);
  985. for_array(i, body->stmts) {
  986. Ast *clause = body->stmts[i];
  987. ast_node(cc, CaseClause, clause);
  988. body_blocks[i] = lb_create_block(p, cc->list.count == 0 ? "switch.default.body" : "switch.case.body");
  989. if (cc->list.count == 0) {
  990. default_block = body_blocks[i];
  991. }
  992. }
  993. LLVMValueRef switch_instr = nullptr;
  994. if (is_trivial) {
  995. isize num_cases = 0;
  996. for (Ast *clause : body->stmts) {
  997. ast_node(cc, CaseClause, clause);
  998. num_cases += cc->list.count;
  999. }
  1000. LLVMBasicBlockRef end_block = done->block;
  1001. if (default_block) {
  1002. end_block = default_block->block;
  1003. }
  1004. switch_instr = LLVMBuildSwitch(p->builder, tag.value, end_block, cast(unsigned)num_cases);
  1005. }
  1006. for_array(i, body->stmts) {
  1007. Ast *clause = body->stmts[i];
  1008. ast_node(cc, CaseClause, clause);
  1009. lbBlock *body = body_blocks[i];
  1010. fall = done;
  1011. if (i+1 < case_count) {
  1012. fall = body_blocks[i+1];
  1013. }
  1014. if (cc->list.count == 0) {
  1015. // default case
  1016. default_stmts = cc->stmts;
  1017. default_fall = fall;
  1018. if (switch_instr == nullptr) {
  1019. default_block = body;
  1020. } else {
  1021. GB_ASSERT(default_block != nullptr);
  1022. }
  1023. continue;
  1024. }
  1025. lbBlock *next_cond = nullptr;
  1026. for (Ast *expr : cc->list) {
  1027. expr = unparen_expr(expr);
  1028. if (switch_instr != nullptr) {
  1029. lbValue on_val = {};
  1030. if (expr->tav.mode == Addressing_Type) {
  1031. GB_ASSERT(is_type_typeid(tag.type));
  1032. lbValue e = lb_typeid(p->module, expr->tav.type);
  1033. on_val = lb_emit_conv(p, e, tag.type);
  1034. } else {
  1035. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  1036. GB_ASSERT(!is_ast_range(expr));
  1037. on_val = lb_build_expr(p, expr);
  1038. on_val = lb_emit_conv(p, on_val, tag.type);
  1039. }
  1040. GB_ASSERT(LLVMIsConstant(on_val.value));
  1041. LLVMAddCase(switch_instr, on_val.value, body->block);
  1042. continue;
  1043. }
  1044. next_cond = lb_create_block(p, "switch.case.next");
  1045. lbValue cond = {};
  1046. if (is_ast_range(expr)) {
  1047. ast_node(ie, BinaryExpr, expr);
  1048. TokenKind op = Token_Invalid;
  1049. switch (ie->op.kind) {
  1050. case Token_Ellipsis: op = Token_LtEq; break;
  1051. case Token_RangeFull: op = Token_LtEq; break;
  1052. case Token_RangeHalf: op = Token_Lt; break;
  1053. default: GB_PANIC("Invalid interval operator"); break;
  1054. }
  1055. lbValue lhs = lb_build_expr(p, ie->left);
  1056. lbValue rhs = lb_build_expr(p, ie->right);
  1057. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  1058. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  1059. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  1060. } else {
  1061. if (expr->tav.mode == Addressing_Type) {
  1062. GB_ASSERT(is_type_typeid(tag.type));
  1063. lbValue e = lb_typeid(p->module, expr->tav.type);
  1064. e = lb_emit_conv(p, e, tag.type);
  1065. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  1066. } else {
  1067. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  1068. }
  1069. }
  1070. lb_emit_if(p, cond, body, next_cond);
  1071. lb_start_block(p, next_cond);
  1072. }
  1073. lb_start_block(p, body);
  1074. lb_push_target_list(p, ss->label, done, nullptr, fall);
  1075. lb_open_scope(p, body->scope);
  1076. lb_build_stmt_list(p, cc->stmts);
  1077. lb_close_scope(p, lbDeferExit_Default, body);
  1078. lb_pop_target_list(p);
  1079. lb_emit_jump(p, done);
  1080. if (switch_instr == nullptr) {
  1081. lb_start_block(p, next_cond);
  1082. }
  1083. }
  1084. if (default_block != nullptr) {
  1085. if (switch_instr == nullptr) {
  1086. lb_emit_jump(p, default_block);
  1087. }
  1088. lb_start_block(p, default_block);
  1089. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  1090. lb_open_scope(p, default_block->scope);
  1091. lb_build_stmt_list(p, default_stmts);
  1092. lb_close_scope(p, lbDeferExit_Default, default_block);
  1093. lb_pop_target_list(p);
  1094. }
  1095. lb_emit_jump(p, done);
  1096. lb_start_block(p, done);
  1097. lb_close_scope(p, lbDeferExit_Default, done);
  1098. }
  1099. gb_internal void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  1100. Entity *e = implicit_entity_of_node(clause);
  1101. GB_ASSERT(e != nullptr);
  1102. if (e->flags & EntityFlag_Value) {
  1103. // by value
  1104. GB_ASSERT(are_types_identical(e->type, value.type));
  1105. lbAddr x = lb_add_local(p, e->type, e, false);
  1106. lb_addr_store(p, x, value);
  1107. } else {
  1108. // by reference
  1109. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  1110. lb_add_entity(p->module, e, value);
  1111. }
  1112. }
  1113. gb_internal lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  1114. Entity *e = entity_of_node(stmt_val);
  1115. if (e == nullptr) {
  1116. return {};
  1117. }
  1118. if ((e->flags & EntityFlag_Value) == 0) {
  1119. if (LLVMIsALoadInst(value.value)) {
  1120. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  1121. lb_add_entity(p->module, e, ptr);
  1122. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  1123. return lb_addr(ptr);
  1124. }
  1125. }
  1126. // by value
  1127. lbAddr addr = lb_add_local(p, e->type, e, false);
  1128. lb_addr_store(p, addr, value);
  1129. return addr;
  1130. }
  1131. gb_internal void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  1132. ast_node(cc, CaseClause, clause);
  1133. lb_push_target_list(p, label, done, nullptr, nullptr);
  1134. lb_build_stmt_list(p, cc->stmts);
  1135. lb_close_scope(p, lbDeferExit_Default, body);
  1136. lb_pop_target_list(p);
  1137. lb_emit_jump(p, done);
  1138. }
  1139. gb_internal void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  1140. lbModule *m = p->module;
  1141. lb_open_scope(p, ss->scope);
  1142. ast_node(as, AssignStmt, ss->tag);
  1143. GB_ASSERT(as->lhs.count == 1);
  1144. GB_ASSERT(as->rhs.count == 1);
  1145. lbValue parent = lb_build_expr(p, as->rhs[0]);
  1146. bool is_parent_ptr = is_type_pointer(parent.type);
  1147. Type *parent_base_type = type_deref(parent.type);
  1148. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  1149. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  1150. lbValue parent_value = parent;
  1151. lbValue parent_ptr = parent;
  1152. if (!is_parent_ptr) {
  1153. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  1154. }
  1155. lbValue tag = {};
  1156. lbValue union_data = {};
  1157. if (switch_kind == TypeSwitch_Union) {
  1158. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  1159. Type *union_type = type_deref(parent_ptr.type);
  1160. if (is_type_union_maybe_pointer(union_type)) {
  1161. tag = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  1162. } else if (union_tag_size(union_type) == 0) {
  1163. tag = {}; // there is no tag for a zero sized union
  1164. } else {
  1165. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  1166. tag = lb_emit_load(p, tag_ptr);
  1167. }
  1168. } else if (switch_kind == TypeSwitch_Any) {
  1169. tag = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  1170. } else {
  1171. GB_PANIC("Unknown switch kind");
  1172. }
  1173. ast_node(body, BlockStmt, ss->body);
  1174. lbBlock *done = lb_create_block(p, "typeswitch.done");
  1175. lbBlock *else_block = done;
  1176. lbBlock *default_block = nullptr;
  1177. isize num_cases = 0;
  1178. for (Ast *clause : body->stmts) {
  1179. ast_node(cc, CaseClause, clause);
  1180. num_cases += cc->list.count;
  1181. if (cc->list.count == 0) {
  1182. GB_ASSERT(default_block == nullptr);
  1183. default_block = lb_create_block(p, "typeswitch.default.body");
  1184. else_block = default_block;
  1185. }
  1186. }
  1187. LLVMValueRef switch_instr = nullptr;
  1188. if (type_size_of(parent_base_type) == 0) {
  1189. GB_ASSERT(tag.value == nullptr);
  1190. switch_instr = LLVMBuildSwitch(p->builder, lb_const_bool(p->module, t_llvm_bool, false).value, else_block->block, cast(unsigned)num_cases);
  1191. } else {
  1192. GB_ASSERT(tag.value != nullptr);
  1193. switch_instr = LLVMBuildSwitch(p->builder, tag.value, else_block->block, cast(unsigned)num_cases);
  1194. }
  1195. bool all_by_reference = false;
  1196. for (Ast *clause : body->stmts) {
  1197. ast_node(cc, CaseClause, clause);
  1198. if (cc->list.count != 1) {
  1199. continue;
  1200. }
  1201. Entity *case_entity = implicit_entity_of_node(clause);
  1202. all_by_reference |= (case_entity->flags & EntityFlag_Value) == 0;
  1203. break;
  1204. }
  1205. // NOTE(bill, 2023-02-17): In the case of a pass by value, the value does need to be copied
  1206. // to prevent errors such as these:
  1207. //
  1208. // switch v in some_union {
  1209. // case i32:
  1210. // fmt.println(v) // 'i32'
  1211. // some_union = f32(123)
  1212. // fmt.println(v) // if `v` is an implicit reference, then the data is now completely corrupted
  1213. // case f32:
  1214. // fmt.println(v)
  1215. // }
  1216. //
  1217. lbAddr backing_data = {};
  1218. if (!all_by_reference) {
  1219. bool variants_found = false;
  1220. i64 max_size = 0;
  1221. i64 max_align = 1;
  1222. for (Ast *clause : body->stmts) {
  1223. ast_node(cc, CaseClause, clause);
  1224. if (cc->list.count != 1) {
  1225. continue;
  1226. }
  1227. Entity *case_entity = implicit_entity_of_node(clause);
  1228. if (!is_type_untyped_nil(case_entity->type)) {
  1229. max_size = gb_max(max_size, type_size_of(case_entity->type));
  1230. max_align = gb_max(max_align, type_align_of(case_entity->type));
  1231. variants_found = true;
  1232. }
  1233. }
  1234. if (variants_found) {
  1235. Type *t = alloc_type_array(t_u8, max_size);
  1236. backing_data = lb_add_local(p, t, nullptr, false, true);
  1237. GB_ASSERT(lb_try_update_alignment(backing_data.addr, cast(unsigned)max_align));
  1238. }
  1239. }
  1240. lbValue backing_ptr = backing_data.addr;
  1241. for (Ast *clause : body->stmts) {
  1242. ast_node(cc, CaseClause, clause);
  1243. lb_open_scope(p, cc->scope);
  1244. if (cc->list.count == 0) {
  1245. lb_start_block(p, default_block);
  1246. lb_store_type_case_implicit(p, clause, parent_value);
  1247. lb_type_case_body(p, ss->label, clause, p->curr_block, done);
  1248. continue;
  1249. }
  1250. lbBlock *body = lb_create_block(p, "typeswitch.body");
  1251. if (p->debug_info != nullptr) {
  1252. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, clause));
  1253. }
  1254. bool saw_nil = false;
  1255. for (Ast *type_expr : cc->list) {
  1256. Type *case_type = type_of_expr(type_expr);
  1257. lbValue on_val = {};
  1258. if (switch_kind == TypeSwitch_Union) {
  1259. Type *ut = base_type(type_deref(parent.type));
  1260. on_val = lb_const_union_tag(m, ut, case_type);
  1261. } else if (switch_kind == TypeSwitch_Any) {
  1262. if (is_type_untyped_nil(case_type)) {
  1263. saw_nil = true;
  1264. on_val = lb_const_nil(m, t_typeid);
  1265. } else {
  1266. on_val = lb_typeid(m, case_type);
  1267. }
  1268. }
  1269. GB_ASSERT(on_val.value != nullptr);
  1270. LLVMAddCase(switch_instr, on_val.value, body->block);
  1271. }
  1272. Entity *case_entity = implicit_entity_of_node(clause);
  1273. lb_start_block(p, body);
  1274. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  1275. if (cc->list.count == 1 && !saw_nil) {
  1276. lbValue data = {};
  1277. if (switch_kind == TypeSwitch_Union) {
  1278. data = union_data;
  1279. } else if (switch_kind == TypeSwitch_Any) {
  1280. data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  1281. }
  1282. Type *ct = case_entity->type;
  1283. Type *ct_ptr = alloc_type_pointer(ct);
  1284. lbValue ptr = {};
  1285. if (backing_data.addr.value) { // by value
  1286. GB_ASSERT(!by_reference);
  1287. // make a copy of the case value
  1288. lb_mem_copy_non_overlapping(p,
  1289. backing_ptr, // dst
  1290. data, // src
  1291. lb_const_int(p->module, t_int, type_size_of(case_entity->type)));
  1292. ptr = lb_emit_conv(p, backing_ptr, ct_ptr);
  1293. } else { // by reference
  1294. GB_ASSERT(by_reference);
  1295. ptr = lb_emit_conv(p, data, ct_ptr);
  1296. }
  1297. GB_ASSERT(are_types_identical(case_entity->type, type_deref(ptr.type)));
  1298. lb_add_entity(p->module, case_entity, ptr);
  1299. lb_add_debug_local_variable(p, ptr.value, case_entity->type, case_entity->token);
  1300. } else {
  1301. // TODO(bill): is the correct expected behaviour?
  1302. lb_store_type_case_implicit(p, clause, parent_value);
  1303. }
  1304. lb_type_case_body(p, ss->label, clause, body, done);
  1305. }
  1306. lb_emit_jump(p, done);
  1307. lb_start_block(p, done);
  1308. lb_close_scope(p, lbDeferExit_Default, done);
  1309. }
  1310. gb_internal void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  1311. for_array(i, vd->names) {
  1312. lbValue value = {};
  1313. if (vd->values.count > 0) {
  1314. GB_ASSERT(vd->names.count == vd->values.count);
  1315. Ast *ast_value = vd->values[i];
  1316. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  1317. ast_value->tav.mode == Addressing_Invalid);
  1318. bool allow_local = false;
  1319. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  1320. }
  1321. Ast *ident = vd->names[i];
  1322. GB_ASSERT(!is_blank_ident(ident));
  1323. Entity *e = entity_of_node(ident);
  1324. GB_ASSERT(e->flags & EntityFlag_Static);
  1325. String name = e->token.string;
  1326. String mangled_name = {};
  1327. {
  1328. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  1329. str = gb_string_appendc(str, "-");
  1330. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  1331. mangled_name.text = cast(u8 *)str;
  1332. mangled_name.len = gb_string_length(str);
  1333. }
  1334. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  1335. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  1336. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  1337. if (value.value != nullptr) {
  1338. LLVMSetInitializer(global, value.value);
  1339. } else {
  1340. }
  1341. if (e->Variable.thread_local_model != "") {
  1342. LLVMSetThreadLocal(global, true);
  1343. String m = e->Variable.thread_local_model;
  1344. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1345. if (m == "default") {
  1346. mode = LLVMGeneralDynamicTLSModel;
  1347. } else if (m == "localdynamic") {
  1348. mode = LLVMLocalDynamicTLSModel;
  1349. } else if (m == "initialexec") {
  1350. mode = LLVMInitialExecTLSModel;
  1351. } else if (m == "localexec") {
  1352. mode = LLVMLocalExecTLSModel;
  1353. } else {
  1354. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1355. }
  1356. LLVMSetThreadLocalMode(global, mode);
  1357. } else {
  1358. LLVMSetLinkage(global, LLVMInternalLinkage);
  1359. }
  1360. lbValue global_val = {global, alloc_type_pointer(e->type)};
  1361. lb_add_entity(p->module, e, global_val);
  1362. lb_add_member(p->module, mangled_name, global_val);
  1363. }
  1364. }
  1365. gb_internal isize lb_append_tuple_values(lbProcedure *p, Array<lbValue> *dst_values, lbValue src_value) {
  1366. isize init_count = dst_values->count;
  1367. Type *t = src_value.type;
  1368. if (t->kind == Type_Tuple) {
  1369. lbTupleFix *tf = map_get(&p->tuple_fix_map, src_value.value);
  1370. if (tf) {
  1371. for (lbValue const &value : tf->values) {
  1372. array_add(dst_values, value);
  1373. }
  1374. } else {
  1375. for_array(i, t->Tuple.variables) {
  1376. lbValue v = lb_emit_tuple_ev(p, src_value, cast(i32)i);
  1377. array_add(dst_values, v);
  1378. }
  1379. }
  1380. } else {
  1381. array_add(dst_values, src_value);
  1382. }
  1383. return dst_values->count - init_count;
  1384. }
  1385. gb_internal void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  1386. if (values.count == 0) {
  1387. return;
  1388. }
  1389. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  1390. for (Ast *rhs : values) {
  1391. lbValue init = lb_build_expr(p, rhs);
  1392. lb_append_tuple_values(p, &inits, init);
  1393. }
  1394. bool prev_in_assignment = p->in_multi_assignment;
  1395. isize lval_count = 0;
  1396. for (lbAddr const &lval : lvals) {
  1397. if (lval.addr.value != nullptr) {
  1398. // check if it is not a blank identifier
  1399. lval_count += 1;
  1400. }
  1401. }
  1402. p->in_multi_assignment = lval_count > 1;
  1403. GB_ASSERT(lvals.count == inits.count);
  1404. for_array(i, inits) {
  1405. lbAddr lval = lvals[i];
  1406. lbValue init = inits[i];
  1407. lb_addr_store(p, lval, init);
  1408. }
  1409. p->in_multi_assignment = prev_in_assignment;
  1410. }
  1411. gb_internal void lb_build_return_stmt_internal(lbProcedure *p, lbValue res) {
  1412. lbFunctionType *ft = lb_get_function_type(p->module, p->type);
  1413. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  1414. bool split_returns = ft->multiple_return_original_type != nullptr;
  1415. if (split_returns) {
  1416. GB_ASSERT(res.value == nullptr || !is_type_tuple(res.type));
  1417. }
  1418. if (return_by_pointer) {
  1419. if (res.value != nullptr) {
  1420. LLVMValueRef res_val = res.value;
  1421. i64 sz = type_size_of(res.type);
  1422. if (LLVMIsALoadInst(res_val) && sz > build_context.word_size) {
  1423. lbValue ptr = lb_address_from_load_or_generate_local(p, res);
  1424. lb_mem_copy_non_overlapping(p, p->return_ptr.addr, ptr, lb_const_int(p->module, t_int, sz));
  1425. } else {
  1426. LLVMBuildStore(p->builder, res_val, p->return_ptr.addr.value);
  1427. }
  1428. } else {
  1429. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  1430. }
  1431. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1432. LLVMBuildRetVoid(p->builder);
  1433. } else {
  1434. LLVMValueRef ret_val = res.value;
  1435. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  1436. if (p->abi_function_type->ret.cast_type != nullptr) {
  1437. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  1438. }
  1439. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1440. LLVMBuildRet(p->builder, ret_val);
  1441. }
  1442. }
  1443. gb_internal void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results) {
  1444. lb_ensure_abi_function_type(p->module, p);
  1445. lbValue res = {};
  1446. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  1447. isize return_count = p->type->Proc.result_count;
  1448. isize res_count = return_results.count;
  1449. lbFunctionType *ft = lb_get_function_type(p->module, p->type);
  1450. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  1451. if (return_count == 0) {
  1452. // No return values
  1453. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1454. LLVMBuildRetVoid(p->builder);
  1455. return;
  1456. } else if (return_count == 1) {
  1457. Entity *e = tuple->variables[0];
  1458. if (res_count == 0) {
  1459. lbValue found = map_must_get(&p->module->values, e);
  1460. res = lb_emit_load(p, found);
  1461. } else {
  1462. res = lb_build_expr(p, return_results[0]);
  1463. res = lb_emit_conv(p, res, e->type);
  1464. }
  1465. if (p->type->Proc.has_named_results) {
  1466. // NOTE(bill): store the named values before returning
  1467. if (e->token.string != "") {
  1468. lbValue found = map_must_get(&p->module->values, e);
  1469. lb_emit_store(p, found, lb_emit_conv(p, res, e->type));
  1470. }
  1471. }
  1472. } else {
  1473. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  1474. if (res_count != 0) {
  1475. for (isize res_index = 0; res_index < res_count; res_index++) {
  1476. lbValue res = lb_build_expr(p, return_results[res_index]);
  1477. lb_append_tuple_values(p, &results, res);
  1478. }
  1479. } else {
  1480. for (isize res_index = 0; res_index < return_count; res_index++) {
  1481. Entity *e = tuple->variables[res_index];
  1482. lbValue found = map_must_get(&p->module->values, e);
  1483. lbValue res = lb_emit_load(p, found);
  1484. array_add(&results, res);
  1485. }
  1486. }
  1487. GB_ASSERT(results.count == return_count);
  1488. if (p->type->Proc.has_named_results) {
  1489. auto named_results = slice_make<lbValue>(temporary_allocator(), results.count);
  1490. auto values = slice_make<lbValue>(temporary_allocator(), results.count);
  1491. // NOTE(bill): store the named values before returning
  1492. for_array(i, p->type->Proc.results->Tuple.variables) {
  1493. Entity *e = p->type->Proc.results->Tuple.variables[i];
  1494. if (e->kind != Entity_Variable) {
  1495. continue;
  1496. }
  1497. if (e->token.string == "") {
  1498. continue;
  1499. }
  1500. named_results[i] = map_must_get(&p->module->values, e);
  1501. values[i] = lb_emit_conv(p, results[i], e->type);
  1502. }
  1503. for_array(i, named_results) {
  1504. lb_emit_store(p, named_results[i], values[i]);
  1505. }
  1506. }
  1507. bool split_returns = ft->multiple_return_original_type != nullptr;
  1508. if (split_returns) {
  1509. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  1510. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count-1);
  1511. for_array(i, results) {
  1512. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  1513. }
  1514. isize param_offset = return_by_pointer ? 1 : 0;
  1515. param_offset += ft->original_arg_count;
  1516. for_array(i, result_eps) {
  1517. lbValue result_ep = {};
  1518. result_ep.value = LLVMGetParam(p->value, cast(unsigned)(param_offset+i));
  1519. result_ep.type = alloc_type_pointer(tuple->variables[i]->type);
  1520. result_eps[i] = result_ep;
  1521. }
  1522. for_array(i, result_eps) {
  1523. lb_emit_store(p, result_eps[i], result_values[i]);
  1524. }
  1525. if (return_by_pointer) {
  1526. GB_ASSERT(result_values.count-1 == result_eps.count);
  1527. lb_addr_store(p, p->return_ptr, result_values[result_values.count-1]);
  1528. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1529. LLVMBuildRetVoid(p->builder);
  1530. return;
  1531. } else {
  1532. return lb_build_return_stmt_internal(p, result_values[result_values.count-1]);
  1533. }
  1534. } else {
  1535. Type *ret_type = p->type->Proc.results;
  1536. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1537. if (return_by_pointer) {
  1538. res = p->return_ptr.addr;
  1539. } else {
  1540. res = lb_add_local_generated(p, ret_type, false).addr;
  1541. }
  1542. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  1543. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count);
  1544. for_array(i, results) {
  1545. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  1546. }
  1547. for_array(i, results) {
  1548. result_eps[i] = lb_emit_struct_ep(p, res, cast(i32)i);
  1549. }
  1550. for_array(i, result_eps) {
  1551. lb_emit_store(p, result_eps[i], result_values[i]);
  1552. }
  1553. if (return_by_pointer) {
  1554. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1555. LLVMBuildRetVoid(p->builder);
  1556. return;
  1557. }
  1558. res = lb_emit_load(p, res);
  1559. }
  1560. }
  1561. lb_build_return_stmt_internal(p, res);
  1562. }
  1563. gb_internal void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  1564. ast_node(is, IfStmt, node);
  1565. lb_open_scope(p, is->scope); // Scope #1
  1566. defer (lb_close_scope(p, lbDeferExit_Default, nullptr));
  1567. if (is->init != nullptr) {
  1568. // TODO(bill): Should this have a separate block to begin with?
  1569. #if 1
  1570. lbBlock *init = lb_create_block(p, "if.init");
  1571. lb_emit_jump(p, init);
  1572. lb_start_block(p, init);
  1573. #endif
  1574. lb_build_stmt(p, is->init);
  1575. }
  1576. lbBlock *then = lb_create_block(p, "if.then");
  1577. lbBlock *done = lb_create_block(p, "if.done");
  1578. lbBlock *else_ = done;
  1579. if (is->else_stmt != nullptr) {
  1580. else_ = lb_create_block(p, "if.else");
  1581. }
  1582. lbValue cond = lb_build_cond(p, is->cond, then, else_);
  1583. // Note `cond.value` only set for non-and/or conditions and const negs so that the `LLVMIsConstant()`
  1584. // and `LLVMConstIntGetZExtValue()` calls below will be valid and `LLVMInstructionEraseFromParent()`
  1585. // will target the correct (& only) branch statement
  1586. if (is->label != nullptr) {
  1587. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  1588. tl->is_block = true;
  1589. }
  1590. if (cond.value && LLVMIsConstant(cond.value)) {
  1591. // NOTE(bill): Do a compile time short circuit for when the condition is constantly known.
  1592. // This done manually rather than relying on the SSA passes because sometimes the SSA passes
  1593. // miss some even if they are constantly known, especially with few optimization passes.
  1594. bool const_cond = LLVMConstIntGetZExtValue(cond.value) != 0;
  1595. LLVMValueRef if_instr = LLVMGetLastInstruction(p->curr_block->block);
  1596. GB_ASSERT(LLVMGetInstructionOpcode(if_instr) == LLVMBr);
  1597. GB_ASSERT(LLVMIsConditional(if_instr));
  1598. LLVMInstructionEraseFromParent(if_instr);
  1599. if (const_cond) {
  1600. lb_emit_jump(p, then);
  1601. lb_start_block(p, then);
  1602. lb_build_stmt(p, is->body);
  1603. lb_emit_jump(p, done);
  1604. } else {
  1605. if (is->else_stmt != nullptr) {
  1606. lb_emit_jump(p, else_);
  1607. lb_start_block(p, else_);
  1608. lb_open_scope(p, scope_of_node(is->else_stmt));
  1609. lb_build_stmt(p, is->else_stmt);
  1610. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1611. }
  1612. lb_emit_jump(p, done);
  1613. }
  1614. } else {
  1615. lb_start_block(p, then);
  1616. lb_build_stmt(p, is->body);
  1617. lb_emit_jump(p, done);
  1618. if (is->else_stmt != nullptr) {
  1619. lb_start_block(p, else_);
  1620. lb_open_scope(p, scope_of_node(is->else_stmt));
  1621. lb_build_stmt(p, is->else_stmt);
  1622. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1623. lb_emit_jump(p, done);
  1624. }
  1625. }
  1626. if (is->label != nullptr) {
  1627. lb_pop_target_list(p);
  1628. }
  1629. lb_start_block(p, done);
  1630. }
  1631. gb_internal void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  1632. ast_node(fs, ForStmt, node);
  1633. lb_open_scope(p, fs->scope); // Open Scope here
  1634. if (p->debug_info != nullptr) {
  1635. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  1636. }
  1637. if (fs->init != nullptr) {
  1638. #if 1
  1639. lbBlock *init = lb_create_block(p, "for.init");
  1640. lb_emit_jump(p, init);
  1641. lb_start_block(p, init);
  1642. #endif
  1643. lb_build_stmt(p, fs->init);
  1644. }
  1645. lbBlock *body = lb_create_block(p, "for.body");
  1646. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  1647. lbBlock *loop = body;
  1648. if (fs->cond != nullptr) {
  1649. loop = lb_create_block(p, "for.loop");
  1650. }
  1651. lbBlock *post = loop;
  1652. if (fs->post != nullptr) {
  1653. post = lb_create_block(p, "for.post");
  1654. }
  1655. lb_emit_jump(p, loop);
  1656. lb_start_block(p, loop);
  1657. if (loop != body) {
  1658. // right now the condition (all expressions) will not set it's debug location, so we will do it here
  1659. if (p->debug_info != nullptr) {
  1660. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, fs->cond));
  1661. }
  1662. lb_build_cond(p, fs->cond, body, done);
  1663. lb_start_block(p, body);
  1664. }
  1665. lb_push_target_list(p, fs->label, done, post, nullptr);
  1666. lb_build_stmt(p, fs->body);
  1667. lb_pop_target_list(p);
  1668. if (p->debug_info != nullptr) {
  1669. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_end_location_from_ast(p, fs->body));
  1670. }
  1671. lb_emit_jump(p, post);
  1672. if (fs->post != nullptr) {
  1673. lb_start_block(p, post);
  1674. lb_build_stmt(p, fs->post);
  1675. lb_emit_jump(p, loop);
  1676. }
  1677. lb_start_block(p, done);
  1678. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1679. }
  1680. gb_internal void lb_build_assign_stmt_array(lbProcedure *p, TokenKind op, lbAddr const &lhs, lbValue const &value) {
  1681. GB_ASSERT(op != Token_Eq);
  1682. Type *lhs_type = lb_addr_type(lhs);
  1683. Type *array_type = base_type(lhs_type);
  1684. GB_ASSERT(is_type_array_like(array_type));
  1685. i64 count = get_array_type_count(array_type);
  1686. Type *elem_type = base_array_type(array_type);
  1687. lbValue rhs = lb_emit_conv(p, value, lhs_type);
  1688. bool inline_array_arith = lb_can_try_to_inline_array_arith(array_type);
  1689. if (lhs.kind == lbAddr_Swizzle) {
  1690. GB_ASSERT(is_type_array(lhs_type));
  1691. struct ValueAndIndex {
  1692. lbValue value;
  1693. u8 index;
  1694. };
  1695. bool indices_handled[4] = {};
  1696. i32 indices[4] = {};
  1697. i32 index_count = 0;
  1698. for (u8 i = 0; i < lhs.swizzle.count; i++) {
  1699. u8 index = lhs.swizzle.indices[i];
  1700. if (indices_handled[index]) {
  1701. continue;
  1702. }
  1703. indices[index_count++] = index;
  1704. }
  1705. lbValue lhs_ptrs[4] = {};
  1706. lbValue x_loads[4] = {};
  1707. lbValue y_loads[4] = {};
  1708. lbValue ops[4] = {};
  1709. for (i32 i = 0; i < index_count; i++) {
  1710. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  1711. }
  1712. for (i32 i = 0; i < index_count; i++) {
  1713. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1714. }
  1715. for (i32 i = 0; i < index_count; i++) {
  1716. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1717. y_loads[i].type = elem_type;
  1718. }
  1719. for (i32 i = 0; i < index_count; i++) {
  1720. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1721. }
  1722. for (i32 i = 0; i < index_count; i++) {
  1723. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1724. }
  1725. return;
  1726. } else if (lhs.kind == lbAddr_SwizzleLarge) {
  1727. GB_ASSERT(is_type_array(lhs_type));
  1728. struct ValueAndIndex {
  1729. lbValue value;
  1730. u32 index;
  1731. };
  1732. Type *bt = base_type(lhs_type);
  1733. GB_ASSERT(bt->kind == Type_Array);
  1734. auto indices_handled = slice_make<bool>(temporary_allocator(), bt->Array.count);
  1735. auto indices = slice_make<i32>(temporary_allocator(), bt->Array.count);
  1736. i32 index_count = 0;
  1737. for (i32 index : lhs.swizzle_large.indices) {
  1738. if (indices_handled[index]) {
  1739. continue;
  1740. }
  1741. indices[index_count++] = index;
  1742. }
  1743. lbValue lhs_ptrs[4] = {};
  1744. lbValue x_loads[4] = {};
  1745. lbValue y_loads[4] = {};
  1746. lbValue ops[4] = {};
  1747. for (i32 i = 0; i < index_count; i++) {
  1748. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  1749. }
  1750. for (i32 i = 0; i < index_count; i++) {
  1751. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1752. }
  1753. for (i32 i = 0; i < index_count; i++) {
  1754. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1755. y_loads[i].type = elem_type;
  1756. }
  1757. for (i32 i = 0; i < index_count; i++) {
  1758. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1759. }
  1760. for (i32 i = 0; i < index_count; i++) {
  1761. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1762. }
  1763. return;
  1764. }
  1765. lbValue x = lb_addr_get_ptr(p, lhs);
  1766. if (inline_array_arith) {
  1767. unsigned n = cast(unsigned)count;
  1768. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  1769. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  1770. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  1771. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  1772. for (unsigned i = 0; i < n; i++) {
  1773. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  1774. }
  1775. for (unsigned i = 0; i < n; i++) {
  1776. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1777. }
  1778. for (unsigned i = 0; i < n; i++) {
  1779. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1780. y_loads[i].type = elem_type;
  1781. }
  1782. for (unsigned i = 0; i < n; i++) {
  1783. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1784. }
  1785. for (unsigned i = 0; i < n; i++) {
  1786. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1787. }
  1788. } else {
  1789. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  1790. auto loop_data = lb_loop_start(p, cast(isize)count, t_i32);
  1791. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  1792. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  1793. lbValue a = lb_emit_load(p, a_ptr);
  1794. lbValue b = lb_emit_load(p, b_ptr);
  1795. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  1796. lb_emit_store(p, a_ptr, c);
  1797. lb_loop_end(p, loop_data);
  1798. }
  1799. }
  1800. gb_internal void lb_build_assign_stmt(lbProcedure *p, AstAssignStmt *as) {
  1801. if (as->op.kind == Token_Eq) {
  1802. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  1803. for (Ast *lhs : as->lhs) {
  1804. lbAddr lval = {};
  1805. if (!is_blank_ident(lhs)) {
  1806. lval = lb_build_addr(p, lhs);
  1807. }
  1808. array_add(&lvals, lval);
  1809. }
  1810. lb_build_assignment(p, lvals, as->rhs);
  1811. return;
  1812. }
  1813. GB_ASSERT(as->lhs.count == 1);
  1814. GB_ASSERT(as->rhs.count == 1);
  1815. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  1816. // +=, -=, etc
  1817. i32 op_ = cast(i32)as->op.kind;
  1818. op_ += Token_Add - Token_AddEq; // Convert += to +
  1819. TokenKind op = cast(TokenKind)op_;
  1820. if (op == Token_CmpAnd || op == Token_CmpOr) {
  1821. Type *type = as->lhs[0]->tav.type;
  1822. lbValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type);
  1823. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  1824. lb_addr_store(p, lhs, new_value);
  1825. } else {
  1826. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  1827. lbValue value = lb_build_expr(p, as->rhs[0]);
  1828. Type *lhs_type = lb_addr_type(lhs);
  1829. // NOTE(bill): Allow for the weird edge case of:
  1830. // array *= matrix
  1831. if (op == Token_Mul && is_type_matrix(value.type) && is_type_array(lhs_type)) {
  1832. lbValue old_value = lb_addr_load(p, lhs);
  1833. Type *type = old_value.type;
  1834. lbValue new_value = lb_emit_vector_mul_matrix(p, old_value, value, type);
  1835. lb_addr_store(p, lhs, new_value);
  1836. return;
  1837. }
  1838. if (is_type_array(lhs_type)) {
  1839. lb_build_assign_stmt_array(p, op, lhs, value);
  1840. return;
  1841. } else {
  1842. lbValue old_value = lb_addr_load(p, lhs);
  1843. Type *type = old_value.type;
  1844. lbValue change = lb_emit_conv(p, value, type);
  1845. lbValue new_value = lb_emit_arith(p, op, old_value, change, type);
  1846. lb_addr_store(p, lhs, new_value);
  1847. }
  1848. }
  1849. }
  1850. gb_internal void lb_build_stmt(lbProcedure *p, Ast *node) {
  1851. Ast *prev_stmt = p->curr_stmt;
  1852. defer (p->curr_stmt = prev_stmt);
  1853. p->curr_stmt = node;
  1854. if (p->curr_block != nullptr) {
  1855. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1856. if (lb_is_instr_terminating(last_instr)) {
  1857. return;
  1858. }
  1859. }
  1860. if (p->debug_info != nullptr) {
  1861. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  1862. }
  1863. u16 prev_state_flags = p->state_flags;
  1864. defer (p->state_flags = prev_state_flags);
  1865. if (node->state_flags != 0) {
  1866. u16 in = node->state_flags;
  1867. u16 out = p->state_flags;
  1868. if (in & StateFlag_bounds_check) {
  1869. out |= StateFlag_bounds_check;
  1870. out &= ~StateFlag_no_bounds_check;
  1871. } else if (in & StateFlag_no_bounds_check) {
  1872. out |= StateFlag_no_bounds_check;
  1873. out &= ~StateFlag_bounds_check;
  1874. }
  1875. if (in & StateFlag_no_type_assert) {
  1876. out |= StateFlag_no_type_assert;
  1877. out &= ~StateFlag_type_assert;
  1878. } else if (in & StateFlag_type_assert) {
  1879. out |= StateFlag_type_assert;
  1880. out &= ~StateFlag_no_type_assert;
  1881. }
  1882. p->state_flags = out;
  1883. }
  1884. switch (node->kind) {
  1885. case_ast_node(bs, EmptyStmt, node);
  1886. case_end;
  1887. case_ast_node(us, UsingStmt, node);
  1888. case_end;
  1889. case_ast_node(ws, WhenStmt, node);
  1890. lb_build_when_stmt(p, ws);
  1891. case_end;
  1892. case_ast_node(bs, BlockStmt, node);
  1893. lbBlock *done = nullptr;
  1894. if (bs->label != nullptr) {
  1895. done = lb_create_block(p, "block.done");
  1896. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  1897. tl->is_block = true;
  1898. }
  1899. lb_open_scope(p, bs->scope);
  1900. lb_build_stmt_list(p, bs->stmts);
  1901. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1902. if (done != nullptr) {
  1903. lb_emit_jump(p, done);
  1904. lb_start_block(p, done);
  1905. }
  1906. if (bs->label != nullptr) {
  1907. lb_pop_target_list(p);
  1908. }
  1909. case_end;
  1910. case_ast_node(vd, ValueDecl, node);
  1911. if (!vd->is_mutable) {
  1912. return;
  1913. }
  1914. bool is_static = false;
  1915. if (vd->names.count > 0) {
  1916. for (Ast *name : vd->names) {
  1917. if (!is_blank_ident(name)) {
  1918. GB_ASSERT(name->kind == Ast_Ident);
  1919. Entity *e = entity_of_node(name);
  1920. TokenPos pos = ast_token(name).pos;
  1921. GB_ASSERT_MSG(e != nullptr, "\n%s missing entity for %.*s", token_pos_to_string(pos), LIT(name->Ident.token.string));
  1922. if (e->flags & EntityFlag_Static) {
  1923. // NOTE(bill): If one of the entities is static, they all are
  1924. is_static = true;
  1925. break;
  1926. }
  1927. }
  1928. }
  1929. }
  1930. if (is_static) {
  1931. lb_build_static_variables(p, vd);
  1932. return;
  1933. }
  1934. TEMPORARY_ALLOCATOR_GUARD();
  1935. auto const &values = vd->values;
  1936. if (values.count == 0) {
  1937. auto lvals = slice_make<lbAddr>(temporary_allocator(), vd->names.count);
  1938. for_array(i, vd->names) {
  1939. Ast *name = vd->names[i];
  1940. if (!is_blank_ident(name)) {
  1941. Entity *e = entity_of_node(name);
  1942. // bool zero_init = true; // Always do it
  1943. bool zero_init = values.count == 0;
  1944. lvals[i] = lb_add_local(p, e->type, e, zero_init);
  1945. }
  1946. }
  1947. } else {
  1948. auto lvals_preused = slice_make<bool>(temporary_allocator(), vd->names.count);
  1949. auto lvals = slice_make<lbAddr>(temporary_allocator(), vd->names.count);
  1950. auto inits = array_make<lbValue>(temporary_allocator(), 0, lvals.count);
  1951. isize lval_index = 0;
  1952. for (Ast *rhs : values) {
  1953. rhs = unparen_expr(rhs);
  1954. lbValue init = lb_build_expr(p, rhs);
  1955. if (rhs->kind == Ast_CompoundLit) {
  1956. // NOTE(bill, 2023-02-17): lb_const_value might produce a stack local variable for the
  1957. // compound literal, so reusing that variable should minimize the stack wastage
  1958. lbAddr *comp_lit_addr = map_get(&p->module->exact_value_compound_literal_addr_map, rhs);
  1959. if (comp_lit_addr) {
  1960. if (Entity *e = entity_of_node(vd->names[lval_index])) {
  1961. lbValue val = comp_lit_addr->addr;
  1962. lb_add_entity(p->module, e, val);
  1963. lb_add_debug_local_variable(p, val.value, e->type, e->token);
  1964. lvals_preused[lval_index] = true;
  1965. }
  1966. }
  1967. }
  1968. lval_index += lb_append_tuple_values(p, &inits, init);
  1969. }
  1970. GB_ASSERT(lval_index == lvals.count);
  1971. for_array(i, vd->names) {
  1972. Ast *name = vd->names[i];
  1973. if (!is_blank_ident(name) && !lvals_preused[i]) {
  1974. Entity *e = entity_of_node(name);
  1975. bool zero_init = values.count == 0;
  1976. lvals[i] = lb_add_local(p, e->type, e, zero_init);
  1977. }
  1978. }
  1979. GB_ASSERT(lvals.count == inits.count);
  1980. for_array(i, inits) {
  1981. lbAddr lval = lvals[i];
  1982. lbValue init = inits[i];
  1983. lb_addr_store(p, lval, init);
  1984. }
  1985. }
  1986. case_end;
  1987. case_ast_node(as, AssignStmt, node);
  1988. lb_build_assign_stmt(p, as);
  1989. case_end;
  1990. case_ast_node(es, ExprStmt, node);
  1991. lb_build_expr(p, es->expr);
  1992. case_end;
  1993. case_ast_node(ds, DeferStmt, node);
  1994. lb_add_defer_node(p, p->scope_index, ds->stmt);
  1995. case_end;
  1996. case_ast_node(rs, ReturnStmt, node);
  1997. lb_build_return_stmt(p, rs->results);
  1998. case_end;
  1999. case_ast_node(is, IfStmt, node);
  2000. lb_build_if_stmt(p, node);
  2001. case_end;
  2002. case_ast_node(fs, ForStmt, node);
  2003. lb_build_for_stmt(p, node);
  2004. case_end;
  2005. case_ast_node(rs, RangeStmt, node);
  2006. lb_build_range_stmt(p, rs, rs->scope);
  2007. case_end;
  2008. case_ast_node(rs, UnrollRangeStmt, node);
  2009. lb_build_unroll_range_stmt(p, rs, rs->scope);
  2010. case_end;
  2011. case_ast_node(ss, SwitchStmt, node);
  2012. lb_build_switch_stmt(p, ss, ss->scope);
  2013. case_end;
  2014. case_ast_node(ss, TypeSwitchStmt, node);
  2015. lb_build_type_switch_stmt(p, ss);
  2016. case_end;
  2017. case_ast_node(bs, BranchStmt, node);
  2018. lbBlock *block = nullptr;
  2019. if (bs->label != nullptr) {
  2020. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  2021. switch (bs->token.kind) {
  2022. case Token_break: block = bb.break_; break;
  2023. case Token_continue: block = bb.continue_; break;
  2024. case Token_fallthrough:
  2025. GB_PANIC("fallthrough cannot have a label");
  2026. break;
  2027. }
  2028. } else {
  2029. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2030. if (t->is_block) {
  2031. continue;
  2032. }
  2033. switch (bs->token.kind) {
  2034. case Token_break: block = t->break_; break;
  2035. case Token_continue: block = t->continue_; break;
  2036. case Token_fallthrough: block = t->fallthrough_; break;
  2037. }
  2038. }
  2039. }
  2040. if (block != nullptr) {
  2041. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2042. }
  2043. lb_emit_jump(p, block);
  2044. lb_start_block(p, lb_create_block(p, "unreachable"));
  2045. case_end;
  2046. }
  2047. }
  2048. gb_internal void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  2049. if (p->curr_block == nullptr) {
  2050. return;
  2051. }
  2052. // NOTE(bill): The prev block may defer injection before it's terminator
  2053. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2054. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  2055. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  2056. return;
  2057. }
  2058. isize prev_context_stack_count = p->context_stack.count;
  2059. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  2060. defer (p->context_stack.count = prev_context_stack_count);
  2061. p->context_stack.count = d.context_stack_count;
  2062. lbBlock *b = lb_create_block(p, "defer");
  2063. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  2064. lb_emit_jump(p, b);
  2065. }
  2066. lb_start_block(p, b);
  2067. if (d.kind == lbDefer_Node) {
  2068. lb_build_stmt(p, d.stmt);
  2069. } else if (d.kind == lbDefer_Proc) {
  2070. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  2071. }
  2072. }
  2073. gb_internal void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  2074. isize count = p->defer_stmts.count;
  2075. isize i = count;
  2076. while (i --> 0) {
  2077. lbDefer const &d = p->defer_stmts[i];
  2078. if (kind == lbDeferExit_Default) {
  2079. if (p->scope_index == d.scope_index &&
  2080. d.scope_index > 0) {
  2081. lb_build_defer_stmt(p, d);
  2082. array_pop(&p->defer_stmts);
  2083. continue;
  2084. } else {
  2085. break;
  2086. }
  2087. } else if (kind == lbDeferExit_Return) {
  2088. lb_build_defer_stmt(p, d);
  2089. } else if (kind == lbDeferExit_Branch) {
  2090. GB_ASSERT(block != nullptr);
  2091. isize lower_limit = block->scope_index;
  2092. if (lower_limit < d.scope_index) {
  2093. lb_build_defer_stmt(p, d);
  2094. }
  2095. }
  2096. }
  2097. }
  2098. gb_internal void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  2099. Type *pt = base_type(p->type);
  2100. GB_ASSERT(pt->kind == Type_Proc);
  2101. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2102. GB_ASSERT(p->context_stack.count != 0);
  2103. }
  2104. lbDefer *d = array_add_and_get(&p->defer_stmts);
  2105. d->kind = lbDefer_Node;
  2106. d->scope_index = scope_index;
  2107. d->context_stack_count = p->context_stack.count;
  2108. d->block = p->curr_block;
  2109. d->stmt = stmt;
  2110. }
  2111. gb_internal void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  2112. Type *pt = base_type(p->type);
  2113. GB_ASSERT(pt->kind == Type_Proc);
  2114. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2115. GB_ASSERT(p->context_stack.count != 0);
  2116. }
  2117. lbDefer *d = array_add_and_get(&p->defer_stmts);
  2118. d->kind = lbDefer_Proc;
  2119. d->scope_index = p->scope_index;
  2120. d->block = p->curr_block;
  2121. d->context_stack_count = p->context_stack.count;
  2122. d->proc.deferred = deferred;
  2123. d->proc.result_as_args = result_as_args;
  2124. }