llvm_backend_general.cpp 96 KB

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