llvm_backend_general.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  1. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token);
  2. gb_global Entity *lb_global_type_info_data_entity = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. void lb_init_module(lbModule *m, Checker *c) {
  15. m->info = &c->info;
  16. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  17. if (m->pkg) {
  18. module_name = gb_string_appendc(module_name, "-");
  19. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  20. } else if (USE_SEPARATE_MODULES) {
  21. module_name = gb_string_appendc(module_name, "-builtin");
  22. }
  23. m->ctx = LLVMContextCreate();
  24. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  25. // m->debug_builder = nullptr;
  26. if (build_context.ODIN_DEBUG) {
  27. enum {DEBUG_METADATA_VERSION = 3};
  28. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  29. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  30. switch (build_context.metrics.os) {
  31. case TargetOs_windows:
  32. LLVMAddModuleFlag(m->mod,
  33. LLVMModuleFlagBehaviorWarning,
  34. "CodeView", 8,
  35. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  36. break;
  37. case TargetOs_darwin:
  38. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  39. LLVMAddModuleFlag(m->mod,
  40. LLVMModuleFlagBehaviorWarning,
  41. "Dwarf Version", 13,
  42. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  43. break;
  44. }
  45. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  46. }
  47. gbAllocator a = heap_allocator();
  48. map_init(&m->types, a);
  49. map_init(&m->struct_field_remapping, a);
  50. map_init(&m->values, a);
  51. map_init(&m->soa_values, a);
  52. string_map_init(&m->members, a);
  53. map_init(&m->procedure_values, a);
  54. string_map_init(&m->procedures, a);
  55. string_map_init(&m->const_strings, a);
  56. map_init(&m->function_type_map, a);
  57. map_init(&m->equal_procs, a);
  58. map_init(&m->hasher_procs, a);
  59. array_init(&m->procedures_to_generate, a, 0, 1024);
  60. array_init(&m->foreign_library_paths, a, 0, 1024);
  61. array_init(&m->missing_procedures_to_check, a, 0, 16);
  62. map_init(&m->debug_values, a);
  63. array_init(&m->debug_incomplete_types, a, 0, 1024);
  64. }
  65. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  66. if (global_error_collector.count != 0) {
  67. return false;
  68. }
  69. isize tc = c->parser->total_token_count;
  70. if (tc < 2) {
  71. return false;
  72. }
  73. String init_fullpath = c->parser->init_fullpath;
  74. if (build_context.out_filepath.len == 0) {
  75. gen->output_name = remove_directory_from_path(init_fullpath);
  76. gen->output_name = remove_extension_from_path(gen->output_name);
  77. gen->output_name = string_trim_whitespace(gen->output_name);
  78. if (gen->output_name.len == 0) {
  79. gen->output_name = c->info.init_scope->pkg->name;
  80. }
  81. gen->output_base = gen->output_name;
  82. } else {
  83. gen->output_name = build_context.out_filepath;
  84. gen->output_name = string_trim_whitespace(gen->output_name);
  85. if (gen->output_name.len == 0) {
  86. gen->output_name = c->info.init_scope->pkg->name;
  87. }
  88. isize pos = string_extension_position(gen->output_name);
  89. if (pos < 0) {
  90. gen->output_base = gen->output_name;
  91. } else {
  92. gen->output_base = substring(gen->output_name, 0, pos);
  93. }
  94. }
  95. gbAllocator ha = heap_allocator();
  96. array_init(&gen->output_object_paths, ha);
  97. array_init(&gen->output_temp_paths, ha);
  98. gen->output_base = path_to_full_path(ha, gen->output_base);
  99. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  100. output_file_path = gb_string_appendc(output_file_path, ".obj");
  101. defer (gb_string_free(output_file_path));
  102. gen->info = &c->info;
  103. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  104. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  105. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  106. if (USE_SEPARATE_MODULES) {
  107. for_array(i, gen->info->packages.entries) {
  108. AstPackage *pkg = gen->info->packages.entries[i].value;
  109. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  110. m->pkg = pkg;
  111. m->gen = gen;
  112. map_set(&gen->modules, pkg, m);
  113. lb_init_module(m, c);
  114. }
  115. }
  116. gen->default_module.gen = gen;
  117. map_set(&gen->modules, cast(AstPackage *)nullptr, &gen->default_module);
  118. lb_init_module(&gen->default_module, c);
  119. for_array(i, gen->modules.entries) {
  120. lbModule *m = gen->modules.entries[i].value;
  121. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  122. map_set(&gen->modules_through_ctx, ctx, m);
  123. }
  124. return true;
  125. }
  126. lbValue lb_global_type_info_data_ptr(lbModule *m) {
  127. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  128. return v;
  129. }
  130. struct lbLoopData {
  131. lbAddr idx_addr;
  132. lbValue idx;
  133. lbBlock *body;
  134. lbBlock *done;
  135. lbBlock *loop;
  136. };
  137. struct lbCompoundLitElemTempData {
  138. Ast * expr;
  139. lbValue value;
  140. i32 elem_index;
  141. lbValue gep;
  142. };
  143. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32) {
  144. lbLoopData data = {};
  145. lbValue max = lb_const_int(p->module, t_int, count);
  146. data.idx_addr = lb_add_local_generated(p, index_type, true);
  147. data.body = lb_create_block(p, "loop.body");
  148. data.done = lb_create_block(p, "loop.done");
  149. data.loop = lb_create_block(p, "loop.loop");
  150. lb_emit_jump(p, data.loop);
  151. lb_start_block(p, data.loop);
  152. data.idx = lb_addr_load(p, data.idx_addr);
  153. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  154. lb_emit_if(p, cond, data.body, data.done);
  155. lb_start_block(p, data.body);
  156. return data;
  157. }
  158. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  159. if (data.idx_addr.addr.value != nullptr) {
  160. lb_emit_increment(p, data.idx_addr.addr);
  161. lb_emit_jump(p, data.loop);
  162. lb_start_block(p, data.done);
  163. }
  164. }
  165. LLVMValueRef llvm_zero(lbModule *m) {
  166. return LLVMConstInt(lb_type(m, t_int), 0, false);
  167. }
  168. LLVMValueRef llvm_zero32(lbModule *m) {
  169. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  170. }
  171. LLVMValueRef llvm_one(lbModule *m) {
  172. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  173. }
  174. lbValue lb_zero(lbModule *m, Type *t) {
  175. lbValue v = {};
  176. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  177. v.type = t;
  178. return v;
  179. }
  180. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  181. lbValue v = lb_find_or_add_entity_string(m, str);
  182. unsigned indices[1] = {0};
  183. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  184. }
  185. bool lb_is_instr_terminating(LLVMValueRef instr) {
  186. if (instr != nullptr) {
  187. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  188. switch (op) {
  189. case LLVMRet:
  190. case LLVMBr:
  191. case LLVMSwitch:
  192. case LLVMIndirectBr:
  193. case LLVMInvoke:
  194. case LLVMUnreachable:
  195. case LLVMCallBr:
  196. return true;
  197. }
  198. }
  199. return false;
  200. }
  201. lbModule *lb_pkg_module(lbGenerator *gen, AstPackage *pkg) {
  202. auto *found = map_get(&gen->modules, pkg);
  203. if (found) {
  204. return *found;
  205. }
  206. return &gen->default_module;
  207. }
  208. lbAddr lb_addr(lbValue addr) {
  209. lbAddr v = {lbAddr_Default, addr};
  210. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  211. GB_ASSERT(is_type_pointer(addr.type));
  212. v.kind = lbAddr_RelativePointer;
  213. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  214. GB_ASSERT(is_type_pointer(addr.type));
  215. v.kind = lbAddr_RelativeSlice;
  216. }
  217. return v;
  218. }
  219. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  220. lbAddr v = {lbAddr_Map, addr};
  221. v.map.key = map_key;
  222. v.map.type = map_type;
  223. v.map.result = map_result;
  224. return v;
  225. }
  226. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  227. lbAddr v = {lbAddr_SoaVariable, addr};
  228. v.soa.index = index;
  229. v.soa.index_expr = index_expr;
  230. return v;
  231. }
  232. lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  233. GB_ASSERT(is_type_array(array_type));
  234. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  235. lbAddr v = {lbAddr_Swizzle, addr};
  236. v.swizzle.type = array_type;
  237. v.swizzle.count = swizzle_count;
  238. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  239. return v;
  240. }
  241. lbAddr lb_addr_swizzle_large(lbValue addr, Type *array_type, Slice<i32> const &swizzle_indices) {
  242. GB_ASSERT_MSG(is_type_array(array_type), "%s", type_to_string(array_type));
  243. lbAddr v = {lbAddr_SwizzleLarge, addr};
  244. v.swizzle_large.type = array_type;
  245. v.swizzle_large.indices = swizzle_indices;
  246. return v;
  247. }
  248. Type *lb_addr_type(lbAddr const &addr) {
  249. if (addr.addr.value == nullptr) {
  250. return nullptr;
  251. }
  252. if (addr.kind == lbAddr_Map) {
  253. Type *t = base_type(addr.map.type);
  254. GB_ASSERT(is_type_map(t));
  255. return t->Map.value;
  256. }
  257. if (addr.kind == lbAddr_Swizzle) {
  258. return addr.swizzle.type;
  259. }
  260. if (addr.kind == lbAddr_SwizzleLarge) {
  261. return addr.swizzle_large.type;
  262. }
  263. return type_deref(addr.addr.type);
  264. }
  265. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  266. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  267. }
  268. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  269. if (addr.addr.value == nullptr) {
  270. GB_PANIC("Illegal addr -> nullptr");
  271. return {};
  272. }
  273. switch (addr.kind) {
  274. case lbAddr_Map: {
  275. Type *map_type = base_type(addr.map.type);
  276. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  277. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  278. auto args = array_make<lbValue>(permanent_allocator(), 2);
  279. args[0] = h;
  280. args[1] = key;
  281. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  282. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  283. }
  284. case lbAddr_RelativePointer: {
  285. Type *rel_ptr = base_type(lb_addr_type(addr));
  286. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  287. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  288. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  289. offset = lb_emit_load(p, offset);
  290. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  291. offset = lb_emit_conv(p, offset, t_i64);
  292. }
  293. offset = lb_emit_conv(p, offset, t_uintptr);
  294. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  295. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  296. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  297. // NOTE(bill): nil check
  298. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  299. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  300. return final_ptr;
  301. }
  302. case lbAddr_SoaVariable:
  303. // TODO(bill): FIX THIS HACK
  304. return lb_address_from_load(p, lb_addr_load(p, addr));
  305. case lbAddr_Context:
  306. GB_PANIC("lbAddr_Context should be handled elsewhere");
  307. break;
  308. case lbAddr_Swizzle:
  309. case lbAddr_SwizzleLarge:
  310. // TOOD(bill): is this good enough logic?
  311. break;
  312. }
  313. return addr.addr;
  314. }
  315. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  316. lbAddr addr = lb_build_addr(p, expr);
  317. return lb_addr_get_ptr(p, addr);
  318. }
  319. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  320. if (build_context.no_bounds_check) {
  321. return;
  322. }
  323. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  324. return;
  325. }
  326. index = lb_emit_conv(p, index, t_int);
  327. len = lb_emit_conv(p, len, t_int);
  328. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  329. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  330. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  331. auto args = array_make<lbValue>(permanent_allocator(), 5);
  332. args[0] = file;
  333. args[1] = line;
  334. args[2] = column;
  335. args[3] = index;
  336. args[4] = len;
  337. lb_emit_runtime_call(p, "bounds_check_error", args);
  338. }
  339. void lb_emit_matrix_bounds_check(lbProcedure *p, Token token, lbValue row_index, lbValue column_index, lbValue row_count, lbValue column_count) {
  340. if (build_context.no_bounds_check) {
  341. return;
  342. }
  343. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  344. return;
  345. }
  346. row_index = lb_emit_conv(p, row_index, t_int);
  347. column_index = lb_emit_conv(p, column_index, t_int);
  348. row_count = lb_emit_conv(p, row_count, t_int);
  349. column_count = lb_emit_conv(p, column_count, t_int);
  350. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  351. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  352. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  353. auto args = array_make<lbValue>(permanent_allocator(), 7);
  354. args[0] = file;
  355. args[1] = line;
  356. args[2] = column;
  357. args[3] = row_index;
  358. args[4] = column_index;
  359. args[5] = row_count;
  360. args[6] = column_count;
  361. lb_emit_runtime_call(p, "matrix_bounds_check_error", args);
  362. }
  363. void lb_emit_multi_pointer_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high) {
  364. if (build_context.no_bounds_check) {
  365. return;
  366. }
  367. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  368. return;
  369. }
  370. low = lb_emit_conv(p, low, t_int);
  371. high = lb_emit_conv(p, high, t_int);
  372. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  373. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  374. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  375. auto args = array_make<lbValue>(permanent_allocator(), 5);
  376. args[0] = file;
  377. args[1] = line;
  378. args[2] = column;
  379. args[3] = low;
  380. args[4] = high;
  381. lb_emit_runtime_call(p, "multi_pointer_slice_expr_error", args);
  382. }
  383. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  384. if (build_context.no_bounds_check) {
  385. return;
  386. }
  387. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  388. return;
  389. }
  390. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  391. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  392. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  393. high = lb_emit_conv(p, high, t_int);
  394. if (!lower_value_used) {
  395. auto args = array_make<lbValue>(permanent_allocator(), 5);
  396. args[0] = file;
  397. args[1] = line;
  398. args[2] = column;
  399. args[3] = high;
  400. args[4] = len;
  401. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  402. } else {
  403. // No need to convert unless used
  404. low = lb_emit_conv(p, low, t_int);
  405. auto args = array_make<lbValue>(permanent_allocator(), 6);
  406. args[0] = file;
  407. args[1] = line;
  408. args[2] = column;
  409. args[3] = low;
  410. args[4] = high;
  411. args[5] = len;
  412. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  413. }
  414. }
  415. bool lb_try_update_alignment(LLVMValueRef addr_ptr, unsigned alignment) {
  416. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  417. if (LLVMGetAlignment(addr_ptr) < alignment) {
  418. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  419. LLVMSetAlignment(addr_ptr, alignment);
  420. }
  421. }
  422. return LLVMGetAlignment(addr_ptr) >= alignment;
  423. }
  424. return false;
  425. }
  426. bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  427. return lb_try_update_alignment(ptr.value, alignment);
  428. }
  429. bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  430. Type *array_type = base_type(type_deref(ptr.type));
  431. GB_ASSERT(is_type_array_like(array_type));
  432. i64 count = get_array_type_count(array_type);
  433. Type *elem_type = base_array_type(array_type);
  434. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  435. if (type_size_of(array_type) <= build_context.max_align &&
  436. is_type_valid_vector_elem(elem_type)) {
  437. // Try to treat it like a vector if possible
  438. bool possible = false;
  439. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  440. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  441. LLVMValueRef addr_ptr = ptr.value;
  442. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  443. unsigned alignment = LLVMGetAlignment(addr_ptr);
  444. alignment = gb_max(alignment, vector_alignment);
  445. possible = true;
  446. LLVMSetAlignment(addr_ptr, alignment);
  447. } else if (LLVMIsALoadInst(addr_ptr)) {
  448. unsigned alignment = LLVMGetAlignment(addr_ptr);
  449. possible = alignment >= vector_alignment;
  450. }
  451. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  452. // then it cannot be treated as a vector
  453. if (possible) {
  454. if (vector_type_) *vector_type_ =vector_type;
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  461. if (addr.addr.value == nullptr) {
  462. return;
  463. }
  464. GB_ASSERT(value.type != nullptr);
  465. if (is_type_untyped_undef(value.type)) {
  466. Type *t = lb_addr_type(addr);
  467. value.type = t;
  468. value.value = LLVMGetUndef(lb_type(p->module, t));
  469. } else if (is_type_untyped_nil(value.type)) {
  470. Type *t = lb_addr_type(addr);
  471. value.type = t;
  472. value.value = LLVMConstNull(lb_type(p->module, t));
  473. }
  474. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  475. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  476. }
  477. if (addr.kind == lbAddr_RelativePointer) {
  478. Type *rel_ptr = base_type(lb_addr_type(addr));
  479. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  480. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  481. GB_ASSERT(is_type_pointer(addr.addr.type));
  482. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  483. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  484. lbValue offset = {};
  485. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  486. offset.type = t_uintptr;
  487. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  488. offset = lb_emit_conv(p, offset, t_i64);
  489. }
  490. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  491. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  492. offset = lb_emit_select(p,
  493. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  494. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  495. offset
  496. );
  497. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  498. return;
  499. } else if (addr.kind == lbAddr_RelativeSlice) {
  500. Type *rel_ptr = base_type(lb_addr_type(addr));
  501. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  502. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  503. GB_ASSERT(is_type_pointer(addr.addr.type));
  504. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  505. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  506. lbValue offset = {};
  507. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  508. offset.type = t_uintptr;
  509. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  510. offset = lb_emit_conv(p, offset, t_i64);
  511. }
  512. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  513. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  514. offset = lb_emit_select(p,
  515. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  516. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  517. offset
  518. );
  519. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  520. lbValue len = lb_slice_len(p, value);
  521. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  522. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  523. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  524. return;
  525. } else if (addr.kind == lbAddr_Map) {
  526. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  527. return;
  528. } else if (addr.kind == lbAddr_Context) {
  529. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  530. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  531. // This has to be done manually since the optimizer cannot determine when this is possible
  532. bool create_new = true;
  533. for_array(i, p->context_stack) {
  534. lbContextData *ctx_data = &p->context_stack[i];
  535. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  536. if (ctx_data->uses > 0) {
  537. create_new = true;
  538. } else if (p->scope_index > ctx_data->scope_index) {
  539. create_new = true;
  540. } else {
  541. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  542. create_new = false;
  543. }
  544. break;
  545. }
  546. }
  547. lbValue next = {};
  548. if (create_new) {
  549. lbValue old = lb_addr_load(p, old_addr);
  550. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  551. lb_addr_store(p, next_addr, old);
  552. lb_push_context_onto_stack(p, next_addr);
  553. next = next_addr.addr;
  554. } else {
  555. next = old_addr.addr;
  556. }
  557. if (addr.ctx.sel.index.count > 0) {
  558. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  559. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  560. lb_emit_store(p, lhs, rhs);
  561. } else {
  562. lbValue lhs = next;
  563. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  564. lb_emit_store(p, lhs, rhs);
  565. }
  566. return;
  567. } else if (addr.kind == lbAddr_SoaVariable) {
  568. Type *t = type_deref(addr.addr.type);
  569. t = base_type(t);
  570. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  571. Type *elem_type = t->Struct.soa_elem;
  572. value = lb_emit_conv(p, value, elem_type);
  573. elem_type = base_type(elem_type);
  574. lbValue index = addr.soa.index;
  575. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  576. Type *t = base_type(type_deref(addr.addr.type));
  577. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  578. lbValue len = lb_soa_struct_len(p, addr.addr);
  579. if (addr.soa.index_expr != nullptr) {
  580. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  581. }
  582. }
  583. isize field_count = 0;
  584. switch (elem_type->kind) {
  585. case Type_Struct:
  586. field_count = elem_type->Struct.fields.count;
  587. break;
  588. case Type_Array:
  589. field_count = cast(isize)elem_type->Array.count;
  590. break;
  591. }
  592. for (isize i = 0; i < field_count; i++) {
  593. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  594. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  595. if (t->Struct.soa_kind == StructSoa_Fixed) {
  596. dst = lb_emit_array_ep(p, dst, index);
  597. lb_emit_store(p, dst, src);
  598. } else {
  599. lbValue field = lb_emit_load(p, dst);
  600. dst = lb_emit_ptr_offset(p, field, index);
  601. lb_emit_store(p, dst, src);
  602. }
  603. }
  604. return;
  605. } else if (addr.kind == lbAddr_Swizzle) {
  606. GB_ASSERT(addr.swizzle.count <= 4);
  607. GB_ASSERT(value.value != nullptr);
  608. value = lb_emit_conv(p, value, lb_addr_type(addr));
  609. lbValue dst = lb_addr_get_ptr(p, addr);
  610. lbValue src = lb_address_from_load_or_generate_local(p, value);
  611. {
  612. lbValue src_ptrs[4] = {};
  613. lbValue src_loads[4] = {};
  614. lbValue dst_ptrs[4] = {};
  615. for (u8 i = 0; i < addr.swizzle.count; i++) {
  616. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  617. }
  618. for (u8 i = 0; i < addr.swizzle.count; i++) {
  619. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  620. }
  621. for (u8 i = 0; i < addr.swizzle.count; i++) {
  622. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  623. }
  624. for (u8 i = 0; i < addr.swizzle.count; i++) {
  625. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  626. }
  627. }
  628. return;
  629. } else if (addr.kind == lbAddr_SwizzleLarge) {
  630. GB_ASSERT(value.value != nullptr);
  631. value = lb_emit_conv(p, value, lb_addr_type(addr));
  632. lbValue dst = lb_addr_get_ptr(p, addr);
  633. lbValue src = lb_address_from_load_or_generate_local(p, value);
  634. for_array(i, addr.swizzle_large.indices) {
  635. lbValue src_ptr = lb_emit_array_epi(p, src, i);
  636. lbValue dst_ptr = lb_emit_array_epi(p, dst, addr.swizzle_large.indices[i]);
  637. lbValue src_load = lb_emit_load(p, src_ptr);
  638. lb_emit_store(p, dst_ptr, src_load);
  639. }
  640. return;
  641. }
  642. GB_ASSERT(value.value != nullptr);
  643. value = lb_emit_conv(p, value, lb_addr_type(addr));
  644. // if (lb_is_const_or_global(value)) {
  645. // // NOTE(bill): Just bypass the actual storage and set the initializer
  646. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  647. // LLVMValueRef dst = addr.addr.value;
  648. // LLVMValueRef src = value.value;
  649. // LLVMSetInitializer(dst, src);
  650. // return;
  651. // }
  652. // }
  653. lb_emit_store(p, addr.addr, value);
  654. }
  655. void lb_const_store(lbValue ptr, lbValue value) {
  656. GB_ASSERT(lb_is_const(ptr));
  657. GB_ASSERT(lb_is_const(value));
  658. GB_ASSERT(is_type_pointer(ptr.type));
  659. LLVMSetInitializer(ptr.value, value.value);
  660. }
  661. bool lb_is_type_proc_recursive(Type *t) {
  662. for (;;) {
  663. if (t == nullptr) {
  664. return false;
  665. }
  666. switch (t->kind) {
  667. case Type_Named:
  668. t = t->Named.base;
  669. break;
  670. case Type_Pointer:
  671. t = t->Pointer.elem;
  672. break;
  673. case Type_Array:
  674. t = t->Array.elem;
  675. break;
  676. case Type_EnumeratedArray:
  677. t = t->EnumeratedArray.elem;
  678. break;
  679. case Type_Slice:
  680. t = t->Slice.elem;
  681. break;
  682. case Type_DynamicArray:
  683. t = t->DynamicArray.elem;
  684. break;
  685. case Type_Proc:
  686. return true;
  687. default:
  688. return false;
  689. }
  690. }
  691. }
  692. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  693. GB_ASSERT(value.value != nullptr);
  694. Type *a = type_deref(ptr.type);
  695. if (is_type_boolean(a)) {
  696. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  697. value = lb_emit_conv(p, value, a);
  698. }
  699. Type *ca = core_type(a);
  700. if (ca->kind == Type_Basic) {
  701. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  702. }
  703. if (lb_is_type_proc_recursive(a)) {
  704. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  705. // stored as regular pointer with no procedure information
  706. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  707. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  708. LLVMBuildStore(p->builder, v, ptr.value);
  709. } else {
  710. Type *ca = core_type(a);
  711. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  712. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  713. } else {
  714. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  715. }
  716. LLVMBuildStore(p->builder, value.value, ptr.value);
  717. }
  718. }
  719. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  720. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  721. }
  722. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  723. GB_ASSERT(value.value != nullptr);
  724. if (is_type_multi_pointer(value.type)) {
  725. Type *vt = base_type(value.type);
  726. GB_ASSERT(vt->kind == Type_MultiPointer);
  727. Type *t = vt->MultiPointer.elem;
  728. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  729. return lbValue{v, t};
  730. }
  731. GB_ASSERT(is_type_pointer(value.type));
  732. Type *t = type_deref(value.type);
  733. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  734. return lbValue{v, t};
  735. }
  736. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  737. GB_ASSERT(addr.addr.value != nullptr);
  738. if (addr.kind == lbAddr_RelativePointer) {
  739. Type *rel_ptr = base_type(lb_addr_type(addr));
  740. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  741. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  742. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  743. offset = lb_emit_load(p, offset);
  744. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  745. offset = lb_emit_conv(p, offset, t_i64);
  746. }
  747. offset = lb_emit_conv(p, offset, t_uintptr);
  748. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  749. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  750. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  751. // NOTE(bill): nil check
  752. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  753. lbValue final_ptr = {};
  754. final_ptr.type = absolute_ptr.type;
  755. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  756. return lb_emit_load(p, final_ptr);
  757. } else if (addr.kind == lbAddr_RelativeSlice) {
  758. Type *rel_ptr = base_type(lb_addr_type(addr));
  759. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  760. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  761. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  762. lbValue offset = lb_emit_load(p, offset_ptr);
  763. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  764. offset = lb_emit_conv(p, offset, t_i64);
  765. }
  766. offset = lb_emit_conv(p, offset, t_uintptr);
  767. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  768. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  769. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  770. Type *slice_elem = slice_type->Slice.elem;
  771. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  772. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  773. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  774. // NOTE(bill): nil check
  775. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  776. lbValue data = {};
  777. data.type = absolute_ptr.type;
  778. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  779. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  780. len = lb_emit_conv(p, len, t_int);
  781. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  782. lb_fill_slice(p, slice, data, len);
  783. return lb_addr_load(p, slice);
  784. } else if (addr.kind == lbAddr_Map) {
  785. Type *map_type = base_type(addr.map.type);
  786. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  787. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  788. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  789. auto args = array_make<lbValue>(permanent_allocator(), 2);
  790. args[0] = h;
  791. args[1] = key;
  792. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  793. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  794. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  795. lbBlock *then = lb_create_block(p, "map.get.then");
  796. lbBlock *done = lb_create_block(p, "map.get.done");
  797. lb_emit_if(p, ok, then, done);
  798. lb_start_block(p, then);
  799. {
  800. // TODO(bill): mem copy it instead?
  801. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  802. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  803. lb_emit_store(p, gep0, lb_emit_load(p, value));
  804. }
  805. lb_emit_jump(p, done);
  806. lb_start_block(p, done);
  807. if (is_type_tuple(addr.map.result)) {
  808. return lb_addr_load(p, v);
  809. } else {
  810. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  811. return lb_emit_load(p, single);
  812. }
  813. } else if (addr.kind == lbAddr_Context) {
  814. lbValue a = addr.addr;
  815. for_array(i, p->context_stack) {
  816. lbContextData *ctx_data = &p->context_stack[i];
  817. if (ctx_data->ctx.addr.value == a.value) {
  818. ctx_data->uses += 1;
  819. break;
  820. }
  821. }
  822. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  823. if (addr.ctx.sel.index.count > 0) {
  824. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  825. return lb_emit_load(p, b);
  826. } else {
  827. return lb_emit_load(p, a);
  828. }
  829. } else if (addr.kind == lbAddr_SoaVariable) {
  830. Type *t = type_deref(addr.addr.type);
  831. t = base_type(t);
  832. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  833. Type *elem = t->Struct.soa_elem;
  834. lbValue len = {};
  835. if (t->Struct.soa_kind == StructSoa_Fixed) {
  836. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  837. } else {
  838. lbValue v = lb_emit_load(p, addr.addr);
  839. len = lb_soa_struct_len(p, v);
  840. }
  841. lbAddr res = lb_add_local_generated(p, elem, true);
  842. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  843. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  844. }
  845. if (t->Struct.soa_kind == StructSoa_Fixed) {
  846. for_array(i, t->Struct.fields) {
  847. Entity *field = t->Struct.fields[i];
  848. Type *base_type = field->type;
  849. GB_ASSERT(base_type->kind == Type_Array);
  850. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  851. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  852. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  853. lbValue src = lb_emit_load(p, src_ptr);
  854. lb_emit_store(p, dst, src);
  855. }
  856. } else {
  857. isize field_count = t->Struct.fields.count;
  858. if (t->Struct.soa_kind == StructSoa_Slice) {
  859. field_count -= 1;
  860. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  861. field_count -= 3;
  862. }
  863. for (isize i = 0; i < field_count; i++) {
  864. Entity *field = t->Struct.fields[i];
  865. Type *base_type = field->type;
  866. GB_ASSERT(base_type->kind == Type_Pointer);
  867. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  868. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  869. lbValue src = lb_emit_load(p, src_ptr);
  870. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  871. src = lb_emit_load(p, src);
  872. lb_emit_store(p, dst, src);
  873. }
  874. }
  875. return lb_addr_load(p, res);
  876. } else if (addr.kind == lbAddr_Swizzle) {
  877. Type *array_type = base_type(addr.swizzle.type);
  878. GB_ASSERT(array_type->kind == Type_Array);
  879. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  880. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  881. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  882. if (lb_try_update_alignment(addr.addr, res_align)) {
  883. Type *pt = alloc_type_pointer(addr.swizzle.type);
  884. lbValue res = {};
  885. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  886. res.type = pt;
  887. return lb_emit_load(p, res);
  888. }
  889. }
  890. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  891. lbValue ptr = lb_addr_get_ptr(p, res);
  892. GB_ASSERT(is_type_pointer(ptr.type));
  893. LLVMTypeRef vector_type = nullptr;
  894. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  895. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(vector_type));
  896. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  897. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  898. LLVMValueRef scalars[4] = {};
  899. for (u8 i = 0; i < addr.swizzle.count; i++) {
  900. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  901. }
  902. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  903. LLVMValueRef sv = LLVMBuildShuffleVector(p->builder, v, LLVMGetUndef(vector_type), mask, "");
  904. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  905. LLVMBuildStore(p->builder, sv, dst);
  906. } else {
  907. for (u8 i = 0; i < addr.swizzle.count; i++) {
  908. u8 index = addr.swizzle.indices[i];
  909. lbValue dst = lb_emit_array_epi(p, ptr, i);
  910. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  911. lb_emit_store(p, dst, lb_emit_load(p, src));
  912. }
  913. }
  914. return lb_addr_load(p, res);
  915. } else if (addr.kind == lbAddr_SwizzleLarge) {
  916. Type *array_type = base_type(addr.swizzle_large.type);
  917. GB_ASSERT(array_type->kind == Type_Array);
  918. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle_large.type);
  919. gb_unused(res_align);
  920. lbAddr res = lb_add_local_generated(p, addr.swizzle_large.type, false);
  921. lbValue ptr = lb_addr_get_ptr(p, res);
  922. GB_ASSERT(is_type_pointer(ptr.type));
  923. for_array(i, addr.swizzle_large.indices) {
  924. i32 index = addr.swizzle_large.indices[i];
  925. lbValue dst = lb_emit_array_epi(p, ptr, i);
  926. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  927. lb_emit_store(p, dst, lb_emit_load(p, src));
  928. }
  929. return lb_addr_load(p, res);
  930. }
  931. if (is_type_proc(addr.addr.type)) {
  932. return addr.addr;
  933. }
  934. return lb_emit_load(p, addr.addr);
  935. }
  936. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  937. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  938. }
  939. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  940. Type *t = u.type;
  941. GB_ASSERT_MSG(is_type_pointer(t) &&
  942. is_type_union(type_deref(t)), "%s", type_to_string(t));
  943. Type *ut = type_deref(t);
  944. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  945. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  946. GB_ASSERT(type_size_of(ut) > 0);
  947. Type *tag_type = union_tag_type(ut);
  948. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  949. unsigned element_count = LLVMCountStructElementTypes(uvt);
  950. GB_ASSERT_MSG(element_count == 2, "element_count=%u (%s) != (%s)", element_count, type_to_string(ut), LLVMPrintTypeToString(uvt));
  951. lbValue tag_ptr = {};
  952. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 1, "");
  953. tag_ptr.type = alloc_type_pointer(tag_type);
  954. return tag_ptr;
  955. }
  956. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  957. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  958. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  959. return lb_emit_load(p, tag_ptr);
  960. }
  961. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  962. Type *t = type_deref(parent.type);
  963. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  964. // No tag needed!
  965. } else {
  966. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  967. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  968. }
  969. }
  970. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  971. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  972. lb_emit_store(p, underlying, variant);
  973. lb_emit_store_union_variant_tag(p, parent, variant_type);
  974. }
  975. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  976. unsigned field_count = LLVMCountStructElementTypes(src);
  977. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  978. LLVMGetStructElementTypes(src, fields);
  979. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  980. }
  981. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  982. switch (alignment) {
  983. case 1:
  984. return LLVMArrayType(lb_type(m, t_u8), 0);
  985. case 2:
  986. return LLVMArrayType(lb_type(m, t_u16), 0);
  987. case 4:
  988. return LLVMArrayType(lb_type(m, t_u32), 0);
  989. case 8:
  990. return LLVMArrayType(lb_type(m, t_u64), 0);
  991. default: case 16:
  992. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  993. }
  994. }
  995. String lb_mangle_name(lbModule *m, Entity *e) {
  996. String name = e->token.string;
  997. AstPackage *pkg = e->pkg;
  998. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  999. String pkgn = pkg->name;
  1000. GB_ASSERT(!rune_is_digit(pkgn[0]));
  1001. if (pkgn == "llvm") {
  1002. pkgn = str_lit("llvm$");
  1003. }
  1004. isize max_len = pkgn.len + 1 + name.len + 1;
  1005. bool require_suffix_id = is_type_polymorphic(e->type, true);
  1006. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  1007. require_suffix_id = true;
  1008. } else if (is_blank_ident(e->token)) {
  1009. require_suffix_id = true;
  1010. }if (e->flags & EntityFlag_NotExported) {
  1011. require_suffix_id = true;
  1012. }
  1013. if (require_suffix_id) {
  1014. max_len += 21;
  1015. }
  1016. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  1017. isize new_name_len = gb_snprintf(
  1018. new_name, max_len,
  1019. "%.*s.%.*s", LIT(pkgn), LIT(name)
  1020. );
  1021. if (require_suffix_id) {
  1022. char *str = new_name + new_name_len-1;
  1023. isize len = max_len-new_name_len;
  1024. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  1025. new_name_len += extra-1;
  1026. }
  1027. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  1028. return mangled_name;
  1029. }
  1030. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  1031. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  1032. // and as a result, the declaration does not have time to determine what it should be
  1033. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  1034. if (e->TypeName.ir_mangled_name.len != 0) {
  1035. return e->TypeName.ir_mangled_name;
  1036. }
  1037. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  1038. if (p == nullptr) {
  1039. Entity *proc = nullptr;
  1040. if (e->parent_proc_decl != nullptr) {
  1041. proc = e->parent_proc_decl->entity;
  1042. } else {
  1043. Scope *scope = e->scope;
  1044. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  1045. scope = scope->parent;
  1046. }
  1047. GB_ASSERT(scope != nullptr);
  1048. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  1049. proc = scope->procedure_entity;
  1050. }
  1051. GB_ASSERT(proc->kind == Entity_Procedure);
  1052. if (proc->code_gen_procedure != nullptr) {
  1053. p = proc->code_gen_procedure;
  1054. }
  1055. }
  1056. // NOTE(bill): Generate a new name
  1057. // parent_proc.name-guid
  1058. String ts_name = e->token.string;
  1059. if (p != nullptr) {
  1060. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  1061. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1062. u32 guid = ++p->module->nested_type_name_guid;
  1063. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  1064. String name = make_string(cast(u8 *)name_text, name_len-1);
  1065. e->TypeName.ir_mangled_name = name;
  1066. return name;
  1067. } else {
  1068. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  1069. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  1070. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1071. static u32 guid = 0;
  1072. guid += 1;
  1073. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  1074. String name = make_string(cast(u8 *)name_text, name_len-1);
  1075. e->TypeName.ir_mangled_name = name;
  1076. return name;
  1077. }
  1078. }
  1079. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  1080. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  1081. return e->TypeName.ir_mangled_name;
  1082. }
  1083. GB_ASSERT(e != nullptr);
  1084. if (e->pkg == nullptr) {
  1085. return e->token.string;
  1086. }
  1087. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  1088. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  1089. }
  1090. String name = {};
  1091. bool no_name_mangle = false;
  1092. if (e->kind == Entity_Variable) {
  1093. bool is_foreign = e->Variable.is_foreign;
  1094. bool is_export = e->Variable.is_export;
  1095. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  1096. if (e->Variable.link_name.len > 0) {
  1097. return e->Variable.link_name;
  1098. }
  1099. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  1100. return e->Procedure.link_name;
  1101. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  1102. no_name_mangle = true;
  1103. }
  1104. if (!no_name_mangle) {
  1105. name = lb_mangle_name(m, e);
  1106. }
  1107. if (name.len == 0) {
  1108. name = e->token.string;
  1109. }
  1110. if (e->kind == Entity_TypeName) {
  1111. e->TypeName.ir_mangled_name = name;
  1112. } else if (e->kind == Entity_Procedure) {
  1113. e->Procedure.link_name = name;
  1114. }
  1115. return name;
  1116. }
  1117. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  1118. LLVMContextRef ctx = m->ctx;
  1119. i64 size = type_size_of(type); // Check size
  1120. gb_unused(size);
  1121. GB_ASSERT(type != t_invalid);
  1122. switch (type->kind) {
  1123. case Type_Basic:
  1124. switch (type->Basic.kind) {
  1125. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  1126. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  1127. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  1128. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  1129. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  1130. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  1131. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  1132. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  1133. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  1134. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  1135. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  1136. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  1137. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  1138. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  1139. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  1140. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  1141. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  1142. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  1143. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  1144. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  1145. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  1146. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  1147. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  1148. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  1149. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  1150. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  1151. case Basic_complex32:
  1152. {
  1153. char const *name = "..complex32";
  1154. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1155. if (type != nullptr) {
  1156. return type;
  1157. }
  1158. type = LLVMStructCreateNamed(ctx, name);
  1159. LLVMTypeRef fields[2] = {
  1160. lb_type(m, t_f16),
  1161. lb_type(m, t_f16),
  1162. };
  1163. LLVMStructSetBody(type, fields, 2, false);
  1164. return type;
  1165. }
  1166. case Basic_complex64:
  1167. {
  1168. char const *name = "..complex64";
  1169. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1170. if (type != nullptr) {
  1171. return type;
  1172. }
  1173. type = LLVMStructCreateNamed(ctx, name);
  1174. LLVMTypeRef fields[2] = {
  1175. lb_type(m, t_f32),
  1176. lb_type(m, t_f32),
  1177. };
  1178. LLVMStructSetBody(type, fields, 2, false);
  1179. return type;
  1180. }
  1181. case Basic_complex128:
  1182. {
  1183. char const *name = "..complex128";
  1184. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1185. if (type != nullptr) {
  1186. return type;
  1187. }
  1188. type = LLVMStructCreateNamed(ctx, name);
  1189. LLVMTypeRef fields[2] = {
  1190. lb_type(m, t_f64),
  1191. lb_type(m, t_f64),
  1192. };
  1193. LLVMStructSetBody(type, fields, 2, false);
  1194. return type;
  1195. }
  1196. case Basic_quaternion64:
  1197. {
  1198. char const *name = "..quaternion64";
  1199. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1200. if (type != nullptr) {
  1201. return type;
  1202. }
  1203. type = LLVMStructCreateNamed(ctx, name);
  1204. LLVMTypeRef fields[4] = {
  1205. lb_type(m, t_f16),
  1206. lb_type(m, t_f16),
  1207. lb_type(m, t_f16),
  1208. lb_type(m, t_f16),
  1209. };
  1210. LLVMStructSetBody(type, fields, 4, false);
  1211. return type;
  1212. }
  1213. case Basic_quaternion128:
  1214. {
  1215. char const *name = "..quaternion128";
  1216. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1217. if (type != nullptr) {
  1218. return type;
  1219. }
  1220. type = LLVMStructCreateNamed(ctx, name);
  1221. LLVMTypeRef fields[4] = {
  1222. lb_type(m, t_f32),
  1223. lb_type(m, t_f32),
  1224. lb_type(m, t_f32),
  1225. lb_type(m, t_f32),
  1226. };
  1227. LLVMStructSetBody(type, fields, 4, false);
  1228. return type;
  1229. }
  1230. case Basic_quaternion256:
  1231. {
  1232. char const *name = "..quaternion256";
  1233. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1234. if (type != nullptr) {
  1235. return type;
  1236. }
  1237. type = LLVMStructCreateNamed(ctx, name);
  1238. LLVMTypeRef fields[4] = {
  1239. lb_type(m, t_f64),
  1240. lb_type(m, t_f64),
  1241. lb_type(m, t_f64),
  1242. lb_type(m, t_f64),
  1243. };
  1244. LLVMStructSetBody(type, fields, 4, false);
  1245. return type;
  1246. }
  1247. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1248. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1249. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1250. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1251. case Basic_string:
  1252. {
  1253. char const *name = "..string";
  1254. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1255. if (type != nullptr) {
  1256. return type;
  1257. }
  1258. type = LLVMStructCreateNamed(ctx, name);
  1259. LLVMTypeRef fields[2] = {
  1260. LLVMPointerType(lb_type(m, t_u8), 0),
  1261. lb_type(m, t_int),
  1262. };
  1263. LLVMStructSetBody(type, fields, 2, false);
  1264. return type;
  1265. }
  1266. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1267. case Basic_any:
  1268. {
  1269. char const *name = "..any";
  1270. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1271. if (type != nullptr) {
  1272. return type;
  1273. }
  1274. type = LLVMStructCreateNamed(ctx, name);
  1275. LLVMTypeRef fields[2] = {
  1276. lb_type(m, t_rawptr),
  1277. lb_type(m, t_typeid),
  1278. };
  1279. LLVMStructSetBody(type, fields, 2, false);
  1280. return type;
  1281. }
  1282. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1283. // Endian Specific Types
  1284. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1285. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1286. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1287. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1288. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1289. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1290. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1291. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1292. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1293. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1294. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1295. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1296. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1297. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1298. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1299. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1300. // Untyped types
  1301. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1302. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1303. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1304. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1305. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1306. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1307. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1308. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1309. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1310. }
  1311. break;
  1312. case Type_Named:
  1313. {
  1314. Type *base = base_type(type->Named.base);
  1315. switch (base->kind) {
  1316. case Type_Basic:
  1317. return lb_type_internal(m, base);
  1318. case Type_Named:
  1319. case Type_Generic:
  1320. GB_PANIC("INVALID TYPE");
  1321. break;
  1322. case Type_Pointer:
  1323. case Type_Array:
  1324. case Type_EnumeratedArray:
  1325. case Type_Slice:
  1326. case Type_DynamicArray:
  1327. case Type_Map:
  1328. case Type_Enum:
  1329. case Type_BitSet:
  1330. case Type_SimdVector:
  1331. return lb_type_internal(m, base);
  1332. // TODO(bill): Deal with this correctly. Can this be named?
  1333. case Type_Proc:
  1334. return lb_type_internal(m, base);
  1335. case Type_Tuple:
  1336. return lb_type_internal(m, base);
  1337. }
  1338. LLVMTypeRef *found = map_get(&m->types, base);
  1339. if (found) {
  1340. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1341. if (kind == LLVMStructTypeKind) {
  1342. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1343. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1344. if (llvm_type != nullptr) {
  1345. return llvm_type;
  1346. }
  1347. llvm_type = LLVMStructCreateNamed(ctx, name);
  1348. map_set(&m->types, type, llvm_type);
  1349. lb_clone_struct_type(llvm_type, *found);
  1350. return llvm_type;
  1351. }
  1352. }
  1353. switch (base->kind) {
  1354. case Type_Struct:
  1355. case Type_Union:
  1356. {
  1357. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1358. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1359. if (llvm_type != nullptr) {
  1360. return llvm_type;
  1361. }
  1362. llvm_type = LLVMStructCreateNamed(ctx, name);
  1363. map_set(&m->types, type, llvm_type);
  1364. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1365. return llvm_type;
  1366. }
  1367. }
  1368. return lb_type_internal(m, base);
  1369. }
  1370. case Type_Pointer:
  1371. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1372. case Type_MultiPointer:
  1373. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1374. case Type_Array: {
  1375. m->internal_type_level -= 1;
  1376. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1377. m->internal_type_level += 1;
  1378. return t;
  1379. }
  1380. case Type_EnumeratedArray: {
  1381. m->internal_type_level -= 1;
  1382. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1383. m->internal_type_level += 1;
  1384. return t;
  1385. }
  1386. case Type_Slice:
  1387. {
  1388. LLVMTypeRef fields[2] = {
  1389. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1390. lb_type(m, t_int), // len
  1391. };
  1392. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1393. }
  1394. break;
  1395. case Type_DynamicArray:
  1396. {
  1397. LLVMTypeRef fields[4] = {
  1398. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1399. lb_type(m, t_int), // len
  1400. lb_type(m, t_int), // cap
  1401. lb_type(m, t_allocator), // allocator
  1402. };
  1403. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1404. }
  1405. break;
  1406. case Type_Map:
  1407. init_map_internal_types(type);
  1408. {
  1409. Type *internal_type = type->Map.internal_type;
  1410. GB_ASSERT(internal_type->kind == Type_Struct);
  1411. m->internal_type_level -= 1;
  1412. defer (m->internal_type_level += 1);
  1413. unsigned field_count = cast(unsigned)(internal_type->Struct.fields.count);
  1414. GB_ASSERT(field_count == 2);
  1415. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1416. LLVMTypeRef entries_fields[] = {
  1417. lb_type(m, t_rawptr), // data
  1418. lb_type(m, t_int), // len
  1419. lb_type(m, t_int), // cap
  1420. lb_type(m, t_allocator), // allocator
  1421. };
  1422. fields[0] = lb_type(m, internal_type->Struct.fields[0]->type);
  1423. fields[1] = LLVMStructTypeInContext(ctx, entries_fields, gb_count_of(entries_fields), false);
  1424. { // Add this to simplify things
  1425. lbStructFieldRemapping entries_field_remapping = {};
  1426. slice_init(&entries_field_remapping, permanent_allocator(), gb_count_of(entries_fields));
  1427. for_array(i, entries_field_remapping) {
  1428. entries_field_remapping[i] = cast(i32)i;
  1429. }
  1430. map_set(&m->struct_field_remapping, cast(void *)fields[1], entries_field_remapping);
  1431. }
  1432. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1433. }
  1434. case Type_Struct:
  1435. {
  1436. type_set_offsets(type);
  1437. i64 full_type_size = type_size_of(type);
  1438. i64 full_type_align = type_align_of(type);
  1439. GB_ASSERT(full_type_size % full_type_align == 0);
  1440. if (type->Struct.is_raw_union) {
  1441. lbStructFieldRemapping field_remapping = {};
  1442. slice_init(&field_remapping, permanent_allocator(), 1);
  1443. LLVMTypeRef fields[1] = {};
  1444. fields[0] = lb_type_padding_filler(m, full_type_size, full_type_align);
  1445. field_remapping[0] = 0;
  1446. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1447. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1448. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1449. return struct_type;
  1450. }
  1451. lbStructFieldRemapping field_remapping = {};
  1452. slice_init(&field_remapping, permanent_allocator(), type->Struct.fields.count);
  1453. m->internal_type_level += 1;
  1454. defer (m->internal_type_level -= 1);
  1455. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, type->Struct.fields.count*2 + 2);
  1456. if (are_struct_fields_reordered(type)) {
  1457. // NOTE(bill, 2021-10-02): Minor hack to enforce `llvm_const_named_struct` usage correctly
  1458. LLVMTypeRef padding_type = lb_type_padding_filler(m, 0, type_align_of(type));
  1459. array_add(&fields, padding_type);
  1460. }
  1461. i64 padding_offset = 0;
  1462. for (i32 field_index : struct_fields_index_by_increasing_offset(temporary_allocator(), type)) {
  1463. Entity *field = type->Struct.fields[field_index];
  1464. i64 padding = type->Struct.offsets[field_index] - padding_offset;
  1465. if (padding != 0) {
  1466. LLVMTypeRef padding_type = lb_type_padding_filler(m, padding, type_align_of(field->type));
  1467. array_add(&fields, padding_type);
  1468. }
  1469. field_remapping[field_index] = cast(i32)fields.count;
  1470. array_add(&fields, lb_type(m, field->type));
  1471. if (!type->Struct.is_packed) {
  1472. padding_offset = align_formula(padding_offset, type_align_of(field->type));
  1473. }
  1474. padding_offset += type_size_of(field->type);
  1475. }
  1476. i64 end_padding = full_type_size-padding_offset;
  1477. if (end_padding > 0) {
  1478. array_add(&fields, lb_type_padding_filler(m, end_padding, 1));
  1479. }
  1480. for_array(i, fields) {
  1481. GB_ASSERT(fields[i] != nullptr);
  1482. }
  1483. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, type->Struct.is_packed);
  1484. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1485. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1486. #if 0
  1487. GB_ASSERT_MSG(lb_sizeof(struct_type) == full_type_size,
  1488. "(%lld) %s vs (%lld) %s",
  1489. cast(long long)lb_sizeof(struct_type), LLVMPrintTypeToString(struct_type),
  1490. cast(long long)full_type_size, type_to_string(type));
  1491. #endif
  1492. return struct_type;
  1493. }
  1494. break;
  1495. case Type_Union:
  1496. if (type->Union.variants.count == 0) {
  1497. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1498. } else {
  1499. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1500. // LLVM takes the first element's alignment as the entire alignment (like C)
  1501. i64 align = type_align_of(type);
  1502. i64 size = type_size_of(type);
  1503. gb_unused(size);
  1504. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1505. LLVMTypeRef fields[] = {lb_type(m, type->Union.variants[0])};
  1506. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1507. }
  1508. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1509. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, 2);
  1510. if (is_type_union_maybe_pointer(type)) {
  1511. LLVMTypeRef variant = lb_type(m, type->Union.variants[0]);
  1512. array_add(&fields, variant);
  1513. } else {
  1514. LLVMTypeRef block_type = lb_type_padding_filler(m, block_size, align);
  1515. LLVMTypeRef tag_type = lb_type(m, union_tag_type(type));
  1516. array_add(&fields, block_type);
  1517. array_add(&fields, tag_type);
  1518. }
  1519. return LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, false);
  1520. }
  1521. break;
  1522. case Type_Enum:
  1523. return lb_type(m, base_enum_type(type));
  1524. case Type_Tuple:
  1525. if (type->Tuple.variables.count == 1) {
  1526. return lb_type(m, type->Tuple.variables[0]->type);
  1527. } else {
  1528. m->internal_type_level += 1;
  1529. defer (m->internal_type_level -= 1);
  1530. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1531. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1532. for_array(i, type->Tuple.variables) {
  1533. Entity *field = type->Tuple.variables[i];
  1534. LLVMTypeRef param_type = nullptr;
  1535. param_type = lb_type(m, field->type);
  1536. fields[i] = param_type;
  1537. }
  1538. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1539. }
  1540. case Type_Proc:
  1541. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1542. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1543. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1544. } else {
  1545. unsigned param_count = 0;
  1546. if (type->Proc.calling_convention == ProcCC_Odin) {
  1547. param_count += 1;
  1548. }
  1549. if (type->Proc.param_count != 0) {
  1550. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1551. for_array(i, type->Proc.params->Tuple.variables) {
  1552. Entity *e = type->Proc.params->Tuple.variables[i];
  1553. if (e->kind != Entity_Variable) {
  1554. continue;
  1555. }
  1556. if (e->flags & EntityFlag_CVarArg) {
  1557. continue;
  1558. }
  1559. param_count += 1;
  1560. }
  1561. }
  1562. m->internal_type_level += 1;
  1563. defer (m->internal_type_level -= 1);
  1564. LLVMTypeRef ret = nullptr;
  1565. LLVMTypeRef *params = gb_alloc_array(permanent_allocator(), LLVMTypeRef, param_count);
  1566. if (type->Proc.result_count != 0) {
  1567. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1568. ret = lb_type(m, single_ret);
  1569. if (ret != nullptr) {
  1570. if (is_type_boolean(single_ret) &&
  1571. is_calling_convention_none(type->Proc.calling_convention) &&
  1572. type_size_of(single_ret) <= 1) {
  1573. ret = LLVMInt1TypeInContext(m->ctx);
  1574. }
  1575. }
  1576. }
  1577. unsigned param_index = 0;
  1578. if (type->Proc.param_count != 0) {
  1579. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1580. for_array(i, type->Proc.params->Tuple.variables) {
  1581. Entity *e = type->Proc.params->Tuple.variables[i];
  1582. if (e->kind != Entity_Variable) {
  1583. continue;
  1584. }
  1585. if (e->flags & EntityFlag_CVarArg) {
  1586. continue;
  1587. }
  1588. Type *e_type = reduce_tuple_to_single_type(e->type);
  1589. LLVMTypeRef param_type = nullptr;
  1590. if (is_type_boolean(e_type) &&
  1591. type_size_of(e_type) <= 1) {
  1592. param_type = LLVMInt1TypeInContext(m->ctx);
  1593. } else {
  1594. if (is_type_proc(e_type)) {
  1595. param_type = lb_type(m, t_rawptr);
  1596. } else {
  1597. param_type = lb_type(m, e_type);
  1598. }
  1599. }
  1600. params[param_index++] = param_type;
  1601. }
  1602. }
  1603. if (param_index < param_count) {
  1604. params[param_index++] = lb_type(m, t_rawptr);
  1605. }
  1606. GB_ASSERT(param_index == param_count);
  1607. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1608. {
  1609. for_array(j, ft->args) {
  1610. auto arg = ft->args[j];
  1611. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1612. "\n\t%s %td/%td"
  1613. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1614. LLVMPrintTypeToString(arg.type),
  1615. j, ft->args.count,
  1616. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1617. }
  1618. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1619. "\n\t%s"
  1620. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1621. LLVMPrintTypeToString(ft->ret.type),
  1622. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1623. }
  1624. map_set(&m->function_type_map, type, ft);
  1625. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1626. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1627. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1628. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1629. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1630. return new_abi_fn_ptr_type;
  1631. }
  1632. break;
  1633. case Type_BitSet:
  1634. {
  1635. Type *ut = bit_set_to_int(type);
  1636. return lb_type(m, ut);
  1637. }
  1638. case Type_SimdVector:
  1639. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1640. case Type_RelativePointer:
  1641. return lb_type_internal(m, type->RelativePointer.base_integer);
  1642. case Type_RelativeSlice:
  1643. {
  1644. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1645. unsigned field_count = 2;
  1646. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1647. fields[0] = base_integer;
  1648. fields[1] = base_integer;
  1649. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1650. }
  1651. case Type_Matrix:
  1652. {
  1653. i64 size = type_size_of(type);
  1654. i64 elem_size = type_size_of(type->Matrix.elem);
  1655. GB_ASSERT(elem_size > 0);
  1656. i64 elem_count = size/elem_size;
  1657. GB_ASSERT_MSG(elem_count > 0, "%s", type_to_string(type));
  1658. m->internal_type_level -= 1;
  1659. LLVMTypeRef elem = lb_type(m, type->Matrix.elem);
  1660. LLVMTypeRef t = LLVMArrayType(elem, cast(unsigned)elem_count);
  1661. m->internal_type_level += 1;
  1662. return t;
  1663. }
  1664. }
  1665. GB_PANIC("Invalid type %s", type_to_string(type));
  1666. return LLVMInt32TypeInContext(ctx);
  1667. }
  1668. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1669. type = default_type(type);
  1670. LLVMTypeRef *found = map_get(&m->types, type);
  1671. if (found) {
  1672. return *found;
  1673. }
  1674. LLVMTypeRef llvm_type = nullptr;
  1675. m->internal_type_level += 1;
  1676. llvm_type = lb_type_internal(m, type);
  1677. m->internal_type_level -= 1;
  1678. if (m->internal_type_level == 0) {
  1679. map_set(&m->types, type, llvm_type);
  1680. }
  1681. return llvm_type;
  1682. }
  1683. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1684. lbFunctionType **ft_found = nullptr;
  1685. ft_found = map_get(&m->function_type_map, pt);
  1686. if (!ft_found) {
  1687. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1688. gb_unused(llvm_proc_type);
  1689. ft_found = map_get(&m->function_type_map, pt);
  1690. }
  1691. GB_ASSERT(ft_found != nullptr);
  1692. return *ft_found;
  1693. }
  1694. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1695. if (p->abi_function_type != nullptr) {
  1696. return;
  1697. }
  1698. lbFunctionType **ft_found = map_get(&m->function_type_map, p->type);
  1699. if (ft_found == nullptr) {
  1700. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1701. gb_unused(llvm_proc_type);
  1702. ft_found = map_get(&m->function_type_map, p->type);
  1703. }
  1704. GB_ASSERT(ft_found != nullptr);
  1705. p->abi_function_type = *ft_found;
  1706. GB_ASSERT(p->abi_function_type != nullptr);
  1707. }
  1708. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1709. if (e != nullptr) {
  1710. map_set(&m->values, e, val);
  1711. }
  1712. }
  1713. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1714. if (name.len > 0) {
  1715. string_map_set(&m->members, name, val);
  1716. }
  1717. }
  1718. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1719. string_map_set(&m->members, key, val);
  1720. }
  1721. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1722. if (p->entity != nullptr) {
  1723. map_set(&m->procedure_values, p->value, p->entity);
  1724. }
  1725. string_map_set(&m->procedures, p->name, p);
  1726. }
  1727. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  1728. unsigned kind = 0;
  1729. String s = make_string_c(name);
  1730. #if ODIN_LLVM_MINIMUM_VERSION_12
  1731. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1732. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1733. return LLVMCreateTypeAttribute(ctx, kind, type);
  1734. #else
  1735. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1736. // and the current LLVM C API does not expose this functionality yet.
  1737. // It is better to ignore the attributes for the time being
  1738. if (s == "byval") {
  1739. // return nullptr;
  1740. } else if (s == "byref") {
  1741. return nullptr;
  1742. } else if (s == "preallocated") {
  1743. return nullptr;
  1744. } else if (s == "sret") {
  1745. // return nullptr;
  1746. }
  1747. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1748. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1749. return LLVMCreateEnumAttribute(ctx, kind, 0);
  1750. #endif
  1751. }
  1752. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1753. String s = make_string_c(name);
  1754. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1755. // and the current LLVM C API does not expose this functionality yet.
  1756. // It is better to ignore the attributes for the time being
  1757. if (s == "byval") {
  1758. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1759. } else if (s == "byref") {
  1760. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1761. } else if (s == "preallocated") {
  1762. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1763. } else if (s == "sret") {
  1764. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1765. }
  1766. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1767. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1768. return LLVMCreateEnumAttribute(ctx, kind, value);
  1769. }
  1770. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1771. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1772. GB_ASSERT(attr != nullptr);
  1773. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1774. }
  1775. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1776. lb_add_proc_attribute_at_index(p, index, name, 0);
  1777. }
  1778. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  1779. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  1780. }
  1781. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1782. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1783. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1784. array_add(&from->succs, to);
  1785. array_add(&to->preds, from);
  1786. }
  1787. }
  1788. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1789. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  1790. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1791. b->appended = false;
  1792. if (append) {
  1793. b->appended = true;
  1794. LLVMAppendExistingBasicBlock(p->value, b->block);
  1795. }
  1796. b->scope = p->curr_scope;
  1797. b->scope_index = p->scope_index;
  1798. b->preds.allocator = heap_allocator();
  1799. b->succs.allocator = heap_allocator();
  1800. array_add(&p->blocks, b);
  1801. return b;
  1802. }
  1803. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1804. if (p->curr_block == nullptr) {
  1805. return;
  1806. }
  1807. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1808. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1809. return;
  1810. }
  1811. lb_add_edge(p->curr_block, target_block);
  1812. LLVMBuildBr(p->builder, target_block->block);
  1813. p->curr_block = nullptr;
  1814. }
  1815. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1816. lbBlock *b = p->curr_block;
  1817. if (b == nullptr) {
  1818. return;
  1819. }
  1820. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1821. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1822. return;
  1823. }
  1824. lb_add_edge(b, true_block);
  1825. lb_add_edge(b, false_block);
  1826. LLVMValueRef cv = cond.value;
  1827. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1828. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1829. }
  1830. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  1831. LLVMContextRef ctx = p->module->ctx;
  1832. LLVMTypeRef src_type = LLVMTypeOf(val);
  1833. if (src_type == dst_type) {
  1834. return val;
  1835. }
  1836. i64 src_size = lb_sizeof(src_type);
  1837. i64 dst_size = lb_sizeof(dst_type);
  1838. i64 src_align = lb_alignof(src_type);
  1839. i64 dst_align = lb_alignof(dst_type);
  1840. if (LLVMIsALoadInst(val)) {
  1841. src_align = gb_min(src_align, LLVMGetAlignment(val));
  1842. }
  1843. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  1844. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  1845. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  1846. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1847. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  1848. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  1849. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1850. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  1851. }
  1852. if (src_size != dst_size) {
  1853. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  1854. // Okay
  1855. } else {
  1856. goto general_end;
  1857. }
  1858. }
  1859. if (src_kind == dst_kind) {
  1860. if (src_kind == LLVMPointerTypeKind) {
  1861. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  1862. } else if (src_kind == LLVMArrayTypeKind) {
  1863. // ignore
  1864. } else if (src_kind != LLVMStructTypeKind) {
  1865. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  1866. }
  1867. } else {
  1868. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  1869. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  1870. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  1871. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  1872. }
  1873. }
  1874. general_end:;
  1875. // make the alignment big if necessary
  1876. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  1877. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  1878. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  1879. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  1880. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  1881. }
  1882. }
  1883. src_size = align_formula(src_size, src_align);
  1884. dst_size = align_formula(dst_size, dst_align);
  1885. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  1886. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  1887. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  1888. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  1889. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  1890. return loaded_val;
  1891. } else {
  1892. GB_ASSERT(p->decl_block != p->curr_block);
  1893. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1894. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  1895. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1896. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  1897. max_align = gb_max(max_align, 4);
  1898. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  1899. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  1900. LLVMBuildStore(p->builder, val, nptr);
  1901. return LLVMBuildLoad(p->builder, ptr, "");
  1902. }
  1903. }
  1904. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  1905. StringHashKey key = string_hash_string(str);
  1906. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  1907. if (found != nullptr) {
  1908. return *found;
  1909. } else {
  1910. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  1911. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  1912. cast(char const *)str.text,
  1913. cast(unsigned)str.len,
  1914. false);
  1915. isize max_len = 7+8+1;
  1916. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  1917. u32 id = m->gen->global_array_index.fetch_add(1);
  1918. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  1919. len -= 1;
  1920. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  1921. LLVMSetInitializer(global_data, data);
  1922. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  1923. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  1924. string_map_set(&m->const_strings, key, ptr);
  1925. return ptr;
  1926. }
  1927. }
  1928. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  1929. LLVMValueRef ptr = nullptr;
  1930. if (str.len != 0) {
  1931. ptr = lb_find_or_add_entity_string_ptr(m, str);
  1932. } else {
  1933. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  1934. }
  1935. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  1936. LLVMValueRef values[2] = {ptr, str_len};
  1937. lbValue res = {};
  1938. res.value = llvm_const_named_struct(m, t_string, values, 2);
  1939. res.type = t_string;
  1940. return res;
  1941. }
  1942. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  1943. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  1944. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  1945. cast(char const *)str.text,
  1946. cast(unsigned)str.len,
  1947. false);
  1948. char *name = nullptr;
  1949. {
  1950. isize max_len = 7+8+1;
  1951. name = gb_alloc_array(permanent_allocator(), char, max_len);
  1952. u32 id = m->gen->global_array_index.fetch_add(1);
  1953. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  1954. len -= 1;
  1955. }
  1956. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  1957. LLVMSetInitializer(global_data, data);
  1958. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  1959. LLVMValueRef ptr = nullptr;
  1960. if (str.len != 0) {
  1961. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  1962. } else {
  1963. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  1964. }
  1965. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  1966. LLVMValueRef values[2] = {ptr, len};
  1967. lbValue res = {};
  1968. res.value = llvm_const_named_struct(m, t_u8_slice, values, 2);
  1969. res.type = t_u8_slice;
  1970. return res;
  1971. }
  1972. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  1973. auto *found = map_get(&m->values, e);
  1974. if (found) {
  1975. auto v = *found;
  1976. // NOTE(bill): This is because pointers are already pointers in LLVM
  1977. if (is_type_proc(v.type)) {
  1978. return v;
  1979. }
  1980. return lb_emit_load(p, v);
  1981. } else if (e != nullptr && e->kind == Entity_Variable) {
  1982. return lb_addr_load(p, lb_build_addr(p, expr));
  1983. }
  1984. if (e->kind == Entity_Procedure) {
  1985. return lb_find_procedure_value_from_entity(m, e);
  1986. }
  1987. if (USE_SEPARATE_MODULES) {
  1988. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  1989. if (other_module != m) {
  1990. String name = lb_get_entity_name(other_module, e);
  1991. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  1992. lbValue g = {};
  1993. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1994. g.type = alloc_type_pointer(e->type);
  1995. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1996. lb_add_entity(m, e, g);
  1997. lb_add_member(m, name, g);
  1998. return lb_emit_load(p, g);
  1999. }
  2000. }
  2001. String pkg = {};
  2002. if (e->pkg) {
  2003. pkg = e->pkg->name;
  2004. }
  2005. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  2006. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  2007. return {};
  2008. }
  2009. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  2010. GB_ASSERT(is_type_proc(e->type));
  2011. e = strip_entity_wrapping(e);
  2012. GB_ASSERT(e != nullptr);
  2013. auto *found = map_get(&m->values, e);
  2014. if (found) {
  2015. return *found;
  2016. }
  2017. bool ignore_body = false;
  2018. lbModule *other_module = m;
  2019. if (USE_SEPARATE_MODULES) {
  2020. other_module = lb_pkg_module(m->gen, e->pkg);
  2021. }
  2022. if (other_module == m) {
  2023. debugf("Missing Procedure (lb_find_procedure_value_from_entity): %.*s\n", LIT(e->token.string));
  2024. }
  2025. ignore_body = other_module != m;
  2026. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  2027. if (!ignore_body) {
  2028. array_add(&m->missing_procedures_to_check, missing_proc);
  2029. }
  2030. found = map_get(&m->values, e);
  2031. if (found) {
  2032. return *found;
  2033. }
  2034. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2035. return {};
  2036. }
  2037. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  2038. GB_ASSERT(type != nullptr);
  2039. type = default_type(type);
  2040. isize max_len = 7+8+1;
  2041. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  2042. u32 id = m->gen->global_generated_index.fetch_add(1);
  2043. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  2044. String name = make_string(str, len-1);
  2045. Scope *scope = nullptr;
  2046. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  2047. lbValue g = {};
  2048. g.type = alloc_type_pointer(type);
  2049. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  2050. if (value.value != nullptr) {
  2051. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  2052. LLVMSetInitializer(g.value, value.value);
  2053. } else {
  2054. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  2055. }
  2056. lb_add_entity(m, e, g);
  2057. lb_add_member(m, name, g);
  2058. return lb_addr(g);
  2059. }
  2060. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  2061. AstPackage *p = m->info->runtime_package;
  2062. Entity *e = scope_lookup_current(p->scope, name);
  2063. return lb_find_value_from_entity(m, e);
  2064. }
  2065. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  2066. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  2067. return lb_find_value_from_entity(m, e);
  2068. }
  2069. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  2070. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  2071. return lb_addr_get_ptr(p, addr);
  2072. }
  2073. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  2074. e = strip_entity_wrapping(e);
  2075. GB_ASSERT(e != nullptr);
  2076. GB_ASSERT(e->token.string != "_");
  2077. if (e->kind == Entity_Procedure) {
  2078. return lb_find_procedure_value_from_entity(m, e);
  2079. }
  2080. auto *found = map_get(&m->values, e);
  2081. if (found) {
  2082. return *found;
  2083. }
  2084. if (USE_SEPARATE_MODULES) {
  2085. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  2086. // TODO(bill): correct this logic
  2087. bool is_external = other_module != m;
  2088. if (!is_external) {
  2089. if (e->code_gen_module != nullptr) {
  2090. other_module = e->code_gen_module;
  2091. } else {
  2092. other_module = nullptr;
  2093. }
  2094. is_external = other_module != m;
  2095. }
  2096. if (is_external) {
  2097. String name = lb_get_entity_name(other_module, e);
  2098. lbValue g = {};
  2099. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2100. g.type = alloc_type_pointer(e->type);
  2101. lb_add_entity(m, e, g);
  2102. lb_add_member(m, name, g);
  2103. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2104. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2105. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  2106. if (e->Variable.thread_local_model != "") {
  2107. LLVMSetThreadLocal(g.value, true);
  2108. String m = e->Variable.thread_local_model;
  2109. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2110. if (m == "default") {
  2111. mode = LLVMGeneralDynamicTLSModel;
  2112. } else if (m == "localdynamic") {
  2113. mode = LLVMLocalDynamicTLSModel;
  2114. } else if (m == "initialexec") {
  2115. mode = LLVMInitialExecTLSModel;
  2116. } else if (m == "localexec") {
  2117. mode = LLVMLocalExecTLSModel;
  2118. } else {
  2119. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2120. }
  2121. LLVMSetThreadLocalMode(g.value, mode);
  2122. }
  2123. return g;
  2124. }
  2125. }
  2126. GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2127. return {};
  2128. }
  2129. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  2130. Token token = {Token_Ident};
  2131. isize name_len = prefix.len + 1 + 20;
  2132. auto suffix_id = cast(unsigned long long)id;
  2133. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  2134. gb_snprintf(text, name_len,
  2135. "%.*s-%llu", LIT(prefix), suffix_id);
  2136. text[name_len] = 0;
  2137. String s = make_string_c(text);
  2138. Type *t = alloc_type_array(elem_type, count);
  2139. lbValue g = {};
  2140. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  2141. g.type = alloc_type_pointer(t);
  2142. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  2143. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  2144. string_map_set(&m->members, s, g);
  2145. return g;
  2146. }
  2147. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2148. GB_ASSERT(cond != nullptr);
  2149. GB_ASSERT(true_block != nullptr);
  2150. GB_ASSERT(false_block != nullptr);
  2151. switch (cond->kind) {
  2152. case_ast_node(pe, ParenExpr, cond);
  2153. return lb_build_cond(p, pe->expr, true_block, false_block);
  2154. case_end;
  2155. case_ast_node(ue, UnaryExpr, cond);
  2156. if (ue->op.kind == Token_Not) {
  2157. return lb_build_cond(p, ue->expr, false_block, true_block);
  2158. }
  2159. case_end;
  2160. case_ast_node(be, BinaryExpr, cond);
  2161. if (be->op.kind == Token_CmpAnd) {
  2162. lbBlock *block = lb_create_block(p, "cmp.and");
  2163. lb_build_cond(p, be->left, block, false_block);
  2164. lb_start_block(p, block);
  2165. return lb_build_cond(p, be->right, true_block, false_block);
  2166. } else if (be->op.kind == Token_CmpOr) {
  2167. lbBlock *block = lb_create_block(p, "cmp.or");
  2168. lb_build_cond(p, be->left, true_block, block);
  2169. lb_start_block(p, block);
  2170. return lb_build_cond(p, be->right, true_block, false_block);
  2171. }
  2172. case_end;
  2173. }
  2174. lbValue v = {};
  2175. if (lb_is_expr_untyped_const(cond)) {
  2176. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2177. } else {
  2178. v = lb_build_expr(p, cond);
  2179. }
  2180. v = lb_emit_conv(p, v, t_llvm_bool);
  2181. lb_emit_if(p, v, true_block, false_block);
  2182. return v;
  2183. }
  2184. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index, bool force_no_init) {
  2185. GB_ASSERT(p->decl_block != p->curr_block);
  2186. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2187. char const *name = "";
  2188. if (e != nullptr) {
  2189. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2190. }
  2191. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2192. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2193. unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(llvm_type));
  2194. if (is_type_matrix(type)) {
  2195. alignment *= 2; // NOTE(bill): Just in case
  2196. }
  2197. LLVMSetAlignment(ptr, alignment);
  2198. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2199. if (!zero_init && !force_no_init) {
  2200. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  2201. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2202. if (kind == LLVMStructTypeKind) {
  2203. i64 sz = type_size_of(type);
  2204. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  2205. zero_init = true;
  2206. }
  2207. } else if (kind == LLVMArrayTypeKind) {
  2208. zero_init = true;
  2209. }
  2210. }
  2211. if (zero_init) {
  2212. lb_mem_zero_ptr(p, ptr, type, alignment);
  2213. }
  2214. lbValue val = {};
  2215. val.value = ptr;
  2216. val.type = alloc_type_pointer(type);
  2217. if (e != nullptr) {
  2218. lb_add_entity(p->module, e, val);
  2219. lb_add_debug_local_variable(p, ptr, type, e->token);
  2220. }
  2221. return lb_addr(val);
  2222. }
  2223. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2224. return lb_add_local(p, type, nullptr, zero_init);
  2225. }
  2226. lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  2227. lbAddr res = lb_add_local(p, type, nullptr, false, 0, true);
  2228. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  2229. return res;
  2230. }
  2231. void lb_set_linkage_from_entity_flags(lbModule *m, LLVMValueRef value, u64 flags) {
  2232. if (flags & EntityFlag_CustomLinkage_Internal) {
  2233. LLVMSetLinkage(value, LLVMInternalLinkage);
  2234. } else if (flags & EntityFlag_CustomLinkage_Strong) {
  2235. LLVMSetLinkage(value, LLVMExternalLinkage);
  2236. } else if (flags & EntityFlag_CustomLinkage_Weak) {
  2237. LLVMSetLinkage(value, LLVMExternalWeakLinkage);
  2238. } else if (flags & EntityFlag_CustomLinkage_LinkOnce) {
  2239. LLVMSetLinkage(value, LLVMLinkOnceAnyLinkage);
  2240. }
  2241. }