llvm_backend_stmt.cpp 68 KB

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