llvm_backend_stmt.cpp 67 KB

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