llvm_backend.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053
  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. gb_internal 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_internal 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. gb_internal 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. gb_internal void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  84. TEMPORARY_ALLOCATOR_GUARD();
  85. GB_ASSERT(addr.kind == lbAddr_Context);
  86. GB_ASSERT(addr.ctx.sel.index.count == 0);
  87. auto args = array_make<lbValue>(temporary_allocator(), 1);
  88. args[0] = addr.addr;
  89. lb_emit_runtime_call(p, "__init_context", args);
  90. }
  91. gb_internal lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  92. Type *pt = base_type(p->type);
  93. GB_ASSERT(pt->kind == Type_Proc);
  94. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  95. String name = str_lit("__.context_ptr");
  96. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  97. e->flags |= EntityFlag_NoAlias;
  98. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  99. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  100. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  101. lbValue param = {context_ptr, e->type};
  102. lb_add_entity(p->module, e, param);
  103. lbAddr ctx_addr = {};
  104. ctx_addr.kind = lbAddr_Context;
  105. ctx_addr.addr = param;
  106. lbContextData *cd = array_add_and_get(&p->context_stack);
  107. cd->ctx = ctx_addr;
  108. cd->scope_index = -1;
  109. cd->uses = +1; // make sure it has been used already
  110. return cd;
  111. }
  112. gb_internal lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  113. ctx.kind = lbAddr_Context;
  114. lbContextData *cd = array_add_and_get(&p->context_stack);
  115. cd->ctx = ctx;
  116. cd->scope_index = p->scope_index;
  117. return cd;
  118. }
  119. gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
  120. type = base_type(type);
  121. GB_ASSERT(is_type_comparable(type));
  122. Type *pt = alloc_type_pointer(type);
  123. LLVMTypeRef ptr_type = lb_type(m, pt);
  124. lbProcedure **found = map_get(&m->equal_procs, type);
  125. lbProcedure *compare_proc = nullptr;
  126. if (found) {
  127. compare_proc = *found;
  128. GB_ASSERT(compare_proc != nullptr);
  129. return {compare_proc->value, compare_proc->type};
  130. }
  131. static std::atomic<u32> proc_index;
  132. char buf[32] = {};
  133. isize n = gb_snprintf(buf, 32, "__$equal%u", 1+proc_index.fetch_add(1));
  134. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  135. String proc_name = make_string_c(str);
  136. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  137. map_set(&m->equal_procs, type, p);
  138. lb_begin_procedure_body(p);
  139. // lb_add_attribute_to_proc(m, p->value, "readonly");
  140. lb_add_attribute_to_proc(m, p->value, "nounwind");
  141. LLVMValueRef x = LLVMGetParam(p->value, 0);
  142. LLVMValueRef y = LLVMGetParam(p->value, 1);
  143. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  144. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  145. lbValue lhs = {x, pt};
  146. lbValue rhs = {y, pt};
  147. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  148. lb_add_proc_attribute_at_index(p, 1+1, "nonnull");
  149. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  150. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  151. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  152. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  153. lb_start_block(p, block_same_ptr);
  154. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  155. lb_start_block(p, block_diff_ptr);
  156. if (type->kind == Type_Struct) {
  157. type_set_offsets(type);
  158. lbBlock *block_false = lb_create_block(p, "bfalse");
  159. lbValue res = lb_const_bool(m, t_bool, true);
  160. for_array(i, type->Struct.fields) {
  161. lbBlock *next_block = lb_create_block(p, "btrue");
  162. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  163. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  164. lbValue left = lb_emit_load(p, pleft);
  165. lbValue right = lb_emit_load(p, pright);
  166. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  167. lb_emit_if(p, ok, next_block, block_false);
  168. lb_emit_jump(p, next_block);
  169. lb_start_block(p, next_block);
  170. }
  171. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  172. lb_start_block(p, block_false);
  173. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  174. } else if (type->kind == Type_Union) {
  175. if (type_size_of(type) == 0) {
  176. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  177. } else if (is_type_union_maybe_pointer(type)) {
  178. Type *v = type->Union.variants[0];
  179. Type *pv = alloc_type_pointer(v);
  180. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  181. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  182. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  183. ok = lb_emit_conv(p, ok, t_bool);
  184. LLVMBuildRet(p->builder, ok.value);
  185. } else {
  186. lbBlock *block_false = lb_create_block(p, "bfalse");
  187. lbBlock *block_switch = lb_create_block(p, "bswitch");
  188. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  189. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  190. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  191. lb_emit_if(p, tag_eq, block_switch, block_false);
  192. lb_start_block(p, block_switch);
  193. unsigned variant_count = cast(unsigned)type->Union.variants.count;
  194. if (type->Union.kind != UnionType_no_nil) {
  195. variant_count += 1;
  196. }
  197. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, variant_count);
  198. if (type->Union.kind != UnionType_no_nil) {
  199. lbBlock *case_block = lb_create_block(p, "bcase");
  200. lb_start_block(p, case_block);
  201. lbValue case_tag = lb_const_int(p->module, union_tag_type(type), 0);
  202. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  203. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  204. }
  205. for (Type *v : type->Union.variants) {
  206. lbBlock *case_block = lb_create_block(p, "bcase");
  207. lb_start_block(p, case_block);
  208. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  209. Type *vp = alloc_type_pointer(v);
  210. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  211. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  212. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  213. ok = lb_emit_conv(p, ok, t_bool);
  214. LLVMBuildRet(p->builder, ok.value);
  215. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  216. }
  217. lb_start_block(p, block_false);
  218. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  219. }
  220. } else {
  221. lbValue left = lb_emit_load(p, lhs);
  222. lbValue right = lb_emit_load(p, rhs);
  223. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  224. ok = lb_emit_conv(p, ok, t_bool);
  225. LLVMBuildRet(p->builder, ok.value);
  226. }
  227. lb_end_procedure_body(p);
  228. compare_proc = p;
  229. return {compare_proc->value, compare_proc->type};
  230. }
  231. gb_internal lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  232. TEMPORARY_ALLOCATOR_GUARD();
  233. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  234. auto args = array_make<lbValue>(temporary_allocator(), 3);
  235. args[0] = data;
  236. args[1] = seed;
  237. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  238. return lb_emit_runtime_call(p, "default_hasher", args);
  239. }
  240. gb_internal void lb_add_callsite_force_inline(lbProcedure *p, lbValue ret_value) {
  241. LLVMAddCallSiteAttribute(ret_value.value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  242. }
  243. gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
  244. type = core_type(type);
  245. GB_ASSERT_MSG(is_type_valid_for_keys(type), "%s", type_to_string(type));
  246. Type *pt = alloc_type_pointer(type);
  247. lbProcedure **found = map_get(&m->hasher_procs, type);
  248. if (found) {
  249. GB_ASSERT(*found != nullptr);
  250. return {(*found)->value, (*found)->type};
  251. }
  252. static std::atomic<u32> proc_index;
  253. char buf[32] = {};
  254. isize n = gb_snprintf(buf, 32, "__$hasher%u", 1+proc_index.fetch_add(1));
  255. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  256. String proc_name = make_string_c(str);
  257. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  258. map_set(&m->hasher_procs, type, p);
  259. lb_begin_procedure_body(p);
  260. defer (lb_end_procedure_body(p));
  261. // lb_add_attribute_to_proc(m, p->value, "readonly");
  262. lb_add_attribute_to_proc(m, p->value, "nounwind");
  263. LLVMValueRef x = LLVMGetParam(p->value, 0);
  264. LLVMValueRef y = LLVMGetParam(p->value, 1);
  265. lbValue data = {x, t_rawptr};
  266. lbValue seed = {y, t_uintptr};
  267. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  268. // lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  269. if (is_type_simple_compare(type)) {
  270. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  271. lb_add_callsite_force_inline(p, res);
  272. LLVMBuildRet(p->builder, res.value);
  273. return {p->value, p->type};
  274. }
  275. TEMPORARY_ALLOCATOR_GUARD();
  276. if (type->kind == Type_Struct) {
  277. type_set_offsets(type);
  278. data = lb_emit_conv(p, data, t_u8_ptr);
  279. auto args = array_make<lbValue>(temporary_allocator(), 2);
  280. for_array(i, type->Struct.fields) {
  281. GB_ASSERT(type->Struct.offsets != nullptr);
  282. i64 offset = type->Struct.offsets[i];
  283. Entity *field = type->Struct.fields[i];
  284. lbValue field_hasher = lb_hasher_proc_for_type(m, field->type);
  285. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  286. args[0] = ptr;
  287. args[1] = seed;
  288. seed = lb_emit_call(p, field_hasher, args);
  289. }
  290. LLVMBuildRet(p->builder, seed.value);
  291. } else if (type->kind == Type_Union) {
  292. auto args = array_make<lbValue>(temporary_allocator(), 2);
  293. if (is_type_union_maybe_pointer(type)) {
  294. Type *v = type->Union.variants[0];
  295. lbValue variant_hasher = lb_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. lb_add_callsite_force_inline(p, res);
  300. LLVMBuildRet(p->builder, res.value);
  301. }
  302. lbBlock *end_block = lb_create_block(p, "bend");
  303. data = lb_emit_conv(p, data, pt);
  304. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  305. lbValue tag = lb_emit_load(p, tag_ptr);
  306. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  307. for (Type *v : type->Union.variants) {
  308. lbBlock *case_block = lb_create_block(p, "bcase");
  309. lb_start_block(p, case_block);
  310. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  311. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  312. args[0] = data;
  313. args[1] = seed;
  314. lbValue res = lb_emit_call(p, variant_hasher, args);
  315. LLVMBuildRet(p->builder, res.value);
  316. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  317. }
  318. lb_start_block(p, end_block);
  319. LLVMBuildRet(p->builder, seed.value);
  320. } else if (type->kind == Type_Array) {
  321. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  322. lb_addr_store(p, pres, seed);
  323. auto args = array_make<lbValue>(temporary_allocator(), 2);
  324. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->Array.elem);
  325. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  326. data = lb_emit_conv(p, data, pt);
  327. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  328. args[0] = ptr;
  329. args[1] = lb_addr_load(p, pres);
  330. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  331. lb_addr_store(p, pres, new_seed);
  332. lb_loop_end(p, loop_data);
  333. lbValue res = lb_addr_load(p, pres);
  334. LLVMBuildRet(p->builder, res.value);
  335. } else if (type->kind == Type_EnumeratedArray) {
  336. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  337. lb_addr_store(p, res, seed);
  338. auto args = array_make<lbValue>(temporary_allocator(), 2);
  339. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  340. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  341. data = lb_emit_conv(p, data, pt);
  342. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  343. args[0] = ptr;
  344. args[1] = lb_addr_load(p, res);
  345. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  346. lb_addr_store(p, res, new_seed);
  347. lb_loop_end(p, loop_data);
  348. lbValue vres = lb_addr_load(p, res);
  349. LLVMBuildRet(p->builder, vres.value);
  350. } else if (is_type_cstring(type)) {
  351. auto args = array_make<lbValue>(temporary_allocator(), 2);
  352. args[0] = data;
  353. args[1] = seed;
  354. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  355. lb_add_callsite_force_inline(p, res);
  356. LLVMBuildRet(p->builder, res.value);
  357. } else if (is_type_string(type)) {
  358. auto args = array_make<lbValue>(temporary_allocator(), 2);
  359. args[0] = data;
  360. args[1] = seed;
  361. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  362. lb_add_callsite_force_inline(p, res);
  363. LLVMBuildRet(p->builder, res.value);
  364. } else {
  365. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  366. }
  367. return {p->value, p->type};
  368. }
  369. #define LLVM_SET_VALUE_NAME(value, name) LLVMSetValueName2((value), (name), gb_count_of((name))-1);
  370. gb_internal lbValue lb_map_get_proc_for_type(lbModule *m, Type *type) {
  371. GB_ASSERT(!build_context.dynamic_map_calls);
  372. type = base_type(type);
  373. GB_ASSERT(type->kind == Type_Map);
  374. lbProcedure **found = map_get(&m->map_get_procs, type);
  375. if (found) {
  376. GB_ASSERT(*found != nullptr);
  377. return {(*found)->value, (*found)->type};
  378. }
  379. static std::atomic<u32> proc_index;
  380. char buf[32] = {};
  381. isize n = gb_snprintf(buf, 32, "__$map_get-%u", 1+proc_index.fetch_add(1));
  382. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  383. String proc_name = make_string_c(str);
  384. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_get_proc);
  385. map_set(&m->map_get_procs, type, p);
  386. lb_begin_procedure_body(p);
  387. defer (lb_end_procedure_body(p));
  388. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  389. lb_add_attribute_to_proc(m, p->value, "nounwind");
  390. if (build_context.ODIN_DEBUG) {
  391. lb_add_attribute_to_proc(m, p->value, "noinline");
  392. }
  393. LLVMValueRef x = LLVMGetParam(p->value, 0);
  394. LLVMValueRef y = LLVMGetParam(p->value, 1);
  395. LLVMValueRef z = LLVMGetParam(p->value, 2);
  396. lbValue map_ptr = {x, t_rawptr};
  397. lbValue h = {y, t_uintptr};
  398. lbValue key_ptr = {z, t_rawptr};
  399. LLVM_SET_VALUE_NAME(h.value, "hash");
  400. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  401. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  402. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  403. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  404. lbBlock *loop_block = lb_create_block(p, "loop");
  405. lbBlock *hash_block = lb_create_block(p, "hash");
  406. lbBlock *probe_block = lb_create_block(p, "probe");
  407. lbBlock *increment_block = lb_create_block(p, "increment");
  408. lbBlock *hash_compare_block = lb_create_block(p, "hash_compare");
  409. lbBlock *key_compare_block = lb_create_block(p, "key_compare");
  410. lbBlock *value_block = lb_create_block(p, "value");
  411. lbBlock *nil_block = lb_create_block(p, "nil");
  412. map_ptr = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  413. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  414. lbValue map = lb_emit_load(p, map_ptr);
  415. LLVM_SET_VALUE_NAME(map.value, "map");
  416. lbValue length = lb_map_len(p, map);
  417. LLVM_SET_VALUE_NAME(length.value, "length");
  418. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, length, lb_const_nil(m, t_int)), nil_block, hash_block);
  419. lb_start_block(p, hash_block);
  420. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  421. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  422. lbValue key = lb_emit_load(p, key_ptr);
  423. LLVM_SET_VALUE_NAME(key.value, "key");
  424. lbAddr pos = lb_add_local_generated(p, t_uintptr, false);
  425. lbAddr distance = lb_add_local_generated(p, t_uintptr, true);
  426. LLVM_SET_VALUE_NAME(pos.addr.value, "pos");
  427. LLVM_SET_VALUE_NAME(distance.addr.value, "distance");
  428. lbValue capacity = lb_map_cap(p, map);
  429. LLVM_SET_VALUE_NAME(capacity.value, "capacity");
  430. lbValue cap_minus_1 = lb_emit_arith(p, Token_Sub, capacity, lb_const_int(m, t_int, 1), t_int);
  431. lbValue mask = lb_emit_conv(p, cap_minus_1, t_uintptr);
  432. LLVM_SET_VALUE_NAME(mask.value, "mask");
  433. {
  434. // map_desired_position inlined
  435. lbValue the_pos = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  436. the_pos = lb_emit_conv(p, the_pos, t_uintptr);
  437. lb_addr_store(p, pos, the_pos);
  438. }
  439. lbValue zero_uintptr = lb_const_int(m, t_uintptr, 0);
  440. lbValue one_uintptr = lb_const_int(m, t_uintptr, 1);
  441. lbValue ks = lb_map_data_uintptr(p, map);
  442. lbValue vs = lb_map_cell_index_static(p, type->Map.key, ks, capacity);
  443. lbValue hs = lb_map_cell_index_static(p, type->Map.value, vs, capacity);
  444. ks = lb_emit_conv(p, ks, alloc_type_pointer(type->Map.key));
  445. vs = lb_emit_conv(p, vs, alloc_type_pointer(type->Map.value));
  446. hs = lb_emit_conv(p, hs, alloc_type_pointer(t_uintptr));
  447. LLVM_SET_VALUE_NAME(ks.value, "ks");
  448. LLVM_SET_VALUE_NAME(vs.value, "vs");
  449. LLVM_SET_VALUE_NAME(hs.value, "hs");
  450. lb_emit_jump(p, loop_block);
  451. lb_start_block(p, loop_block);
  452. lbValue element_hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, lb_addr_load(p, pos)));
  453. LLVM_SET_VALUE_NAME(element_hash.value, "element_hash");
  454. {
  455. // if element_hash == 0 { return nil }
  456. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, zero_uintptr), nil_block, probe_block);
  457. }
  458. lb_start_block(p, probe_block);
  459. {
  460. // map_probe_distance inlined
  461. lbValue probe_distance = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  462. probe_distance = lb_emit_conv(p, probe_distance, t_uintptr);
  463. lbValue cap = lb_emit_conv(p, capacity, t_uintptr);
  464. lbValue base = lb_emit_arith(p, Token_Add, lb_addr_load(p, pos), cap, t_uintptr);
  465. probe_distance = lb_emit_arith(p, Token_Sub, base, probe_distance, t_uintptr);
  466. probe_distance = lb_emit_arith(p, Token_And, probe_distance, mask, t_uintptr);
  467. LLVM_SET_VALUE_NAME(probe_distance.value, "probe_distance");
  468. lbValue cond = lb_emit_comp(p, Token_Gt, lb_addr_load(p, distance), probe_distance);
  469. lb_emit_if(p, cond, nil_block, hash_compare_block);
  470. }
  471. lb_start_block(p, hash_compare_block);
  472. {
  473. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, h), key_compare_block, increment_block);
  474. }
  475. lb_start_block(p, key_compare_block);
  476. {
  477. lbValue element_key = lb_map_cell_index_static(p, type->Map.key, ks, lb_addr_load(p, pos));
  478. element_key = lb_emit_conv(p, element_key, ks.type);
  479. LLVM_SET_VALUE_NAME(element_key.value, "element_key_ptr");
  480. lbValue cond = lb_emit_comp(p, Token_CmpEq, lb_emit_load(p, element_key), key);
  481. lb_emit_if(p, cond, value_block, increment_block);
  482. }
  483. lb_start_block(p, value_block);
  484. {
  485. lbValue element_value = lb_map_cell_index_static(p, type->Map.value, vs, lb_addr_load(p, pos));
  486. LLVM_SET_VALUE_NAME(element_value.value, "element_value_ptr");
  487. element_value = lb_emit_conv(p, element_value, t_rawptr);
  488. LLVMBuildRet(p->builder, element_value.value);
  489. }
  490. lb_start_block(p, increment_block);
  491. {
  492. lbValue pp = lb_addr_load(p, pos);
  493. pp = lb_emit_arith(p, Token_Add, pp, one_uintptr, t_uintptr);
  494. pp = lb_emit_arith(p, Token_And, pp, mask, t_uintptr);
  495. lb_addr_store(p, pos, pp);
  496. lb_emit_increment(p, distance.addr);
  497. }
  498. lb_emit_jump(p, loop_block);
  499. lb_start_block(p, nil_block);
  500. {
  501. lbValue res = lb_const_nil(m, t_rawptr);
  502. LLVMBuildRet(p->builder, res.value);
  503. }
  504. // gb_printf_err("%s\n", LLVMPrintValueToString(p->value));
  505. return {p->value, p->type};
  506. }
  507. // gb_internal void lb_debug_print(lbProcedure *p, String const &str) {
  508. // auto args = array_make<lbValue>(heap_allocator(), 1);
  509. // args[0] = lb_const_string(p->module, str);
  510. // lb_emit_runtime_call(p, "print_string", args);
  511. // }
  512. gb_internal lbValue lb_map_set_proc_for_type(lbModule *m, Type *type) {
  513. TEMPORARY_ALLOCATOR_GUARD();
  514. GB_ASSERT(!build_context.dynamic_map_calls);
  515. type = base_type(type);
  516. GB_ASSERT(type->kind == Type_Map);
  517. lbProcedure **found = map_get(&m->map_set_procs, type);
  518. if (found) {
  519. GB_ASSERT(*found != nullptr);
  520. return {(*found)->value, (*found)->type};
  521. }
  522. static std::atomic<u32> proc_index;
  523. char buf[32] = {};
  524. isize n = gb_snprintf(buf, 32, "__$map_set-%u", 1+proc_index.fetch_add(1));
  525. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  526. String proc_name = make_string_c(str);
  527. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_set_proc);
  528. map_set(&m->map_set_procs, type, p);
  529. lb_begin_procedure_body(p);
  530. defer (lb_end_procedure_body(p));
  531. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  532. lb_add_attribute_to_proc(m, p->value, "nounwind");
  533. if (build_context.ODIN_DEBUG) {
  534. lb_add_attribute_to_proc(m, p->value, "noinline");
  535. }
  536. lbValue map_ptr = {LLVMGetParam(p->value, 0), t_rawptr};
  537. lbValue hash_param = {LLVMGetParam(p->value, 1), t_uintptr};
  538. lbValue key_ptr = {LLVMGetParam(p->value, 2), t_rawptr};
  539. lbValue value_ptr = {LLVMGetParam(p->value, 3), t_rawptr};
  540. lbValue location_ptr = {LLVMGetParam(p->value, 4), t_source_code_location_ptr};
  541. map_ptr = lb_emit_conv(p, map_ptr, alloc_type_pointer(type));
  542. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  543. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  544. LLVM_SET_VALUE_NAME(hash_param.value, "hash_param");
  545. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  546. LLVM_SET_VALUE_NAME(value_ptr.value, "value_ptr");
  547. LLVM_SET_VALUE_NAME(location_ptr.value, "location");
  548. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  549. lb_add_proc_attribute_at_index(p, 1+0, "noalias");
  550. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  551. if (!are_types_identical(type->Map.key, type->Map.value)) {
  552. lb_add_proc_attribute_at_index(p, 1+2, "noalias");
  553. }
  554. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  555. lb_add_proc_attribute_at_index(p, 1+3, "nonnull");
  556. if (!are_types_identical(type->Map.key, type->Map.value)) {
  557. lb_add_proc_attribute_at_index(p, 1+3, "noalias");
  558. }
  559. lb_add_proc_attribute_at_index(p, 1+3, "readonly");
  560. lb_add_proc_attribute_at_index(p, 1+4, "nonnull");
  561. lb_add_proc_attribute_at_index(p, 1+4, "noalias");
  562. lb_add_proc_attribute_at_index(p, 1+4, "readonly");
  563. lbAddr hash_addr = lb_add_local_generated(p, t_uintptr, false);
  564. lb_addr_store(p, hash_addr, hash_param);
  565. LLVM_SET_VALUE_NAME(hash_addr.addr.value, "hash");
  566. ////
  567. lbValue found_ptr = {};
  568. {
  569. lbValue map_get_proc = lb_map_get_proc_for_type(m, type);
  570. auto args = array_make<lbValue>(temporary_allocator(), 3);
  571. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  572. args[1] = lb_addr_load(p, hash_addr);
  573. args[2] = key_ptr;
  574. found_ptr = lb_emit_call(p, map_get_proc, args);
  575. }
  576. LLVM_SET_VALUE_NAME(found_ptr.value, "found_ptr");
  577. lbBlock *found_block = lb_create_block(p, "found");
  578. lbBlock *check_grow_block = lb_create_block(p, "check-grow");
  579. lbBlock *grow_fail_block = lb_create_block(p, "grow-fail");
  580. lbBlock *insert_block = lb_create_block(p, "insert");
  581. lbBlock *check_has_grown_block = lb_create_block(p, "check-has-grown");
  582. lbBlock *rehash_block = lb_create_block(p, "rehash");
  583. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, found_ptr), found_block, check_grow_block);
  584. lb_start_block(p, found_block);
  585. {
  586. lb_mem_copy_non_overlapping(p, found_ptr, value_ptr, lb_const_int(m, t_int, type_size_of(type->Map.value)));
  587. LLVMBuildRet(p->builder, lb_emit_conv(p, found_ptr, t_rawptr).value);
  588. }
  589. lb_start_block(p, check_grow_block);
  590. lbValue map_info = lb_gen_map_info_ptr(p->module, type);
  591. LLVM_SET_VALUE_NAME(map_info.value, "map_info");
  592. {
  593. auto args = array_make<lbValue>(temporary_allocator(), 3);
  594. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  595. args[1] = map_info;
  596. args[2] = lb_emit_load(p, location_ptr);
  597. lbValue grow_err_and_has_grown = lb_emit_runtime_call(p, "__dynamic_map_check_grow", args);
  598. lbValue grow_err = lb_emit_struct_ev(p, grow_err_and_has_grown, 0);
  599. lbValue has_grown = lb_emit_struct_ev(p, grow_err_and_has_grown, 1);
  600. LLVM_SET_VALUE_NAME(grow_err.value, "grow_err");
  601. LLVM_SET_VALUE_NAME(has_grown.value, "has_grown");
  602. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, grow_err), grow_fail_block, check_has_grown_block);
  603. lb_start_block(p, grow_fail_block);
  604. LLVMBuildRet(p->builder, LLVMConstNull(lb_type(m, t_rawptr)));
  605. lb_start_block(p, check_has_grown_block);
  606. lb_emit_if(p, has_grown, rehash_block, insert_block);
  607. lb_start_block(p, rehash_block);
  608. lbValue key = lb_emit_load(p, key_ptr);
  609. lbValue new_hash = lb_gen_map_key_hash(p, map_ptr, key, nullptr);
  610. LLVM_SET_VALUE_NAME(new_hash.value, "new_hash");
  611. lb_addr_store(p, hash_addr, new_hash);
  612. lb_emit_jump(p, insert_block);
  613. }
  614. lb_start_block(p, insert_block);
  615. {
  616. auto args = array_make<lbValue>(temporary_allocator(), 5);
  617. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  618. args[1] = map_info;
  619. args[2] = lb_addr_load(p, hash_addr);
  620. args[3] = lb_emit_conv(p, key_ptr, t_uintptr);
  621. args[4] = lb_emit_conv(p, value_ptr, t_uintptr);
  622. lbValue result = lb_emit_runtime_call(p, "map_insert_hash_dynamic", args);
  623. lb_emit_increment(p, lb_map_len_ptr(p, map_ptr));
  624. LLVMBuildRet(p->builder, lb_emit_conv(p, result, t_rawptr).value);
  625. }
  626. return {p->value, p->type};
  627. }
  628. gb_internal lbValue lb_gen_map_cell_info_ptr(lbModule *m, Type *type) {
  629. lbAddr *found = map_get(&m->map_cell_info_map, type);
  630. if (found) {
  631. return found->addr;
  632. }
  633. i64 size = 0, len = 0;
  634. map_cell_size_and_len(type, &size, &len);
  635. LLVMValueRef const_values[4] = {};
  636. const_values[0] = lb_const_int(m, t_uintptr, type_size_of(type)).value;
  637. const_values[1] = lb_const_int(m, t_uintptr, type_align_of(type)).value;
  638. const_values[2] = lb_const_int(m, t_uintptr, size).value;
  639. const_values[3] = lb_const_int(m, t_uintptr, len).value;
  640. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_cell_info, const_values, gb_count_of(const_values));
  641. lbValue res = {llvm_res, t_map_cell_info};
  642. lbAddr addr = lb_add_global_generated(m, t_map_cell_info, res, nullptr);
  643. lb_make_global_private_const(addr);
  644. map_set(&m->map_cell_info_map, type, addr);
  645. return addr.addr;
  646. }
  647. gb_internal lbValue lb_gen_map_info_ptr(lbModule *m, Type *map_type) {
  648. map_type = base_type(map_type);
  649. GB_ASSERT(map_type->kind == Type_Map);
  650. lbAddr *found = map_get(&m->map_info_map, map_type);
  651. if (found) {
  652. return found->addr;
  653. }
  654. GB_ASSERT(t_map_info != nullptr);
  655. GB_ASSERT(t_map_cell_info != nullptr);
  656. LLVMValueRef key_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.key).value;
  657. LLVMValueRef value_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.value).value;
  658. LLVMValueRef const_values[4] = {};
  659. const_values[0] = key_cell_info;
  660. const_values[1] = value_cell_info;
  661. const_values[2] = lb_hasher_proc_for_type(m, map_type->Map.key).value;
  662. const_values[3] = lb_equal_proc_for_type(m, map_type->Map.key).value;
  663. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_info, const_values, gb_count_of(const_values));
  664. lbValue res = {llvm_res, t_map_info};
  665. lbAddr addr = lb_add_global_generated(m, t_map_info, res, nullptr);
  666. lb_make_global_private_const(addr);
  667. map_set(&m->map_info_map, map_type, addr);
  668. return addr.addr;
  669. }
  670. gb_internal lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  671. if (true) {
  672. return {};
  673. }
  674. lbValue hashed_key = {};
  675. #if 0
  676. if (lb_is_const(key)) {
  677. u64 hash = 0xcbf29ce484222325;
  678. if (is_type_cstring(key_type)) {
  679. size_t length = 0;
  680. char const *text = LLVMGetAsString(key.value, &length);
  681. hash = fnv64a(text, cast(isize)length);
  682. } else if (is_type_string(key_type)) {
  683. unsigned data_indices[] = {0};
  684. unsigned len_indices[] = {1};
  685. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  686. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  687. i64 length = LLVMConstIntGetSExtValue(len);
  688. char const *text = nullptr;
  689. if (false && length != 0) {
  690. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  691. return {};
  692. }
  693. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  694. size_t ulength = 0;
  695. text = LLVMGetAsString(data, &ulength);
  696. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  697. length = gb_min(length, cast(i64)ulength);
  698. }
  699. hash = fnv64a(text, cast(isize)length);
  700. } else {
  701. return {};
  702. }
  703. // TODO(bill): other const hash types
  704. if (build_context.word_size == 4) {
  705. hash &= 0xffffffffull;
  706. }
  707. hashed_key = lb_const_int(m, t_uintptr, hash);
  708. }
  709. #endif
  710. return hashed_key;
  711. }
  712. gb_internal lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue const &map_ptr, lbValue key, lbValue *key_ptr_) {
  713. TEMPORARY_ALLOCATOR_GUARD();
  714. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  715. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  716. if (key_ptr_) *key_ptr_ = key_ptr;
  717. Type* key_type = base_type(type_deref(map_ptr.type))->Map.key;
  718. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  719. if (hashed_key.value == nullptr) {
  720. lbValue hasher = lb_hasher_proc_for_type(p->module, key_type);
  721. lbValue seed = {};
  722. {
  723. auto args = array_make<lbValue>(temporary_allocator(), 1);
  724. args[0] = lb_map_data_uintptr(p, lb_emit_load(p, map_ptr));
  725. seed = lb_emit_runtime_call(p, "map_seed_from_map_data", args);
  726. }
  727. auto args = array_make<lbValue>(temporary_allocator(), 2);
  728. args[0] = key_ptr;
  729. args[1] = seed;
  730. hashed_key = lb_emit_call(p, hasher, args);
  731. }
  732. return hashed_key;
  733. }
  734. gb_internal lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  735. TEMPORARY_ALLOCATOR_GUARD();
  736. Type *map_type = base_type(type_deref(map_ptr.type));
  737. GB_ASSERT(map_type->kind == Type_Map);
  738. lbValue ptr = {};
  739. lbValue key_ptr = {};
  740. lbValue hash = lb_gen_map_key_hash(p, map_ptr, key, &key_ptr);
  741. if (build_context.dynamic_map_calls) {
  742. auto args = array_make<lbValue>(temporary_allocator(), 4);
  743. args[0] = lb_emit_transmute(p, map_ptr, t_raw_map_ptr);
  744. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  745. args[2] = hash;
  746. args[3] = key_ptr;
  747. ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  748. } else {
  749. lbValue map_get_proc = lb_map_get_proc_for_type(p->module, map_type);
  750. auto args = array_make<lbValue>(temporary_allocator(), 3);
  751. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  752. args[1] = hash;
  753. args[2] = key_ptr;
  754. ptr = lb_emit_call(p, map_get_proc, args);
  755. }
  756. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  757. }
  758. gb_internal void lb_internal_dynamic_map_set(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  759. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  760. TEMPORARY_ALLOCATOR_GUARD();
  761. map_type = base_type(map_type);
  762. GB_ASSERT(map_type->kind == Type_Map);
  763. lbValue key_ptr = {};
  764. lbValue hash = lb_gen_map_key_hash(p, map_ptr, map_key, &key_ptr);
  765. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  766. lbValue value_ptr = lb_address_from_load_or_generate_local(p, v);
  767. if (build_context.dynamic_map_calls) {
  768. auto args = array_make<lbValue>(temporary_allocator(), 6);
  769. args[0] = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  770. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  771. args[2] = hash;
  772. args[3] = lb_emit_conv(p, key_ptr, t_rawptr);
  773. args[4] = lb_emit_conv(p, value_ptr, t_rawptr);
  774. args[5] = lb_emit_source_code_location_as_global(p, node);
  775. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  776. } else {
  777. lbValue map_set_proc = lb_map_set_proc_for_type(p->module, map_type);
  778. auto args = array_make<lbValue>(temporary_allocator(), 5);
  779. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  780. args[1] = hash;
  781. args[2] = lb_emit_conv(p, key_ptr, t_rawptr);
  782. args[3] = lb_emit_conv(p, value_ptr, t_rawptr);
  783. args[4] = lb_emit_source_code_location_as_global(p, node);
  784. lb_emit_call(p, map_set_proc, args);
  785. }
  786. }
  787. gb_internal lbValue lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  788. GB_ASSERT(!build_context.no_dynamic_literals);
  789. TEMPORARY_ALLOCATOR_GUARD();
  790. String proc_name = {};
  791. if (p->entity) {
  792. proc_name = p->entity->token.string;
  793. }
  794. auto args = array_make<lbValue>(temporary_allocator(), 4);
  795. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  796. args[1] = lb_gen_map_info_ptr(p->module, type_deref(map_ptr.type));
  797. args[2] = lb_const_int(p->module, t_uint, capacity);
  798. args[3] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  799. return lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  800. }
  801. struct lbGlobalVariable {
  802. lbValue var;
  803. lbValue init;
  804. DeclInfo *decl;
  805. bool is_initialized;
  806. };
  807. gb_internal lbProcedure *lb_create_startup_type_info(lbModule *m) {
  808. if (build_context.no_rtti) {
  809. return nullptr;
  810. }
  811. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  812. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  813. p->is_startup = true;
  814. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  815. lb_add_attribute_to_proc(m, p->value, "nounwind");
  816. if (!LB_USE_GIANT_PACKED_STRUCT) {
  817. lb_add_attribute_to_proc(m, p->value, "optnone");
  818. lb_add_attribute_to_proc(m, p->value, "noinline");
  819. }
  820. lb_begin_procedure_body(p);
  821. lb_setup_type_info_data(p);
  822. lb_end_procedure_body(p);
  823. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  824. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  825. LLVMDumpValue(p->value);
  826. gb_printf_err("\n\n\n\n");
  827. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  828. }
  829. return p;
  830. }
  831. gb_internal lbProcedure *lb_create_objc_names(lbModule *main_module) {
  832. if (build_context.metrics.os != TargetOs_darwin) {
  833. return nullptr;
  834. }
  835. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  836. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  837. lb_add_attribute_to_proc(p->module, p->value, "nounwind");
  838. p->is_startup = true;
  839. return p;
  840. }
  841. gb_internal void lb_finalize_objc_names(lbProcedure *p) {
  842. if (p == nullptr) {
  843. return;
  844. }
  845. lbModule *m = p->module;
  846. TEMPORARY_ALLOCATOR_GUARD();
  847. auto args = array_make<lbValue>(temporary_allocator(), 1);
  848. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  849. lb_begin_procedure_body(p);
  850. for (auto const &entry : m->objc_classes) {
  851. String name = entry.key;
  852. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  853. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  854. lb_addr_store(p, entry.value, ptr);
  855. }
  856. for (auto const &entry : m->objc_selectors) {
  857. String name = entry.key;
  858. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  859. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  860. lb_addr_store(p, entry.value, ptr);
  861. }
  862. lb_end_procedure_body(p);
  863. }
  864. gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  865. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  866. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  867. p->is_startup = true;
  868. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  869. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  870. lb_begin_procedure_body(p);
  871. if (startup_type_info) {
  872. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, startup_type_info->type), startup_type_info->value, nullptr, 0, "");
  873. }
  874. if (objc_names) {
  875. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, objc_names->type), objc_names->value, nullptr, 0, "");
  876. }
  877. for (auto &var : global_variables) {
  878. if (var.is_initialized) {
  879. continue;
  880. }
  881. lbModule *entity_module = main_module;
  882. Entity *e = var.decl->entity;
  883. GB_ASSERT(e->kind == Entity_Variable);
  884. e->code_gen_module = entity_module;
  885. Ast *init_expr = var.decl->init_expr;
  886. if (init_expr != nullptr) {
  887. lbValue init = lb_build_expr(p, init_expr);
  888. if (init.value == nullptr) {
  889. LLVMTypeRef global_type = llvm_addr_type(p->module, var.var);
  890. if (is_type_untyped_nil(init.type)) {
  891. LLVMSetInitializer(var.var.value, LLVMConstNull(global_type));
  892. var.is_initialized = true;
  893. continue;
  894. }
  895. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  896. }
  897. if (is_type_any(e->type) || is_type_union(e->type)) {
  898. var.init = init;
  899. } else if (lb_is_const_or_global(init)) {
  900. if (!var.is_initialized) {
  901. if (is_type_proc(init.type)) {
  902. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  903. }
  904. LLVMSetInitializer(var.var.value, init.value);
  905. var.is_initialized = true;
  906. continue;
  907. }
  908. } else {
  909. var.init = init;
  910. }
  911. }
  912. if (var.init.value != nullptr) {
  913. GB_ASSERT(!var.is_initialized);
  914. Type *t = type_deref(var.var.type);
  915. if (is_type_any(t)) {
  916. // NOTE(bill): Edge case for 'any' type
  917. Type *var_type = default_type(var.init.type);
  918. lbAddr g = lb_add_global_generated(main_module, var_type, var.init);
  919. lb_addr_store(p, g, var.init);
  920. lbValue gp = lb_addr_get_ptr(p, g);
  921. lbValue data = lb_emit_struct_ep(p, var.var, 0);
  922. lbValue ti = lb_emit_struct_ep(p, var.var, 1);
  923. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  924. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  925. } else {
  926. LLVMTypeRef vt = llvm_addr_type(p->module, var.var);
  927. lbValue src0 = lb_emit_conv(p, var.init, t);
  928. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  929. LLVMValueRef dst = var.var.value;
  930. LLVMBuildStore(p->builder, src, dst);
  931. }
  932. var.is_initialized = true;
  933. }
  934. }
  935. CheckerInfo *info = main_module->gen->info;
  936. for (Entity *e : info->init_procedures) {
  937. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  938. lb_emit_call(p, value, {}, ProcInlining_none);
  939. }
  940. lb_end_procedure_body(p);
  941. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  942. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  943. LLVMDumpValue(p->value);
  944. gb_printf_err("\n\n\n\n");
  945. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  946. }
  947. return p;
  948. }
  949. gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // Cleanup Runtime
  950. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  951. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
  952. p->is_startup = true;
  953. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  954. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  955. lb_begin_procedure_body(p);
  956. CheckerInfo *info = main_module->gen->info;
  957. for (Entity *e : info->fini_procedures) {
  958. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  959. lb_emit_call(p, value, {}, ProcInlining_none);
  960. }
  961. lb_end_procedure_body(p);
  962. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  963. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  964. LLVMDumpValue(p->value);
  965. gb_printf_err("\n\n\n\n");
  966. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  967. }
  968. return p;
  969. }
  970. gb_internal WORKER_TASK_PROC(lb_generate_procedures_and_types_per_module) {
  971. lbModule *m = cast(lbModule *)data;
  972. for (Entity *e : m->global_procedures_and_types_to_create) {
  973. if (e->kind == Entity_TypeName) {
  974. (void)lb_get_entity_name(m, e);
  975. lb_type(m, e->type);
  976. }
  977. }
  978. for (Entity *e : m->global_procedures_and_types_to_create) {
  979. if (e->kind == Entity_Procedure) {
  980. (void)lb_get_entity_name(m, e);
  981. array_add(&m->procedures_to_generate, lb_create_procedure(m, e));
  982. }
  983. }
  984. return 0;
  985. }
  986. gb_internal void lb_create_global_procedures_and_types(lbGenerator *gen, CheckerInfo *info, bool do_threading) {
  987. auto *min_dep_set = &info->minimum_dependency_set;
  988. for (Entity *e : info->entities) {
  989. String name = e->token.string;
  990. Scope * scope = e->scope;
  991. if ((scope->flags & ScopeFlag_File) == 0) {
  992. continue;
  993. }
  994. Scope *package_scope = scope->parent;
  995. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  996. switch (e->kind) {
  997. case Entity_Variable:
  998. // NOTE(bill): Handled above as it requires a specific load order
  999. continue;
  1000. case Entity_ProcGroup:
  1001. continue;
  1002. case Entity_TypeName:
  1003. case Entity_Procedure:
  1004. break;
  1005. case Entity_Constant:
  1006. if (build_context.ODIN_DEBUG) {
  1007. add_debug_info_for_global_constant_from_entity(gen, e);
  1008. }
  1009. break;
  1010. }
  1011. bool polymorphic_struct = false;
  1012. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1013. Type *bt = base_type(e->type);
  1014. if (bt->kind == Type_Struct) {
  1015. polymorphic_struct = is_type_polymorphic(bt);
  1016. }
  1017. }
  1018. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1019. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1020. continue;
  1021. }
  1022. lbModule *m = &gen->default_module;
  1023. if (USE_SEPARATE_MODULES) {
  1024. m = lb_module_of_entity(gen, e);
  1025. }
  1026. array_add(&m->global_procedures_and_types_to_create, e);
  1027. }
  1028. for (auto const &entry : gen->modules) {
  1029. lbModule *m = entry.value;
  1030. if (do_threading) {
  1031. thread_pool_add_task(lb_generate_procedures_and_types_per_module, m);
  1032. } else {
  1033. lb_generate_procedures_and_types_per_module(m);
  1034. }
  1035. }
  1036. thread_pool_wait();
  1037. }
  1038. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p);
  1039. gb_internal bool lb_is_module_empty(lbModule *m) {
  1040. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  1041. LLVMGetFirstGlobal(m->mod) == nullptr) {
  1042. return true;
  1043. }
  1044. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  1045. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  1046. return false;
  1047. }
  1048. }
  1049. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  1050. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  1051. continue;
  1052. }
  1053. if (!LLVMIsExternallyInitialized(g)) {
  1054. return false;
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. struct lbLLVMEmitWorker {
  1060. LLVMTargetMachineRef target_machine;
  1061. LLVMCodeGenFileType code_gen_file_type;
  1062. String filepath_obj;
  1063. lbModule *m;
  1064. };
  1065. gb_internal WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  1066. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  1067. char *llvm_error = nullptr;
  1068. auto wd = cast(lbLLVMEmitWorker *)data;
  1069. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  1070. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1071. gb_exit(1);
  1072. }
  1073. debugf("Generated File: %.*s\n", LIT(wd->filepath_obj));
  1074. return 0;
  1075. }
  1076. gb_internal void lb_llvm_function_pass_per_function_internal(lbModule *module, lbProcedure *p, lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default) {
  1077. LLVMPassManagerRef pass_manager = module->function_pass_managers[pass_manager_kind];
  1078. lb_run_function_pass_manager(pass_manager, p, pass_manager_kind);
  1079. }
  1080. gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
  1081. lbModule *m = cast(lbModule *)data;
  1082. {
  1083. GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
  1084. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1085. m->function_pass_managers[i] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1086. }
  1087. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1088. LLVMInitializeFunctionPassManager(m->function_pass_managers[i]);
  1089. }
  1090. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default], false, build_context.optimization_level);
  1091. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true, build_context.optimization_level);
  1092. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none], -1);
  1093. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_minimal], 0);
  1094. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_size], 1);
  1095. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_speed], 2);
  1096. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_aggressive], 3);
  1097. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1098. LLVMFinalizeFunctionPassManager(m->function_pass_managers[i]);
  1099. }
  1100. }
  1101. if (m == &m->gen->default_module) {
  1102. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_type_info);
  1103. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_runtime);
  1104. lb_llvm_function_pass_per_function_internal(m, m->gen->cleanup_runtime);
  1105. lb_llvm_function_pass_per_function_internal(m, m->gen->objc_names);
  1106. }
  1107. for (lbProcedure *p : m->procedures_to_generate) {
  1108. if (p->body != nullptr) { // Build Procedure
  1109. lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
  1110. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  1111. pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
  1112. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1113. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1114. } else {
  1115. if (p->entity && p->entity->kind == Entity_Procedure) {
  1116. switch (p->entity->Procedure.optimization_mode) {
  1117. case ProcedureOptimizationMode_None:
  1118. case ProcedureOptimizationMode_Minimal:
  1119. pass_manager_kind = lbFunctionPassManager_minimal;
  1120. break;
  1121. case ProcedureOptimizationMode_Size:
  1122. pass_manager_kind = lbFunctionPassManager_size;
  1123. lb_add_attribute_to_proc(p->module, p->value, "optsize");
  1124. break;
  1125. case ProcedureOptimizationMode_Speed:
  1126. pass_manager_kind = lbFunctionPassManager_speed;
  1127. break;
  1128. }
  1129. }
  1130. }
  1131. lb_llvm_function_pass_per_function_internal(m, p, pass_manager_kind);
  1132. }
  1133. }
  1134. for (auto const &entry : m->equal_procs) {
  1135. lbProcedure *p = entry.value;
  1136. lb_llvm_function_pass_per_function_internal(m, p);
  1137. }
  1138. for (auto const &entry : m->hasher_procs) {
  1139. lbProcedure *p = entry.value;
  1140. lb_llvm_function_pass_per_function_internal(m, p);
  1141. }
  1142. for (auto const &entry : m->map_get_procs) {
  1143. lbProcedure *p = entry.value;
  1144. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1145. }
  1146. for (auto const &entry : m->map_set_procs) {
  1147. lbProcedure *p = entry.value;
  1148. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1149. }
  1150. return 0;
  1151. }
  1152. struct lbLLVMModulePassWorkerData {
  1153. lbModule *m;
  1154. LLVMTargetMachineRef target_machine;
  1155. };
  1156. gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  1157. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  1158. lb_run_remove_unused_function_pass(wd->m);
  1159. lb_run_remove_unused_globals_pass(wd->m);
  1160. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  1161. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  1162. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  1163. #if LB_USE_NEW_PASS_SYSTEM
  1164. auto passes = array_make<char const *>(heap_allocator(), 0, 64);
  1165. defer (array_free(&passes));
  1166. LLVMPassBuilderOptionsRef pb_options = LLVMCreatePassBuilderOptions();
  1167. defer (LLVMDisposePassBuilderOptions(pb_options));
  1168. switch (build_context.optimization_level) {
  1169. case -1:
  1170. break;
  1171. case 0:
  1172. array_add(&passes, "always-inline");
  1173. array_add(&passes, "function(annotation-remarks)");
  1174. break;
  1175. case 1:
  1176. // default<Os>
  1177. // Passes removed: coro, openmp, sroa
  1178. array_add(&passes, u8R"(
  1179. annotation2metadata,
  1180. forceattrs,
  1181. inferattrs,
  1182. function<eager-inv>(
  1183. lower-expect,
  1184. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1185. early-cse<>
  1186. ),
  1187. ipsccp,
  1188. called-value-propagation,
  1189. globalopt,
  1190. function<eager-inv>(
  1191. mem2reg,
  1192. instcombine<max-iterations=1000;no-use-loop-info>,
  1193. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>),
  1194. require<globals-aa>,
  1195. function(
  1196. invalidate<aa>
  1197. ),
  1198. require<profile-summary>,
  1199. cgscc(
  1200. devirt<4>(
  1201. inline<only-mandatory>,
  1202. inline,
  1203. function-attrs<skip-non-recursive>,
  1204. function<eager-inv;no-rerun>(
  1205. early-cse<memssa>,
  1206. speculative-execution,
  1207. jump-threading,
  1208. correlated-propagation,
  1209. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1210. instcombine<max-iterations=1000;no-use-loop-info>,
  1211. aggressive-instcombine,
  1212. constraint-elimination,
  1213. tailcallelim,
  1214. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1215. reassociate,
  1216. loop-mssa(
  1217. loop-instsimplify,
  1218. loop-simplifycfg,
  1219. licm<no-allowspeculation>,
  1220. loop-rotate<header-duplication;no-prepare-for-lto>,
  1221. licm<allowspeculation>,
  1222. simple-loop-unswitch<no-nontrivial;trivial>
  1223. ),
  1224. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1225. instcombine<max-iterations=1000;no-use-loop-info>,
  1226. loop(
  1227. loop-idiom,
  1228. indvars,
  1229. loop-deletion,
  1230. loop-unroll-full
  1231. ),
  1232. vector-combine,
  1233. mldst-motion<no-split-footer-bb>,
  1234. gvn<>,
  1235. sccp,
  1236. bdce,
  1237. instcombine<max-iterations=1000;no-use-loop-info>,
  1238. jump-threading,
  1239. correlated-propagation,
  1240. adce,
  1241. memcpyopt,
  1242. dse,
  1243. move-auto-init,
  1244. loop-mssa(
  1245. licm<allowspeculation>
  1246. ),
  1247. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1248. instcombine<max-iterations=1000;no-use-loop-info>
  1249. ),
  1250. function-attrs,
  1251. function(
  1252. require<should-not-run-function-passes>
  1253. )
  1254. )
  1255. ),
  1256. deadargelim,
  1257. globalopt,
  1258. globaldce,
  1259. elim-avail-extern,
  1260. rpo-function-attrs,
  1261. recompute-globalsaa,
  1262. function<eager-inv>(
  1263. float2int,
  1264. lower-constant-intrinsics,
  1265. loop(
  1266. loop-rotate<header-duplication;no-prepare-for-lto>,
  1267. loop-deletion
  1268. ),
  1269. loop-distribute,
  1270. inject-tli-mappings,
  1271. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1272. loop-load-elim,
  1273. instcombine<max-iterations=1000;no-use-loop-info>,
  1274. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1275. slp-vectorizer,
  1276. vector-combine,
  1277. instcombine<max-iterations=1000;no-use-loop-info>,
  1278. loop-unroll<O2>,
  1279. transform-warning,
  1280. instcombine<max-iterations=1000;no-use-loop-info>,
  1281. loop-mssa(
  1282. licm<allowspeculation>
  1283. ),
  1284. alignment-from-assumptions,
  1285. loop-sink,
  1286. instsimplify,
  1287. div-rem-pairs,
  1288. tailcallelim,
  1289. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1290. ),
  1291. globaldce,
  1292. constmerge,
  1293. cg-profile,
  1294. rel-lookup-table-converter,
  1295. function(
  1296. annotation-remarks
  1297. ),
  1298. verify
  1299. )");
  1300. break;
  1301. // default<O2>
  1302. // Passes removed: coro, openmp, sroa
  1303. case 2:
  1304. array_add(&passes, u8R"(
  1305. annotation2metadata,
  1306. forceattrs,
  1307. inferattrs,
  1308. function<eager-inv>(
  1309. lower-expect,
  1310. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1311. early-cse<>
  1312. ),
  1313. ipsccp,
  1314. called-value-propagation,
  1315. globalopt,
  1316. function<eager-inv>(
  1317. mem2reg,
  1318. instcombine<max-iterations=1000;no-use-loop-info>,
  1319. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1320. ),
  1321. require<globals-aa>,
  1322. function(
  1323. invalidate<aa>
  1324. ),
  1325. require<profile-summary>,
  1326. cgscc(
  1327. devirt<4>(
  1328. inline<only-mandatory>,
  1329. inline,
  1330. function-attrs<skip-non-recursive>,
  1331. function<eager-inv;no-rerun>(
  1332. early-cse<memssa>,
  1333. speculative-execution,
  1334. jump-threading,
  1335. correlated-propagation,
  1336. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1337. instcombine<max-iterations=1000;no-use-loop-info>,
  1338. aggressive-instcombine,
  1339. constraint-elimination,
  1340. libcalls-shrinkwrap,
  1341. tailcallelim,
  1342. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1343. reassociate,
  1344. loop-mssa(
  1345. loop-instsimplify,
  1346. loop-simplifycfg,
  1347. licm<no-allowspeculation>,
  1348. loop-rotate<header-duplication;no-prepare-for-lto>,
  1349. licm<allowspeculation>,
  1350. simple-loop-unswitch<no-nontrivial;trivial>
  1351. ),
  1352. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1353. instcombine<max-iterations=1000;no-use-loop-info>,
  1354. loop(
  1355. loop-idiom,
  1356. indvars,
  1357. loop-deletion,
  1358. loop-unroll-full
  1359. ),
  1360. vector-combine,
  1361. mldst-motion<no-split-footer-bb>,
  1362. gvn<>,
  1363. sccp,
  1364. bdce,
  1365. instcombine<max-iterations=1000;no-use-loop-info>,
  1366. jump-threading,
  1367. correlated-propagation,
  1368. adce,
  1369. memcpyopt,
  1370. dse,
  1371. move-auto-init,
  1372. loop-mssa(
  1373. licm<allowspeculation>
  1374. ),
  1375. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1376. instcombine<max-iterations=1000;no-use-loop-info>
  1377. ),
  1378. function-attrs,
  1379. function(
  1380. require<should-not-run-function-passes>
  1381. )
  1382. )
  1383. ),
  1384. deadargelim,
  1385. globalopt,
  1386. globaldce,
  1387. elim-avail-extern,
  1388. rpo-function-attrs,
  1389. recompute-globalsaa,
  1390. function<eager-inv>(
  1391. float2int,
  1392. lower-constant-intrinsics,
  1393. loop(
  1394. loop-rotate<header-duplication;no-prepare-for-lto>,
  1395. loop-deletion
  1396. ),
  1397. loop-distribute,
  1398. inject-tli-mappings,
  1399. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1400. loop-load-elim,
  1401. instcombine<max-iterations=1000;no-use-loop-info>,
  1402. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1403. slp-vectorizer,
  1404. vector-combine,
  1405. instcombine<max-iterations=1000;no-use-loop-info>,
  1406. loop-unroll<O2>,
  1407. transform-warning,
  1408. instcombine<max-iterations=1000;no-use-loop-info>,
  1409. loop-mssa(
  1410. licm<allowspeculation>
  1411. ),
  1412. alignment-from-assumptions,
  1413. loop-sink,
  1414. instsimplify,
  1415. div-rem-pairs,
  1416. tailcallelim,
  1417. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1418. ),
  1419. globaldce,
  1420. constmerge,
  1421. cg-profile,
  1422. rel-lookup-table-converter,
  1423. function(
  1424. annotation-remarks
  1425. ),
  1426. verify
  1427. )");
  1428. break;
  1429. case 3:
  1430. // default<O3>
  1431. // Passes removed: coro, openmp, sroa
  1432. array_add(&passes, u8R"(
  1433. annotation2metadata,
  1434. forceattrs,
  1435. inferattrs,
  1436. function<eager-inv>(
  1437. lower-expect,
  1438. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1439. early-cse<>,
  1440. callsite-splitting
  1441. ),
  1442. ipsccp,
  1443. called-value-propagation,
  1444. globalopt,
  1445. function<eager-inv>(
  1446. mem2reg,
  1447. instcombine<max-iterations=1000;no-use-loop-info>,
  1448. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1449. ),
  1450. require<globals-aa>,
  1451. function(
  1452. invalidate<aa>
  1453. ),
  1454. require<profile-summary>,
  1455. cgscc(
  1456. devirt<4>(
  1457. inline<only-mandatory>,
  1458. inline,
  1459. function-attrs<skip-non-recursive>,
  1460. argpromotion,
  1461. function<eager-inv;no-rerun>(
  1462. early-cse<memssa>,
  1463. speculative-execution,
  1464. jump-threading,
  1465. correlated-propagation,
  1466. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1467. instcombine<max-iterations=1000;no-use-loop-info>,
  1468. aggressive-instcombine,
  1469. constraint-elimination,
  1470. libcalls-shrinkwrap,
  1471. tailcallelim,
  1472. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1473. reassociate,
  1474. loop-mssa(
  1475. loop-instsimplify,
  1476. loop-simplifycfg,
  1477. licm<no-allowspeculation>,
  1478. loop-rotate<header-duplication;no-prepare-for-lto>,
  1479. licm<allowspeculation>,
  1480. simple-loop-unswitch<nontrivial;trivial>
  1481. ),
  1482. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1483. instcombine<max-iterations=1000;no-use-loop-info>,
  1484. loop(
  1485. loop-idiom,
  1486. indvars,
  1487. loop-deletion,
  1488. loop-unroll-full
  1489. ),
  1490. vector-combine,
  1491. mldst-motion<no-split-footer-bb>,
  1492. gvn<>,
  1493. sccp,
  1494. bdce,
  1495. instcombine<max-iterations=1000;no-use-loop-info>,
  1496. jump-threading,
  1497. correlated-propagation,
  1498. adce,
  1499. memcpyopt,
  1500. dse,
  1501. move-auto-init,
  1502. loop-mssa(
  1503. licm<allowspeculation>
  1504. ),
  1505. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1506. instcombine<max-iterations=1000;no-use-loop-info>
  1507. ),
  1508. function-attrs,
  1509. function(
  1510. require<should-not-run-function-passes>
  1511. ),
  1512. )
  1513. ),
  1514. deadargelim,
  1515. globalopt,
  1516. globaldce,
  1517. elim-avail-extern,
  1518. rpo-function-attrs,
  1519. recompute-globalsaa,
  1520. function<eager-inv>(
  1521. float2int,
  1522. lower-constant-intrinsics,
  1523. chr,
  1524. loop(
  1525. loop-rotate<header-duplication;no-prepare-for-lto>,
  1526. loop-deletion
  1527. ),
  1528. loop-distribute,
  1529. inject-tli-mappings,
  1530. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1531. loop-load-elim,
  1532. instcombine<max-iterations=1000;no-use-loop-info>,
  1533. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1534. slp-vectorizer,
  1535. vector-combine,
  1536. instcombine<max-iterations=1000;no-use-loop-info>,
  1537. loop-unroll<O3>,
  1538. transform-warning,
  1539. instcombine<max-iterations=1000;no-use-loop-info>,
  1540. loop-mssa(
  1541. licm<allowspeculation>
  1542. ),
  1543. alignment-from-assumptions,
  1544. loop-sink,
  1545. instsimplify,
  1546. div-rem-pairs,
  1547. tailcallelim,
  1548. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1549. ),
  1550. globaldce,
  1551. constmerge,
  1552. cg-profile,
  1553. rel-lookup-table-converter,
  1554. function(
  1555. annotation-remarks
  1556. ),
  1557. verify
  1558. )");
  1559. break;
  1560. }
  1561. // asan - Linux, Darwin, Windows
  1562. // msan - linux
  1563. // tsan - Linux, Darwin
  1564. // ubsan - Linux, Darwin, Windows (NOT SUPPORTED WITH LLVM C-API)
  1565. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  1566. array_add(&passes, "asan");
  1567. }
  1568. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  1569. array_add(&passes, "msan");
  1570. }
  1571. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  1572. array_add(&passes, "tsan");
  1573. }
  1574. if (passes.count == 0) {
  1575. array_add(&passes, "verify");
  1576. }
  1577. gbString passes_str = gb_string_make_reserve(heap_allocator(), 1024);
  1578. defer (gb_string_free(passes_str));
  1579. for_array(i, passes) {
  1580. if (i != 0) {
  1581. passes_str = gb_string_appendc(passes_str, ",");
  1582. }
  1583. passes_str = gb_string_appendc(passes_str, passes[i]);
  1584. }
  1585. for (isize i = 0; i < gb_string_length(passes_str); /**/) {
  1586. switch (passes_str[i]) {
  1587. case ' ':
  1588. case '\n':
  1589. case '\t':
  1590. gb_memmove(&passes_str[i], &passes_str[i+1], gb_string_length(passes_str)-i);
  1591. GB_STRING_HEADER(passes_str)->length -= 1;
  1592. continue;
  1593. default:
  1594. i += 1;
  1595. break;
  1596. }
  1597. }
  1598. LLVMErrorRef llvm_err = LLVMRunPasses(wd->m->mod, passes_str, wd->target_machine, pb_options);
  1599. defer (LLVMConsumeError(llvm_err));
  1600. if (llvm_err != nullptr) {
  1601. char *llvm_error = LLVMGetErrorMessage(llvm_err);
  1602. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1603. LLVMDisposeErrorMessage(llvm_error);
  1604. llvm_error = nullptr;
  1605. if (build_context.keep_temp_files) {
  1606. TIME_SECTION("LLVM Print Module to File");
  1607. String filepath_ll = lb_filepath_ll_for_module(wd->m);
  1608. if (LLVMPrintModuleToFile(wd->m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1609. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1610. }
  1611. }
  1612. gb_exit(1);
  1613. return 1;
  1614. }
  1615. #endif
  1616. return 0;
  1617. }
  1618. gb_internal WORKER_TASK_PROC(lb_generate_procedures_worker_proc) {
  1619. lbModule *m = cast(lbModule *)data;
  1620. for (isize i = 0; i < m->procedures_to_generate.count; i++) {
  1621. lbProcedure *p = m->procedures_to_generate[i];
  1622. lb_generate_procedure(p->module, p);
  1623. }
  1624. return 0;
  1625. }
  1626. gb_internal void lb_generate_procedures(lbGenerator *gen, bool do_threading) {
  1627. for (auto const &entry : gen->modules) {
  1628. lbModule *m = entry.value;
  1629. if (do_threading) {
  1630. thread_pool_add_task(lb_generate_procedures_worker_proc, m);
  1631. } else {
  1632. lb_generate_procedures_worker_proc(m);
  1633. }
  1634. }
  1635. thread_pool_wait();
  1636. }
  1637. gb_internal WORKER_TASK_PROC(lb_generate_missing_procedures_to_check_worker_proc) {
  1638. lbModule *m = cast(lbModule *)data;
  1639. for (isize i = 0; i < m->missing_procedures_to_check.count; i++) {
  1640. lbProcedure *p = m->missing_procedures_to_check[i];
  1641. debugf("Generate missing procedure: %.*s module %p\n", LIT(p->name), m);
  1642. lb_generate_procedure(m, p);
  1643. }
  1644. return 0;
  1645. }
  1646. gb_internal void lb_generate_missing_procedures(lbGenerator *gen, bool do_threading) {
  1647. for (auto const &entry : gen->modules) {
  1648. lbModule *m = entry.value;
  1649. // NOTE(bill): procedures may be added during generation
  1650. if (do_threading) {
  1651. thread_pool_add_task(lb_generate_missing_procedures_to_check_worker_proc, m);
  1652. } else {
  1653. lb_generate_missing_procedures_to_check_worker_proc(m);
  1654. }
  1655. }
  1656. thread_pool_wait();
  1657. }
  1658. gb_internal void lb_debug_info_complete_types_and_finalize(lbGenerator *gen) {
  1659. for (auto const &entry : gen->modules) {
  1660. lbModule *m = entry.value;
  1661. if (m->debug_builder != nullptr) {
  1662. lb_debug_complete_types(m);
  1663. }
  1664. }
  1665. for (auto const &entry : gen->modules) {
  1666. lbModule *m = entry.value;
  1667. if (m->debug_builder != nullptr) {
  1668. LLVMDIBuilderFinalize(m->debug_builder);
  1669. }
  1670. }
  1671. }
  1672. gb_internal void lb_llvm_function_passes(lbGenerator *gen, bool do_threading) {
  1673. for (auto const &entry : gen->modules) {
  1674. lbModule *m = entry.value;
  1675. if (do_threading) {
  1676. thread_pool_add_task(lb_llvm_function_pass_per_module, m);
  1677. } else {
  1678. lb_llvm_function_pass_per_module(m);
  1679. }
  1680. }
  1681. thread_pool_wait();
  1682. }
  1683. gb_internal void lb_llvm_module_passes(lbGenerator *gen, bool do_threading) {
  1684. for (auto const &entry : gen->modules) {
  1685. lbModule *m = entry.value;
  1686. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1687. wd->m = m;
  1688. wd->target_machine = m->target_machine;
  1689. if (do_threading) {
  1690. thread_pool_add_task(lb_llvm_module_pass_worker_proc, wd);
  1691. } else {
  1692. lb_llvm_module_pass_worker_proc(wd);
  1693. }
  1694. }
  1695. thread_pool_wait();
  1696. }
  1697. gb_internal String lb_filepath_ll_for_module(lbModule *m) {
  1698. String path = concatenate3_strings(permanent_allocator(),
  1699. build_context.build_paths[BuildPath_Output].basename,
  1700. STR_LIT("/"),
  1701. build_context.build_paths[BuildPath_Output].name
  1702. );
  1703. if (m->file) {
  1704. char buf[32] = {};
  1705. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1706. String suffix = make_string((u8 *)buf, n-1);
  1707. path = concatenate_strings(permanent_allocator(), path, suffix);
  1708. } else if (m->pkg) {
  1709. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1710. } else if (USE_SEPARATE_MODULES) {
  1711. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  1712. }
  1713. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  1714. return path;
  1715. }
  1716. gb_internal String lb_filepath_obj_for_module(lbModule *m) {
  1717. String path = concatenate3_strings(permanent_allocator(),
  1718. build_context.build_paths[BuildPath_Output].basename,
  1719. STR_LIT("/"),
  1720. build_context.build_paths[BuildPath_Output].name
  1721. );
  1722. if (m->file) {
  1723. char buf[32] = {};
  1724. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1725. String suffix = make_string((u8 *)buf, n-1);
  1726. path = concatenate_strings(permanent_allocator(), path, suffix);
  1727. } else if (m->pkg) {
  1728. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1729. }
  1730. String ext = {};
  1731. if (build_context.build_mode == BuildMode_Assembly) {
  1732. ext = STR_LIT(".S");
  1733. } else {
  1734. if (is_arch_wasm()) {
  1735. ext = STR_LIT(".wasm.o");
  1736. } else {
  1737. switch (build_context.metrics.os) {
  1738. case TargetOs_windows:
  1739. ext = STR_LIT(".obj");
  1740. break;
  1741. default:
  1742. case TargetOs_darwin:
  1743. case TargetOs_linux:
  1744. case TargetOs_essence:
  1745. ext = STR_LIT(".o");
  1746. break;
  1747. case TargetOs_freestanding:
  1748. switch (build_context.metrics.abi) {
  1749. default:
  1750. case TargetABI_Default:
  1751. case TargetABI_SysV:
  1752. ext = STR_LIT(".o");
  1753. break;
  1754. case TargetABI_Win64:
  1755. ext = STR_LIT(".obj");
  1756. break;
  1757. }
  1758. break;
  1759. }
  1760. }
  1761. }
  1762. return concatenate_strings(permanent_allocator(), path, ext);
  1763. }
  1764. gb_internal WORKER_TASK_PROC(lb_llvm_module_verification_worker_proc) {
  1765. char *llvm_error = nullptr;
  1766. defer (LLVMDisposeMessage(llvm_error));
  1767. lbModule *m = cast(lbModule *)data;
  1768. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1769. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1770. if (build_context.keep_temp_files) {
  1771. TIME_SECTION("LLVM Print Module to File");
  1772. String filepath_ll = lb_filepath_ll_for_module(m);
  1773. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1774. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1775. gb_exit(1);
  1776. return false;
  1777. }
  1778. }
  1779. gb_exit(1);
  1780. return 1;
  1781. }
  1782. return 0;
  1783. }
  1784. gb_internal bool lb_llvm_module_verification(lbGenerator *gen, bool do_threading) {
  1785. for (auto const &entry : gen->modules) {
  1786. lbModule *m = entry.value;
  1787. if (do_threading) {
  1788. thread_pool_add_task(lb_llvm_module_verification_worker_proc, m);
  1789. } else {
  1790. if (lb_llvm_module_verification_worker_proc(m)) {
  1791. return false;
  1792. }
  1793. }
  1794. }
  1795. thread_pool_wait();
  1796. return true;
  1797. }
  1798. gb_internal void lb_add_foreign_library_paths(lbGenerator *gen) {
  1799. for (auto const &entry : gen->modules) {
  1800. lbModule *m = entry.value;
  1801. for (Entity *e : m->info->required_foreign_imports_through_force) {
  1802. lb_add_foreign_library_path(m, e);
  1803. }
  1804. if (lb_is_module_empty(m)) {
  1805. continue;
  1806. }
  1807. }
  1808. }
  1809. gb_internal bool lb_llvm_object_generation(lbGenerator *gen, bool do_threading) {
  1810. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1811. if (build_context.build_mode == BuildMode_Assembly) {
  1812. code_gen_file_type = LLVMAssemblyFile;
  1813. }
  1814. char *llvm_error = nullptr;
  1815. defer (LLVMDisposeMessage(llvm_error));
  1816. if (do_threading) {
  1817. for (auto const &entry : gen->modules) {
  1818. lbModule *m = entry.value;
  1819. if (lb_is_module_empty(m)) {
  1820. continue;
  1821. }
  1822. String filepath_ll = lb_filepath_ll_for_module(m);
  1823. String filepath_obj = lb_filepath_obj_for_module(m);
  1824. // gb_printf_err("%.*s\n", LIT(filepath_obj));
  1825. array_add(&gen->output_object_paths, filepath_obj);
  1826. array_add(&gen->output_temp_paths, filepath_ll);
  1827. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1828. wd->target_machine = m->target_machine;
  1829. wd->code_gen_file_type = code_gen_file_type;
  1830. wd->filepath_obj = filepath_obj;
  1831. wd->m = m;
  1832. thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1833. }
  1834. thread_pool_wait(&global_thread_pool);
  1835. } else {
  1836. for (auto const &entry : gen->modules) {
  1837. lbModule *m = entry.value;
  1838. if (lb_is_module_empty(m)) {
  1839. continue;
  1840. }
  1841. String filepath_obj = lb_filepath_obj_for_module(m);
  1842. array_add(&gen->output_object_paths, filepath_obj);
  1843. String short_name = remove_directory_from_path(filepath_obj);
  1844. gbString section_name = gb_string_make(permanent_allocator(), "LLVM Generate Object: ");
  1845. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1846. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1847. if (LLVMTargetMachineEmitToFile(m->target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1848. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1849. gb_exit(1);
  1850. return false;
  1851. }
  1852. debugf("Generated File: %.*s\n", LIT(filepath_obj));
  1853. }
  1854. }
  1855. return true;
  1856. }
  1857. gb_internal lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime, lbProcedure *cleanup_runtime) {
  1858. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  1859. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  1860. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  1861. Type *params = alloc_type_tuple();
  1862. Type *results = alloc_type_tuple();
  1863. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  1864. bool call_cleanup = true;
  1865. bool has_args = false;
  1866. bool is_dll_main = false;
  1867. String name = str_lit("main");
  1868. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  1869. is_dll_main = true;
  1870. name = str_lit("DllMain");
  1871. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  1872. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  1873. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  1874. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  1875. call_cleanup = false;
  1876. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  1877. name = str_lit("mainCRTStartup");
  1878. } else if (is_arch_wasm()) {
  1879. name = str_lit("_start");
  1880. call_cleanup = false;
  1881. } else {
  1882. has_args = true;
  1883. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  1884. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  1885. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  1886. }
  1887. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  1888. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  1889. Type *proc_type = alloc_type_proc(nullptr,
  1890. params, params->Tuple.variables.count,
  1891. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  1892. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  1893. p->is_startup = true;
  1894. lb_begin_procedure_body(p);
  1895. if (has_args) { // initialize `runtime.args__`
  1896. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  1897. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  1898. LLVMSetValueName2(argc.value, "argc", 4);
  1899. LLVMSetValueName2(argv.value, "argv", 4);
  1900. argc = lb_emit_conv(p, argc, t_int);
  1901. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  1902. lb_fill_slice(p, args, argv, argc);
  1903. }
  1904. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  1905. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none);
  1906. if (build_context.command_kind == Command_test) {
  1907. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  1908. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  1909. Type *slice_type = alloc_type_slice(t_Internal_Test);
  1910. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  1911. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  1912. LLVMValueRef indices[2] = {};
  1913. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  1914. isize testing_proc_index = 0;
  1915. for (Entity *testing_proc : m->info->testing_procedures) {
  1916. String name = testing_proc->token.string;
  1917. String pkg_name = {};
  1918. if (testing_proc->pkg != nullptr) {
  1919. pkg_name = testing_proc->pkg->name;
  1920. }
  1921. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  1922. lbValue v_name = lb_find_or_add_entity_string(m, name);
  1923. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  1924. indices[1] = LLVMConstInt(lb_type(m, t_int), testing_proc_index++, false);
  1925. LLVMValueRef vals[3] = {};
  1926. vals[0] = v_pkg.value;
  1927. vals[1] = v_name.value;
  1928. vals[2] = v_proc.value;
  1929. GB_ASSERT(LLVMIsConstant(vals[0]));
  1930. GB_ASSERT(LLVMIsConstant(vals[1]));
  1931. GB_ASSERT(LLVMIsConstant(vals[2]));
  1932. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  1933. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  1934. LLVMBuildStore(p->builder, src, dst);
  1935. }
  1936. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  1937. lb_fill_slice(p, all_tests_slice,
  1938. lb_array_elem(p, all_tests_array),
  1939. lb_const_int(m, t_int, m->info->testing_procedures.count));
  1940. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  1941. TEMPORARY_ALLOCATOR_GUARD();
  1942. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1943. args[0] = lb_addr_load(p, all_tests_slice);
  1944. lbValue result = lb_emit_call(p, runner, args);
  1945. lbValue exit_runner = lb_find_package_value(m, str_lit("os"), str_lit("exit"));
  1946. auto exit_args = array_make<lbValue>(temporary_allocator(), 1);
  1947. exit_args[0] = lb_emit_select(p, result, lb_const_int(m, t_int, 0), lb_const_int(m, t_int, 1));
  1948. lb_emit_call(p, exit_runner, exit_args, ProcInlining_none);
  1949. } else {
  1950. if (m->info->entry_point != nullptr) {
  1951. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  1952. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  1953. }
  1954. if (call_cleanup) {
  1955. lbValue cleanup_runtime_value = {cleanup_runtime->value, cleanup_runtime->type};
  1956. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none);
  1957. }
  1958. if (is_dll_main) {
  1959. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  1960. } else {
  1961. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  1962. }
  1963. }
  1964. lb_end_procedure_body(p);
  1965. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  1966. if (is_arch_wasm()) {
  1967. lb_set_wasm_export_attributes(p->value, p->name);
  1968. }
  1969. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1970. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  1971. LLVMDumpValue(p->value);
  1972. gb_printf_err("\n\n\n\n");
  1973. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  1974. }
  1975. lb_run_function_pass_manager(default_function_pass_manager, p, lbFunctionPassManager_default);
  1976. return p;
  1977. }
  1978. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  1979. if (p->is_done) {
  1980. return;
  1981. }
  1982. if (p->body != nullptr) { // Build Procedure
  1983. m->curr_procedure = p;
  1984. lb_begin_procedure_body(p);
  1985. lb_build_stmt(p, p->body);
  1986. lb_end_procedure_body(p);
  1987. p->is_done = true;
  1988. m->curr_procedure = nullptr;
  1989. }
  1990. lb_end_procedure(p);
  1991. // Add Flags
  1992. if (p->body != nullptr) {
  1993. if (p->name == "memcpy" || p->name == "memmove" ||
  1994. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  1995. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  1996. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  1997. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  1998. }
  1999. }
  2000. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  2001. char *llvm_error = nullptr;
  2002. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  2003. LLVMDumpValue(p->value);
  2004. gb_printf_err("\n\n\n\n");
  2005. String filepath_ll = lb_filepath_ll_for_module(m);
  2006. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2007. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2008. }
  2009. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  2010. gb_exit(1);
  2011. }
  2012. }
  2013. gb_internal bool lb_generate_code(lbGenerator *gen) {
  2014. TIME_SECTION("LLVM Initializtion");
  2015. isize thread_count = gb_max(build_context.thread_count, 1);
  2016. isize worker_count = thread_count-1;
  2017. bool do_threading = !!(LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  2018. lbModule *default_module = &gen->default_module;
  2019. CheckerInfo *info = gen->info;
  2020. auto *min_dep_set = &info->minimum_dependency_set;
  2021. switch (build_context.metrics.arch) {
  2022. case TargetArch_amd64:
  2023. case TargetArch_i386:
  2024. LLVMInitializeX86TargetInfo();
  2025. LLVMInitializeX86Target();
  2026. LLVMInitializeX86TargetMC();
  2027. LLVMInitializeX86AsmPrinter();
  2028. LLVMInitializeX86AsmParser();
  2029. LLVMInitializeX86Disassembler();
  2030. break;
  2031. case TargetArch_arm64:
  2032. LLVMInitializeAArch64TargetInfo();
  2033. LLVMInitializeAArch64Target();
  2034. LLVMInitializeAArch64TargetMC();
  2035. LLVMInitializeAArch64AsmPrinter();
  2036. LLVMInitializeAArch64AsmParser();
  2037. LLVMInitializeAArch64Disassembler();
  2038. break;
  2039. case TargetArch_wasm32:
  2040. case TargetArch_wasm64p32:
  2041. LLVMInitializeWebAssemblyTargetInfo();
  2042. LLVMInitializeWebAssemblyTarget();
  2043. LLVMInitializeWebAssemblyTargetMC();
  2044. LLVMInitializeWebAssemblyAsmPrinter();
  2045. LLVMInitializeWebAssemblyAsmParser();
  2046. LLVMInitializeWebAssemblyDisassembler();
  2047. break;
  2048. default:
  2049. LLVMInitializeAllTargetInfos();
  2050. LLVMInitializeAllTargets();
  2051. LLVMInitializeAllTargetMCs();
  2052. LLVMInitializeAllAsmPrinters();
  2053. LLVMInitializeAllAsmParsers();
  2054. LLVMInitializeAllDisassemblers();
  2055. break;
  2056. }
  2057. if (build_context.microarch == "native") {
  2058. LLVMInitializeNativeTarget();
  2059. }
  2060. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  2061. for (auto const &entry : gen->modules) {
  2062. LLVMSetTarget(entry.value->mod, target_triple);
  2063. }
  2064. LLVMTargetRef target = {};
  2065. char *llvm_error = nullptr;
  2066. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  2067. GB_ASSERT(target != nullptr);
  2068. TIME_SECTION("LLVM Create Target Machine");
  2069. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  2070. if (is_arch_wasm()) {
  2071. code_mode = LLVMCodeModelJITDefault;
  2072. } else if (build_context.metrics.os == TargetOs_freestanding) {
  2073. code_mode = LLVMCodeModelKernel;
  2074. }
  2075. char const *host_cpu_name = LLVMGetHostCPUName();
  2076. char const *llvm_cpu = "generic";
  2077. char const *llvm_features = "";
  2078. if (build_context.microarch.len != 0) {
  2079. if (build_context.microarch == "native") {
  2080. llvm_cpu = host_cpu_name;
  2081. } else {
  2082. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  2083. }
  2084. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  2085. llvm_features = LLVMGetHostCPUFeatures();
  2086. }
  2087. } else if (build_context.metrics.arch == TargetArch_amd64) {
  2088. // NOTE(bill): x86-64-v2 is more than enough for everyone
  2089. //
  2090. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  2091. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  2092. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  2093. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  2094. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  2095. if (build_context.metrics.os == TargetOs_freestanding) {
  2096. llvm_cpu = "x86-64";
  2097. } else {
  2098. llvm_cpu = "x86-64-v2";
  2099. }
  2100. }
  2101. }
  2102. if (build_context.target_features_set.entries.count != 0) {
  2103. llvm_features = target_features_set_to_cstring(permanent_allocator(), false);
  2104. }
  2105. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  2106. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  2107. if (!LB_USE_NEW_PASS_SYSTEM) {
  2108. build_context.optimization_level = gb_clamp(build_context.optimization_level, -1, 2);
  2109. }
  2110. switch (build_context.optimization_level) {
  2111. default:/*fallthrough*/
  2112. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  2113. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  2114. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  2115. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  2116. }
  2117. // NOTE(bill): Target Machine Creation
  2118. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  2119. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), 0, gen->modules.count);
  2120. // NOTE(dweiler): Dynamic libraries require position-independent code.
  2121. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  2122. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  2123. reloc_mode = LLVMRelocPIC;
  2124. }
  2125. switch (build_context.reloc_mode) {
  2126. case RelocMode_Default:
  2127. if (build_context.metrics.os == TargetOs_openbsd) {
  2128. // Always use PIC for OpenBSD: it defaults to PIE
  2129. reloc_mode = LLVMRelocPIC;
  2130. }
  2131. break;
  2132. case RelocMode_Static:
  2133. reloc_mode = LLVMRelocStatic;
  2134. break;
  2135. case RelocMode_PIC:
  2136. reloc_mode = LLVMRelocPIC;
  2137. break;
  2138. case RelocMode_DynamicNoPIC:
  2139. reloc_mode = LLVMRelocDynamicNoPic;
  2140. break;
  2141. }
  2142. for (auto const &entry : gen->modules) {
  2143. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  2144. target, target_triple, llvm_cpu,
  2145. llvm_features,
  2146. code_gen_level,
  2147. reloc_mode,
  2148. code_mode);
  2149. lbModule *m = entry.value;
  2150. m->target_machine = target_machine;
  2151. LLVMSetModuleDataLayout(m->mod, LLVMCreateTargetDataLayout(target_machine));
  2152. array_add(&target_machines, target_machine);
  2153. }
  2154. for (auto const &entry : gen->modules) {
  2155. lbModule *m = entry.value;
  2156. if (m->debug_builder) { // Debug Info
  2157. for (auto const &file_entry : info->files) {
  2158. AstFile *f = file_entry.value;
  2159. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  2160. cast(char const *)f->filename.text, f->filename.len,
  2161. cast(char const *)f->directory.text, f->directory.len);
  2162. lb_set_llvm_metadata(m, f, res);
  2163. }
  2164. TEMPORARY_ALLOCATOR_GUARD();
  2165. gbString producer = gb_string_make(temporary_allocator(), "odin");
  2166. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  2167. // #ifdef NIGHTLY
  2168. // producer = gb_string_appendc(producer, "-nightly");
  2169. // #endif
  2170. // #ifdef GIT_SHA
  2171. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  2172. // #endif
  2173. gbString split_name = gb_string_make(temporary_allocator(), "");
  2174. LLVMBool is_optimized = build_context.optimization_level > 0;
  2175. AstFile *init_file = m->info->init_package->files[0];
  2176. if (Entity *entry_point = m->info->entry_point) {
  2177. if (Ast *ident = entry_point->identifier.load()) {
  2178. if (ident->file_id) {
  2179. init_file = ident->file();
  2180. }
  2181. }
  2182. }
  2183. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  2184. LLVMBool debug_info_for_profiling = false;
  2185. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  2186. lb_get_llvm_metadata(m, init_file),
  2187. producer, gb_string_length(producer),
  2188. is_optimized, "", 0,
  2189. 1, split_name, gb_string_length(split_name),
  2190. LLVMDWARFEmissionFull,
  2191. 0, split_debug_inlining,
  2192. debug_info_for_profiling,
  2193. "", 0, // sys_root
  2194. "", 0 // SDK
  2195. );
  2196. GB_ASSERT(m->debug_compile_unit != nullptr);
  2197. }
  2198. }
  2199. TIME_SECTION("LLVM Global Variables");
  2200. if (!build_context.no_rtti) {
  2201. lbModule *m = default_module;
  2202. { // Add type info data
  2203. isize max_type_info_count = info->minimum_dependency_type_info_set.count+1;
  2204. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  2205. // IMPORTANT NOTE(bill): As LLVM does not have a union type, an array of unions cannot be initialized
  2206. // at compile time without cheating in some way. This means to emulate an array of unions is to use
  2207. // a giant packed struct of "corrected" data types.
  2208. LLVMTypeRef internal_llvm_type = lb_setup_type_info_data_internal_type(m, max_type_info_count);
  2209. LLVMValueRef g = LLVMAddGlobal(m->mod, internal_llvm_type, LB_TYPE_INFO_DATA_NAME);
  2210. LLVMSetInitializer(g, LLVMConstNull(internal_llvm_type));
  2211. LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2212. lbValue value = {};
  2213. value.value = g;
  2214. value.type = alloc_type_pointer(t);
  2215. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  2216. lb_add_entity(m, lb_global_type_info_data_entity, value);
  2217. if (LB_USE_GIANT_PACKED_STRUCT) {
  2218. LLVMSetLinkage(g, LLVMPrivateLinkage);
  2219. LLVMSetUnnamedAddress(g, LLVMGlobalUnnamedAddr);
  2220. LLVMSetGlobalConstant(g, /*true*/false);
  2221. }
  2222. }
  2223. { // Type info member buffer
  2224. // NOTE(bill): Removes need for heap allocation by making it global memory
  2225. isize count = 0;
  2226. for (Type *t : m->info->type_info_types) {
  2227. isize index = lb_type_info_index(m->info, t, false);
  2228. if (index < 0) {
  2229. continue;
  2230. }
  2231. switch (t->kind) {
  2232. case Type_Union:
  2233. count += t->Union.variants.count;
  2234. break;
  2235. case Type_Struct:
  2236. count += t->Struct.fields.count;
  2237. break;
  2238. case Type_Tuple:
  2239. count += t->Tuple.variables.count;
  2240. break;
  2241. }
  2242. }
  2243. {
  2244. char const *name = LB_TYPE_INFO_TYPES_NAME;
  2245. Type *t = alloc_type_array(t_type_info_ptr, count);
  2246. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2247. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2248. LLVMSetLinkage(g, LLVMInternalLinkage);
  2249. if (LB_USE_GIANT_PACKED_STRUCT) {
  2250. lb_make_global_private_const(g);
  2251. }
  2252. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  2253. }
  2254. {
  2255. char const *name = LB_TYPE_INFO_NAMES_NAME;
  2256. Type *t = alloc_type_array(t_string, count);
  2257. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2258. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2259. LLVMSetLinkage(g, LLVMInternalLinkage);
  2260. if (LB_USE_GIANT_PACKED_STRUCT) {
  2261. lb_make_global_private_const(g);
  2262. }
  2263. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  2264. }
  2265. {
  2266. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  2267. Type *t = alloc_type_array(t_uintptr, count);
  2268. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2269. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2270. LLVMSetLinkage(g, LLVMInternalLinkage);
  2271. if (LB_USE_GIANT_PACKED_STRUCT) {
  2272. lb_make_global_private_const(g);
  2273. }
  2274. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  2275. }
  2276. {
  2277. char const *name = LB_TYPE_INFO_USINGS_NAME;
  2278. Type *t = alloc_type_array(t_bool, count);
  2279. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2280. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2281. LLVMSetLinkage(g, LLVMInternalLinkage);
  2282. if (LB_USE_GIANT_PACKED_STRUCT) {
  2283. lb_make_global_private_const(g);
  2284. }
  2285. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  2286. }
  2287. {
  2288. char const *name = LB_TYPE_INFO_TAGS_NAME;
  2289. Type *t = alloc_type_array(t_string, count);
  2290. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2291. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2292. LLVMSetLinkage(g, LLVMInternalLinkage);
  2293. if (LB_USE_GIANT_PACKED_STRUCT) {
  2294. lb_make_global_private_const(g);
  2295. }
  2296. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  2297. }
  2298. }
  2299. }
  2300. isize global_variable_max_count = 0;
  2301. bool already_has_entry_point = false;
  2302. for (Entity *e : info->entities) {
  2303. String name = e->token.string;
  2304. if (e->kind == Entity_Variable) {
  2305. global_variable_max_count++;
  2306. } else if (e->kind == Entity_Procedure) {
  2307. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  2308. GB_ASSERT(e == info->entry_point);
  2309. }
  2310. if (build_context.command_kind == Command_test &&
  2311. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  2312. String link_name = e->Procedure.link_name;
  2313. if (e->pkg->kind == Package_Runtime) {
  2314. if (link_name == "main" ||
  2315. link_name == "DllMain" ||
  2316. link_name == "WinMain" ||
  2317. link_name == "wWinMain" ||
  2318. link_name == "mainCRTStartup" ||
  2319. link_name == "_start") {
  2320. already_has_entry_point = true;
  2321. }
  2322. }
  2323. }
  2324. }
  2325. }
  2326. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  2327. for (DeclInfo *d : info->variable_init_order) {
  2328. Entity *e = d->entity;
  2329. if ((e->scope->flags & ScopeFlag_File) == 0) {
  2330. continue;
  2331. }
  2332. if (!ptr_set_exists(min_dep_set, e)) {
  2333. continue;
  2334. }
  2335. DeclInfo *decl = decl_info_of_entity(e);
  2336. if (decl == nullptr) {
  2337. continue;
  2338. }
  2339. GB_ASSERT(e->kind == Entity_Variable);
  2340. bool is_foreign = e->Variable.is_foreign;
  2341. bool is_export = e->Variable.is_export;
  2342. lbModule *m = &gen->default_module;
  2343. String name = lb_get_entity_name(m, e);
  2344. lbValue g = {};
  2345. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2346. g.type = alloc_type_pointer(e->type);
  2347. if (e->Variable.thread_local_model != "") {
  2348. LLVMSetThreadLocal(g.value, true);
  2349. String m = e->Variable.thread_local_model;
  2350. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2351. if (m == "default") {
  2352. mode = LLVMGeneralDynamicTLSModel;
  2353. } else if (m == "localdynamic") {
  2354. mode = LLVMLocalDynamicTLSModel;
  2355. } else if (m == "initialexec") {
  2356. mode = LLVMInitialExecTLSModel;
  2357. } else if (m == "localexec") {
  2358. mode = LLVMLocalExecTLSModel;
  2359. } else {
  2360. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2361. }
  2362. LLVMSetThreadLocalMode(g.value, mode);
  2363. }
  2364. if (is_foreign) {
  2365. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2366. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  2367. LLVMSetExternallyInitialized(g.value, true);
  2368. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  2369. lb_set_wasm_import_attributes(g.value, e, name);
  2370. } else {
  2371. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  2372. }
  2373. if (is_export) {
  2374. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  2375. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  2376. } else if (!is_foreign) {
  2377. LLVMSetLinkage(g.value, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2378. }
  2379. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  2380. if (e->Variable.link_section.len > 0) {
  2381. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  2382. }
  2383. lbGlobalVariable var = {};
  2384. var.var = g;
  2385. var.decl = decl;
  2386. if (decl->init_expr != nullptr) {
  2387. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  2388. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  2389. if (tav.mode != Addressing_Invalid) {
  2390. if (tav.value.kind != ExactValue_Invalid) {
  2391. ExactValue v = tav.value;
  2392. lbValue init = lb_const_value(m, tav.type, v);
  2393. LLVMSetInitializer(g.value, init.value);
  2394. var.is_initialized = true;
  2395. }
  2396. }
  2397. }
  2398. if (!var.is_initialized && is_type_untyped_nil(tav.type)) {
  2399. var.is_initialized = true;
  2400. }
  2401. }
  2402. array_add(&global_variables, var);
  2403. lb_add_entity(m, e, g);
  2404. lb_add_member(m, name, g);
  2405. if (m->debug_builder) {
  2406. String global_name = e->token.string;
  2407. if (global_name.len != 0 && global_name != "_") {
  2408. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  2409. LLVMMetadataRef llvm_scope = llvm_file;
  2410. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  2411. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2412. LLVMMetadataRef llvm_decl = nullptr;
  2413. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  2414. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  2415. m->debug_builder, llvm_scope,
  2416. cast(char const *)global_name.text, global_name.len,
  2417. "", 0, // linkage
  2418. llvm_file, e->token.pos.line,
  2419. lb_debug_type(m, e->type),
  2420. local_to_unit,
  2421. llvm_expr,
  2422. llvm_decl,
  2423. align_in_bits
  2424. );
  2425. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  2426. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  2427. }
  2428. }
  2429. }
  2430. TIME_SECTION("LLVM Runtime Type Information Creation");
  2431. gen->startup_type_info = lb_create_startup_type_info(default_module);
  2432. gen->objc_names = lb_create_objc_names(default_module);
  2433. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables & @(init))");
  2434. gen->startup_runtime = lb_create_startup_runtime(default_module, gen->startup_type_info, gen->objc_names, global_variables);
  2435. TIME_SECTION("LLVM Runtime Cleanup Creation & @(fini)");
  2436. gen->cleanup_runtime = lb_create_cleanup_runtime(default_module);
  2437. if (build_context.ODIN_DEBUG) {
  2438. for (auto const &entry : builtin_pkg->scope->elements) {
  2439. Entity *e = entry.value;
  2440. add_debug_info_for_global_constant_from_entity(gen, e);
  2441. }
  2442. }
  2443. if (gen->modules.count <= 1) {
  2444. do_threading = false;
  2445. }
  2446. TIME_SECTION("LLVM Global Procedures and Types");
  2447. lb_create_global_procedures_and_types(gen, info, do_threading);
  2448. TIME_SECTION("LLVM Procedure Generation");
  2449. lb_generate_procedures(gen, do_threading);
  2450. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  2451. TIME_SECTION("LLVM main");
  2452. lb_create_main_procedure(default_module, gen->startup_runtime, gen->cleanup_runtime);
  2453. }
  2454. TIME_SECTION("LLVM Procedure Generation (missing)");
  2455. lb_generate_missing_procedures(gen, do_threading);
  2456. if (gen->objc_names) {
  2457. TIME_SECTION("Finalize objc names");
  2458. lb_finalize_objc_names(gen->objc_names);
  2459. }
  2460. if (build_context.ODIN_DEBUG) {
  2461. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  2462. lb_debug_info_complete_types_and_finalize(gen);
  2463. }
  2464. if (do_threading) {
  2465. isize non_empty_module_count = 0;
  2466. for (auto const &entry : gen->modules) {
  2467. lbModule *m = entry.value;
  2468. if (!lb_is_module_empty(m)) {
  2469. non_empty_module_count += 1;
  2470. }
  2471. }
  2472. if (non_empty_module_count <= 1) {
  2473. do_threading = false;
  2474. }
  2475. }
  2476. TIME_SECTION("LLVM Function Pass");
  2477. lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
  2478. TIME_SECTION("LLVM Module Pass");
  2479. lb_llvm_module_passes(gen, do_threading);
  2480. TIME_SECTION("LLVM Module Verification");
  2481. if (!lb_llvm_module_verification(gen, do_threading)) {
  2482. return false;
  2483. }
  2484. llvm_error = nullptr;
  2485. defer (LLVMDisposeMessage(llvm_error));
  2486. if (build_context.keep_temp_files ||
  2487. build_context.build_mode == BuildMode_LLVM_IR) {
  2488. TIME_SECTION("LLVM Print Module to File");
  2489. for (auto const &entry : gen->modules) {
  2490. lbModule *m = entry.value;
  2491. if (lb_is_module_empty(m)) {
  2492. continue;
  2493. }
  2494. String filepath_ll = lb_filepath_ll_for_module(m);
  2495. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2496. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2497. gb_exit(1);
  2498. return false;
  2499. }
  2500. array_add(&gen->output_temp_paths, filepath_ll);
  2501. }
  2502. if (build_context.build_mode == BuildMode_LLVM_IR) {
  2503. return true;
  2504. }
  2505. }
  2506. TIME_SECTION("LLVM Add Foreign Library Paths");
  2507. lb_add_foreign_library_paths(gen);
  2508. TIME_SECTION("LLVM Object Generation");
  2509. if (build_context.ignore_llvm_build) {
  2510. gb_printf_err("LLVM object generation has been ignored!\n");
  2511. return false;
  2512. }
  2513. if (!lb_llvm_object_generation(gen, do_threading)) {
  2514. return false;
  2515. }
  2516. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  2517. if (build_context.metrics.os == TargetOs_windows) {
  2518. auto paths = array_make<String>(heap_allocator(), 0, 1);
  2519. String path = concatenate_strings(permanent_allocator(), build_context.ODIN_ROOT, str_lit("\\bin\\llvm\\windows\\clang_rt.asan-x86_64.lib"));
  2520. array_add(&paths, path);
  2521. Entity *lib = alloc_entity_library_name(nullptr, make_token_ident("asan_lib"), nullptr, slice_from_array(paths), str_lit("asan_lib"));
  2522. array_add(&gen->foreign_libraries, lib);
  2523. } else if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2524. if (!build_context.extra_linker_flags.text) {
  2525. build_context.extra_linker_flags = str_lit("-fsanitize=address");
  2526. } else {
  2527. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=address"));
  2528. }
  2529. }
  2530. }
  2531. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  2532. if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2533. if (!build_context.extra_linker_flags.text) {
  2534. build_context.extra_linker_flags = str_lit("-fsanitize=memory");
  2535. } else {
  2536. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=memory"));
  2537. }
  2538. }
  2539. }
  2540. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  2541. if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2542. if (!build_context.extra_linker_flags.text) {
  2543. build_context.extra_linker_flags = str_lit("-fsanitize=thread");
  2544. } else {
  2545. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=thread"));
  2546. }
  2547. }
  2548. }
  2549. gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
  2550. return true;
  2551. }