llvm_backend.cpp 54 KB

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