llvm_backend_general.cpp 91 KB

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