llvm_backend_general.cpp 101 KB

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