llvm_backend.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef USE_SEPARATE_MODULES
  3. #define USE_SEPARATE_MODULES build_context.use_separate_modules
  4. #endif
  5. #ifndef MULTITHREAD_OBJECT_GENERATION
  6. #define MULTITHREAD_OBJECT_GENERATION 0
  7. #endif
  8. #include "llvm_backend.hpp"
  9. #include "llvm_abi.cpp"
  10. #include "llvm_backend_opt.cpp"
  11. #include "llvm_backend_general.cpp"
  12. #include "llvm_backend_debug.cpp"
  13. #include "llvm_backend_const.cpp"
  14. #include "llvm_backend_type.cpp"
  15. #include "llvm_backend_utility.cpp"
  16. #include "llvm_backend_expr.cpp"
  17. #include "llvm_backend_stmt.cpp"
  18. #include "llvm_backend_proc.cpp"
  19. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  20. if (e == nullptr) {
  21. return;
  22. }
  23. GB_ASSERT(e->kind == Entity_LibraryName);
  24. GB_ASSERT(e->flags & EntityFlag_Used);
  25. mutex_lock(&m->gen->foreign_mutex);
  26. if (!ptr_set_update(&m->gen->foreign_libraries_set, e)) {
  27. array_add(&m->gen->foreign_libraries, e);
  28. }
  29. mutex_unlock(&m->gen->foreign_mutex);
  30. }
  31. GB_COMPARE_PROC(foreign_library_cmp) {
  32. int cmp = 0;
  33. Entity *x = *(Entity **)a;
  34. Entity *y = *(Entity **)b;
  35. if (x == y) {
  36. return 0;
  37. }
  38. GB_ASSERT(x->kind == Entity_LibraryName);
  39. GB_ASSERT(y->kind == Entity_LibraryName);
  40. cmp = i64_cmp(x->LibraryName.priority_index, y->LibraryName.priority_index);
  41. if (cmp) {
  42. return cmp;
  43. }
  44. if (x->pkg != y->pkg) {
  45. isize order_x = x->pkg ? x->pkg->order : 0;
  46. isize order_y = y->pkg ? y->pkg->order : 0;
  47. cmp = isize_cmp(order_x, order_y);
  48. if (cmp) {
  49. return cmp;
  50. }
  51. }
  52. if (x->file != y->file) {
  53. String fullpath_x = x->file ? x->file->fullpath : (String{});
  54. String fullpath_y = y->file ? y->file->fullpath : (String{});
  55. String file_x = filename_from_path(fullpath_x);
  56. String file_y = filename_from_path(fullpath_y);
  57. cmp = string_compare(file_x, file_y);
  58. if (cmp) {
  59. return cmp;
  60. }
  61. }
  62. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  63. if (cmp) {
  64. return cmp;
  65. }
  66. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  67. }
  68. void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  69. if (other_module == nullptr) {
  70. return;
  71. }
  72. char const *cname = alloc_cstring(temporary_allocator(), name);
  73. LLVMValueRef other_global = nullptr;
  74. if (e->kind == Entity_Variable) {
  75. other_global = LLVMGetNamedGlobal(other_module->mod, cname);
  76. } else if (e->kind == Entity_Procedure) {
  77. other_global = LLVMGetNamedFunction(other_module->mod, cname);
  78. }
  79. if (other_global) {
  80. LLVMSetLinkage(other_global, LLVMExternalLinkage);
  81. }
  82. }
  83. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  84. GB_ASSERT(addr.kind == lbAddr_Context);
  85. GB_ASSERT(addr.ctx.sel.index.count == 0);
  86. auto args = array_make<lbValue>(permanent_allocator(), 1);
  87. args[0] = addr.addr;
  88. lb_emit_runtime_call(p, "__init_context", args);
  89. }
  90. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  91. Type *pt = base_type(p->type);
  92. GB_ASSERT(pt->kind == Type_Proc);
  93. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  94. String name = str_lit("__.context_ptr");
  95. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  96. e->flags |= EntityFlag_NoAlias;
  97. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  98. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  99. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  100. lbValue param = {context_ptr, e->type};
  101. lb_add_entity(p->module, e, param);
  102. lbAddr ctx_addr = {};
  103. ctx_addr.kind = lbAddr_Context;
  104. ctx_addr.addr = param;
  105. lbContextData *cd = array_add_and_get(&p->context_stack);
  106. cd->ctx = ctx_addr;
  107. cd->scope_index = -1;
  108. cd->uses = +1; // make sure it has been used already
  109. return cd;
  110. }
  111. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  112. ctx.kind = lbAddr_Context;
  113. lbContextData *cd = array_add_and_get(&p->context_stack);
  114. cd->ctx = ctx;
  115. cd->scope_index = p->scope_index;
  116. return cd;
  117. }
  118. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  119. type = base_type(type);
  120. GB_ASSERT(is_type_comparable(type));
  121. Type *pt = alloc_type_pointer(type);
  122. LLVMTypeRef ptr_type = lb_type(m, pt);
  123. lbProcedure **found = map_get(&m->equal_procs, type);
  124. lbProcedure *compare_proc = nullptr;
  125. if (found) {
  126. compare_proc = *found;
  127. GB_ASSERT(compare_proc != nullptr);
  128. return {compare_proc->value, compare_proc->type};
  129. }
  130. static u32 proc_index = 0;
  131. char buf[16] = {};
  132. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  133. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  134. String proc_name = make_string_c(str);
  135. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  136. map_set(&m->equal_procs, type, p);
  137. lb_begin_procedure_body(p);
  138. LLVMValueRef x = LLVMGetParam(p->value, 0);
  139. LLVMValueRef y = LLVMGetParam(p->value, 1);
  140. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  141. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  142. lbValue lhs = {x, pt};
  143. lbValue rhs = {y, pt};
  144. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  145. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  146. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  147. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  148. lb_start_block(p, block_same_ptr);
  149. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  150. lb_start_block(p, block_diff_ptr);
  151. if (type->kind == Type_Struct) {
  152. type_set_offsets(type);
  153. lbBlock *block_false = lb_create_block(p, "bfalse");
  154. lbValue res = lb_const_bool(m, t_bool, true);
  155. for_array(i, type->Struct.fields) {
  156. lbBlock *next_block = lb_create_block(p, "btrue");
  157. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  158. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  159. lbValue left = lb_emit_load(p, pleft);
  160. lbValue right = lb_emit_load(p, pright);
  161. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  162. lb_emit_if(p, ok, next_block, block_false);
  163. lb_emit_jump(p, next_block);
  164. lb_start_block(p, next_block);
  165. }
  166. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  167. lb_start_block(p, block_false);
  168. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  169. } else if (type->kind == Type_Union) {
  170. if (is_type_union_maybe_pointer(type)) {
  171. Type *v = type->Union.variants[0];
  172. Type *pv = alloc_type_pointer(v);
  173. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  174. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  175. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  176. ok = lb_emit_conv(p, ok, t_bool);
  177. LLVMBuildRet(p->builder, ok.value);
  178. } else {
  179. lbBlock *block_false = lb_create_block(p, "bfalse");
  180. lbBlock *block_switch = lb_create_block(p, "bswitch");
  181. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  182. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  183. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  184. lb_emit_if(p, tag_eq, block_switch, block_false);
  185. lb_start_block(p, block_switch);
  186. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  187. for_array(i, type->Union.variants) {
  188. lbBlock *case_block = lb_create_block(p, "bcase");
  189. lb_start_block(p, case_block);
  190. Type *v = type->Union.variants[i];
  191. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  192. Type *vp = alloc_type_pointer(v);
  193. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  194. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  195. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  196. ok = lb_emit_conv(p, ok, t_bool);
  197. LLVMBuildRet(p->builder, ok.value);
  198. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  199. }
  200. lb_start_block(p, block_false);
  201. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  202. }
  203. } else {
  204. lbValue left = lb_emit_load(p, lhs);
  205. lbValue right = lb_emit_load(p, rhs);
  206. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  207. ok = lb_emit_conv(p, ok, t_bool);
  208. LLVMBuildRet(p->builder, ok.value);
  209. }
  210. lb_end_procedure_body(p);
  211. compare_proc = p;
  212. return {compare_proc->value, compare_proc->type};
  213. }
  214. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  215. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  216. i64 sz = type_size_of(type);
  217. if (1 <= sz && sz <= 16) {
  218. char name[20] = {};
  219. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  220. auto args = array_make<lbValue>(permanent_allocator(), 2);
  221. args[0] = data;
  222. args[1] = seed;
  223. return lb_emit_runtime_call(p, name, args);
  224. }
  225. auto args = array_make<lbValue>(permanent_allocator(), 3);
  226. args[0] = data;
  227. args[1] = seed;
  228. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  229. return lb_emit_runtime_call(p, "default_hasher_n", args);
  230. }
  231. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  232. type = core_type(type);
  233. GB_ASSERT(is_type_valid_for_keys(type));
  234. Type *pt = alloc_type_pointer(type);
  235. lbProcedure **found = map_get(&m->hasher_procs, type);
  236. if (found) {
  237. GB_ASSERT(*found != nullptr);
  238. return {(*found)->value, (*found)->type};
  239. }
  240. static u32 proc_index = 0;
  241. char buf[16] = {};
  242. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  243. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  244. String proc_name = make_string_c(str);
  245. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  246. map_set(&m->hasher_procs, type, p);
  247. lb_begin_procedure_body(p);
  248. defer (lb_end_procedure_body(p));
  249. LLVMValueRef x = LLVMGetParam(p->value, 0);
  250. LLVMValueRef y = LLVMGetParam(p->value, 1);
  251. lbValue data = {x, t_rawptr};
  252. lbValue seed = {y, t_uintptr};
  253. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  254. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  255. if (is_type_simple_compare(type)) {
  256. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  257. LLVMBuildRet(p->builder, res.value);
  258. return {p->value, p->type};
  259. }
  260. if (type->kind == Type_Struct) {
  261. type_set_offsets(type);
  262. data = lb_emit_conv(p, data, t_u8_ptr);
  263. auto args = array_make<lbValue>(permanent_allocator(), 2);
  264. for_array(i, type->Struct.fields) {
  265. GB_ASSERT(type->Struct.offsets != nullptr);
  266. i64 offset = type->Struct.offsets[i];
  267. Entity *field = type->Struct.fields[i];
  268. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  269. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  270. args[0] = ptr;
  271. args[1] = seed;
  272. seed = lb_emit_call(p, field_hasher, args);
  273. }
  274. LLVMBuildRet(p->builder, seed.value);
  275. } else if (type->kind == Type_Union) {
  276. auto args = array_make<lbValue>(permanent_allocator(), 2);
  277. if (is_type_union_maybe_pointer(type)) {
  278. Type *v = type->Union.variants[0];
  279. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  280. args[0] = data;
  281. args[1] = seed;
  282. lbValue res = lb_emit_call(p, variant_hasher, args);
  283. LLVMBuildRet(p->builder, res.value);
  284. }
  285. lbBlock *end_block = lb_create_block(p, "bend");
  286. data = lb_emit_conv(p, data, pt);
  287. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  288. lbValue tag = lb_emit_load(p, tag_ptr);
  289. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  290. for_array(i, type->Union.variants) {
  291. lbBlock *case_block = lb_create_block(p, "bcase");
  292. lb_start_block(p, case_block);
  293. Type *v = type->Union.variants[i];
  294. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  295. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  296. args[0] = data;
  297. args[1] = seed;
  298. lbValue res = lb_emit_call(p, variant_hasher, args);
  299. LLVMBuildRet(p->builder, res.value);
  300. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  301. }
  302. lb_start_block(p, end_block);
  303. LLVMBuildRet(p->builder, seed.value);
  304. } else if (type->kind == Type_Array) {
  305. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  306. lb_addr_store(p, pres, seed);
  307. auto args = array_make<lbValue>(permanent_allocator(), 2);
  308. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  309. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  310. data = lb_emit_conv(p, data, pt);
  311. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  312. args[0] = ptr;
  313. args[1] = lb_addr_load(p, pres);
  314. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  315. lb_addr_store(p, pres, new_seed);
  316. lb_loop_end(p, loop_data);
  317. lbValue res = lb_addr_load(p, pres);
  318. LLVMBuildRet(p->builder, res.value);
  319. } else if (type->kind == Type_EnumeratedArray) {
  320. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  321. lb_addr_store(p, res, seed);
  322. auto args = array_make<lbValue>(permanent_allocator(), 2);
  323. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  324. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  325. data = lb_emit_conv(p, data, pt);
  326. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  327. args[0] = ptr;
  328. args[1] = lb_addr_load(p, res);
  329. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  330. lb_addr_store(p, res, new_seed);
  331. lb_loop_end(p, loop_data);
  332. lbValue vres = lb_addr_load(p, res);
  333. LLVMBuildRet(p->builder, vres.value);
  334. } else if (is_type_cstring(type)) {
  335. auto args = array_make<lbValue>(permanent_allocator(), 2);
  336. args[0] = data;
  337. args[1] = seed;
  338. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  339. LLVMBuildRet(p->builder, res.value);
  340. } else if (is_type_string(type)) {
  341. auto args = array_make<lbValue>(permanent_allocator(), 2);
  342. args[0] = data;
  343. args[1] = seed;
  344. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  345. LLVMBuildRet(p->builder, res.value);
  346. } else {
  347. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  348. }
  349. return {p->value, p->type};
  350. }
  351. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  352. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, expr);
  353. if (found) {
  354. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  355. }
  356. ast_node(pl, ProcLit, expr);
  357. // NOTE(bill): Generate a new name
  358. // parent$count
  359. isize name_len = prefix_name.len + 1 + 8 + 1;
  360. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  361. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  362. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  363. String name = make_string((u8 *)name_text, name_len-1);
  364. Type *type = type_of_expr(expr);
  365. Token token = {};
  366. token.pos = ast_token(expr).pos;
  367. token.kind = Token_Ident;
  368. token.string = name;
  369. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  370. e->file = expr->file();
  371. e->decl_info = pl->decl;
  372. e->code_gen_module = m;
  373. e->flags |= EntityFlag_ProcBodyChecked;
  374. lbProcedure *p = lb_create_procedure(m, e);
  375. lbValue value = {};
  376. value.value = p->value;
  377. value.type = p->type;
  378. array_add(&m->procedures_to_generate, p);
  379. if (parent != nullptr) {
  380. array_add(&parent->children, p);
  381. } else {
  382. string_map_set(&m->members, name, value);
  383. }
  384. map_set(&m->gen->anonymous_proc_lits, expr, p);
  385. return value;
  386. }
  387. lbValue lb_gen_map_header_table_internal(lbProcedure *p, Type *map_type) {
  388. lbModule *m = p->module;
  389. map_type = base_type(map_type);
  390. GB_ASSERT(map_type->kind == Type_Map);
  391. lbAddr *found = map_get(&m->map_header_table_map, map_type);
  392. if (found) {
  393. return lb_addr_load(p, *found);
  394. }
  395. GB_ASSERT(map_type->Map.entry_type->kind == Type_Struct);
  396. i64 entry_size = type_size_of (map_type->Map.entry_type);
  397. i64 entry_align = type_align_of (map_type->Map.entry_type);
  398. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  399. i64 key_size = type_size_of (map_type->Map.key);
  400. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  401. i64 value_size = type_size_of (map_type->Map.value);
  402. Type *key_type = map_type->Map.key;
  403. Type *val_type = map_type->Map.value;
  404. gb_unused(val_type);
  405. Type *st = base_type(t_map_header_table);
  406. GB_ASSERT(st->Struct.fields.count == 7);
  407. LLVMValueRef const_values[7] = {};
  408. const_values[0] = lb_get_equal_proc_for_type(m, key_type) .value;
  409. const_values[1] = lb_const_int(m, t_int, entry_size) .value;
  410. const_values[2] = lb_const_int(m, t_int, entry_align) .value;
  411. const_values[3] = lb_const_int(m, t_uintptr, key_offset) .value;
  412. const_values[4] = lb_const_int(m, t_int, key_size) .value;
  413. const_values[5] = lb_const_int(m, t_uintptr, value_offset).value;
  414. const_values[6] = lb_const_int(m, t_int, value_size) .value;
  415. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_header_table, const_values, gb_count_of(const_values));
  416. lbValue res = {llvm_res, t_map_header_table};
  417. lbAddr addr = lb_add_global_generated(m, t_map_header_table, res, nullptr);
  418. LLVMValueRef global_data = addr.addr.value;
  419. LLVMSetLinkage(global_data, LLVMPrivateLinkage);
  420. LLVMSetUnnamedAddress(global_data, LLVMGlobalUnnamedAddr);
  421. LLVMSetGlobalConstant(global_data, true);
  422. map_set(&m->map_header_table_map, map_type, addr);
  423. return lb_addr_load(p, addr);
  424. }
  425. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  426. if (true) {
  427. return {};
  428. }
  429. lbValue hashed_key = {};
  430. #if 0
  431. if (lb_is_const(key)) {
  432. u64 hash = 0xcbf29ce484222325;
  433. if (is_type_cstring(key_type)) {
  434. size_t length = 0;
  435. char const *text = LLVMGetAsString(key.value, &length);
  436. hash = fnv64a(text, cast(isize)length);
  437. } else if (is_type_string(key_type)) {
  438. unsigned data_indices[] = {0};
  439. unsigned len_indices[] = {1};
  440. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  441. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  442. i64 length = LLVMConstIntGetSExtValue(len);
  443. char const *text = nullptr;
  444. if (false && length != 0) {
  445. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  446. return {};
  447. }
  448. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  449. size_t ulength = 0;
  450. text = LLVMGetAsString(data, &ulength);
  451. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  452. length = gb_min(length, cast(i64)ulength);
  453. }
  454. hash = fnv64a(text, cast(isize)length);
  455. } else {
  456. return {};
  457. }
  458. // TODO(bill): other const hash types
  459. if (build_context.word_size == 4) {
  460. hash &= 0xffffffffull;
  461. }
  462. hashed_key = lb_const_int(m, t_uintptr, hash);
  463. }
  464. #endif
  465. return hashed_key;
  466. }
  467. lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue key, Type *key_type, lbValue *key_ptr_) {
  468. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  469. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  470. if (key_ptr_) *key_ptr_ = key_ptr;
  471. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  472. if (hashed_key.value == nullptr) {
  473. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  474. auto args = array_make<lbValue>(permanent_allocator(), 2);
  475. args[0] = key_ptr;
  476. args[1] = lb_const_int(p->module, t_uintptr, 0);
  477. hashed_key = lb_emit_call(p, hasher, args);
  478. }
  479. return hashed_key;
  480. }
  481. lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  482. Type *map_type = base_type(type_deref(map_ptr.type));
  483. lbValue key_ptr = {};
  484. auto args = array_make<lbValue>(permanent_allocator(), 4);
  485. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  486. args[1] = lb_gen_map_header_table_internal(p, map_type);
  487. args[2] = lb_gen_map_key_hash(p, key, map_type->Map.key, &key_ptr);
  488. args[3] = key_ptr;
  489. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  490. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  491. }
  492. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  493. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  494. map_type = base_type(map_type);
  495. GB_ASSERT(map_type->kind == Type_Map);
  496. lbValue key_ptr = {};
  497. lbValue key_hash = lb_gen_map_key_hash(p, map_key, map_type->Map.key, &key_ptr);
  498. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  499. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  500. lb_addr_store(p, value_addr, v);
  501. auto args = array_make<lbValue>(permanent_allocator(), 6);
  502. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  503. args[1] = lb_gen_map_header_table_internal(p, map_type);
  504. args[2] = key_hash;
  505. args[3] = key_ptr;
  506. args[4] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  507. args[5] = lb_emit_source_code_location(p, node);
  508. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  509. }
  510. void lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  511. GB_ASSERT(!build_context.no_dynamic_literals);
  512. String proc_name = {};
  513. if (p->entity) {
  514. proc_name = p->entity->token.string;
  515. }
  516. auto args = array_make<lbValue>(permanent_allocator(), 4);
  517. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  518. args[1] = lb_gen_map_header_table_internal(p, type_deref(map_ptr.type));
  519. args[2] = lb_const_int(p->module, t_int, capacity);
  520. args[3] = lb_emit_source_code_location(p, proc_name, pos);
  521. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  522. }
  523. struct lbGlobalVariable {
  524. lbValue var;
  525. lbValue init;
  526. DeclInfo *decl;
  527. bool is_initialized;
  528. };
  529. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  530. if (build_context.disallow_rtti) {
  531. return nullptr;
  532. }
  533. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  534. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  535. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  536. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  537. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  538. p->is_startup = true;
  539. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  540. lb_begin_procedure_body(p);
  541. lb_setup_type_info_data(p);
  542. lb_end_procedure_body(p);
  543. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  544. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  545. LLVMDumpValue(p->value);
  546. gb_printf_err("\n\n\n\n");
  547. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  548. }
  549. lb_run_function_pass_manager(default_function_pass_manager, p);
  550. return p;
  551. }
  552. lbProcedure *lb_create_objc_names(lbModule *main_module) {
  553. if (build_context.metrics.os != TargetOs_darwin) {
  554. return nullptr;
  555. }
  556. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  557. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  558. p->is_startup = true;
  559. return p;
  560. }
  561. void lb_finalize_objc_names(lbProcedure *p) {
  562. if (p == nullptr) {
  563. return;
  564. }
  565. lbModule *m = p->module;
  566. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  567. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  568. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  569. auto args = array_make<lbValue>(permanent_allocator(), 1);
  570. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  571. lb_begin_procedure_body(p);
  572. for_array(i, m->objc_classes.entries) {
  573. auto const &entry = m->objc_classes.entries[i];
  574. String name = entry.key.string;
  575. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  576. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  577. lb_addr_store(p, entry.value, ptr);
  578. }
  579. for_array(i, m->objc_selectors.entries) {
  580. auto const &entry = m->objc_selectors.entries[i];
  581. String name = entry.key.string;
  582. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  583. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  584. lb_addr_store(p, entry.value, ptr);
  585. }
  586. lb_end_procedure_body(p);
  587. lb_run_function_pass_manager(default_function_pass_manager, p);
  588. }
  589. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  590. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  591. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  592. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  593. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  594. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  595. p->is_startup = true;
  596. lb_begin_procedure_body(p);
  597. if (startup_type_info) {
  598. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, startup_type_info->type), startup_type_info->value, nullptr, 0, "");
  599. }
  600. if (objc_names) {
  601. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, objc_names->type), objc_names->value, nullptr, 0, "");
  602. }
  603. for_array(i, global_variables) {
  604. auto *var = &global_variables[i];
  605. if (var->is_initialized) {
  606. continue;
  607. }
  608. lbModule *entity_module = main_module;
  609. Entity *e = var->decl->entity;
  610. GB_ASSERT(e->kind == Entity_Variable);
  611. e->code_gen_module = entity_module;
  612. Ast *init_expr = var->decl->init_expr;
  613. if (init_expr != nullptr) {
  614. lbValue init = lb_build_expr(p, init_expr);
  615. if (init.value == nullptr) {
  616. LLVMTypeRef global_type = llvm_addr_type(p->module, var->var);
  617. if (is_type_untyped_undef(init.type)) {
  618. // LLVMSetInitializer(var->var.value, LLVMGetUndef(global_type));
  619. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  620. var->is_initialized = true;
  621. continue;
  622. } else if (is_type_untyped_nil(init.type)) {
  623. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  624. var->is_initialized = true;
  625. continue;
  626. }
  627. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  628. }
  629. if (is_type_any(e->type) || is_type_union(e->type)) {
  630. var->init = init;
  631. } else if (lb_is_const_or_global(init)) {
  632. if (!var->is_initialized) {
  633. if (is_type_proc(init.type)) {
  634. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  635. }
  636. LLVMSetInitializer(var->var.value, init.value);
  637. var->is_initialized = true;
  638. continue;
  639. }
  640. } else {
  641. var->init = init;
  642. }
  643. }
  644. if (var->init.value != nullptr) {
  645. GB_ASSERT(!var->is_initialized);
  646. Type *t = type_deref(var->var.type);
  647. if (is_type_any(t)) {
  648. // NOTE(bill): Edge case for 'any' type
  649. Type *var_type = default_type(var->init.type);
  650. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  651. lb_addr_store(p, g, var->init);
  652. lbValue gp = lb_addr_get_ptr(p, g);
  653. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  654. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  655. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  656. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  657. } else {
  658. LLVMTypeRef vt = llvm_addr_type(p->module, var->var);
  659. lbValue src0 = lb_emit_conv(p, var->init, t);
  660. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  661. LLVMValueRef dst = var->var.value;
  662. LLVMBuildStore(p->builder, src, dst);
  663. }
  664. var->is_initialized = true;
  665. }
  666. }
  667. CheckerInfo *info = main_module->gen->info;
  668. for (Entity *e : info->init_procedures) {
  669. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  670. lb_emit_call(p, value, {}, ProcInlining_none, false);
  671. }
  672. lb_end_procedure_body(p);
  673. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  674. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  675. LLVMDumpValue(p->value);
  676. gb_printf_err("\n\n\n\n");
  677. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  678. }
  679. lb_run_function_pass_manager(default_function_pass_manager, p);
  680. return p;
  681. }
  682. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  683. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  684. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  685. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  686. Type *params = alloc_type_tuple();
  687. Type *results = alloc_type_tuple();
  688. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  689. bool call_cleanup = true;
  690. bool has_args = false;
  691. bool is_dll_main = false;
  692. String name = str_lit("main");
  693. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  694. is_dll_main = true;
  695. name = str_lit("DllMain");
  696. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  697. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  698. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  699. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  700. call_cleanup = false;
  701. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  702. name = str_lit("mainCRTStartup");
  703. } else if (is_arch_wasm()) {
  704. name = str_lit("_start");
  705. call_cleanup = false;
  706. } else {
  707. has_args = true;
  708. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  709. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  710. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  711. }
  712. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  713. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  714. Type *proc_type = alloc_type_proc(nullptr,
  715. params, params->Tuple.variables.count,
  716. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  717. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  718. p->is_startup = true;
  719. lb_begin_procedure_body(p);
  720. if (has_args) { // initialize `runtime.args__`
  721. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  722. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  723. LLVMSetValueName2(argc.value, "argc", 4);
  724. LLVMSetValueName2(argv.value, "argv", 4);
  725. argc = lb_emit_conv(p, argc, t_int);
  726. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  727. lb_fill_slice(p, args, argv, argc);
  728. }
  729. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  730. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none, false);
  731. if (build_context.command_kind == Command_test) {
  732. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  733. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  734. Type *slice_type = alloc_type_slice(t_Internal_Test);
  735. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  736. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  737. LLVMValueRef indices[2] = {};
  738. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  739. for_array(i, m->info->testing_procedures) {
  740. Entity *testing_proc = m->info->testing_procedures[i];
  741. String name = testing_proc->token.string;
  742. String pkg_name = {};
  743. if (testing_proc->pkg != nullptr) {
  744. pkg_name = testing_proc->pkg->name;
  745. }
  746. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  747. lbValue v_name = lb_find_or_add_entity_string(m, name);
  748. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  749. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  750. LLVMValueRef vals[3] = {};
  751. vals[0] = v_pkg.value;
  752. vals[1] = v_name.value;
  753. vals[2] = v_proc.value;
  754. GB_ASSERT(LLVMIsConstant(vals[0]));
  755. GB_ASSERT(LLVMIsConstant(vals[1]));
  756. GB_ASSERT(LLVMIsConstant(vals[2]));
  757. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  758. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  759. LLVMBuildStore(p->builder, src, dst);
  760. }
  761. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  762. lb_fill_slice(p, all_tests_slice,
  763. lb_array_elem(p, all_tests_array),
  764. lb_const_int(m, t_int, m->info->testing_procedures.count));
  765. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  766. auto args = array_make<lbValue>(heap_allocator(), 1);
  767. args[0] = lb_addr_load(p, all_tests_slice);
  768. lb_emit_call(p, runner, args);
  769. } else {
  770. if (m->info->entry_point != nullptr) {
  771. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  772. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  773. }
  774. }
  775. if (call_cleanup) {
  776. lbValue cleanup_runtime_value = lb_find_runtime_value(m, str_lit("_cleanup_runtime"));
  777. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none, false);
  778. }
  779. if (is_dll_main) {
  780. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  781. } else {
  782. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  783. }
  784. lb_end_procedure_body(p);
  785. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  786. if (is_arch_wasm()) {
  787. lb_set_wasm_export_attributes(p->value, p->name);
  788. }
  789. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  790. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  791. LLVMDumpValue(p->value);
  792. gb_printf_err("\n\n\n\n");
  793. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  794. }
  795. lb_run_function_pass_manager(default_function_pass_manager, p);
  796. return p;
  797. }
  798. String lb_filepath_ll_for_module(lbModule *m) {
  799. String path = concatenate3_strings(permanent_allocator(),
  800. build_context.build_paths[BuildPath_Output].basename,
  801. STR_LIT("/"),
  802. build_context.build_paths[BuildPath_Output].name
  803. );
  804. if (m->pkg) {
  805. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  806. } else if (USE_SEPARATE_MODULES) {
  807. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  808. }
  809. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  810. return path;
  811. }
  812. String lb_filepath_obj_for_module(lbModule *m) {
  813. String path = concatenate3_strings(permanent_allocator(),
  814. build_context.build_paths[BuildPath_Output].basename,
  815. STR_LIT("/"),
  816. build_context.build_paths[BuildPath_Output].name
  817. );
  818. if (m->pkg) {
  819. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  820. }
  821. String ext = {};
  822. if (build_context.build_mode == BuildMode_Assembly) {
  823. ext = STR_LIT(".S");
  824. } else {
  825. if (is_arch_wasm()) {
  826. ext = STR_LIT(".wasm.o");
  827. } else {
  828. switch (build_context.metrics.os) {
  829. case TargetOs_windows:
  830. ext = STR_LIT(".obj");
  831. break;
  832. default:
  833. case TargetOs_darwin:
  834. case TargetOs_linux:
  835. case TargetOs_essence:
  836. ext = STR_LIT(".o");
  837. break;
  838. case TargetOs_freestanding:
  839. switch (build_context.metrics.abi) {
  840. default:
  841. case TargetABI_Default:
  842. case TargetABI_SysV:
  843. ext = STR_LIT(".o");
  844. break;
  845. case TargetABI_Win64:
  846. ext = STR_LIT(".obj");
  847. break;
  848. }
  849. break;
  850. }
  851. }
  852. }
  853. return concatenate_strings(permanent_allocator(), path, ext);
  854. }
  855. bool lb_is_module_empty(lbModule *m) {
  856. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  857. LLVMGetFirstGlobal(m->mod) == nullptr) {
  858. return true;
  859. }
  860. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  861. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  862. return false;
  863. }
  864. }
  865. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  866. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  867. continue;
  868. }
  869. if (!LLVMIsExternallyInitialized(g)) {
  870. return false;
  871. }
  872. }
  873. return true;
  874. }
  875. struct lbLLVMEmitWorker {
  876. LLVMTargetMachineRef target_machine;
  877. LLVMCodeGenFileType code_gen_file_type;
  878. String filepath_obj;
  879. lbModule *m;
  880. };
  881. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  882. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  883. char *llvm_error = nullptr;
  884. auto wd = cast(lbLLVMEmitWorker *)data;
  885. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  886. gb_printf_err("LLVM Error: %s\n", llvm_error);
  887. gb_exit(1);
  888. }
  889. return 0;
  890. }
  891. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  892. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  893. auto m = cast(lbModule *)data;
  894. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  895. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  896. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  897. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  898. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  899. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  900. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  901. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  902. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  903. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  904. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  905. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  906. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  907. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  908. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  909. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  910. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  911. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  912. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  913. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  914. for_array(i, m->procedures_to_generate) {
  915. lbProcedure *p = m->procedures_to_generate[i];
  916. if (p->body != nullptr) { // Build Procedure
  917. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  918. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  919. } else {
  920. if (p->entity && p->entity->kind == Entity_Procedure) {
  921. switch (p->entity->Procedure.optimization_mode) {
  922. case ProcedureOptimizationMode_None:
  923. case ProcedureOptimizationMode_Minimal:
  924. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  925. break;
  926. case ProcedureOptimizationMode_Size:
  927. lb_run_function_pass_manager(function_pass_manager_size, p);
  928. break;
  929. case ProcedureOptimizationMode_Speed:
  930. lb_run_function_pass_manager(function_pass_manager_speed, p);
  931. break;
  932. default:
  933. lb_run_function_pass_manager(default_function_pass_manager, p);
  934. break;
  935. }
  936. } else {
  937. lb_run_function_pass_manager(default_function_pass_manager, p);
  938. }
  939. }
  940. }
  941. }
  942. for_array(i, m->equal_procs.entries) {
  943. lbProcedure *p = m->equal_procs.entries[i].value;
  944. lb_run_function_pass_manager(default_function_pass_manager, p);
  945. }
  946. for_array(i, m->hasher_procs.entries) {
  947. lbProcedure *p = m->hasher_procs.entries[i].value;
  948. lb_run_function_pass_manager(default_function_pass_manager, p);
  949. }
  950. return 0;
  951. }
  952. struct lbLLVMModulePassWorkerData {
  953. lbModule *m;
  954. LLVMTargetMachineRef target_machine;
  955. };
  956. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  957. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  958. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  959. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  960. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  961. return 0;
  962. }
  963. void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  964. if (p->is_done) {
  965. return;
  966. }
  967. if (p->body != nullptr) { // Build Procedure
  968. m->curr_procedure = p;
  969. lb_begin_procedure_body(p);
  970. lb_build_stmt(p, p->body);
  971. lb_end_procedure_body(p);
  972. p->is_done = true;
  973. m->curr_procedure = nullptr;
  974. }
  975. lb_end_procedure(p);
  976. // Add Flags
  977. if (p->body != nullptr) {
  978. if (p->name == "memcpy" || p->name == "memmove" ||
  979. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  980. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  981. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  982. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  983. }
  984. }
  985. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  986. char *llvm_error = nullptr;
  987. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  988. LLVMDumpValue(p->value);
  989. gb_printf_err("\n\n\n\n");
  990. String filepath_ll = lb_filepath_ll_for_module(m);
  991. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  992. gb_printf_err("LLVM Error: %s\n", llvm_error);
  993. }
  994. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  995. gb_exit(1);
  996. }
  997. }
  998. void lb_generate_code(lbGenerator *gen) {
  999. TIME_SECTION("LLVM Initializtion");
  1000. isize thread_count = gb_max(build_context.thread_count, 1);
  1001. isize worker_count = thread_count-1;
  1002. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  1003. lbModule *default_module = &gen->default_module;
  1004. CheckerInfo *info = gen->info;
  1005. auto *min_dep_set = &info->minimum_dependency_set;
  1006. switch (build_context.metrics.arch) {
  1007. case TargetArch_amd64:
  1008. case TargetArch_i386:
  1009. LLVMInitializeX86TargetInfo();
  1010. LLVMInitializeX86Target();
  1011. LLVMInitializeX86TargetMC();
  1012. LLVMInitializeX86AsmPrinter();
  1013. LLVMInitializeX86AsmParser();
  1014. LLVMInitializeX86Disassembler();
  1015. break;
  1016. case TargetArch_arm64:
  1017. LLVMInitializeAArch64TargetInfo();
  1018. LLVMInitializeAArch64Target();
  1019. LLVMInitializeAArch64TargetMC();
  1020. LLVMInitializeAArch64AsmPrinter();
  1021. LLVMInitializeAArch64AsmParser();
  1022. LLVMInitializeAArch64Disassembler();
  1023. break;
  1024. case TargetArch_wasm32:
  1025. case TargetArch_wasm64:
  1026. LLVMInitializeWebAssemblyTargetInfo();
  1027. LLVMInitializeWebAssemblyTarget();
  1028. LLVMInitializeWebAssemblyTargetMC();
  1029. LLVMInitializeWebAssemblyAsmPrinter();
  1030. LLVMInitializeWebAssemblyAsmParser();
  1031. LLVMInitializeWebAssemblyDisassembler();
  1032. break;
  1033. default:
  1034. LLVMInitializeAllTargetInfos();
  1035. LLVMInitializeAllTargets();
  1036. LLVMInitializeAllTargetMCs();
  1037. LLVMInitializeAllAsmPrinters();
  1038. LLVMInitializeAllAsmParsers();
  1039. LLVMInitializeAllDisassemblers();
  1040. break;
  1041. }
  1042. if (build_context.microarch == "native") {
  1043. LLVMInitializeNativeTarget();
  1044. }
  1045. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  1046. for_array(i, gen->modules.entries) {
  1047. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  1048. }
  1049. LLVMTargetRef target = {};
  1050. char *llvm_error = nullptr;
  1051. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  1052. GB_ASSERT(target != nullptr);
  1053. TIME_SECTION("LLVM Create Target Machine");
  1054. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  1055. if (is_arch_wasm()) {
  1056. code_mode = LLVMCodeModelJITDefault;
  1057. } else if (build_context.metrics.os == TargetOs_freestanding) {
  1058. code_mode = LLVMCodeModelKernel;
  1059. }
  1060. char const *host_cpu_name = LLVMGetHostCPUName();
  1061. char const *llvm_cpu = "generic";
  1062. char const *llvm_features = "";
  1063. if (build_context.microarch.len != 0) {
  1064. if (build_context.microarch == "native") {
  1065. llvm_cpu = host_cpu_name;
  1066. } else {
  1067. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  1068. }
  1069. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  1070. llvm_features = LLVMGetHostCPUFeatures();
  1071. }
  1072. } else if (build_context.metrics.arch == TargetArch_amd64) {
  1073. // NOTE(bill): x86-64-v2 is more than enough for everyone
  1074. //
  1075. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  1076. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  1077. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  1078. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  1079. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  1080. if (build_context.metrics.os == TargetOs_freestanding) {
  1081. llvm_cpu = "x86-64";
  1082. } else {
  1083. llvm_cpu = "x86-64-v2";
  1084. }
  1085. }
  1086. }
  1087. if (build_context.target_features_set.entries.count != 0) {
  1088. llvm_features = target_features_set_to_cstring(permanent_allocator(), false);
  1089. }
  1090. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  1091. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  1092. switch (build_context.optimization_level) {
  1093. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  1094. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  1095. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  1096. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  1097. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  1098. }
  1099. // NOTE(bill): Target Machine Creation
  1100. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  1101. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  1102. // NOTE(dweiler): Dynamic libraries require position-independent code.
  1103. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  1104. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  1105. reloc_mode = LLVMRelocPIC;
  1106. }
  1107. switch (build_context.reloc_mode) {
  1108. case RelocMode_Default:
  1109. if (build_context.metrics.os == TargetOs_openbsd) {
  1110. // Always use PIC for OpenBSD: it defaults to PIE
  1111. reloc_mode = LLVMRelocPIC;
  1112. }
  1113. break;
  1114. case RelocMode_Static:
  1115. reloc_mode = LLVMRelocStatic;
  1116. break;
  1117. case RelocMode_PIC:
  1118. reloc_mode = LLVMRelocPIC;
  1119. break;
  1120. case RelocMode_DynamicNoPIC:
  1121. reloc_mode = LLVMRelocDynamicNoPic;
  1122. break;
  1123. }
  1124. for_array(i, gen->modules.entries) {
  1125. target_machines[i] = LLVMCreateTargetMachine(
  1126. target, target_triple, llvm_cpu,
  1127. llvm_features,
  1128. code_gen_level,
  1129. reloc_mode,
  1130. code_mode);
  1131. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  1132. }
  1133. for_array(i, gen->modules.entries) {
  1134. lbModule *m = gen->modules.entries[i].value;
  1135. if (m->debug_builder) { // Debug Info
  1136. for_array(i, info->files.entries) {
  1137. AstFile *f = info->files.entries[i].value;
  1138. String fullpath = f->fullpath;
  1139. String filename = remove_directory_from_path(fullpath);
  1140. String directory = directory_from_path(fullpath);
  1141. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  1142. cast(char const *)filename.text, filename.len,
  1143. cast(char const *)directory.text, directory.len);
  1144. lb_set_llvm_metadata(m, f, res);
  1145. }
  1146. gbString producer = gb_string_make(heap_allocator(), "odin");
  1147. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  1148. // #ifdef NIGHTLY
  1149. // producer = gb_string_appendc(producer, "-nightly");
  1150. // #endif
  1151. // #ifdef GIT_SHA
  1152. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  1153. // #endif
  1154. gbString split_name = gb_string_make(heap_allocator(), "");
  1155. LLVMBool is_optimized = build_context.optimization_level > 0;
  1156. AstFile *init_file = m->info->init_package->files[0];
  1157. if (Entity *entry_point = m->info->entry_point) {
  1158. if (Ast *ident = entry_point->identifier.load()) {
  1159. if (ident->file_id) {
  1160. init_file = ident->file();
  1161. }
  1162. }
  1163. }
  1164. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  1165. LLVMBool debug_info_for_profiling = false;
  1166. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  1167. lb_get_llvm_metadata(m, init_file),
  1168. producer, gb_string_length(producer),
  1169. is_optimized, "", 0,
  1170. 1, split_name, gb_string_length(split_name),
  1171. LLVMDWARFEmissionFull,
  1172. 0, split_debug_inlining,
  1173. debug_info_for_profiling,
  1174. "", 0, // sys_root
  1175. "", 0 // SDK
  1176. );
  1177. GB_ASSERT(m->debug_compile_unit != nullptr);
  1178. }
  1179. }
  1180. TIME_SECTION("LLVM Global Variables");
  1181. if (!build_context.disallow_rtti) {
  1182. lbModule *m = default_module;
  1183. { // Add type info data
  1184. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  1185. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  1186. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  1187. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  1188. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1189. if (!USE_SEPARATE_MODULES) {
  1190. LLVMSetLinkage(g, LLVMInternalLinkage);
  1191. }
  1192. lbValue value = {};
  1193. value.value = g;
  1194. value.type = alloc_type_pointer(t);
  1195. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  1196. lb_add_entity(m, lb_global_type_info_data_entity, value);
  1197. }
  1198. { // Type info member buffer
  1199. // NOTE(bill): Removes need for heap allocation by making it global memory
  1200. isize count = 0;
  1201. for_array(entry_index, m->info->type_info_types) {
  1202. Type *t = m->info->type_info_types[entry_index];
  1203. isize index = lb_type_info_index(m->info, t, false);
  1204. if (index < 0) {
  1205. continue;
  1206. }
  1207. switch (t->kind) {
  1208. case Type_Union:
  1209. count += t->Union.variants.count;
  1210. break;
  1211. case Type_Struct:
  1212. count += t->Struct.fields.count;
  1213. break;
  1214. case Type_Tuple:
  1215. count += t->Tuple.variables.count;
  1216. break;
  1217. }
  1218. }
  1219. if (count > 0) {
  1220. {
  1221. char const *name = LB_TYPE_INFO_TYPES_NAME;
  1222. Type *t = alloc_type_array(t_type_info_ptr, count);
  1223. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1224. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1225. LLVMSetLinkage(g, LLVMInternalLinkage);
  1226. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  1227. }
  1228. {
  1229. char const *name = LB_TYPE_INFO_NAMES_NAME;
  1230. Type *t = alloc_type_array(t_string, count);
  1231. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1232. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1233. LLVMSetLinkage(g, LLVMInternalLinkage);
  1234. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  1235. }
  1236. {
  1237. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  1238. Type *t = alloc_type_array(t_uintptr, count);
  1239. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1240. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1241. LLVMSetLinkage(g, LLVMInternalLinkage);
  1242. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  1243. }
  1244. {
  1245. char const *name = LB_TYPE_INFO_USINGS_NAME;
  1246. Type *t = alloc_type_array(t_bool, count);
  1247. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1248. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1249. LLVMSetLinkage(g, LLVMInternalLinkage);
  1250. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  1251. }
  1252. {
  1253. char const *name = LB_TYPE_INFO_TAGS_NAME;
  1254. Type *t = alloc_type_array(t_string, count);
  1255. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1256. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1257. LLVMSetLinkage(g, LLVMInternalLinkage);
  1258. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  1259. }
  1260. }
  1261. }
  1262. }
  1263. isize global_variable_max_count = 0;
  1264. bool already_has_entry_point = false;
  1265. for_array(i, info->entities) {
  1266. Entity *e = info->entities[i];
  1267. String name = e->token.string;
  1268. if (e->kind == Entity_Variable) {
  1269. global_variable_max_count++;
  1270. } else if (e->kind == Entity_Procedure) {
  1271. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  1272. GB_ASSERT(e == info->entry_point);
  1273. }
  1274. if (build_context.command_kind == Command_test &&
  1275. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  1276. String link_name = e->Procedure.link_name;
  1277. if (e->pkg->kind == Package_Runtime) {
  1278. if (link_name == "main" ||
  1279. link_name == "DllMain" ||
  1280. link_name == "WinMain" ||
  1281. link_name == "wWinMain" ||
  1282. link_name == "mainCRTStartup" ||
  1283. link_name == "_start") {
  1284. already_has_entry_point = true;
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  1291. for_array(i, info->variable_init_order) {
  1292. DeclInfo *d = info->variable_init_order[i];
  1293. Entity *e = d->entity;
  1294. if ((e->scope->flags & ScopeFlag_File) == 0) {
  1295. continue;
  1296. }
  1297. if (!ptr_set_exists(min_dep_set, e)) {
  1298. continue;
  1299. }
  1300. DeclInfo *decl = decl_info_of_entity(e);
  1301. if (decl == nullptr) {
  1302. continue;
  1303. }
  1304. GB_ASSERT(e->kind == Entity_Variable);
  1305. bool is_foreign = e->Variable.is_foreign;
  1306. bool is_export = e->Variable.is_export;
  1307. lbModule *m = &gen->default_module;
  1308. String name = lb_get_entity_name(m, e);
  1309. lbValue g = {};
  1310. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1311. g.type = alloc_type_pointer(e->type);
  1312. if (e->Variable.thread_local_model != "") {
  1313. LLVMSetThreadLocal(g.value, true);
  1314. String m = e->Variable.thread_local_model;
  1315. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1316. if (m == "default") {
  1317. mode = LLVMGeneralDynamicTLSModel;
  1318. } else if (m == "localdynamic") {
  1319. mode = LLVMLocalDynamicTLSModel;
  1320. } else if (m == "initialexec") {
  1321. mode = LLVMInitialExecTLSModel;
  1322. } else if (m == "localexec") {
  1323. mode = LLVMLocalExecTLSModel;
  1324. } else {
  1325. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1326. }
  1327. LLVMSetThreadLocalMode(g.value, mode);
  1328. }
  1329. if (is_foreign) {
  1330. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1331. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  1332. LLVMSetExternallyInitialized(g.value, true);
  1333. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  1334. lb_set_wasm_import_attributes(g.value, e, name);
  1335. } else {
  1336. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  1337. }
  1338. if (is_export) {
  1339. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  1340. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  1341. } else if (!is_foreign) {
  1342. if (USE_SEPARATE_MODULES) {
  1343. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1344. } else {
  1345. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  1346. }
  1347. }
  1348. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  1349. if (e->Variable.link_section.len > 0) {
  1350. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  1351. }
  1352. lbGlobalVariable var = {};
  1353. var.var = g;
  1354. var.decl = decl;
  1355. if (decl->init_expr != nullptr) {
  1356. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  1357. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  1358. if (tav.mode != Addressing_Invalid) {
  1359. if (tav.value.kind != ExactValue_Invalid) {
  1360. ExactValue v = tav.value;
  1361. lbValue init = lb_const_value(m, tav.type, v);
  1362. LLVMSetInitializer(g.value, init.value);
  1363. var.is_initialized = true;
  1364. }
  1365. }
  1366. }
  1367. if (!var.is_initialized &&
  1368. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  1369. var.is_initialized = true;
  1370. }
  1371. }
  1372. array_add(&global_variables, var);
  1373. lb_add_entity(m, e, g);
  1374. lb_add_member(m, name, g);
  1375. if (m->debug_builder) {
  1376. String global_name = e->token.string;
  1377. if (global_name.len != 0 && global_name != "_") {
  1378. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  1379. LLVMMetadataRef llvm_scope = llvm_file;
  1380. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  1381. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  1382. LLVMMetadataRef llvm_decl = nullptr;
  1383. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  1384. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  1385. m->debug_builder, llvm_scope,
  1386. cast(char const *)global_name.text, global_name.len,
  1387. "", 0, // linkage
  1388. llvm_file, e->token.pos.line,
  1389. lb_debug_type(m, e->type),
  1390. local_to_unit,
  1391. llvm_expr,
  1392. llvm_decl,
  1393. align_in_bits
  1394. );
  1395. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  1396. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  1397. }
  1398. }
  1399. }
  1400. TIME_SECTION("LLVM Runtime Type Information Creation");
  1401. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  1402. lbProcedure *objc_names = lb_create_objc_names(default_module);
  1403. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  1404. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, objc_names, global_variables);
  1405. gb_unused(startup_runtime);
  1406. TIME_SECTION("LLVM Global Procedures and Types");
  1407. for_array(i, info->entities) {
  1408. Entity *e = info->entities[i];
  1409. String name = e->token.string;
  1410. Scope * scope = e->scope;
  1411. if ((scope->flags & ScopeFlag_File) == 0) {
  1412. continue;
  1413. }
  1414. Scope *package_scope = scope->parent;
  1415. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1416. switch (e->kind) {
  1417. case Entity_Variable:
  1418. // NOTE(bill): Handled above as it requires a specific load order
  1419. continue;
  1420. case Entity_ProcGroup:
  1421. continue;
  1422. case Entity_TypeName:
  1423. case Entity_Procedure:
  1424. break;
  1425. }
  1426. bool polymorphic_struct = false;
  1427. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1428. Type *bt = base_type(e->type);
  1429. if (bt->kind == Type_Struct) {
  1430. polymorphic_struct = is_type_polymorphic(bt);
  1431. }
  1432. }
  1433. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1434. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1435. continue;
  1436. }
  1437. lbModule *m = &gen->default_module;
  1438. if (USE_SEPARATE_MODULES) {
  1439. m = lb_pkg_module(gen, e->pkg);
  1440. }
  1441. String mangled_name = lb_get_entity_name(m, e);
  1442. switch (e->kind) {
  1443. case Entity_TypeName:
  1444. lb_type(m, e->type);
  1445. break;
  1446. case Entity_Procedure:
  1447. {
  1448. lbProcedure *p = lb_create_procedure(m, e);
  1449. array_add(&m->procedures_to_generate, p);
  1450. }
  1451. break;
  1452. }
  1453. }
  1454. TIME_SECTION("LLVM Procedure Generation");
  1455. for_array(j, gen->modules.entries) {
  1456. lbModule *m = gen->modules.entries[j].value;
  1457. for_array(i, m->procedures_to_generate) {
  1458. lbProcedure *p = m->procedures_to_generate[i];
  1459. lb_generate_procedure(m, p);
  1460. }
  1461. }
  1462. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  1463. TIME_SECTION("LLVM main");
  1464. lb_create_main_procedure(default_module, startup_runtime);
  1465. }
  1466. for_array(j, gen->modules.entries) {
  1467. lbModule *m = gen->modules.entries[j].value;
  1468. for_array(i, m->missing_procedures_to_check) {
  1469. lbProcedure *p = m->missing_procedures_to_check[i];
  1470. debugf("Generate missing procedure: %.*s\n", LIT(p->name));
  1471. lb_generate_procedure(m, p);
  1472. }
  1473. }
  1474. lb_finalize_objc_names(objc_names);
  1475. if (build_context.ODIN_DEBUG) {
  1476. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  1477. for_array(j, gen->modules.entries) {
  1478. lbModule *m = gen->modules.entries[j].value;
  1479. if (m->debug_builder != nullptr) {
  1480. lb_debug_complete_types(m);
  1481. LLVMDIBuilderFinalize(m->debug_builder);
  1482. }
  1483. }
  1484. }
  1485. TIME_SECTION("LLVM Function Pass");
  1486. for_array(i, gen->modules.entries) {
  1487. lbModule *m = gen->modules.entries[i].value;
  1488. lb_llvm_function_pass_worker_proc(m);
  1489. }
  1490. TIME_SECTION("LLVM Module Pass");
  1491. for_array(i, gen->modules.entries) {
  1492. lbModule *m = gen->modules.entries[i].value;
  1493. lb_run_remove_unused_function_pass(m);
  1494. lb_run_remove_unused_globals_pass(m);
  1495. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1496. wd->m = m;
  1497. wd->target_machine = target_machines[i];
  1498. lb_llvm_module_pass_worker_proc(wd);
  1499. }
  1500. llvm_error = nullptr;
  1501. defer (LLVMDisposeMessage(llvm_error));
  1502. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1503. if (build_context.build_mode == BuildMode_Assembly) {
  1504. code_gen_file_type = LLVMAssemblyFile;
  1505. }
  1506. for_array(j, gen->modules.entries) {
  1507. lbModule *m = gen->modules.entries[j].value;
  1508. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1509. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1510. if (build_context.keep_temp_files) {
  1511. TIME_SECTION("LLVM Print Module to File");
  1512. String filepath_ll = lb_filepath_ll_for_module(m);
  1513. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1514. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1515. gb_exit(1);
  1516. return;
  1517. }
  1518. }
  1519. gb_exit(1);
  1520. return;
  1521. }
  1522. }
  1523. llvm_error = nullptr;
  1524. if (build_context.keep_temp_files ||
  1525. build_context.build_mode == BuildMode_LLVM_IR) {
  1526. TIME_SECTION("LLVM Print Module to File");
  1527. for_array(j, gen->modules.entries) {
  1528. lbModule *m = gen->modules.entries[j].value;
  1529. if (lb_is_module_empty(m)) {
  1530. continue;
  1531. }
  1532. String filepath_ll = lb_filepath_ll_for_module(m);
  1533. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1534. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1535. gb_exit(1);
  1536. return;
  1537. }
  1538. array_add(&gen->output_temp_paths, filepath_ll);
  1539. }
  1540. if (build_context.build_mode == BuildMode_LLVM_IR) {
  1541. gb_exit(0);
  1542. return;
  1543. }
  1544. }
  1545. TIME_SECTION("LLVM Add Foreign Library Paths");
  1546. for_array(j, gen->modules.entries) {
  1547. lbModule *m = gen->modules.entries[j].value;
  1548. for_array(i, m->info->required_foreign_imports_through_force) {
  1549. Entity *e = m->info->required_foreign_imports_through_force[i];
  1550. lb_add_foreign_library_path(m, e);
  1551. }
  1552. if (lb_is_module_empty(m)) {
  1553. continue;
  1554. }
  1555. }
  1556. TIME_SECTION("LLVM Object Generation");
  1557. isize non_empty_module_count = 0;
  1558. for_array(j, gen->modules.entries) {
  1559. lbModule *m = gen->modules.entries[j].value;
  1560. if (!lb_is_module_empty(m)) {
  1561. non_empty_module_count += 1;
  1562. }
  1563. }
  1564. if (do_threading && non_empty_module_count > 1) {
  1565. for_array(j, gen->modules.entries) {
  1566. lbModule *m = gen->modules.entries[j].value;
  1567. if (lb_is_module_empty(m)) {
  1568. continue;
  1569. }
  1570. String filepath_ll = lb_filepath_ll_for_module(m);
  1571. String filepath_obj = lb_filepath_obj_for_module(m);
  1572. array_add(&gen->output_object_paths, filepath_obj);
  1573. array_add(&gen->output_temp_paths, filepath_ll);
  1574. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1575. wd->target_machine = target_machines[j];
  1576. wd->code_gen_file_type = code_gen_file_type;
  1577. wd->filepath_obj = filepath_obj;
  1578. wd->m = m;
  1579. global_thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1580. }
  1581. thread_pool_wait(&global_thread_pool);
  1582. } else {
  1583. for_array(j, gen->modules.entries) {
  1584. lbModule *m = gen->modules.entries[j].value;
  1585. if (lb_is_module_empty(m)) {
  1586. continue;
  1587. }
  1588. String filepath_obj = lb_filepath_obj_for_module(m);
  1589. array_add(&gen->output_object_paths, filepath_obj);
  1590. String short_name = remove_directory_from_path(filepath_obj);
  1591. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  1592. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1593. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1594. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1595. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1596. gb_exit(1);
  1597. return;
  1598. }
  1599. }
  1600. }
  1601. gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
  1602. }