llvm_backend_general.cpp 85 KB

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