llvm_backend_general.cpp 108 KB

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