llvm_backend_general.cpp 95 KB

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