llvm_backend_general.cpp 92 KB

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