llvm_backend_general.cpp 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244
  1. gb_internal void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token);
  2. gb_internal LLVMValueRef llvm_const_string_internal(lbModule *m, Type *t, LLVMValueRef data, LLVMValueRef len);
  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. gb_internal 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->file) {
  19. module_name = gb_string_append_fmt(module_name, "-%u", m->file->id+1);
  20. } else if (m->pkg) {
  21. module_name = gb_string_appendc(module_name, "-");
  22. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  23. } else if (USE_SEPARATE_MODULES) {
  24. module_name = gb_string_appendc(module_name, "-builtin");
  25. }
  26. m->ctx = LLVMContextCreate();
  27. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  28. // m->debug_builder = nullptr;
  29. if (build_context.ODIN_DEBUG) {
  30. enum {DEBUG_METADATA_VERSION = 3};
  31. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  32. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  33. switch (build_context.metrics.os) {
  34. case TargetOs_windows:
  35. LLVMAddModuleFlag(m->mod,
  36. LLVMModuleFlagBehaviorWarning,
  37. "CodeView", 8,
  38. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  39. break;
  40. case TargetOs_darwin:
  41. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  42. LLVMAddModuleFlag(m->mod,
  43. LLVMModuleFlagBehaviorWarning,
  44. "Dwarf Version", 13,
  45. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  46. break;
  47. }
  48. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  49. }
  50. gbAllocator a = heap_allocator();
  51. map_init(&m->types);
  52. map_init(&m->func_raw_types);
  53. map_init(&m->struct_field_remapping);
  54. map_init(&m->values);
  55. map_init(&m->soa_values);
  56. string_map_init(&m->members);
  57. string_map_init(&m->procedures);
  58. string_map_init(&m->const_strings);
  59. map_init(&m->function_type_map);
  60. map_init(&m->equal_procs);
  61. map_init(&m->hasher_procs);
  62. map_init(&m->map_get_procs);
  63. map_init(&m->map_set_procs);
  64. if (build_context.use_separate_modules) {
  65. array_init(&m->procedures_to_generate, a, 0, 1<<10);
  66. map_init(&m->procedure_values, 1<<11);
  67. } else {
  68. array_init(&m->procedures_to_generate, a, 0, c->info.all_procedures.count);
  69. map_init(&m->procedure_values, c->info.all_procedures.count*2);
  70. }
  71. array_init(&m->global_procedures_to_create, a, 0, 1024);
  72. array_init(&m->global_types_to_create, a, 0, 1024);
  73. array_init(&m->missing_procedures_to_check, a, 0, 16);
  74. map_init(&m->debug_values);
  75. string_map_init(&m->objc_classes);
  76. string_map_init(&m->objc_selectors);
  77. map_init(&m->map_info_map, 0);
  78. map_init(&m->map_cell_info_map, 0);
  79. map_init(&m->exact_value_compound_literal_addr_map, 1024);
  80. m->const_dummy_builder = LLVMCreateBuilderInContext(m->ctx);
  81. }
  82. gb_internal bool lb_init_generator(lbGenerator *gen, Checker *c) {
  83. if (global_error_collector.count != 0) {
  84. return false;
  85. }
  86. isize tc = c->parser->total_token_count;
  87. if (tc < 2) {
  88. return false;
  89. }
  90. String init_fullpath = c->parser->init_fullpath;
  91. linker_data_init(gen, &c->info, init_fullpath);
  92. #if defined(GB_SYSTEM_OSX) && (LLVM_VERSION_MAJOR < 14)
  93. linker_enable_system_library_linking(gen);
  94. #endif
  95. gen->info = &c->info;
  96. map_init(&gen->modules, gen->info->packages.count*2);
  97. map_init(&gen->modules_through_ctx, gen->info->packages.count*2);
  98. map_init(&gen->anonymous_proc_lits, 1024);
  99. if (USE_SEPARATE_MODULES) {
  100. for (auto const &entry : gen->info->packages) {
  101. AstPackage *pkg = entry.value;
  102. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  103. m->pkg = pkg;
  104. m->gen = gen;
  105. map_set(&gen->modules, cast(void *)pkg, m);
  106. lb_init_module(m, c);
  107. if (build_context.module_per_file) {
  108. // NOTE(bill): Probably per file is not a good idea, so leave this for later
  109. for (AstFile *file : pkg->files) {
  110. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  111. m->file = file;
  112. m->pkg = pkg;
  113. m->gen = gen;
  114. map_set(&gen->modules, cast(void *)file, m);
  115. lb_init_module(m, c);
  116. }
  117. }
  118. }
  119. }
  120. gen->default_module.gen = gen;
  121. map_set(&gen->modules, cast(void *)1, &gen->default_module);
  122. lb_init_module(&gen->default_module, c);
  123. for (auto const &entry : gen->modules) {
  124. lbModule *m = entry.value;
  125. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  126. map_set(&gen->modules_through_ctx, ctx, m);
  127. }
  128. return true;
  129. }
  130. gb_internal lbValue lb_global_type_info_data_ptr(lbModule *m) {
  131. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  132. return v;
  133. }
  134. struct lbLoopData {
  135. lbAddr idx_addr;
  136. lbValue idx;
  137. lbBlock *body;
  138. lbBlock *done;
  139. lbBlock *loop;
  140. };
  141. struct lbCompoundLitElemTempData {
  142. Ast * expr;
  143. lbValue value;
  144. i64 elem_index;
  145. i64 elem_length;
  146. lbValue gep;
  147. };
  148. gb_internal lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32) {
  149. lbLoopData data = {};
  150. lbValue max = lb_const_int(p->module, t_int, count);
  151. data.idx_addr = lb_add_local_generated(p, index_type, true);
  152. data.body = lb_create_block(p, "loop.body");
  153. data.done = lb_create_block(p, "loop.done");
  154. data.loop = lb_create_block(p, "loop.loop");
  155. lb_emit_jump(p, data.loop);
  156. lb_start_block(p, data.loop);
  157. data.idx = lb_addr_load(p, data.idx_addr);
  158. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  159. lb_emit_if(p, cond, data.body, data.done);
  160. lb_start_block(p, data.body);
  161. return data;
  162. }
  163. gb_internal void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  164. if (data.idx_addr.addr.value != nullptr) {
  165. lb_emit_increment(p, data.idx_addr.addr);
  166. lb_emit_jump(p, data.loop);
  167. lb_start_block(p, data.done);
  168. }
  169. }
  170. gb_internal void lb_make_global_private_const(LLVMValueRef global_data) {
  171. LLVMSetLinkage(global_data, LLVMLinkerPrivateLinkage);
  172. LLVMSetUnnamedAddress(global_data, LLVMGlobalUnnamedAddr);
  173. LLVMSetGlobalConstant(global_data, true);
  174. }
  175. gb_internal void lb_make_global_private_const(lbAddr const &addr) {
  176. lb_make_global_private_const(addr.addr.value);
  177. }
  178. // This emits a GEP at 0, index
  179. gb_internal lbValue lb_emit_epi(lbProcedure *p, lbValue const &value, isize index) {
  180. GB_ASSERT(is_type_pointer(value.type));
  181. Type *type = type_deref(value.type);
  182. LLVMValueRef indices[2] = {
  183. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  184. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned long long)index, false),
  185. };
  186. LLVMTypeRef llvm_type = lb_type(p->module, type);
  187. lbValue res = {};
  188. Type *ptr = base_array_type(type);
  189. res.type = alloc_type_pointer(ptr);
  190. if (LLVMIsConstant(value.value)) {
  191. res.value = LLVMConstGEP2(llvm_type, value.value, indices, gb_count_of(indices));
  192. } else {
  193. res.value = LLVMBuildGEP2(p->builder, llvm_type, value.value, indices, gb_count_of(indices), "");
  194. }
  195. return res;
  196. }
  197. // This emits a GEP at 0, index
  198. gb_internal lbValue lb_emit_epi(lbModule *m, lbValue const &value, isize index) {
  199. GB_ASSERT(is_type_pointer(value.type));
  200. GB_ASSERT(LLVMIsConstant(value.value));
  201. Type *type = type_deref(value.type);
  202. LLVMValueRef indices[2] = {
  203. LLVMConstInt(lb_type(m, t_int), 0, false),
  204. LLVMConstInt(lb_type(m, t_int), cast(unsigned long long)index, false),
  205. };
  206. lbValue res = {};
  207. Type *ptr = base_array_type(type);
  208. res.type = alloc_type_pointer(ptr);
  209. res.value = LLVMConstGEP2(lb_type(m, type), value.value, indices, gb_count_of(indices));
  210. return res;
  211. }
  212. gb_internal LLVMValueRef llvm_zero(lbModule *m) {
  213. return LLVMConstInt(lb_type(m, t_int), 0, false);
  214. }
  215. gb_internal LLVMValueRef llvm_alloca(lbProcedure *p, LLVMTypeRef llvm_type, isize alignment, char const *name) {
  216. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  217. LLVMValueRef val = LLVMBuildAlloca(p->builder, llvm_type, name);
  218. LLVMSetAlignment(val, cast(unsigned int)alignment);
  219. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  220. return val;
  221. }
  222. gb_internal lbValue lb_zero(lbModule *m, Type *t) {
  223. lbValue v = {};
  224. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  225. v.type = t;
  226. return v;
  227. }
  228. gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned index) {
  229. LLVMValueRef res = agg;
  230. GB_ASSERT(LLVMIsConstant(res));
  231. res = LLVMBuildExtractValue(m->const_dummy_builder, res, index, "");
  232. GB_ASSERT(LLVMIsConstant(res));
  233. return res;
  234. }
  235. gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned *indices, isize count) {
  236. // return LLVMConstExtractValue(value, indices, count);
  237. LLVMValueRef res = agg;
  238. GB_ASSERT(LLVMIsConstant(res));
  239. for (isize i = 0; i < count; i++) {
  240. res = LLVMBuildExtractValue(m->const_dummy_builder, res, indices[i], "");
  241. GB_ASSERT(LLVMIsConstant(res));
  242. }
  243. return res;
  244. }
  245. gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned index) {
  246. GB_ASSERT(LLVMIsConstant(agg));
  247. GB_ASSERT(LLVMIsConstant(val));
  248. LLVMValueRef extracted_value = val;
  249. LLVMValueRef nested = llvm_const_extract_value(m, agg, index);
  250. GB_ASSERT(LLVMIsConstant(nested));
  251. extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, index, "");
  252. GB_ASSERT(LLVMIsConstant(extracted_value));
  253. return extracted_value;
  254. }
  255. gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned *indices, isize count) {
  256. GB_ASSERT(LLVMIsConstant(agg));
  257. GB_ASSERT(LLVMIsConstant(val));
  258. GB_ASSERT(count > 0);
  259. LLVMValueRef extracted_value = val;
  260. for (isize i = count-1; i >= 0; i--) {
  261. LLVMValueRef nested = llvm_const_extract_value(m, agg, indices, i);
  262. GB_ASSERT(LLVMIsConstant(nested));
  263. extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, indices[i], "");
  264. }
  265. GB_ASSERT(LLVMIsConstant(extracted_value));
  266. return extracted_value;
  267. }
  268. gb_internal LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  269. lbValue v = lb_find_or_add_entity_string(m, str);
  270. unsigned indices[1] = {0};
  271. return llvm_const_extract_value(m, v.value, indices, gb_count_of(indices));
  272. }
  273. gb_internal bool lb_is_instr_terminating(LLVMValueRef instr) {
  274. if (instr != nullptr) {
  275. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  276. switch (op) {
  277. case LLVMRet:
  278. case LLVMBr:
  279. case LLVMSwitch:
  280. case LLVMIndirectBr:
  281. case LLVMInvoke:
  282. case LLVMUnreachable:
  283. case LLVMCallBr:
  284. return true;
  285. }
  286. }
  287. return false;
  288. }
  289. gb_internal lbModule *lb_module_of_expr(lbGenerator *gen, Ast *expr) {
  290. GB_ASSERT(expr != nullptr);
  291. lbModule **found = nullptr;
  292. AstFile *file = expr->file();
  293. if (file) {
  294. found = map_get(&gen->modules, cast(void *)file);
  295. if (found) {
  296. return *found;
  297. }
  298. if (file->pkg) {
  299. found = map_get(&gen->modules, cast(void *)file->pkg);
  300. if (found) {
  301. return *found;
  302. }
  303. }
  304. }
  305. return &gen->default_module;
  306. }
  307. gb_internal lbModule *lb_module_of_entity(lbGenerator *gen, Entity *e) {
  308. GB_ASSERT(e != nullptr);
  309. lbModule **found = nullptr;
  310. if (e->kind == Entity_Procedure &&
  311. e->decl_info &&
  312. e->decl_info->code_gen_module) {
  313. return e->decl_info->code_gen_module;
  314. }
  315. if (e->file) {
  316. found = map_get(&gen->modules, cast(void *)e->file);
  317. if (found) {
  318. return *found;
  319. }
  320. }
  321. if (e->pkg) {
  322. found = map_get(&gen->modules, cast(void *)e->pkg);
  323. if (found) {
  324. return *found;
  325. }
  326. }
  327. return &gen->default_module;
  328. }
  329. gb_internal lbAddr lb_addr(lbValue addr) {
  330. lbAddr v = {lbAddr_Default, addr};
  331. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  332. GB_ASSERT(is_type_pointer(addr.type));
  333. v.kind = lbAddr_RelativePointer;
  334. } else if (addr.type != nullptr && is_type_relative_multi_pointer(type_deref(addr.type))) {
  335. GB_ASSERT(is_type_pointer(addr.type) ||
  336. is_type_multi_pointer(addr.type));
  337. v.kind = lbAddr_RelativePointer;
  338. }
  339. return v;
  340. }
  341. gb_internal lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  342. GB_ASSERT(is_type_pointer(addr.type));
  343. Type *mt = type_deref(addr.type);
  344. GB_ASSERT(is_type_map(mt));
  345. lbAddr v = {lbAddr_Map, addr};
  346. v.map.key = map_key;
  347. v.map.type = map_type;
  348. v.map.result = map_result;
  349. return v;
  350. }
  351. gb_internal lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  352. lbAddr v = {lbAddr_SoaVariable, addr};
  353. v.soa.index = index;
  354. v.soa.index_expr = index_expr;
  355. return v;
  356. }
  357. gb_internal lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  358. GB_ASSERT(is_type_array(array_type) || is_type_simd_vector(array_type));
  359. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  360. lbAddr v = {lbAddr_Swizzle, addr};
  361. v.swizzle.type = array_type;
  362. v.swizzle.count = swizzle_count;
  363. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  364. return v;
  365. }
  366. gb_internal lbAddr lb_addr_swizzle_large(lbValue addr, Type *array_type, Slice<i32> const &swizzle_indices) {
  367. GB_ASSERT_MSG(is_type_array(array_type), "%s", type_to_string(array_type));
  368. lbAddr v = {lbAddr_SwizzleLarge, addr};
  369. v.swizzle_large.type = array_type;
  370. v.swizzle_large.indices = swizzle_indices;
  371. return v;
  372. }
  373. gb_internal lbAddr lb_addr_bit_field(lbValue addr, Type *type, i64 bit_offset, i64 bit_size) {
  374. GB_ASSERT(is_type_pointer(addr.type));
  375. Type *mt = type_deref(addr.type);
  376. GB_ASSERT_MSG(is_type_bit_field(mt), "%s", type_to_string(mt));
  377. lbAddr v = {lbAddr_BitField, addr};
  378. v.bitfield.type = type;
  379. v.bitfield.bit_offset = bit_offset;
  380. v.bitfield.bit_size = bit_size;
  381. return v;
  382. }
  383. gb_internal Type *lb_addr_type(lbAddr const &addr) {
  384. if (addr.addr.value == nullptr) {
  385. return nullptr;
  386. }
  387. switch (addr.kind) {
  388. case lbAddr_Map:
  389. {
  390. Type *t = base_type(addr.map.type);
  391. GB_ASSERT(is_type_map(t));
  392. return t->Map.value;
  393. }
  394. case lbAddr_Swizzle:
  395. return addr.swizzle.type;
  396. case lbAddr_SwizzleLarge:
  397. return addr.swizzle_large.type;
  398. case lbAddr_Context:
  399. if (addr.ctx.sel.index.count > 0) {
  400. Type *t = t_context;
  401. for_array(i, addr.ctx.sel.index) {
  402. GB_ASSERT(is_type_struct(t));
  403. t = base_type(t)->Struct.fields[addr.ctx.sel.index[i]]->type;
  404. }
  405. return t;
  406. }
  407. break;
  408. }
  409. return type_deref(addr.addr.type);
  410. }
  411. gb_internal lbValue lb_relative_pointer_to_pointer(lbProcedure *p, lbAddr const &addr) {
  412. GB_ASSERT(addr.kind == lbAddr_RelativePointer);
  413. Type *t = base_type(lb_addr_type(addr));
  414. GB_ASSERT(is_type_relative_pointer(t) || is_type_relative_multi_pointer(t));
  415. Type *pointer_type = nullptr;
  416. Type *base_integer = nullptr;
  417. if (t->kind == Type_RelativePointer) {
  418. pointer_type = t->RelativePointer.pointer_type;
  419. base_integer = t->RelativePointer.base_integer;
  420. } else if (t->kind == Type_RelativeMultiPointer) {
  421. pointer_type = t->RelativeMultiPointer.pointer_type;
  422. base_integer = t->RelativeMultiPointer.base_integer;
  423. }
  424. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  425. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(base_integer));
  426. offset = lb_emit_load(p, offset);
  427. if (!is_type_unsigned(base_integer)) {
  428. offset = lb_emit_conv(p, offset, t_i64);
  429. }
  430. offset = lb_emit_conv(p, offset, t_uintptr);
  431. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  432. absolute_ptr = lb_emit_conv(p, absolute_ptr, pointer_type);
  433. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, base_integer));
  434. // NOTE(bill): nil check
  435. lbValue nil_ptr = lb_const_nil(p->module, pointer_type);
  436. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  437. return final_ptr;
  438. }
  439. gb_internal lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  440. if (addr.addr.value == nullptr) {
  441. GB_PANIC("Illegal addr -> nullptr");
  442. return {};
  443. }
  444. switch (addr.kind) {
  445. case lbAddr_Map:
  446. return lb_internal_dynamic_map_get_ptr(p, addr.addr, addr.map.key);
  447. case lbAddr_RelativePointer:
  448. return lb_relative_pointer_to_pointer(p, addr);
  449. case lbAddr_SoaVariable:
  450. // TODO(bill): FIX THIS HACK
  451. return lb_address_from_load(p, lb_addr_load(p, addr));
  452. case lbAddr_Context:
  453. GB_PANIC("lbAddr_Context should be handled elsewhere");
  454. break;
  455. case lbAddr_Swizzle:
  456. case lbAddr_SwizzleLarge:
  457. // TOOD(bill): is this good enough logic?
  458. break;
  459. }
  460. return addr.addr;
  461. }
  462. gb_internal lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  463. lbAddr addr = lb_build_addr(p, expr);
  464. if (addr.kind == lbAddr_RelativePointer) {
  465. return addr.addr;
  466. }
  467. return lb_addr_get_ptr(p, addr);
  468. }
  469. gb_internal void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  470. if (build_context.no_bounds_check) {
  471. return;
  472. }
  473. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  474. return;
  475. }
  476. TEMPORARY_ALLOCATOR_GUARD();
  477. index = lb_emit_conv(p, index, t_int);
  478. len = lb_emit_conv(p, len, t_int);
  479. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  480. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  481. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  482. auto args = array_make<lbValue>(temporary_allocator(), 5);
  483. args[0] = file;
  484. args[1] = line;
  485. args[2] = column;
  486. args[3] = index;
  487. args[4] = len;
  488. lb_emit_runtime_call(p, "bounds_check_error", args);
  489. }
  490. gb_internal void lb_emit_matrix_bounds_check(lbProcedure *p, Token token, lbValue row_index, lbValue column_index, lbValue row_count, lbValue column_count) {
  491. if (build_context.no_bounds_check) {
  492. return;
  493. }
  494. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  495. return;
  496. }
  497. TEMPORARY_ALLOCATOR_GUARD();
  498. row_index = lb_emit_conv(p, row_index, t_int);
  499. column_index = lb_emit_conv(p, column_index, t_int);
  500. row_count = lb_emit_conv(p, row_count, t_int);
  501. column_count = lb_emit_conv(p, column_count, t_int);
  502. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  503. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  504. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  505. auto args = array_make<lbValue>(temporary_allocator(), 7);
  506. args[0] = file;
  507. args[1] = line;
  508. args[2] = column;
  509. args[3] = row_index;
  510. args[4] = column_index;
  511. args[5] = row_count;
  512. args[6] = column_count;
  513. lb_emit_runtime_call(p, "matrix_bounds_check_error", args);
  514. }
  515. gb_internal void lb_emit_multi_pointer_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high) {
  516. if (build_context.no_bounds_check) {
  517. return;
  518. }
  519. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  520. return;
  521. }
  522. low = lb_emit_conv(p, low, t_int);
  523. high = lb_emit_conv(p, high, t_int);
  524. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  525. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  526. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  527. auto args = array_make<lbValue>(permanent_allocator(), 5);
  528. args[0] = file;
  529. args[1] = line;
  530. args[2] = column;
  531. args[3] = low;
  532. args[4] = high;
  533. lb_emit_runtime_call(p, "multi_pointer_slice_expr_error", args);
  534. }
  535. gb_internal void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  536. if (build_context.no_bounds_check) {
  537. return;
  538. }
  539. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  540. return;
  541. }
  542. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  543. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  544. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  545. high = lb_emit_conv(p, high, t_int);
  546. if (!lower_value_used) {
  547. auto args = array_make<lbValue>(permanent_allocator(), 5);
  548. args[0] = file;
  549. args[1] = line;
  550. args[2] = column;
  551. args[3] = high;
  552. args[4] = len;
  553. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  554. } else {
  555. // No need to convert unless used
  556. low = lb_emit_conv(p, low, t_int);
  557. auto args = array_make<lbValue>(permanent_allocator(), 6);
  558. args[0] = file;
  559. args[1] = line;
  560. args[2] = column;
  561. args[3] = low;
  562. args[4] = high;
  563. args[5] = len;
  564. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  565. }
  566. }
  567. gb_internal unsigned lb_try_get_alignment(LLVMValueRef addr_ptr, unsigned default_alignment) {
  568. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  569. return LLVMGetAlignment(addr_ptr);
  570. }
  571. return default_alignment;
  572. }
  573. gb_internal bool lb_try_update_alignment(LLVMValueRef addr_ptr, unsigned alignment) {
  574. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  575. if (LLVMGetAlignment(addr_ptr) < alignment) {
  576. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  577. LLVMSetAlignment(addr_ptr, alignment);
  578. }
  579. }
  580. return LLVMGetAlignment(addr_ptr) >= alignment;
  581. }
  582. return false;
  583. }
  584. gb_internal bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  585. return lb_try_update_alignment(ptr.value, alignment);
  586. }
  587. gb_internal bool lb_can_try_to_inline_array_arith(Type *t) {
  588. return type_size_of(t) <= build_context.max_simd_align;
  589. }
  590. gb_internal bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  591. Type *array_type = base_type(type_deref(ptr.type));
  592. GB_ASSERT(is_type_array_like(array_type));
  593. i64 count = get_array_type_count(array_type);
  594. Type *elem_type = base_array_type(array_type);
  595. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  596. if (lb_can_try_to_inline_array_arith(array_type) &&
  597. is_type_valid_vector_elem(elem_type)) {
  598. // Try to treat it like a vector if possible
  599. bool possible = false;
  600. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  601. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  602. LLVMValueRef addr_ptr = ptr.value;
  603. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  604. unsigned alignment = LLVMGetAlignment(addr_ptr);
  605. alignment = gb_max(alignment, vector_alignment);
  606. possible = true;
  607. LLVMSetAlignment(addr_ptr, alignment);
  608. } else if (LLVMIsALoadInst(addr_ptr)) {
  609. unsigned alignment = LLVMGetAlignment(addr_ptr);
  610. possible = alignment >= vector_alignment;
  611. }
  612. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  613. // then it cannot be treated as a vector
  614. if (possible) {
  615. if (vector_type_) *vector_type_ =vector_type;
  616. return true;
  617. }
  618. }
  619. return false;
  620. }
  621. gb_internal void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  622. if (addr.addr.value == nullptr) {
  623. return;
  624. }
  625. GB_ASSERT(value.type != nullptr);
  626. if (is_type_untyped_uninit(value.type)) {
  627. Type *t = lb_addr_type(addr);
  628. value.type = t;
  629. value.value = LLVMGetUndef(lb_type(p->module, t));
  630. } else if (is_type_untyped_nil(value.type)) {
  631. Type *t = lb_addr_type(addr);
  632. value.type = t;
  633. value.value = LLVMConstNull(lb_type(p->module, t));
  634. }
  635. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  636. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  637. }
  638. if (addr.kind == lbAddr_BitField) {
  639. lbValue dst = addr.addr;
  640. if (is_type_endian_big(addr.bitfield.type)) {
  641. i64 shift_amount = 8*type_size_of(value.type) - addr.bitfield.bit_size;
  642. lbValue shifted_value = value;
  643. shifted_value.value = LLVMBuildLShr(p->builder,
  644. shifted_value.value,
  645. LLVMConstInt(LLVMTypeOf(shifted_value.value), shift_amount, false), "");
  646. lbValue src = lb_address_from_load_or_generate_local(p, shifted_value);
  647. auto args = array_make<lbValue>(temporary_allocator(), 4);
  648. args[0] = dst;
  649. args[1] = src;
  650. args[2] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  651. args[3] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  652. lb_emit_runtime_call(p, "__write_bits", args);
  653. } else if ((addr.bitfield.bit_offset % 8) == 0 &&
  654. (addr.bitfield.bit_size % 8) == 0) {
  655. lbValue src = lb_address_from_load_or_generate_local(p, value);
  656. lbValue byte_offset = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset/8);
  657. lbValue byte_size = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size/8);
  658. lbValue dst_offset = lb_emit_conv(p, dst, t_u8_ptr);
  659. dst_offset = lb_emit_ptr_offset(p, dst_offset, byte_offset);
  660. lb_mem_copy_non_overlapping(p, dst_offset, src, byte_size);
  661. } else {
  662. lbValue src = lb_address_from_load_or_generate_local(p, value);
  663. auto args = array_make<lbValue>(temporary_allocator(), 4);
  664. args[0] = dst;
  665. args[1] = src;
  666. args[2] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  667. args[3] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  668. lb_emit_runtime_call(p, "__write_bits", args);
  669. }
  670. return;
  671. } else if (addr.kind == lbAddr_RelativePointer) {
  672. Type *rel_ptr = base_type(lb_addr_type(addr));
  673. GB_ASSERT(rel_ptr->kind == Type_RelativePointer ||
  674. rel_ptr->kind == Type_RelativeMultiPointer);
  675. Type *pointer_type = nullptr;
  676. Type *base_integer = nullptr;
  677. if (rel_ptr->kind == Type_RelativePointer) {
  678. pointer_type = rel_ptr->RelativePointer.pointer_type;
  679. base_integer = rel_ptr->RelativePointer.base_integer;
  680. } else if (rel_ptr->kind == Type_RelativeMultiPointer) {
  681. pointer_type = rel_ptr->RelativeMultiPointer.pointer_type;
  682. base_integer = rel_ptr->RelativeMultiPointer.base_integer;
  683. }
  684. value = lb_emit_conv(p, value, pointer_type);
  685. GB_ASSERT(is_type_pointer(addr.addr.type));
  686. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  687. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  688. lbValue offset = {};
  689. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  690. offset.type = t_uintptr;
  691. if (!is_type_unsigned(base_integer)) {
  692. offset = lb_emit_conv(p, offset, t_i64);
  693. }
  694. offset = lb_emit_conv(p, offset, base_integer);
  695. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(base_integer));
  696. offset = lb_emit_select(p,
  697. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  698. lb_const_nil(p->module, base_integer),
  699. offset
  700. );
  701. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  702. return;
  703. } else if (addr.kind == lbAddr_Map) {
  704. lb_internal_dynamic_map_set(p, addr.addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  705. return;
  706. } else if (addr.kind == lbAddr_Context) {
  707. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  708. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  709. // This has to be done manually since the optimizer cannot determine when this is possible
  710. bool create_new = true;
  711. for_array(i, p->context_stack) {
  712. lbContextData *ctx_data = &p->context_stack[i];
  713. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  714. if (ctx_data->uses > 0) {
  715. create_new = true;
  716. } else if (p->scope_index > ctx_data->scope_index) {
  717. create_new = true;
  718. } else {
  719. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  720. create_new = false;
  721. }
  722. break;
  723. }
  724. }
  725. lbValue next = {};
  726. if (create_new) {
  727. lbValue old = lb_addr_load(p, old_addr);
  728. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  729. lb_addr_store(p, next_addr, old);
  730. lb_push_context_onto_stack(p, next_addr);
  731. next = next_addr.addr;
  732. } else {
  733. next = old_addr.addr;
  734. }
  735. if (addr.ctx.sel.index.count > 0) {
  736. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  737. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  738. lb_emit_store(p, lhs, rhs);
  739. } else {
  740. lbValue lhs = next;
  741. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  742. lb_emit_store(p, lhs, rhs);
  743. }
  744. return;
  745. } else if (addr.kind == lbAddr_SoaVariable) {
  746. Type *t = type_deref(addr.addr.type);
  747. t = base_type(t);
  748. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  749. Type *elem_type = t->Struct.soa_elem;
  750. value = lb_emit_conv(p, value, elem_type);
  751. elem_type = base_type(elem_type);
  752. lbValue index = addr.soa.index;
  753. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  754. Type *t = base_type(type_deref(addr.addr.type));
  755. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  756. lbValue len = lb_soa_struct_len(p, addr.addr);
  757. if (addr.soa.index_expr != nullptr) {
  758. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  759. }
  760. }
  761. isize field_count = 0;
  762. switch (elem_type->kind) {
  763. case Type_Struct:
  764. field_count = elem_type->Struct.fields.count;
  765. break;
  766. case Type_Array:
  767. field_count = cast(isize)elem_type->Array.count;
  768. break;
  769. }
  770. for (isize i = 0; i < field_count; i++) {
  771. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  772. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  773. if (t->Struct.soa_kind == StructSoa_Fixed) {
  774. dst = lb_emit_array_ep(p, dst, index);
  775. lb_emit_store(p, dst, src);
  776. } else {
  777. lbValue field = lb_emit_load(p, dst);
  778. dst = lb_emit_ptr_offset(p, field, index);
  779. lb_emit_store(p, dst, src);
  780. }
  781. }
  782. return;
  783. } else if (addr.kind == lbAddr_Swizzle) {
  784. GB_ASSERT(addr.swizzle.count <= 4);
  785. GB_ASSERT(value.value != nullptr);
  786. value = lb_emit_conv(p, value, lb_addr_type(addr));
  787. lbValue dst = lb_addr_get_ptr(p, addr);
  788. lbValue src = lb_address_from_load_or_generate_local(p, value);
  789. {
  790. lbValue src_ptrs[4] = {};
  791. lbValue src_loads[4] = {};
  792. lbValue dst_ptrs[4] = {};
  793. for (u8 i = 0; i < addr.swizzle.count; i++) {
  794. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  795. }
  796. for (u8 i = 0; i < addr.swizzle.count; i++) {
  797. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  798. }
  799. for (u8 i = 0; i < addr.swizzle.count; i++) {
  800. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  801. }
  802. for (u8 i = 0; i < addr.swizzle.count; i++) {
  803. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  804. }
  805. }
  806. return;
  807. } else if (addr.kind == lbAddr_SwizzleLarge) {
  808. GB_ASSERT(value.value != nullptr);
  809. value = lb_emit_conv(p, value, lb_addr_type(addr));
  810. lbValue dst = lb_addr_get_ptr(p, addr);
  811. lbValue src = lb_address_from_load_or_generate_local(p, value);
  812. for_array(i, addr.swizzle_large.indices) {
  813. lbValue src_ptr = lb_emit_array_epi(p, src, i);
  814. lbValue dst_ptr = lb_emit_array_epi(p, dst, addr.swizzle_large.indices[i]);
  815. lbValue src_load = lb_emit_load(p, src_ptr);
  816. lb_emit_store(p, dst_ptr, src_load);
  817. }
  818. return;
  819. }
  820. GB_ASSERT(value.value != nullptr);
  821. value = lb_emit_conv(p, value, lb_addr_type(addr));
  822. lb_emit_store(p, addr.addr, value);
  823. }
  824. gb_internal bool lb_is_type_proc_recursive(Type *t) {
  825. for (;;) {
  826. if (t == nullptr) {
  827. return false;
  828. }
  829. switch (t->kind) {
  830. case Type_Named:
  831. t = t->Named.base;
  832. break;
  833. case Type_Pointer:
  834. t = t->Pointer.elem;
  835. break;
  836. case Type_Proc:
  837. return true;
  838. default:
  839. return false;
  840. }
  841. }
  842. }
  843. gb_internal void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  844. GB_ASSERT(value.value != nullptr);
  845. if (LLVMIsUndef(value.value)) {
  846. return;
  847. }
  848. Type *a = type_deref(ptr.type, true);
  849. if (LLVMIsNull(value.value)) {
  850. LLVMTypeRef src_t = llvm_addr_type(p->module, ptr);
  851. if (is_type_proc(a)) {
  852. LLVMTypeRef rawptr_type = lb_type(p->module, t_rawptr);
  853. LLVMTypeRef rawptr_ptr_type = LLVMPointerType(rawptr_type, 0);
  854. LLVMBuildStore(p->builder, LLVMConstNull(rawptr_type), LLVMBuildBitCast(p->builder, ptr.value, rawptr_ptr_type, ""));
  855. } else if (lb_sizeof(src_t) <= lb_max_zero_init_size()) {
  856. LLVMBuildStore(p->builder, LLVMConstNull(src_t), ptr.value);
  857. } else {
  858. lb_mem_zero_ptr(p, ptr.value, a, 1);
  859. }
  860. return;
  861. }
  862. if (is_type_boolean(a)) {
  863. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  864. value = lb_emit_conv(p, value, a);
  865. }
  866. Type *ca = core_type(a);
  867. if (ca->kind == Type_Basic) {
  868. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  869. }
  870. enum {MAX_STORE_SIZE = 64};
  871. if (lb_sizeof(LLVMTypeOf(value.value)) > MAX_STORE_SIZE) {
  872. if (!p->in_multi_assignment && LLVMIsALoadInst(value.value)) {
  873. LLVMValueRef dst_ptr = ptr.value;
  874. LLVMValueRef src_ptr_original = LLVMGetOperand(value.value, 0);
  875. LLVMValueRef src_ptr = LLVMBuildPointerCast(p->builder, src_ptr_original, LLVMTypeOf(dst_ptr), "");
  876. LLVMBuildMemMove(p->builder,
  877. dst_ptr, lb_try_get_alignment(dst_ptr, 1),
  878. src_ptr, lb_try_get_alignment(src_ptr_original, 1),
  879. LLVMConstInt(LLVMInt64TypeInContext(p->module->ctx), lb_sizeof(LLVMTypeOf(value.value)), false));
  880. return;
  881. } else if (LLVMIsConstant(value.value)) {
  882. lbAddr addr = lb_add_global_generated(p->module, value.type, value, nullptr);
  883. lb_make_global_private_const(addr);
  884. LLVMValueRef dst_ptr = ptr.value;
  885. LLVMValueRef src_ptr = addr.addr.value;
  886. src_ptr = LLVMBuildPointerCast(p->builder, src_ptr, LLVMTypeOf(dst_ptr), "");
  887. LLVMBuildMemMove(p->builder,
  888. dst_ptr, lb_try_get_alignment(dst_ptr, 1),
  889. src_ptr, lb_try_get_alignment(src_ptr, 1),
  890. LLVMConstInt(LLVMInt64TypeInContext(p->module->ctx), lb_sizeof(LLVMTypeOf(value.value)), false));
  891. return;
  892. }
  893. }
  894. LLVMValueRef instr = nullptr;
  895. if (lb_is_type_proc_recursive(a)) {
  896. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  897. // stored as regular pointer with no procedure information
  898. LLVMTypeRef rawptr_type = lb_type(p->module, t_rawptr);
  899. LLVMTypeRef rawptr_ptr_type = LLVMPointerType(rawptr_type, 0);
  900. instr = LLVMBuildStore(p->builder,
  901. LLVMBuildPointerCast(p->builder, value.value, rawptr_type, ""),
  902. LLVMBuildPointerCast(p->builder, ptr.value, rawptr_ptr_type, ""));
  903. } else {
  904. Type *ca = core_type(a);
  905. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  906. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  907. } else {
  908. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  909. }
  910. instr = LLVMBuildStore(p->builder, value.value, ptr.value);
  911. }
  912. // LLVMSetVolatile(instr, p->in_multi_assignment);
  913. }
  914. gb_internal LLVMTypeRef llvm_addr_type(lbModule *module, lbValue addr_val) {
  915. return lb_type(module, type_deref(addr_val.type));
  916. }
  917. gb_internal lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  918. GB_ASSERT(value.value != nullptr);
  919. if (is_type_multi_pointer(value.type)) {
  920. Type *vt = base_type(value.type);
  921. GB_ASSERT(vt->kind == Type_MultiPointer);
  922. Type *t = vt->MultiPointer.elem;
  923. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(p->module, t), value.value, "");
  924. return lbValue{v, t};
  925. } else if (is_type_soa_pointer(value.type)) {
  926. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  927. lbValue idx = lb_emit_struct_ev(p, value, 1);
  928. lbAddr addr = lb_addr_soa_variable(ptr, idx, nullptr);
  929. return lb_addr_load(p, addr);
  930. }
  931. GB_ASSERT(is_type_pointer(value.type));
  932. Type *t = type_deref(value.type);
  933. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(p->module, t), value.value, "");
  934. // If it is not an instruction it isn't a GEP, so we don't need to track alignment in the metadata,
  935. // which is not possible anyway (only LLVM instructions can have metadata).
  936. if (LLVMIsAInstruction(value.value)) {
  937. u64 is_packed = lb_get_metadata_custom_u64(p->module, value.value, ODIN_METADATA_IS_PACKED);
  938. if (is_packed != 0) {
  939. LLVMSetAlignment(v, 1);
  940. }
  941. }
  942. return lbValue{v, t};
  943. }
  944. gb_internal lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  945. GB_ASSERT(addr.addr.value != nullptr);
  946. if (addr.kind == lbAddr_BitField) {
  947. Type *ct = core_type(addr.bitfield.type);
  948. bool do_mask = false;
  949. if (is_type_unsigned(ct) || is_type_boolean(ct)) {
  950. // Mask
  951. if (addr.bitfield.bit_size != 8*type_size_of(ct)) {
  952. do_mask = true;
  953. }
  954. }
  955. i64 total_bitfield_bit_size = 8*type_size_of(lb_addr_type(addr));
  956. i64 dst_byte_size = type_size_of(addr.bitfield.type);
  957. lbAddr dst = lb_add_local_generated(p, addr.bitfield.type, true);
  958. lbValue src = addr.addr;
  959. lbValue bit_offset = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  960. lbValue bit_size = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  961. lbValue byte_offset = lb_const_int(p->module, t_uintptr, (addr.bitfield.bit_offset+7)/8);
  962. lbValue byte_size = lb_const_int(p->module, t_uintptr, (addr.bitfield.bit_size+7)/8);
  963. GB_ASSERT(type_size_of(addr.bitfield.type) >= ((addr.bitfield.bit_size+7)/8));
  964. lbValue r = {};
  965. if (is_type_endian_big(addr.bitfield.type)) {
  966. auto args = array_make<lbValue>(temporary_allocator(), 4);
  967. args[0] = dst.addr;
  968. args[1] = src;
  969. args[2] = bit_offset;
  970. args[3] = bit_size;
  971. lb_emit_runtime_call(p, "__read_bits", args);
  972. LLVMValueRef shift_amount = LLVMConstInt(
  973. lb_type(p->module, lb_addr_type(dst)),
  974. 8*dst_byte_size - addr.bitfield.bit_size,
  975. false
  976. );
  977. r = lb_addr_load(p, dst);
  978. r.value = LLVMBuildShl(p->builder, r.value, shift_amount, "");
  979. } else if ((addr.bitfield.bit_offset % 8) == 0) {
  980. lbValue copy_size = byte_size;
  981. lbValue src_offset = lb_emit_conv(p, src, t_u8_ptr);
  982. src_offset = lb_emit_ptr_offset(p, src_offset, byte_offset);
  983. if (addr.bitfield.bit_offset + 8*dst_byte_size <= total_bitfield_bit_size) {
  984. do_mask = true;
  985. copy_size = lb_const_int(p->module, t_uintptr, dst_byte_size);
  986. }
  987. lb_mem_copy_non_overlapping(p, dst.addr, src_offset, copy_size, false);
  988. r = lb_addr_load(p, dst);
  989. } else {
  990. auto args = array_make<lbValue>(temporary_allocator(), 4);
  991. args[0] = dst.addr;
  992. args[1] = src;
  993. args[2] = bit_offset;
  994. args[3] = bit_size;
  995. lb_emit_runtime_call(p, "__read_bits", args);
  996. r = lb_addr_load(p, dst);
  997. }
  998. Type *t = addr.bitfield.type;
  999. if (do_mask) {
  1000. GB_ASSERT(addr.bitfield.bit_size <= 8*type_size_of(ct));
  1001. lbValue mask = lb_const_int(p->module, t, (1ull<<cast(u64)addr.bitfield.bit_size)-1);
  1002. r = lb_emit_arith(p, Token_And, r, mask, t);
  1003. }
  1004. if (!is_type_unsigned(ct) && !is_type_boolean(ct)) {
  1005. // Sign extension
  1006. // m := 1<<(bit_size-1)
  1007. // r = (r XOR m) - m
  1008. lbValue m = lb_const_int(p->module, t, 1ull<<(addr.bitfield.bit_size-1));
  1009. r = lb_emit_arith(p, Token_Xor, r, m, t);
  1010. r = lb_emit_arith(p, Token_Sub, r, m, t);
  1011. }
  1012. return r;
  1013. } else if (addr.kind == lbAddr_RelativePointer) {
  1014. Type *rel_ptr = base_type(lb_addr_type(addr));
  1015. Type *base_integer = nullptr;
  1016. Type *pointer_type = nullptr;
  1017. GB_ASSERT(rel_ptr->kind == Type_RelativePointer ||
  1018. rel_ptr->kind == Type_RelativeMultiPointer);
  1019. if (rel_ptr->kind == Type_RelativePointer) {
  1020. base_integer = rel_ptr->RelativePointer.base_integer;
  1021. pointer_type = rel_ptr->RelativePointer.pointer_type;
  1022. } else if (rel_ptr->kind == Type_RelativeMultiPointer) {
  1023. base_integer = rel_ptr->RelativeMultiPointer.base_integer;
  1024. pointer_type = rel_ptr->RelativeMultiPointer.pointer_type;
  1025. }
  1026. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  1027. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(base_integer));
  1028. offset = lb_emit_load(p, offset);
  1029. if (!is_type_unsigned(base_integer)) {
  1030. offset = lb_emit_conv(p, offset, t_i64);
  1031. }
  1032. offset = lb_emit_conv(p, offset, t_uintptr);
  1033. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  1034. absolute_ptr = lb_emit_conv(p, absolute_ptr, pointer_type);
  1035. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, base_integer));
  1036. // NOTE(bill): nil check
  1037. lbValue nil_ptr = lb_const_nil(p->module, pointer_type);
  1038. lbValue final_ptr = {};
  1039. final_ptr.type = absolute_ptr.type;
  1040. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  1041. if (rel_ptr->kind == Type_RelativeMultiPointer) {
  1042. return final_ptr;
  1043. }
  1044. return lb_emit_load(p, final_ptr);
  1045. } else if (addr.kind == lbAddr_Map) {
  1046. Type *map_type = base_type(type_deref(addr.addr.type));
  1047. GB_ASSERT(map_type->kind == Type_Map);
  1048. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  1049. lbValue ptr = lb_internal_dynamic_map_get_ptr(p, addr.addr, addr.map.key);
  1050. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  1051. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  1052. lbBlock *then = lb_create_block(p, "map.get.then");
  1053. lbBlock *done = lb_create_block(p, "map.get.done");
  1054. lb_emit_if(p, ok, then, done);
  1055. lb_start_block(p, then);
  1056. {
  1057. // TODO(bill): mem copy it instead?
  1058. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  1059. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  1060. lb_emit_store(p, gep0, lb_emit_load(p, value));
  1061. }
  1062. lb_emit_jump(p, done);
  1063. lb_start_block(p, done);
  1064. if (is_type_tuple(addr.map.result)) {
  1065. return lb_addr_load(p, v);
  1066. } else {
  1067. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  1068. return lb_emit_load(p, single);
  1069. }
  1070. } else if (addr.kind == lbAddr_Context) {
  1071. lbValue a = addr.addr;
  1072. for_array(i, p->context_stack) {
  1073. lbContextData *ctx_data = &p->context_stack[i];
  1074. if (ctx_data->ctx.addr.value == a.value) {
  1075. ctx_data->uses += 1;
  1076. break;
  1077. }
  1078. }
  1079. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  1080. if (addr.ctx.sel.index.count > 0) {
  1081. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  1082. return lb_emit_load(p, b);
  1083. } else {
  1084. return lb_emit_load(p, a);
  1085. }
  1086. } else if (addr.kind == lbAddr_SoaVariable) {
  1087. Type *t = type_deref(addr.addr.type);
  1088. t = base_type(t);
  1089. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  1090. Type *elem = t->Struct.soa_elem;
  1091. lbValue len = {};
  1092. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1093. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  1094. } else {
  1095. lbValue v = lb_emit_load(p, addr.addr);
  1096. len = lb_soa_struct_len(p, v);
  1097. }
  1098. lbAddr res = lb_add_local_generated(p, elem, true);
  1099. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  1100. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  1101. }
  1102. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1103. for_array(i, t->Struct.fields) {
  1104. Entity *field = t->Struct.fields[i];
  1105. Type *base_type = field->type;
  1106. GB_ASSERT(base_type->kind == Type_Array);
  1107. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  1108. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  1109. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  1110. lbValue src = lb_emit_load(p, src_ptr);
  1111. lb_emit_store(p, dst, src);
  1112. }
  1113. } else {
  1114. isize field_count = t->Struct.fields.count;
  1115. if (t->Struct.soa_kind == StructSoa_Slice) {
  1116. field_count -= 1;
  1117. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  1118. field_count -= 3;
  1119. }
  1120. for (isize i = 0; i < field_count; i++) {
  1121. Entity *field = t->Struct.fields[i];
  1122. Type *base_type = field->type;
  1123. GB_ASSERT(base_type->kind == Type_MultiPointer);
  1124. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  1125. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  1126. lbValue src = lb_emit_load(p, src_ptr);
  1127. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  1128. src = lb_emit_load(p, src);
  1129. lb_emit_store(p, dst, src);
  1130. }
  1131. }
  1132. return lb_addr_load(p, res);
  1133. } else if (addr.kind == lbAddr_Swizzle) {
  1134. Type *array_type = base_type(addr.swizzle.type);
  1135. if (array_type->kind == Type_SimdVector) {
  1136. lbValue vec = lb_emit_load(p, addr.addr);
  1137. u8 index_count = addr.swizzle.count;
  1138. if (index_count == 0) {
  1139. return vec;
  1140. }
  1141. unsigned mask_len = cast(unsigned)index_count;
  1142. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1143. for (isize i = 0; i < index_count; i++) {
  1144. mask_elems[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  1145. }
  1146. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1147. LLVMValueRef v1 = vec.value;
  1148. LLVMValueRef v2 = vec.value;
  1149. lbValue res = {};
  1150. res.type = addr.swizzle.type;
  1151. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1152. return res;
  1153. }
  1154. GB_ASSERT(array_type->kind == Type_Array);
  1155. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  1156. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  1157. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  1158. if (lb_try_update_alignment(addr.addr, res_align)) {
  1159. Type *pt = alloc_type_pointer(addr.swizzle.type);
  1160. lbValue res = {};
  1161. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  1162. res.type = pt;
  1163. return lb_emit_load(p, res);
  1164. }
  1165. }
  1166. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  1167. lbValue ptr = lb_addr_get_ptr(p, res);
  1168. GB_ASSERT(is_type_pointer(ptr.type));
  1169. LLVMTypeRef vector_type = nullptr;
  1170. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  1171. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  1172. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  1173. LLVMValueRef scalars[4] = {};
  1174. for (u8 i = 0; i < addr.swizzle.count; i++) {
  1175. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  1176. }
  1177. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  1178. LLVMValueRef sv = llvm_basic_shuffle(p, v, mask);
  1179. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(LLVMTypeOf(sv)));
  1180. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  1181. LLVMBuildStore(p->builder, sv, dst);
  1182. } else {
  1183. for (u8 i = 0; i < addr.swizzle.count; i++) {
  1184. u8 index = addr.swizzle.indices[i];
  1185. lbValue dst = lb_emit_array_epi(p, ptr, i);
  1186. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  1187. lb_emit_store(p, dst, lb_emit_load(p, src));
  1188. }
  1189. }
  1190. return lb_addr_load(p, res);
  1191. } else if (addr.kind == lbAddr_SwizzleLarge) {
  1192. Type *array_type = base_type(addr.swizzle_large.type);
  1193. GB_ASSERT(array_type->kind == Type_Array);
  1194. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle_large.type);
  1195. gb_unused(res_align);
  1196. lbAddr res = lb_add_local_generated(p, addr.swizzle_large.type, false);
  1197. lbValue ptr = lb_addr_get_ptr(p, res);
  1198. GB_ASSERT(is_type_pointer(ptr.type));
  1199. for_array(i, addr.swizzle_large.indices) {
  1200. i32 index = addr.swizzle_large.indices[i];
  1201. lbValue dst = lb_emit_array_epi(p, ptr, i);
  1202. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  1203. lb_emit_store(p, dst, lb_emit_load(p, src));
  1204. }
  1205. return lb_addr_load(p, res);
  1206. }
  1207. if (is_type_proc(addr.addr.type)) {
  1208. return addr.addr;
  1209. }
  1210. return lb_emit_load(p, addr.addr);
  1211. }
  1212. gb_internal lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  1213. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  1214. }
  1215. gb_internal lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  1216. Type *t = u.type;
  1217. GB_ASSERT_MSG(is_type_pointer(t) &&
  1218. is_type_union(type_deref(t)), "%s", type_to_string(t));
  1219. Type *ut = type_deref(t);
  1220. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  1221. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  1222. GB_ASSERT(type_size_of(ut) > 0);
  1223. Type *tag_type = union_tag_type(ut);
  1224. LLVMTypeRef uvt = llvm_addr_type(p->module, u);
  1225. unsigned element_count = LLVMCountStructElementTypes(uvt);
  1226. GB_ASSERT_MSG(element_count >= 2, "element_count=%u (%s) != (%s)", element_count, type_to_string(ut), LLVMPrintTypeToString(uvt));
  1227. lbValue tag_ptr = {};
  1228. tag_ptr.value = LLVMBuildStructGEP2(p->builder, uvt, u.value, 1, "");
  1229. tag_ptr.type = alloc_type_pointer(tag_type);
  1230. return tag_ptr;
  1231. }
  1232. gb_internal lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  1233. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  1234. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  1235. return lb_emit_load(p, tag_ptr);
  1236. }
  1237. gb_internal void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  1238. Type *t = type_deref(parent.type);
  1239. GB_ASSERT(is_type_union(t));
  1240. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  1241. // No tag needed!
  1242. } else {
  1243. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  1244. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  1245. }
  1246. }
  1247. gb_internal void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  1248. Type *pt = base_type(type_deref(parent.type));
  1249. GB_ASSERT(pt->kind == Type_Union);
  1250. if (pt->Union.kind == UnionType_shared_nil) {
  1251. GB_ASSERT(type_size_of(variant_type));
  1252. lbBlock *if_nil = lb_create_block(p, "shared_nil.if_nil");
  1253. lbBlock *if_not_nil = lb_create_block(p, "shared_nil.if_not_nil");
  1254. lbBlock *done = lb_create_block(p, "shared_nil.done");
  1255. lbValue cond_is_nil = lb_emit_comp_against_nil(p, Token_CmpEq, variant);
  1256. lb_emit_if(p, cond_is_nil, if_nil, if_not_nil);
  1257. lb_start_block(p, if_nil);
  1258. lb_emit_store(p, parent, lb_const_nil(p->module, type_deref(parent.type)));
  1259. lb_emit_jump(p, done);
  1260. lb_start_block(p, if_not_nil);
  1261. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  1262. lb_emit_store(p, underlying, variant);
  1263. lb_emit_store_union_variant_tag(p, parent, variant_type);
  1264. lb_emit_jump(p, done);
  1265. lb_start_block(p, done);
  1266. } else {
  1267. if (type_size_of(variant_type) == 0) {
  1268. unsigned alignment = 1;
  1269. lb_mem_zero_ptr_internal(p, parent.value, pt->Union.variant_block_size, alignment, false);
  1270. } else {
  1271. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  1272. lb_emit_store(p, underlying, variant);
  1273. }
  1274. lb_emit_store_union_variant_tag(p, parent, variant_type);
  1275. }
  1276. }
  1277. gb_internal void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  1278. TEMPORARY_ALLOCATOR_GUARD();
  1279. unsigned field_count = LLVMCountStructElementTypes(src);
  1280. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1281. LLVMGetStructElementTypes(src, fields);
  1282. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  1283. }
  1284. gb_internal String lb_mangle_name(lbModule *m, Entity *e) {
  1285. String name = e->token.string;
  1286. AstPackage *pkg = e->pkg;
  1287. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  1288. String pkgn = pkg->name;
  1289. GB_ASSERT(!rune_is_digit(pkgn[0]));
  1290. if (pkgn == "llvm") {
  1291. pkgn = str_lit("llvm$");
  1292. }
  1293. isize max_len = pkgn.len + 1 + name.len + 1;
  1294. bool require_suffix_id = is_type_polymorphic(e->type, true);
  1295. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  1296. require_suffix_id = true;
  1297. } else if (is_blank_ident(e->token)) {
  1298. require_suffix_id = true;
  1299. }if (e->flags & EntityFlag_NotExported) {
  1300. require_suffix_id = true;
  1301. }
  1302. if (require_suffix_id) {
  1303. max_len += 21;
  1304. }
  1305. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  1306. isize new_name_len = gb_snprintf(
  1307. new_name, max_len,
  1308. "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s", LIT(pkgn), LIT(name)
  1309. );
  1310. if (require_suffix_id) {
  1311. char *str = new_name + new_name_len-1;
  1312. isize len = max_len-new_name_len;
  1313. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  1314. new_name_len += extra-1;
  1315. }
  1316. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  1317. return mangled_name;
  1318. }
  1319. gb_internal String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p, lbModule *module) {
  1320. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  1321. // and as a result, the declaration does not have time to determine what it should be
  1322. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  1323. if (e->TypeName.ir_mangled_name.len != 0) {
  1324. return e->TypeName.ir_mangled_name;
  1325. }
  1326. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  1327. if (p == nullptr) {
  1328. Entity *proc = nullptr;
  1329. if (e->parent_proc_decl != nullptr) {
  1330. proc = e->parent_proc_decl->entity;
  1331. } else {
  1332. Scope *scope = e->scope;
  1333. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  1334. scope = scope->parent;
  1335. }
  1336. GB_ASSERT(scope != nullptr);
  1337. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  1338. proc = scope->procedure_entity;
  1339. }
  1340. if (proc != nullptr) {
  1341. GB_ASSERT(proc->kind == Entity_Procedure);
  1342. if (proc->code_gen_procedure != nullptr) {
  1343. p = proc->code_gen_procedure;
  1344. }
  1345. }
  1346. }
  1347. // NOTE(bill): Generate a new name
  1348. // parent_proc.name-guid
  1349. String ts_name = e->token.string;
  1350. if (p != nullptr) {
  1351. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  1352. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1353. u32 guid = 1+p->module->nested_type_name_guid.fetch_add(1);
  1354. name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  1355. String name = make_string(cast(u8 *)name_text, name_len-1);
  1356. e->TypeName.ir_mangled_name = name;
  1357. return name;
  1358. } else {
  1359. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  1360. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  1361. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1362. static std::atomic<u32> guid;
  1363. name_len = gb_snprintf(name_text, name_len, "_internal" ABI_PKG_NAME_SEPARATOR "%.*s-%u", LIT(ts_name), 1+guid.fetch_add(1));
  1364. String name = make_string(cast(u8 *)name_text, name_len-1);
  1365. e->TypeName.ir_mangled_name = name;
  1366. return name;
  1367. }
  1368. }
  1369. gb_internal String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  1370. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  1371. return e->TypeName.ir_mangled_name;
  1372. }
  1373. GB_ASSERT(e != nullptr);
  1374. if (e->pkg == nullptr) {
  1375. return e->token.string;
  1376. }
  1377. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  1378. return lb_set_nested_type_name_ir_mangled_name(e, nullptr, m);
  1379. }
  1380. String name = {};
  1381. bool no_name_mangle = false;
  1382. if (e->kind == Entity_Variable) {
  1383. bool is_foreign = e->Variable.is_foreign;
  1384. bool is_export = e->Variable.is_export;
  1385. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  1386. if (e->Variable.link_name.len > 0) {
  1387. return e->Variable.link_name;
  1388. }
  1389. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  1390. return e->Procedure.link_name;
  1391. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  1392. no_name_mangle = true;
  1393. }
  1394. if (!no_name_mangle) {
  1395. name = lb_mangle_name(m, e);
  1396. }
  1397. if (name.len == 0) {
  1398. name = e->token.string;
  1399. }
  1400. if (e->kind == Entity_TypeName) {
  1401. e->TypeName.ir_mangled_name = name;
  1402. } else if (e->kind == Entity_Procedure) {
  1403. e->Procedure.link_name = name;
  1404. }
  1405. return name;
  1406. }
  1407. gb_internal LLVMTypeRef lb_type_internal_for_procedures_raw(lbModule *m, Type *type) {
  1408. Type *original_type = type;
  1409. type = base_type(original_type);
  1410. GB_ASSERT(type->kind == Type_Proc);
  1411. mutex_lock(&m->func_raw_types_mutex);
  1412. defer (mutex_unlock(&m->func_raw_types_mutex));
  1413. LLVMTypeRef *found = map_get(&m->func_raw_types, type);
  1414. if (found) {
  1415. return *found;
  1416. }
  1417. unsigned param_count = 0;
  1418. if (type->Proc.param_count != 0) {
  1419. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1420. for_array(i, type->Proc.params->Tuple.variables) {
  1421. Entity *e = type->Proc.params->Tuple.variables[i];
  1422. if (e->kind != Entity_Variable) {
  1423. continue;
  1424. }
  1425. if (e->flags & EntityFlag_CVarArg) {
  1426. continue;
  1427. }
  1428. param_count += 1;
  1429. }
  1430. }
  1431. m->internal_type_level += 1;
  1432. defer (m->internal_type_level -= 1);
  1433. bool return_is_tuple = false;
  1434. LLVMTypeRef ret = nullptr;
  1435. LLVMTypeRef *params = gb_alloc_array(permanent_allocator(), LLVMTypeRef, param_count);
  1436. bool *params_by_ptr = gb_alloc_array(permanent_allocator(), bool, param_count);
  1437. if (type->Proc.result_count != 0) {
  1438. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1439. if (is_type_proc(single_ret)) {
  1440. single_ret = t_rawptr;
  1441. }
  1442. ret = lb_type(m, single_ret);
  1443. if (is_type_tuple(single_ret)) {
  1444. return_is_tuple = true;
  1445. }
  1446. if (is_type_boolean(single_ret) &&
  1447. is_calling_convention_none(type->Proc.calling_convention) &&
  1448. type_size_of(single_ret) <= 1) {
  1449. ret = LLVMInt1TypeInContext(m->ctx);
  1450. }
  1451. }
  1452. unsigned param_index = 0;
  1453. if (type->Proc.param_count != 0) {
  1454. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1455. for_array(i, type->Proc.params->Tuple.variables) {
  1456. Entity *e = type->Proc.params->Tuple.variables[i];
  1457. if (e->kind != Entity_Variable) {
  1458. continue;
  1459. }
  1460. if (e->flags & EntityFlag_CVarArg) {
  1461. continue;
  1462. }
  1463. Type *e_type = reduce_tuple_to_single_type(e->type);
  1464. bool param_is_by_ptr = false;
  1465. LLVMTypeRef param_type = nullptr;
  1466. if (e->flags & EntityFlag_ByPtr) {
  1467. // it will become a pointer afterwards by making it indirect
  1468. param_type = lb_type(m, e_type);
  1469. param_is_by_ptr = true;
  1470. } else if (is_type_boolean(e_type) &&
  1471. type_size_of(e_type) <= 1) {
  1472. param_type = LLVMInt1TypeInContext(m->ctx);
  1473. } else {
  1474. if (is_type_proc(e_type)) {
  1475. param_type = lb_type(m, t_rawptr);
  1476. } else {
  1477. param_type = lb_type(m, e_type);
  1478. }
  1479. }
  1480. params_by_ptr[param_index] = param_is_by_ptr;
  1481. params[param_index++] = param_type;
  1482. }
  1483. }
  1484. GB_ASSERT(param_index == param_count);
  1485. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, return_is_tuple, type->Proc.calling_convention, type);
  1486. {
  1487. for_array(j, ft->args) {
  1488. auto arg = ft->args[j];
  1489. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1490. "\n\t%s %td/%td"
  1491. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1492. LLVMPrintTypeToString(arg.type),
  1493. j, ft->args.count,
  1494. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1495. }
  1496. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1497. "\n\t%s"
  1498. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1499. LLVMPrintTypeToString(ft->ret.type),
  1500. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1501. }
  1502. for (unsigned i = 0; i < param_count; i++) {
  1503. if (params_by_ptr[i]) {
  1504. // NOTE(bill): The parameter needs to be passed "indirectly", override it
  1505. ft->args[i].kind = lbArg_Indirect;
  1506. ft->args[i].attribute = nullptr;
  1507. ft->args[i].align_attribute = nullptr;
  1508. ft->args[i].byval_alignment = 0;
  1509. ft->args[i].is_byval = false;
  1510. }
  1511. }
  1512. map_set(&m->function_type_map, type, ft);
  1513. LLVMTypeRef new_abi_fn_type = lb_function_type_to_llvm_raw(ft, type->Proc.c_vararg);
  1514. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1515. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1516. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1517. map_set(&m->func_raw_types, type, new_abi_fn_type);
  1518. return new_abi_fn_type;
  1519. }
  1520. gb_internal LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  1521. LLVMContextRef ctx = m->ctx;
  1522. i64 size = type_size_of(type); // Check size
  1523. gb_unused(size);
  1524. GB_ASSERT(type != t_invalid);
  1525. bool bigger_int = build_context.ptr_size != build_context.int_size;
  1526. switch (type->kind) {
  1527. case Type_Basic:
  1528. switch (type->Basic.kind) {
  1529. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  1530. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  1531. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  1532. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  1533. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  1534. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  1535. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  1536. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  1537. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  1538. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  1539. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  1540. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  1541. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  1542. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  1543. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  1544. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  1545. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  1546. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  1547. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  1548. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  1549. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  1550. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  1551. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  1552. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  1553. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  1554. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  1555. case Basic_complex32:
  1556. {
  1557. char const *name = "..complex32";
  1558. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1559. if (type != nullptr) {
  1560. return type;
  1561. }
  1562. type = LLVMStructCreateNamed(ctx, name);
  1563. LLVMTypeRef fields[2] = {
  1564. lb_type(m, t_f16),
  1565. lb_type(m, t_f16),
  1566. };
  1567. LLVMStructSetBody(type, fields, 2, false);
  1568. return type;
  1569. }
  1570. case Basic_complex64:
  1571. {
  1572. char const *name = "..complex64";
  1573. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1574. if (type != nullptr) {
  1575. return type;
  1576. }
  1577. type = LLVMStructCreateNamed(ctx, name);
  1578. LLVMTypeRef fields[2] = {
  1579. lb_type(m, t_f32),
  1580. lb_type(m, t_f32),
  1581. };
  1582. LLVMStructSetBody(type, fields, 2, false);
  1583. return type;
  1584. }
  1585. case Basic_complex128:
  1586. {
  1587. char const *name = "..complex128";
  1588. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1589. if (type != nullptr) {
  1590. return type;
  1591. }
  1592. type = LLVMStructCreateNamed(ctx, name);
  1593. LLVMTypeRef fields[2] = {
  1594. lb_type(m, t_f64),
  1595. lb_type(m, t_f64),
  1596. };
  1597. LLVMStructSetBody(type, fields, 2, false);
  1598. return type;
  1599. }
  1600. case Basic_quaternion64:
  1601. {
  1602. char const *name = "..quaternion64";
  1603. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1604. if (type != nullptr) {
  1605. return type;
  1606. }
  1607. type = LLVMStructCreateNamed(ctx, name);
  1608. LLVMTypeRef fields[4] = {
  1609. lb_type(m, t_f16),
  1610. lb_type(m, t_f16),
  1611. lb_type(m, t_f16),
  1612. lb_type(m, t_f16),
  1613. };
  1614. LLVMStructSetBody(type, fields, 4, false);
  1615. return type;
  1616. }
  1617. case Basic_quaternion128:
  1618. {
  1619. char const *name = "..quaternion128";
  1620. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1621. if (type != nullptr) {
  1622. return type;
  1623. }
  1624. type = LLVMStructCreateNamed(ctx, name);
  1625. LLVMTypeRef fields[4] = {
  1626. lb_type(m, t_f32),
  1627. lb_type(m, t_f32),
  1628. lb_type(m, t_f32),
  1629. lb_type(m, t_f32),
  1630. };
  1631. LLVMStructSetBody(type, fields, 4, false);
  1632. return type;
  1633. }
  1634. case Basic_quaternion256:
  1635. {
  1636. char const *name = "..quaternion256";
  1637. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1638. if (type != nullptr) {
  1639. return type;
  1640. }
  1641. type = LLVMStructCreateNamed(ctx, name);
  1642. LLVMTypeRef fields[4] = {
  1643. lb_type(m, t_f64),
  1644. lb_type(m, t_f64),
  1645. lb_type(m, t_f64),
  1646. lb_type(m, t_f64),
  1647. };
  1648. LLVMStructSetBody(type, fields, 4, false);
  1649. return type;
  1650. }
  1651. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1652. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1653. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.ptr_size);
  1654. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1655. case Basic_string:
  1656. {
  1657. char const *name = "..string";
  1658. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1659. if (type != nullptr) {
  1660. return type;
  1661. }
  1662. type = LLVMStructCreateNamed(ctx, name);
  1663. if (build_context.metrics.ptr_size < build_context.metrics.int_size) {
  1664. GB_ASSERT(build_context.metrics.ptr_size == 4);
  1665. GB_ASSERT(build_context.metrics.int_size == 8);
  1666. LLVMTypeRef fields[3] = {
  1667. LLVMPointerType(lb_type(m, t_u8), 0),
  1668. lb_type(m, t_i32),
  1669. lb_type(m, t_int),
  1670. };
  1671. LLVMStructSetBody(type, fields, 3, false);
  1672. } else {
  1673. LLVMTypeRef fields[2] = {
  1674. LLVMPointerType(lb_type(m, t_u8), 0),
  1675. lb_type(m, t_int),
  1676. };
  1677. LLVMStructSetBody(type, fields, 2, false);
  1678. }
  1679. return type;
  1680. }
  1681. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1682. case Basic_any:
  1683. {
  1684. char const *name = "..any";
  1685. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1686. if (type != nullptr) {
  1687. return type;
  1688. }
  1689. type = LLVMStructCreateNamed(ctx, name);
  1690. LLVMTypeRef fields[2] = {
  1691. lb_type(m, t_rawptr),
  1692. lb_type(m, t_typeid),
  1693. };
  1694. LLVMStructSetBody(type, fields, 2, false);
  1695. return type;
  1696. }
  1697. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.ptr_size);
  1698. // Endian Specific Types
  1699. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1700. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1701. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1702. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1703. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1704. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1705. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1706. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1707. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1708. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1709. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1710. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1711. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1712. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1713. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1714. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1715. // Untyped types
  1716. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1717. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1718. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1719. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1720. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1721. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1722. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1723. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1724. case Basic_UntypedUninit: GB_PANIC("Basic_UntypedUninit"); break;
  1725. }
  1726. break;
  1727. case Type_Named:
  1728. {
  1729. Type *base = base_type(type->Named.base);
  1730. switch (base->kind) {
  1731. case Type_Basic:
  1732. return lb_type_internal(m, base);
  1733. case Type_Named:
  1734. case Type_Generic:
  1735. GB_PANIC("INVALID TYPE");
  1736. break;
  1737. case Type_Pointer:
  1738. case Type_Array:
  1739. case Type_EnumeratedArray:
  1740. case Type_Slice:
  1741. case Type_DynamicArray:
  1742. case Type_Map:
  1743. case Type_Enum:
  1744. case Type_BitSet:
  1745. case Type_SimdVector:
  1746. return lb_type_internal(m, base);
  1747. case Type_Proc:
  1748. // TODO(bill): Deal with this correctly. Can this be named?
  1749. return lb_type_internal(m, base);
  1750. case Type_Tuple:
  1751. return lb_type_internal(m, base);
  1752. }
  1753. LLVMTypeRef *found = map_get(&m->types, base);
  1754. if (found) {
  1755. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1756. if (kind == LLVMStructTypeKind) {
  1757. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1758. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1759. if (llvm_type != nullptr) {
  1760. return llvm_type;
  1761. }
  1762. llvm_type = LLVMStructCreateNamed(ctx, name);
  1763. LLVMTypeRef found_val = *found;
  1764. map_set(&m->types, type, llvm_type);
  1765. lb_clone_struct_type(llvm_type, found_val);
  1766. return llvm_type;
  1767. }
  1768. }
  1769. switch (base->kind) {
  1770. case Type_Struct:
  1771. case Type_Union:
  1772. {
  1773. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1774. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1775. if (llvm_type != nullptr) {
  1776. return llvm_type;
  1777. }
  1778. llvm_type = LLVMStructCreateNamed(ctx, name);
  1779. map_set(&m->types, type, llvm_type);
  1780. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1781. return llvm_type;
  1782. }
  1783. }
  1784. return lb_type_internal(m, base);
  1785. }
  1786. case Type_Pointer:
  1787. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1788. case Type_MultiPointer:
  1789. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1790. case Type_Array: {
  1791. m->internal_type_level += 1;
  1792. LLVMTypeRef t = llvm_array_type(lb_type(m, type->Array.elem), type->Array.count);
  1793. m->internal_type_level -= 1;
  1794. return t;
  1795. }
  1796. case Type_EnumeratedArray: {
  1797. m->internal_type_level += 1;
  1798. LLVMTypeRef t = llvm_array_type(lb_type(m, type->EnumeratedArray.elem), type->EnumeratedArray.count);
  1799. m->internal_type_level -= 1;
  1800. return t;
  1801. }
  1802. case Type_Slice:
  1803. {
  1804. if (bigger_int) {
  1805. LLVMTypeRef fields[3] = {
  1806. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1807. lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size), // padding
  1808. lb_type(m, t_int), // len
  1809. };
  1810. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1811. } else {
  1812. LLVMTypeRef fields[2] = {
  1813. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1814. lb_type(m, t_int), // len
  1815. };
  1816. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1817. }
  1818. }
  1819. break;
  1820. case Type_DynamicArray:
  1821. {
  1822. if (bigger_int) {
  1823. LLVMTypeRef fields[5] = {
  1824. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1825. lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size), // padding
  1826. lb_type(m, t_int), // len
  1827. lb_type(m, t_int), // cap
  1828. lb_type(m, t_allocator), // allocator
  1829. };
  1830. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1831. } else {
  1832. LLVMTypeRef fields[4] = {
  1833. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1834. lb_type(m, t_int), // len
  1835. lb_type(m, t_int), // cap
  1836. lb_type(m, t_allocator), // allocator
  1837. };
  1838. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1839. }
  1840. }
  1841. break;
  1842. case Type_Map:
  1843. init_map_internal_debug_types(type);
  1844. GB_ASSERT(t_raw_map != nullptr);
  1845. return lb_type_internal(m, t_raw_map);
  1846. case Type_Struct:
  1847. {
  1848. type_set_offsets(type);
  1849. i64 full_type_size = type_size_of(type);
  1850. i64 full_type_align = type_align_of(type);
  1851. GB_ASSERT(full_type_size % full_type_align == 0);
  1852. if (type->Struct.is_raw_union) {
  1853. lbStructFieldRemapping field_remapping = {};
  1854. slice_init(&field_remapping, permanent_allocator(), 1);
  1855. LLVMTypeRef fields[1] = {};
  1856. fields[0] = lb_type_padding_filler(m, full_type_size, full_type_align);
  1857. field_remapping[0] = 0;
  1858. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1859. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1860. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1861. return struct_type;
  1862. }
  1863. lbStructFieldRemapping field_remapping = {};
  1864. slice_init(&field_remapping, permanent_allocator(), type->Struct.fields.count);
  1865. m->internal_type_level += 1;
  1866. defer (m->internal_type_level -= 1);
  1867. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, type->Struct.fields.count*2 + 2);
  1868. if (are_struct_fields_reordered(type)) {
  1869. // NOTE(bill, 2021-10-02): Minor hack to enforce `llvm_const_named_struct` usage correctly
  1870. LLVMTypeRef padding_type = lb_type_padding_filler(m, 0, type_align_of(type));
  1871. array_add(&fields, padding_type);
  1872. }
  1873. i64 prev_offset = 0;
  1874. for (i32 field_index : struct_fields_index_by_increasing_offset(temporary_allocator(), type)) {
  1875. Entity *field = type->Struct.fields[field_index];
  1876. i64 offset = type->Struct.offsets[field_index];
  1877. GB_ASSERT(offset >= prev_offset);
  1878. i64 padding = offset - prev_offset;
  1879. if (padding != 0) {
  1880. LLVMTypeRef padding_type = lb_type_padding_filler(m, padding, type_align_of(field->type));
  1881. array_add(&fields, padding_type);
  1882. }
  1883. field_remapping[field_index] = cast(i32)fields.count;
  1884. Type *field_type = field->type;
  1885. if (is_type_proc(field_type)) {
  1886. // NOTE(bill, 2022-11-23): Prevent type cycle declaration (e.g. vtable) of procedures
  1887. // because LLVM is dumb with procedure types
  1888. field_type = t_rawptr;
  1889. }
  1890. array_add(&fields, lb_type(m, field_type));
  1891. prev_offset = offset + type_size_of(field->type);
  1892. }
  1893. i64 end_padding = full_type_size-prev_offset;
  1894. if (end_padding > 0) {
  1895. array_add(&fields, lb_type_padding_filler(m, end_padding, 1));
  1896. }
  1897. for_array(i, fields) {
  1898. GB_ASSERT(fields[i] != nullptr);
  1899. }
  1900. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, type->Struct.is_packed);
  1901. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1902. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1903. #if 0
  1904. GB_ASSERT_MSG(lb_sizeof(struct_type) == full_type_size,
  1905. "(%lld) %s vs (%lld) %s",
  1906. cast(long long)lb_sizeof(struct_type), LLVMPrintTypeToString(struct_type),
  1907. cast(long long)full_type_size, type_to_string(type));
  1908. #endif
  1909. return struct_type;
  1910. }
  1911. break;
  1912. case Type_Union:
  1913. if (type->Union.variants.count == 0) {
  1914. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1915. } else {
  1916. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1917. // LLVM takes the first element's alignment as the entire alignment (like C)
  1918. i64 align = type_align_of(type);
  1919. i64 size = type_size_of(type);
  1920. gb_unused(size);
  1921. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1922. LLVMTypeRef fields[] = {lb_type(m, type->Union.variants[0])};
  1923. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1924. }
  1925. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1926. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, 3);
  1927. if (is_type_union_maybe_pointer(type)) {
  1928. LLVMTypeRef variant = lb_type(m, type->Union.variants[0]);
  1929. array_add(&fields, variant);
  1930. } else {
  1931. LLVMTypeRef block_type = lb_type_padding_filler(m, block_size, align);
  1932. LLVMTypeRef tag_type = lb_type(m, union_tag_type(type));
  1933. array_add(&fields, block_type);
  1934. array_add(&fields, tag_type);
  1935. i64 used_size = lb_sizeof(block_type) + lb_sizeof(tag_type);
  1936. i64 padding = size - used_size;
  1937. if (padding > 0) {
  1938. LLVMTypeRef padding_type = lb_type_padding_filler(m, padding, align);
  1939. array_add(&fields, padding_type);
  1940. }
  1941. }
  1942. return LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, false);
  1943. }
  1944. break;
  1945. case Type_Enum:
  1946. return lb_type(m, base_enum_type(type));
  1947. case Type_Tuple:
  1948. if (type->Tuple.variables.count == 1) {
  1949. return lb_type(m, type->Tuple.variables[0]->type);
  1950. } else {
  1951. m->internal_type_level += 1;
  1952. defer (m->internal_type_level -= 1);
  1953. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1954. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1955. for_array(i, type->Tuple.variables) {
  1956. Entity *field = type->Tuple.variables[i];
  1957. LLVMTypeRef param_type = nullptr;
  1958. param_type = lb_type(m, field->type);
  1959. fields[i] = param_type;
  1960. }
  1961. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1962. }
  1963. case Type_Proc:
  1964. {
  1965. LLVMTypeRef proc_raw_type = lb_type_internal_for_procedures_raw(m, type);
  1966. gb_unused(proc_raw_type);
  1967. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1968. }
  1969. break;
  1970. case Type_BitSet:
  1971. {
  1972. Type *ut = bit_set_to_int(type);
  1973. return lb_type(m, ut);
  1974. }
  1975. case Type_SimdVector:
  1976. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1977. case Type_RelativePointer:
  1978. return lb_type_internal(m, type->RelativePointer.base_integer);
  1979. case Type_RelativeMultiPointer:
  1980. return lb_type_internal(m, type->RelativeMultiPointer.base_integer);
  1981. case Type_Matrix:
  1982. {
  1983. i64 size = type_size_of(type);
  1984. i64 elem_size = type_size_of(type->Matrix.elem);
  1985. GB_ASSERT(elem_size > 0);
  1986. i64 elem_count = size/elem_size;
  1987. GB_ASSERT_MSG(elem_count > 0, "%s", type_to_string(type));
  1988. m->internal_type_level -= 1;
  1989. LLVMTypeRef elem = lb_type(m, type->Matrix.elem);
  1990. LLVMTypeRef t = llvm_array_type(elem, elem_count);
  1991. m->internal_type_level += 1;
  1992. return t;
  1993. }
  1994. case Type_SoaPointer:
  1995. {
  1996. unsigned field_count = 2;
  1997. if (bigger_int) {
  1998. field_count = 3;
  1999. }
  2000. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  2001. fields[0] = LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  2002. if (bigger_int) {
  2003. fields[1] = lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size);
  2004. fields[2] = LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  2005. } else {
  2006. fields[1] = LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  2007. }
  2008. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  2009. }
  2010. case Type_BitField:
  2011. return lb_type_internal(m, type->BitField.backing_type);
  2012. }
  2013. GB_PANIC("Invalid type %s", type_to_string(type));
  2014. return LLVMInt32TypeInContext(ctx);
  2015. }
  2016. gb_internal LLVMTypeRef lb_type(lbModule *m, Type *type) {
  2017. type = default_type(type);
  2018. mutex_lock(&m->types_mutex);
  2019. defer (mutex_unlock(&m->types_mutex));
  2020. LLVMTypeRef *found = map_get(&m->types, type);
  2021. if (found) {
  2022. return *found;
  2023. }
  2024. LLVMTypeRef llvm_type = nullptr;
  2025. m->internal_type_level += 1;
  2026. llvm_type = lb_type_internal(m, type);
  2027. m->internal_type_level -= 1;
  2028. if (m->internal_type_level == 0) {
  2029. map_set(&m->types, type, llvm_type);
  2030. }
  2031. return llvm_type;
  2032. }
  2033. gb_internal lbFunctionType *lb_get_function_type(lbModule *m, Type *pt) {
  2034. lbFunctionType **ft_found = nullptr;
  2035. ft_found = map_get(&m->function_type_map, pt);
  2036. if (!ft_found) {
  2037. LLVMTypeRef llvm_proc_type = lb_type(m, pt);
  2038. gb_unused(llvm_proc_type);
  2039. ft_found = map_get(&m->function_type_map, pt);
  2040. }
  2041. GB_ASSERT(ft_found != nullptr);
  2042. return *ft_found;
  2043. }
  2044. gb_internal void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2045. if (p->abi_function_type != nullptr) {
  2046. return;
  2047. }
  2048. lbFunctionType **ft_found = map_get(&m->function_type_map, p->type);
  2049. if (ft_found == nullptr) {
  2050. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2051. gb_unused(llvm_proc_type);
  2052. ft_found = map_get(&m->function_type_map, p->type);
  2053. }
  2054. GB_ASSERT(ft_found != nullptr);
  2055. p->abi_function_type = *ft_found;
  2056. GB_ASSERT(p->abi_function_type != nullptr);
  2057. }
  2058. gb_internal void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2059. if (e != nullptr) {
  2060. rw_mutex_lock(&m->values_mutex);
  2061. map_set(&m->values, e, val);
  2062. rw_mutex_unlock(&m->values_mutex);
  2063. }
  2064. }
  2065. gb_internal void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2066. if (name.len > 0) {
  2067. rw_mutex_lock(&m->values_mutex);
  2068. string_map_set(&m->members, name, val);
  2069. rw_mutex_unlock(&m->values_mutex);
  2070. }
  2071. }
  2072. gb_internal void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2073. rw_mutex_lock(&m->values_mutex);
  2074. if (p->entity != nullptr) {
  2075. map_set(&m->procedure_values, p->value, p->entity);
  2076. }
  2077. string_map_set(&m->procedures, p->name, p);
  2078. rw_mutex_unlock(&m->values_mutex);
  2079. }
  2080. gb_internal LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  2081. unsigned kind = 0;
  2082. String s = make_string_c(name);
  2083. #if ODIN_LLVM_MINIMUM_VERSION_12
  2084. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2085. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2086. return LLVMCreateTypeAttribute(ctx, kind, type);
  2087. #else
  2088. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2089. // and the current LLVM C API does not expose this functionality yet.
  2090. // It is better to ignore the attributes for the time being
  2091. if (s == "byval") {
  2092. // return nullptr;
  2093. } else if (s == "byref") {
  2094. return nullptr;
  2095. } else if (s == "preallocated") {
  2096. return nullptr;
  2097. } else if (s == "sret") {
  2098. // return nullptr;
  2099. }
  2100. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2101. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2102. return LLVMCreateEnumAttribute(ctx, kind, 0);
  2103. #endif
  2104. }
  2105. gb_internal LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2106. String s = make_string_c(name);
  2107. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2108. // and the current LLVM C API does not expose this functionality yet.
  2109. // It is better to ignore the attributes for the time being
  2110. if (s == "byval") {
  2111. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2112. } else if (s == "byref") {
  2113. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2114. } else if (s == "preallocated") {
  2115. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2116. } else if (s == "sret") {
  2117. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2118. }
  2119. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2120. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2121. return LLVMCreateEnumAttribute(ctx, kind, value);
  2122. }
  2123. gb_internal LLVMAttributeRef lb_create_string_attribute(LLVMContextRef ctx, String const &key, String const &value) {
  2124. LLVMAttributeRef attr = LLVMCreateStringAttribute(
  2125. ctx,
  2126. cast(char const *)key.text, cast(unsigned)key.len,
  2127. cast(char const *)value.text, cast(unsigned)value.len);
  2128. return attr;
  2129. }
  2130. gb_internal void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2131. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2132. GB_ASSERT(attr != nullptr);
  2133. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2134. }
  2135. gb_internal void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2136. lb_add_proc_attribute_at_index(p, index, name, 0);
  2137. }
  2138. gb_internal void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2139. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2140. }
  2141. gb_internal bool lb_proc_has_attribute(lbModule *m, LLVMValueRef proc_value, char const *name) {
  2142. LLVMAttributeRef ref = LLVMGetEnumAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, LLVMGetEnumAttributeKindForName(name, gb_strlen(name)));
  2143. return ref != nullptr;
  2144. }
  2145. gb_internal void lb_add_attribute_to_proc_with_string(lbModule *m, LLVMValueRef proc_value, String const &name, String const &value) {
  2146. LLVMAttributeRef attr = lb_create_string_attribute(m->ctx, name, value);
  2147. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, attr);
  2148. }
  2149. gb_internal void lb_add_edge(lbBlock *from, lbBlock *to) {
  2150. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2151. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2152. array_add(&from->succs, to);
  2153. array_add(&to->preds, from);
  2154. }
  2155. }
  2156. gb_internal lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2157. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2158. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2159. b->appended = false;
  2160. if (append) {
  2161. b->appended = true;
  2162. LLVMAppendExistingBasicBlock(p->value, b->block);
  2163. }
  2164. b->scope = p->curr_scope;
  2165. b->scope_index = p->scope_index;
  2166. b->preds.allocator = heap_allocator();
  2167. b->succs.allocator = heap_allocator();
  2168. array_add(&p->blocks, b);
  2169. return b;
  2170. }
  2171. gb_internal void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2172. if (p->curr_block == nullptr) {
  2173. return;
  2174. }
  2175. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2176. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2177. return;
  2178. }
  2179. lb_add_edge(p->curr_block, target_block);
  2180. LLVMBuildBr(p->builder, target_block->block);
  2181. p->curr_block = nullptr;
  2182. }
  2183. gb_internal void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2184. lbBlock *b = p->curr_block;
  2185. if (b == nullptr) {
  2186. return;
  2187. }
  2188. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2189. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2190. return;
  2191. }
  2192. lb_add_edge(b, true_block);
  2193. lb_add_edge(b, false_block);
  2194. LLVMValueRef cv = cond.value;
  2195. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2196. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2197. }
  2198. gb_internal gb_inline LLVMTypeRef OdinLLVMGetInternalElementType(LLVMTypeRef type) {
  2199. return LLVMGetElementType(type);
  2200. }
  2201. gb_internal LLVMTypeRef OdinLLVMGetArrayElementType(LLVMTypeRef type) {
  2202. GB_ASSERT(lb_is_type_kind(type, LLVMArrayTypeKind));
  2203. return OdinLLVMGetInternalElementType(type);
  2204. }
  2205. gb_internal LLVMTypeRef OdinLLVMGetVectorElementType(LLVMTypeRef type) {
  2206. GB_ASSERT(lb_is_type_kind(type, LLVMVectorTypeKind));
  2207. return OdinLLVMGetInternalElementType(type);
  2208. }
  2209. gb_internal LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2210. LLVMContextRef ctx = p->module->ctx;
  2211. LLVMTypeRef src_type = LLVMTypeOf(val);
  2212. if (src_type == dst_type) {
  2213. return val;
  2214. }
  2215. i64 src_size = lb_sizeof(src_type);
  2216. i64 dst_size = lb_sizeof(dst_type);
  2217. i64 src_align = lb_alignof(src_type);
  2218. i64 dst_align = lb_alignof(dst_type);
  2219. if (LLVMIsALoadInst(val)) {
  2220. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2221. }
  2222. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2223. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2224. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2225. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2226. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2227. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2228. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2229. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2230. }
  2231. if (src_size != dst_size) {
  2232. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2233. // Okay
  2234. } else {
  2235. goto general_end;
  2236. }
  2237. }
  2238. if (src_kind == dst_kind) {
  2239. if (src_kind == LLVMPointerTypeKind) {
  2240. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2241. } else if (src_kind == LLVMArrayTypeKind) {
  2242. // ignore
  2243. } else if (src_kind != LLVMStructTypeKind) {
  2244. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2245. }
  2246. } else {
  2247. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2248. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2249. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2250. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2251. }
  2252. }
  2253. general_end:;
  2254. // make the alignment big if necessary
  2255. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2256. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2257. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2258. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2259. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2260. }
  2261. }
  2262. src_size = align_formula(src_size, src_align);
  2263. dst_size = align_formula(dst_size, dst_align);
  2264. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2265. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2266. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2267. LLVMValueRef loaded_val = LLVMBuildLoad2(p->builder, dst_type, val_ptr, "");
  2268. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2269. return loaded_val;
  2270. } else {
  2271. GB_ASSERT(p->decl_block != p->curr_block);
  2272. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2273. max_align = gb_max(max_align, 4);
  2274. LLVMValueRef ptr = llvm_alloca(p, dst_type, max_align);
  2275. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2276. LLVMBuildStore(p->builder, val, nptr);
  2277. return LLVMBuildLoad2(p->builder, dst_type, ptr, "");
  2278. }
  2279. }
  2280. gb_internal LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  2281. StringHashKey key = string_hash_string(str);
  2282. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  2283. if (found != nullptr) {
  2284. return *found;
  2285. } else {
  2286. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  2287. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2288. cast(char const *)str.text,
  2289. cast(unsigned)str.len,
  2290. false);
  2291. isize max_len = 7+8+1;
  2292. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  2293. u32 id = m->gen->global_array_index.fetch_add(1);
  2294. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2295. len -= 1;
  2296. LLVMTypeRef type = LLVMTypeOf(data);
  2297. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2298. LLVMSetInitializer(global_data, data);
  2299. lb_make_global_private_const(global_data);
  2300. LLVMSetAlignment(global_data, 1);
  2301. LLVMValueRef ptr = LLVMConstInBoundsGEP2(type, global_data, indices, 2);
  2302. string_map_set(&m->const_strings, key, ptr);
  2303. return ptr;
  2304. }
  2305. }
  2306. gb_internal lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  2307. LLVMValueRef ptr = nullptr;
  2308. if (str.len != 0) {
  2309. ptr = lb_find_or_add_entity_string_ptr(m, str);
  2310. } else {
  2311. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  2312. }
  2313. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2314. lbValue res = {};
  2315. res.value = llvm_const_string_internal(m, t_string, ptr, str_len);
  2316. res.type = t_string;
  2317. return res;
  2318. }
  2319. gb_internal lbValue lb_find_or_add_entity_string_byte_slice_with_type(lbModule *m, String const &str, Type *slice_type) {
  2320. GB_ASSERT(is_type_slice(slice_type));
  2321. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  2322. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2323. cast(char const *)str.text,
  2324. cast(unsigned)str.len,
  2325. false);
  2326. char *name = nullptr;
  2327. {
  2328. isize max_len = 7+8+1;
  2329. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2330. u32 id = m->gen->global_array_index.fetch_add(1);
  2331. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2332. len -= 1;
  2333. }
  2334. LLVMTypeRef type = LLVMTypeOf(data);
  2335. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2336. LLVMSetInitializer(global_data, data);
  2337. lb_make_global_private_const(global_data);
  2338. LLVMSetAlignment(global_data, 1);
  2339. i64 data_len = str.len;
  2340. LLVMValueRef ptr = nullptr;
  2341. if (data_len != 0) {
  2342. ptr = LLVMConstInBoundsGEP2(type, global_data, indices, 2);
  2343. } else {
  2344. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  2345. }
  2346. if (!is_type_u8_slice(slice_type)) {
  2347. Type *bt = base_type(slice_type);
  2348. Type *elem = bt->Slice.elem;
  2349. i64 sz = type_size_of(elem);
  2350. GB_ASSERT(sz > 0);
  2351. ptr = LLVMConstPointerCast(ptr, lb_type(m, alloc_type_pointer(elem)));
  2352. data_len /= sz;
  2353. }
  2354. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), data_len, true);
  2355. LLVMValueRef values[2] = {ptr, len};
  2356. lbValue res = {};
  2357. res.value = llvm_const_named_struct(m, slice_type, values, 2);
  2358. res.type = slice_type;
  2359. return res;
  2360. }
  2361. gb_internal lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  2362. if (e->flags & EntityFlag_Param) {
  2363. // NOTE(bill): Bypass the stack copied variable for
  2364. // direct parameters as there is no need for the direct load
  2365. auto *found = map_get(&p->direct_parameters, e);
  2366. if (found) {
  2367. return *found;
  2368. }
  2369. }
  2370. lbValue *found = nullptr;
  2371. rw_mutex_shared_lock(&m->values_mutex);
  2372. found = map_get(&m->values, e);
  2373. rw_mutex_shared_unlock(&m->values_mutex);
  2374. if (found) {
  2375. auto v = *found;
  2376. // NOTE(bill): This is because pointers are already pointers in LLVM
  2377. if (is_type_proc(v.type)) {
  2378. return v;
  2379. }
  2380. return lb_emit_load(p, v);
  2381. } else if (e != nullptr && e->kind == Entity_Variable) {
  2382. return lb_addr_load(p, lb_build_addr(p, expr));
  2383. }
  2384. if (e->kind == Entity_Procedure) {
  2385. return lb_find_procedure_value_from_entity(m, e);
  2386. }
  2387. if (USE_SEPARATE_MODULES) {
  2388. lbModule *other_module = lb_module_of_entity(m->gen, e);
  2389. if (other_module != m) {
  2390. String name = lb_get_entity_name(other_module, e);
  2391. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2392. lbValue g = {};
  2393. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2394. g.type = alloc_type_pointer(e->type);
  2395. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2396. lb_add_entity(m, e, g);
  2397. lb_add_member(m, name, g);
  2398. return lb_emit_load(p, g);
  2399. }
  2400. }
  2401. String pkg = {};
  2402. if (e->pkg) {
  2403. pkg = e->pkg->name;
  2404. }
  2405. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  2406. 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);
  2407. return {};
  2408. }
  2409. gb_internal lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  2410. lbGenerator *gen = m->gen;
  2411. GB_ASSERT(is_type_proc(e->type));
  2412. e = strip_entity_wrapping(e);
  2413. GB_ASSERT(e != nullptr);
  2414. GB_ASSERT(e->kind == Entity_Procedure);
  2415. lbValue *found = nullptr;
  2416. rw_mutex_shared_lock(&m->values_mutex);
  2417. found = map_get(&m->values, e);
  2418. rw_mutex_shared_unlock(&m->values_mutex);
  2419. if (found) {
  2420. return *found;
  2421. }
  2422. bool ignore_body = false;
  2423. lbModule *other_module = m;
  2424. if (USE_SEPARATE_MODULES) {
  2425. other_module = lb_module_of_entity(gen, e);
  2426. }
  2427. if (other_module == m) {
  2428. debugf("Missing Procedure (lb_find_procedure_value_from_entity): %.*s module %p\n", LIT(e->token.string), m);
  2429. }
  2430. ignore_body = other_module != m;
  2431. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  2432. if (ignore_body) {
  2433. mutex_lock(&gen->anonymous_proc_lits_mutex);
  2434. defer (mutex_unlock(&gen->anonymous_proc_lits_mutex));
  2435. GB_ASSERT(other_module != nullptr);
  2436. rw_mutex_shared_lock(&other_module->values_mutex);
  2437. auto *found = map_get(&other_module->values, e);
  2438. rw_mutex_shared_unlock(&other_module->values_mutex);
  2439. if (found == nullptr) {
  2440. // THIS IS THE RACE CONDITION
  2441. lbProcedure *missing_proc_in_other_module = lb_create_procedure(other_module, e, false);
  2442. array_add(&other_module->missing_procedures_to_check, missing_proc_in_other_module);
  2443. }
  2444. } else {
  2445. array_add(&m->missing_procedures_to_check, missing_proc);
  2446. }
  2447. rw_mutex_shared_lock(&m->values_mutex);
  2448. found = map_get(&m->values, e);
  2449. rw_mutex_shared_unlock(&m->values_mutex);
  2450. if (found) {
  2451. return *found;
  2452. }
  2453. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2454. return {};
  2455. }
  2456. gb_internal lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  2457. lbGenerator *gen = m->gen;
  2458. mutex_lock(&gen->anonymous_proc_lits_mutex);
  2459. defer (mutex_unlock(&gen->anonymous_proc_lits_mutex));
  2460. TokenPos pos = ast_token(expr).pos;
  2461. lbProcedure **found = map_get(&gen->anonymous_proc_lits, expr);
  2462. if (found) {
  2463. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  2464. }
  2465. ast_node(pl, ProcLit, expr);
  2466. // NOTE(bill): Generate a new name
  2467. // parent$count
  2468. isize name_len = prefix_name.len + 6 + 11;
  2469. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2470. static std::atomic<i32> name_id;
  2471. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), 1+name_id.fetch_add(1));
  2472. String name = make_string((u8 *)name_text, name_len-1);
  2473. Type *type = type_of_expr(expr);
  2474. GB_ASSERT(pl->decl->entity == nullptr);
  2475. Token token = {};
  2476. token.pos = ast_token(expr).pos;
  2477. token.kind = Token_Ident;
  2478. token.string = name;
  2479. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  2480. e->file = expr->file();
  2481. // NOTE(bill): this is to prevent a race condition since these procedure literals can be created anywhere at any time
  2482. pl->decl->code_gen_module = m;
  2483. e->decl_info = pl->decl;
  2484. pl->decl->entity = e;
  2485. e->flags |= EntityFlag_ProcBodyChecked;
  2486. lbProcedure *p = lb_create_procedure(m, e);
  2487. GB_ASSERT(e->code_gen_module == m);
  2488. lbValue value = {};
  2489. value.value = p->value;
  2490. value.type = p->type;
  2491. map_set(&gen->anonymous_proc_lits, expr, p);
  2492. array_add(&m->procedures_to_generate, p);
  2493. if (parent != nullptr) {
  2494. array_add(&parent->children, p);
  2495. } else {
  2496. string_map_set(&m->members, name, value);
  2497. }
  2498. return value;
  2499. }
  2500. gb_internal lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value, Entity **entity_) {
  2501. GB_ASSERT(type != nullptr);
  2502. type = default_type(type);
  2503. isize max_len = 7+8+1;
  2504. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  2505. u32 id = m->gen->global_generated_index.fetch_add(1);
  2506. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  2507. String name = make_string(str, len-1);
  2508. Scope *scope = nullptr;
  2509. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  2510. lbValue g = {};
  2511. g.type = alloc_type_pointer(type);
  2512. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  2513. if (value.value != nullptr) {
  2514. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  2515. LLVMSetInitializer(g.value, value.value);
  2516. } else {
  2517. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  2518. }
  2519. lb_add_entity(m, e, g);
  2520. lb_add_member(m, name, g);
  2521. if (entity_) *entity_ = e;
  2522. return lb_addr(g);
  2523. }
  2524. gb_internal lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  2525. AstPackage *p = m->info->runtime_package;
  2526. Entity *e = scope_lookup_current(p->scope, name);
  2527. return lb_find_value_from_entity(m, e);
  2528. }
  2529. gb_internal lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  2530. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  2531. return lb_find_value_from_entity(m, e);
  2532. }
  2533. gb_internal lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  2534. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  2535. return lb_addr_get_ptr(p, addr);
  2536. }
  2537. gb_internal lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  2538. e = strip_entity_wrapping(e);
  2539. GB_ASSERT(e != nullptr);
  2540. GB_ASSERT(e->token.string != "_");
  2541. if (e->kind == Entity_Procedure) {
  2542. return lb_find_procedure_value_from_entity(m, e);
  2543. }
  2544. lbValue *found = nullptr;
  2545. rw_mutex_shared_lock(&m->values_mutex);
  2546. found = map_get(&m->values, e);
  2547. rw_mutex_shared_unlock(&m->values_mutex);
  2548. if (found) {
  2549. return *found;
  2550. }
  2551. if (USE_SEPARATE_MODULES) {
  2552. lbModule *other_module = lb_module_of_entity(m->gen, e);
  2553. bool is_external = other_module != m;
  2554. if (!is_external) {
  2555. if (e->code_gen_module != nullptr) {
  2556. other_module = e->code_gen_module;
  2557. } else {
  2558. other_module = nullptr;
  2559. }
  2560. is_external = other_module != m;
  2561. }
  2562. if (is_external) {
  2563. String name = lb_get_entity_name(other_module, e);
  2564. lbValue g = {};
  2565. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2566. g.type = alloc_type_pointer(e->type);
  2567. lb_add_entity(m, e, g);
  2568. lb_add_member(m, name, g);
  2569. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2570. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2571. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  2572. if (e->Variable.thread_local_model != "") {
  2573. LLVMSetThreadLocal(g.value, true);
  2574. String m = e->Variable.thread_local_model;
  2575. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2576. if (m == "default") {
  2577. mode = LLVMGeneralDynamicTLSModel;
  2578. } else if (m == "localdynamic") {
  2579. mode = LLVMLocalDynamicTLSModel;
  2580. } else if (m == "initialexec") {
  2581. mode = LLVMInitialExecTLSModel;
  2582. } else if (m == "localexec") {
  2583. mode = LLVMLocalExecTLSModel;
  2584. } else {
  2585. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2586. }
  2587. LLVMSetThreadLocalMode(g.value, mode);
  2588. }
  2589. return g;
  2590. }
  2591. }
  2592. GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2593. return {};
  2594. }
  2595. gb_internal lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  2596. Token token = {Token_Ident};
  2597. isize name_len = prefix.len + 1 + 20;
  2598. auto suffix_id = cast(unsigned long long)id;
  2599. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  2600. gb_snprintf(text, name_len,
  2601. "%.*s-%llu", LIT(prefix), suffix_id);
  2602. text[name_len] = 0;
  2603. String s = make_string_c(text);
  2604. Type *t = alloc_type_array(elem_type, count);
  2605. lbValue g = {};
  2606. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  2607. g.type = alloc_type_pointer(t);
  2608. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  2609. LLVMSetLinkage(g.value, LLVMPrivateLinkage);
  2610. LLVMSetUnnamedAddress(g.value, LLVMGlobalUnnamedAddr);
  2611. string_map_set(&m->members, s, g);
  2612. return g;
  2613. }
  2614. gb_internal lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2615. GB_ASSERT(cond != nullptr);
  2616. GB_ASSERT(true_block != nullptr);
  2617. GB_ASSERT(false_block != nullptr);
  2618. // Use to signal not to do compile time short circuit for consts
  2619. lbValue no_comptime_short_circuit = {};
  2620. switch (cond->kind) {
  2621. case_ast_node(pe, ParenExpr, cond);
  2622. return lb_build_cond(p, pe->expr, true_block, false_block);
  2623. case_end;
  2624. case_ast_node(ue, UnaryExpr, cond);
  2625. if (ue->op.kind == Token_Not) {
  2626. lbValue cond_val = lb_build_cond(p, ue->expr, false_block, true_block);
  2627. if (cond_val.value && LLVMIsConstant(cond_val.value)) {
  2628. return lb_const_bool(p->module, cond_val.type, LLVMConstIntGetZExtValue(cond_val.value) == 0);
  2629. }
  2630. return no_comptime_short_circuit;
  2631. }
  2632. case_end;
  2633. case_ast_node(be, BinaryExpr, cond);
  2634. if (be->op.kind == Token_CmpAnd) {
  2635. lbBlock *block = lb_create_block(p, "cmp.and");
  2636. lb_build_cond(p, be->left, block, false_block);
  2637. lb_start_block(p, block);
  2638. lb_build_cond(p, be->right, true_block, false_block);
  2639. return no_comptime_short_circuit;
  2640. } else if (be->op.kind == Token_CmpOr) {
  2641. lbBlock *block = lb_create_block(p, "cmp.or");
  2642. lb_build_cond(p, be->left, true_block, block);
  2643. lb_start_block(p, block);
  2644. lb_build_cond(p, be->right, true_block, false_block);
  2645. return no_comptime_short_circuit;
  2646. }
  2647. case_end;
  2648. }
  2649. lbValue v = {};
  2650. if (lb_is_expr_untyped_const(cond)) {
  2651. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2652. } else {
  2653. v = lb_build_expr(p, cond);
  2654. }
  2655. v = lb_emit_conv(p, v, t_llvm_bool);
  2656. lb_emit_if(p, v, true_block, false_block);
  2657. return v;
  2658. }
  2659. gb_internal lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, bool force_no_init) {
  2660. GB_ASSERT(p->decl_block != p->curr_block);
  2661. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2662. char const *name = "";
  2663. if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") {
  2664. // NOTE(bill): for debugging purposes only
  2665. name = alloc_cstring(permanent_allocator(), e->token.string);
  2666. }
  2667. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2668. unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(llvm_type));
  2669. if (is_type_matrix(type)) {
  2670. alignment *= 2; // NOTE(bill): Just in case
  2671. }
  2672. LLVMValueRef ptr = llvm_alloca(p, llvm_type, alignment, name);
  2673. if (!zero_init && !force_no_init) {
  2674. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  2675. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2676. if (kind == LLVMArrayTypeKind) {
  2677. kind = LLVMGetTypeKind(lb_type(p->module, core_array_type(type)));
  2678. }
  2679. if (kind == LLVMStructTypeKind) {
  2680. i64 sz = type_size_of(type);
  2681. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  2682. zero_init = true;
  2683. }
  2684. }
  2685. }
  2686. lbValue val = {};
  2687. val.value = ptr;
  2688. val.type = alloc_type_pointer(type);
  2689. if (e != nullptr) {
  2690. lb_add_entity(p->module, e, val);
  2691. lb_add_debug_local_variable(p, ptr, type, e->token);
  2692. }
  2693. if (zero_init) {
  2694. lb_mem_zero_ptr(p, ptr, type, alignment);
  2695. }
  2696. return lb_addr(val);
  2697. }
  2698. gb_internal lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2699. return lb_add_local(p, type, nullptr, zero_init);
  2700. }
  2701. gb_internal lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  2702. lbAddr res = lb_add_local(p, type, nullptr, false, true);
  2703. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  2704. return res;
  2705. }
  2706. gb_internal void lb_set_linkage_from_entity_flags(lbModule *m, LLVMValueRef value, u64 flags) {
  2707. if (flags & EntityFlag_CustomLinkage_Internal) {
  2708. LLVMSetLinkage(value, LLVMInternalLinkage);
  2709. } else if (flags & EntityFlag_CustomLinkage_Strong) {
  2710. LLVMSetLinkage(value, LLVMExternalLinkage);
  2711. } else if (flags & EntityFlag_CustomLinkage_Weak) {
  2712. LLVMSetLinkage(value, LLVMExternalWeakLinkage);
  2713. } else if (flags & EntityFlag_CustomLinkage_LinkOnce) {
  2714. LLVMSetLinkage(value, LLVMLinkOnceAnyLinkage);
  2715. }
  2716. }