llvm_backend_general.cpp 79 KB

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