llvm_backend_stmt.cpp 63 KB

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