llvm_backend.cpp 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef MULTITHREAD_OBJECT_GENERATION
  3. #define MULTITHREAD_OBJECT_GENERATION 0
  4. #endif
  5. #ifndef USE_SEPARATE_MODULES
  6. #define USE_SEPARATE_MODULES build_context.use_separate_modules
  7. #endif
  8. #ifndef LLVM_IGNORE_VERIFICATION
  9. #define LLVM_IGNORE_VERIFICATION 0
  10. #endif
  11. #include "llvm_backend.hpp"
  12. #include "llvm_abi.cpp"
  13. #include "llvm_backend_opt.cpp"
  14. #include "llvm_backend_general.cpp"
  15. #include "llvm_backend_debug.cpp"
  16. #include "llvm_backend_const.cpp"
  17. #include "llvm_backend_type.cpp"
  18. #include "llvm_backend_utility.cpp"
  19. #include "llvm_backend_expr.cpp"
  20. #include "llvm_backend_stmt.cpp"
  21. #include "llvm_backend_proc.cpp"
  22. gb_internal String get_default_microarchitecture() {
  23. String default_march = str_lit("generic");
  24. if (build_context.metrics.arch == TargetArch_amd64) {
  25. // NOTE(bill): x86-64-v2 is more than enough for everyone
  26. //
  27. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  28. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  29. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  30. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  31. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  32. if (build_context.metrics.os == TargetOs_freestanding) {
  33. default_march = str_lit("x86-64");
  34. } else {
  35. default_march = str_lit("x86-64-v2");
  36. }
  37. }
  38. } else if (build_context.metrics.arch == TargetArch_riscv64) {
  39. default_march = str_lit("generic-rv64");
  40. }
  41. return default_march;
  42. }
  43. gb_internal String get_final_microarchitecture() {
  44. BuildContext *bc = &build_context;
  45. String microarch = bc->microarch;
  46. if (microarch.len == 0) {
  47. microarch = get_default_microarchitecture();
  48. } else if (microarch == str_lit("native")) {
  49. microarch = make_string_c(LLVMGetHostCPUName());
  50. }
  51. return microarch;
  52. }
  53. gb_internal String get_default_features() {
  54. BuildContext *bc = &build_context;
  55. int off = 0;
  56. for (int i = 0; i < bc->metrics.arch; i += 1) {
  57. off += target_microarch_counts[i];
  58. }
  59. String microarch = get_final_microarchitecture();
  60. // NOTE(laytan): for riscv64 to work properly with Odin, we need to enforce some features.
  61. // and we also overwrite the generic target to include more features so we don't default to
  62. // a potato feature set.
  63. if (bc->metrics.arch == TargetArch_riscv64) {
  64. if (microarch == str_lit("generic-rv64")) {
  65. // This is what clang does by default (on -march=rv64gc for General Computing), seems good to also default to.
  66. String features = str_lit("64bit,a,c,d,f,m,relax,zicsr,zifencei");
  67. // Update the features string so LLVM uses it later.
  68. if (bc->target_features_string.len > 0) {
  69. bc->target_features_string = concatenate3_strings(permanent_allocator(), features, str_lit(","), bc->target_features_string);
  70. } else {
  71. bc->target_features_string = features;
  72. }
  73. return features;
  74. }
  75. }
  76. for (int i = off; i < off+target_microarch_counts[bc->metrics.arch]; i += 1) {
  77. if (microarch_features_list[i].microarch == microarch) {
  78. return microarch_features_list[i].features;
  79. }
  80. }
  81. GB_PANIC("unknown microarch: %.*s", LIT(microarch));
  82. return {};
  83. }
  84. gb_internal void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  85. if (e == nullptr) {
  86. return;
  87. }
  88. GB_ASSERT(e->kind == Entity_LibraryName);
  89. GB_ASSERT(e->flags & EntityFlag_Used);
  90. mutex_lock(&m->gen->foreign_mutex);
  91. if (!ptr_set_update(&m->gen->foreign_libraries_set, e)) {
  92. array_add(&m->gen->foreign_libraries, e);
  93. }
  94. mutex_unlock(&m->gen->foreign_mutex);
  95. }
  96. gb_internal GB_COMPARE_PROC(foreign_library_cmp) {
  97. int cmp = 0;
  98. Entity *x = *(Entity **)a;
  99. Entity *y = *(Entity **)b;
  100. if (x == y) {
  101. return 0;
  102. }
  103. GB_ASSERT(x->kind == Entity_LibraryName);
  104. GB_ASSERT(y->kind == Entity_LibraryName);
  105. cmp = i64_cmp(x->LibraryName.priority_index, y->LibraryName.priority_index);
  106. if (cmp) {
  107. return cmp;
  108. }
  109. if (x->pkg != y->pkg) {
  110. isize order_x = x->pkg ? x->pkg->order : 0;
  111. isize order_y = y->pkg ? y->pkg->order : 0;
  112. cmp = isize_cmp(order_x, order_y);
  113. if (cmp) {
  114. return cmp;
  115. }
  116. }
  117. if (x->file != y->file) {
  118. String fullpath_x = x->file ? x->file->fullpath : (String{});
  119. String fullpath_y = y->file ? y->file->fullpath : (String{});
  120. String file_x = filename_from_path(fullpath_x);
  121. String file_y = filename_from_path(fullpath_y);
  122. cmp = string_compare(file_x, file_y);
  123. if (cmp) {
  124. return cmp;
  125. }
  126. }
  127. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  128. if (cmp) {
  129. return cmp;
  130. }
  131. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  132. }
  133. gb_internal void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  134. if (other_module == nullptr) {
  135. return;
  136. }
  137. char const *cname = alloc_cstring(permanent_allocator(), name);
  138. mpsc_enqueue(&other_module->gen->entities_to_correct_linkage, lbEntityCorrection{other_module, e, cname});
  139. }
  140. gb_internal void lb_correct_entity_linkage(lbGenerator *gen) {
  141. for (lbEntityCorrection ec = {}; mpsc_dequeue(&gen->entities_to_correct_linkage, &ec); /**/) {
  142. LLVMValueRef other_global = nullptr;
  143. if (ec.e->kind == Entity_Variable) {
  144. other_global = LLVMGetNamedGlobal(ec.other_module->mod, ec.cname);
  145. if (other_global) {
  146. LLVMSetLinkage(other_global, LLVMWeakAnyLinkage);
  147. if (!ec.e->Variable.is_export && !ec.e->Variable.is_foreign) {
  148. LLVMSetVisibility(other_global, LLVMHiddenVisibility);
  149. }
  150. }
  151. } else if (ec.e->kind == Entity_Procedure) {
  152. other_global = LLVMGetNamedFunction(ec.other_module->mod, ec.cname);
  153. if (other_global) {
  154. LLVMSetLinkage(other_global, LLVMWeakAnyLinkage);
  155. if (!ec.e->Procedure.is_export && !ec.e->Procedure.is_foreign) {
  156. LLVMSetVisibility(other_global, LLVMHiddenVisibility);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. gb_internal void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  163. TEMPORARY_ALLOCATOR_GUARD();
  164. GB_ASSERT(addr.kind == lbAddr_Context);
  165. GB_ASSERT(addr.ctx.sel.index.count == 0);
  166. auto args = array_make<lbValue>(temporary_allocator(), 1);
  167. args[0] = addr.addr;
  168. lb_emit_runtime_call(p, "__init_context", args);
  169. }
  170. gb_internal lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  171. Type *pt = base_type(p->type);
  172. GB_ASSERT(pt->kind == Type_Proc);
  173. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  174. String name = str_lit("__.context_ptr");
  175. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  176. e->flags |= EntityFlag_NoAlias;
  177. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  178. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  179. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  180. lbValue param = {context_ptr, e->type};
  181. lb_add_entity(p->module, e, param);
  182. lbAddr ctx_addr = {};
  183. ctx_addr.kind = lbAddr_Context;
  184. ctx_addr.addr = param;
  185. lbContextData *cd = array_add_and_get(&p->context_stack);
  186. cd->ctx = ctx_addr;
  187. cd->scope_index = -1;
  188. cd->uses = +1; // make sure it has been used already
  189. return cd;
  190. }
  191. gb_internal lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  192. ctx.kind = lbAddr_Context;
  193. lbContextData *cd = array_add_and_get(&p->context_stack);
  194. cd->ctx = ctx;
  195. cd->scope_index = p->scope_index;
  196. return cd;
  197. }
  198. gb_internal String lb_internal_gen_name_from_type(char const *prefix, Type *type) {
  199. gbString str = gb_string_make(permanent_allocator(), prefix);
  200. u64 hash = type_hash_canonical_type(type);
  201. str = gb_string_appendc(str, "-");
  202. str = gb_string_append_fmt(str, "%llu", cast(unsigned long long)hash);
  203. String proc_name = make_string(cast(u8 const *)str, gb_string_length(str));
  204. return proc_name;
  205. }
  206. gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
  207. type = base_type(type);
  208. GB_ASSERT(is_type_comparable(type));
  209. Type *pt = alloc_type_pointer(type);
  210. LLVMTypeRef ptr_type = lb_type(m, pt);
  211. String proc_name = lb_internal_gen_name_from_type("__$equal", type);
  212. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  213. lbProcedure *compare_proc = nullptr;
  214. if (found) {
  215. compare_proc = *found;
  216. GB_ASSERT(compare_proc != nullptr);
  217. return {compare_proc->value, compare_proc->type};
  218. }
  219. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  220. string_map_set(&m->gen_procs, proc_name, p);
  221. lb_begin_procedure_body(p);
  222. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  223. // lb_add_attribute_to_proc(m, p->value, "readonly");
  224. lb_add_attribute_to_proc(m, p->value, "nounwind");
  225. LLVMValueRef x = LLVMGetParam(p->value, 0);
  226. LLVMValueRef y = LLVMGetParam(p->value, 1);
  227. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  228. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  229. lbValue lhs = {x, pt};
  230. lbValue rhs = {y, pt};
  231. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  232. lb_add_proc_attribute_at_index(p, 1+1, "nonnull");
  233. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  234. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  235. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  236. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  237. lb_start_block(p, block_same_ptr);
  238. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  239. lb_start_block(p, block_diff_ptr);
  240. if (type->kind == Type_Struct) {
  241. type_set_offsets(type);
  242. lbBlock *block_false = lb_create_block(p, "bfalse");
  243. lbValue res = lb_const_bool(m, t_bool, true);
  244. for_array(i, type->Struct.fields) {
  245. lbBlock *next_block = lb_create_block(p, "btrue");
  246. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  247. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  248. lbValue left = lb_emit_load(p, pleft);
  249. lbValue right = lb_emit_load(p, pright);
  250. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  251. lb_emit_if(p, ok, next_block, block_false);
  252. lb_emit_jump(p, next_block);
  253. lb_start_block(p, next_block);
  254. }
  255. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  256. lb_start_block(p, block_false);
  257. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  258. } else if (type->kind == Type_Union) {
  259. if (type_size_of(type) == 0) {
  260. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  261. } else if (is_type_union_maybe_pointer(type)) {
  262. Type *v = type->Union.variants[0];
  263. Type *pv = alloc_type_pointer(v);
  264. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  265. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  266. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  267. ok = lb_emit_conv(p, ok, t_bool);
  268. LLVMBuildRet(p->builder, ok.value);
  269. } else {
  270. lbBlock *block_false = lb_create_block(p, "bfalse");
  271. lbBlock *block_switch = lb_create_block(p, "bswitch");
  272. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  273. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  274. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  275. lb_emit_if(p, tag_eq, block_switch, block_false);
  276. lb_start_block(p, block_switch);
  277. unsigned variant_count = cast(unsigned)type->Union.variants.count;
  278. if (type->Union.kind != UnionType_no_nil) {
  279. variant_count += 1;
  280. }
  281. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, variant_count);
  282. if (type->Union.kind != UnionType_no_nil) {
  283. lbBlock *case_block = lb_create_block(p, "bcase");
  284. lb_start_block(p, case_block);
  285. lbValue case_tag = lb_const_int(p->module, union_tag_type(type), 0);
  286. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  287. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  288. }
  289. for (Type *v : type->Union.variants) {
  290. lbBlock *case_block = lb_create_block(p, "bcase");
  291. lb_start_block(p, case_block);
  292. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  293. Type *vp = alloc_type_pointer(v);
  294. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  295. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  296. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  297. ok = lb_emit_conv(p, ok, t_bool);
  298. LLVMBuildRet(p->builder, ok.value);
  299. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  300. }
  301. lb_start_block(p, block_false);
  302. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  303. }
  304. } else {
  305. lbValue left = lb_emit_load(p, lhs);
  306. lbValue right = lb_emit_load(p, rhs);
  307. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  308. ok = lb_emit_conv(p, ok, t_bool);
  309. LLVMBuildRet(p->builder, ok.value);
  310. }
  311. lb_end_procedure_body(p);
  312. compare_proc = p;
  313. return {compare_proc->value, compare_proc->type};
  314. }
  315. gb_internal lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  316. TEMPORARY_ALLOCATOR_GUARD();
  317. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  318. auto args = array_make<lbValue>(temporary_allocator(), 3);
  319. args[0] = data;
  320. args[1] = seed;
  321. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  322. return lb_emit_runtime_call(p, "default_hasher", args);
  323. }
  324. gb_internal void lb_add_callsite_force_inline(lbProcedure *p, lbValue ret_value) {
  325. LLVMAddCallSiteAttribute(ret_value.value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  326. }
  327. gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
  328. type = core_type(type);
  329. GB_ASSERT_MSG(is_type_comparable(type), "%s", type_to_string(type));
  330. Type *pt = alloc_type_pointer(type);
  331. String proc_name = lb_internal_gen_name_from_type("__$hasher", type);
  332. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  333. if (found) {
  334. GB_ASSERT(*found != nullptr);
  335. return {(*found)->value, (*found)->type};
  336. }
  337. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  338. string_map_set(&m->gen_procs, proc_name, p);
  339. lb_begin_procedure_body(p);
  340. defer (lb_end_procedure_body(p));
  341. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  342. // lb_add_attribute_to_proc(m, p->value, "readonly");
  343. lb_add_attribute_to_proc(m, p->value, "nounwind");
  344. LLVMValueRef x = LLVMGetParam(p->value, 0);
  345. LLVMValueRef y = LLVMGetParam(p->value, 1);
  346. lbValue data = {x, t_rawptr};
  347. lbValue seed = {y, t_uintptr};
  348. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  349. // lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  350. if (is_type_simple_compare(type)) {
  351. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  352. lb_add_callsite_force_inline(p, res);
  353. LLVMBuildRet(p->builder, res.value);
  354. return {p->value, p->type};
  355. }
  356. TEMPORARY_ALLOCATOR_GUARD();
  357. if (type->kind == Type_Struct) {
  358. type_set_offsets(type);
  359. data = lb_emit_conv(p, data, t_u8_ptr);
  360. auto args = array_make<lbValue>(temporary_allocator(), 2);
  361. for_array(i, type->Struct.fields) {
  362. GB_ASSERT(type->Struct.offsets != nullptr);
  363. i64 offset = type->Struct.offsets[i];
  364. Entity *field = type->Struct.fields[i];
  365. lbValue field_hasher = lb_hasher_proc_for_type(m, field->type);
  366. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  367. args[0] = ptr;
  368. args[1] = seed;
  369. seed = lb_emit_call(p, field_hasher, args);
  370. }
  371. LLVMBuildRet(p->builder, seed.value);
  372. } else if (type->kind == Type_Union) {
  373. auto args = array_make<lbValue>(temporary_allocator(), 2);
  374. if (is_type_union_maybe_pointer(type)) {
  375. Type *v = type->Union.variants[0];
  376. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  377. args[0] = data;
  378. args[1] = seed;
  379. lbValue res = lb_emit_call(p, variant_hasher, args);
  380. lb_add_callsite_force_inline(p, res);
  381. LLVMBuildRet(p->builder, res.value);
  382. }
  383. lbBlock *end_block = lb_create_block(p, "bend");
  384. data = lb_emit_conv(p, data, pt);
  385. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  386. lbValue tag = lb_emit_load(p, tag_ptr);
  387. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  388. for (Type *v : type->Union.variants) {
  389. lbBlock *case_block = lb_create_block(p, "bcase");
  390. lb_start_block(p, case_block);
  391. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  392. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  393. args[0] = data;
  394. args[1] = seed;
  395. lbValue res = lb_emit_call(p, variant_hasher, args);
  396. LLVMBuildRet(p->builder, res.value);
  397. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  398. }
  399. lb_start_block(p, end_block);
  400. LLVMBuildRet(p->builder, seed.value);
  401. } else if (type->kind == Type_Array) {
  402. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  403. lb_addr_store(p, pres, seed);
  404. auto args = array_make<lbValue>(temporary_allocator(), 2);
  405. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->Array.elem);
  406. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  407. data = lb_emit_conv(p, data, pt);
  408. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  409. args[0] = ptr;
  410. args[1] = lb_addr_load(p, pres);
  411. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  412. lb_addr_store(p, pres, new_seed);
  413. lb_loop_end(p, loop_data);
  414. lbValue res = lb_addr_load(p, pres);
  415. LLVMBuildRet(p->builder, res.value);
  416. } else if (type->kind == Type_EnumeratedArray) {
  417. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  418. lb_addr_store(p, res, seed);
  419. auto args = array_make<lbValue>(temporary_allocator(), 2);
  420. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  421. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  422. data = lb_emit_conv(p, data, pt);
  423. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  424. args[0] = ptr;
  425. args[1] = lb_addr_load(p, res);
  426. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  427. lb_addr_store(p, res, new_seed);
  428. lb_loop_end(p, loop_data);
  429. lbValue vres = lb_addr_load(p, res);
  430. LLVMBuildRet(p->builder, vres.value);
  431. } else if (is_type_cstring(type)) {
  432. auto args = array_make<lbValue>(temporary_allocator(), 2);
  433. args[0] = data;
  434. args[1] = seed;
  435. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  436. lb_add_callsite_force_inline(p, res);
  437. LLVMBuildRet(p->builder, res.value);
  438. } else if (is_type_string(type)) {
  439. auto args = array_make<lbValue>(temporary_allocator(), 2);
  440. args[0] = data;
  441. args[1] = seed;
  442. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  443. lb_add_callsite_force_inline(p, res);
  444. LLVMBuildRet(p->builder, res.value);
  445. } else if (is_type_float(type)) {
  446. lbValue ptr = lb_emit_conv(p, data, pt);
  447. lbValue v = lb_emit_load(p, ptr);
  448. v = lb_emit_conv(p, v, t_f64);
  449. auto args = array_make<lbValue>(temporary_allocator(), 2);
  450. args[0] = v;
  451. args[1] = seed;
  452. lbValue res = lb_emit_runtime_call(p, "default_hasher_f64", args);
  453. lb_add_callsite_force_inline(p, res);
  454. LLVMBuildRet(p->builder, res.value);
  455. } else if (is_type_complex(type)) {
  456. lbValue ptr = lb_emit_conv(p, data, pt);
  457. lbValue xp = lb_emit_struct_ep(p, ptr, 0);
  458. lbValue yp = lb_emit_struct_ep(p, ptr, 1);
  459. lbValue x = lb_emit_conv(p, lb_emit_load(p, xp), t_f64);
  460. lbValue y = lb_emit_conv(p, lb_emit_load(p, yp), t_f64);
  461. auto args = array_make<lbValue>(temporary_allocator(), 3);
  462. args[0] = x;
  463. args[1] = y;
  464. args[2] = seed;
  465. lbValue res = lb_emit_runtime_call(p, "default_hasher_complex128", args);
  466. lb_add_callsite_force_inline(p, res);
  467. LLVMBuildRet(p->builder, res.value);
  468. } else if (is_type_quaternion(type)) {
  469. lbValue ptr = lb_emit_conv(p, data, pt);
  470. lbValue xp = lb_emit_struct_ep(p, ptr, 0);
  471. lbValue yp = lb_emit_struct_ep(p, ptr, 1);
  472. lbValue zp = lb_emit_struct_ep(p, ptr, 2);
  473. lbValue wp = lb_emit_struct_ep(p, ptr, 3);
  474. lbValue x = lb_emit_conv(p, lb_emit_load(p, xp), t_f64);
  475. lbValue y = lb_emit_conv(p, lb_emit_load(p, yp), t_f64);
  476. lbValue z = lb_emit_conv(p, lb_emit_load(p, zp), t_f64);
  477. lbValue w = lb_emit_conv(p, lb_emit_load(p, wp), t_f64);
  478. auto args = array_make<lbValue>(temporary_allocator(), 5);
  479. args[0] = x;
  480. args[1] = y;
  481. args[2] = z;
  482. args[3] = w;
  483. args[4] = seed;
  484. lbValue res = lb_emit_runtime_call(p, "default_hasher_quaternion256", args);
  485. lb_add_callsite_force_inline(p, res);
  486. LLVMBuildRet(p->builder, res.value);
  487. } else {
  488. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  489. }
  490. return {p->value, p->type};
  491. }
  492. #define LLVM_SET_VALUE_NAME(value, name) LLVMSetValueName2((value), (name), gb_count_of((name))-1);
  493. gb_internal lbValue lb_map_get_proc_for_type(lbModule *m, Type *type) {
  494. GB_ASSERT(!build_context.dynamic_map_calls);
  495. type = base_type(type);
  496. GB_ASSERT(type->kind == Type_Map);
  497. String proc_name = lb_internal_gen_name_from_type("__$map_get", type);
  498. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  499. if (found) {
  500. GB_ASSERT(*found != nullptr);
  501. return {(*found)->value, (*found)->type};
  502. }
  503. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_get_proc);
  504. string_map_set(&m->gen_procs, proc_name, p);
  505. lb_begin_procedure_body(p);
  506. defer (lb_end_procedure_body(p));
  507. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  508. lb_add_attribute_to_proc(m, p->value, "nounwind");
  509. if (build_context.ODIN_DEBUG) {
  510. lb_add_attribute_to_proc(m, p->value, "noinline");
  511. }
  512. LLVMValueRef x = LLVMGetParam(p->value, 0);
  513. LLVMValueRef y = LLVMGetParam(p->value, 1);
  514. LLVMValueRef z = LLVMGetParam(p->value, 2);
  515. lbValue map_ptr = {x, t_rawptr};
  516. lbValue h = {y, t_uintptr};
  517. lbValue key_ptr = {z, t_rawptr};
  518. LLVM_SET_VALUE_NAME(h.value, "hash");
  519. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  520. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  521. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  522. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  523. lbBlock *loop_block = lb_create_block(p, "loop");
  524. lbBlock *hash_block = lb_create_block(p, "hash");
  525. lbBlock *probe_block = lb_create_block(p, "probe");
  526. lbBlock *increment_block = lb_create_block(p, "increment");
  527. lbBlock *hash_compare_block = lb_create_block(p, "hash_compare");
  528. lbBlock *key_compare_block = lb_create_block(p, "key_compare");
  529. lbBlock *value_block = lb_create_block(p, "value");
  530. lbBlock *nil_block = lb_create_block(p, "nil");
  531. map_ptr = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  532. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  533. lbValue map = lb_emit_load(p, map_ptr);
  534. LLVM_SET_VALUE_NAME(map.value, "map");
  535. lbValue length = lb_map_len(p, map);
  536. LLVM_SET_VALUE_NAME(length.value, "length");
  537. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, length, lb_const_nil(m, t_int)), nil_block, hash_block);
  538. lb_start_block(p, hash_block);
  539. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  540. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  541. lbValue key = lb_emit_load(p, key_ptr);
  542. LLVM_SET_VALUE_NAME(key.value, "key");
  543. lbAddr pos = lb_add_local_generated(p, t_uintptr, false);
  544. lbAddr distance = lb_add_local_generated(p, t_uintptr, true);
  545. LLVM_SET_VALUE_NAME(pos.addr.value, "pos");
  546. LLVM_SET_VALUE_NAME(distance.addr.value, "distance");
  547. lbValue capacity = lb_map_cap(p, map);
  548. LLVM_SET_VALUE_NAME(capacity.value, "capacity");
  549. lbValue cap_minus_1 = lb_emit_arith(p, Token_Sub, capacity, lb_const_int(m, t_int, 1), t_int);
  550. lbValue mask = lb_emit_conv(p, cap_minus_1, t_uintptr);
  551. LLVM_SET_VALUE_NAME(mask.value, "mask");
  552. {
  553. // map_desired_position inlined
  554. lbValue the_pos = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  555. the_pos = lb_emit_conv(p, the_pos, t_uintptr);
  556. lb_addr_store(p, pos, the_pos);
  557. }
  558. lbValue zero_uintptr = lb_const_int(m, t_uintptr, 0);
  559. lbValue one_uintptr = lb_const_int(m, t_uintptr, 1);
  560. lbValue ks = lb_map_data_uintptr(p, map);
  561. lbValue vs = lb_map_cell_index_static(p, type->Map.key, ks, capacity);
  562. lbValue hs = lb_map_cell_index_static(p, type->Map.value, vs, capacity);
  563. ks = lb_emit_conv(p, ks, alloc_type_pointer(type->Map.key));
  564. vs = lb_emit_conv(p, vs, alloc_type_pointer(type->Map.value));
  565. hs = lb_emit_conv(p, hs, alloc_type_pointer(t_uintptr));
  566. LLVM_SET_VALUE_NAME(ks.value, "ks");
  567. LLVM_SET_VALUE_NAME(vs.value, "vs");
  568. LLVM_SET_VALUE_NAME(hs.value, "hs");
  569. lb_emit_jump(p, loop_block);
  570. lb_start_block(p, loop_block);
  571. lbValue element_hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, lb_addr_load(p, pos)));
  572. LLVM_SET_VALUE_NAME(element_hash.value, "element_hash");
  573. {
  574. // if element_hash == 0 { return nil }
  575. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, zero_uintptr), nil_block, probe_block);
  576. }
  577. lb_start_block(p, probe_block);
  578. {
  579. // map_probe_distance inlined
  580. lbValue probe_distance = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  581. probe_distance = lb_emit_conv(p, probe_distance, t_uintptr);
  582. lbValue cap = lb_emit_conv(p, capacity, t_uintptr);
  583. lbValue base = lb_emit_arith(p, Token_Add, lb_addr_load(p, pos), cap, t_uintptr);
  584. probe_distance = lb_emit_arith(p, Token_Sub, base, probe_distance, t_uintptr);
  585. probe_distance = lb_emit_arith(p, Token_And, probe_distance, mask, t_uintptr);
  586. LLVM_SET_VALUE_NAME(probe_distance.value, "probe_distance");
  587. lbValue cond = lb_emit_comp(p, Token_Gt, lb_addr_load(p, distance), probe_distance);
  588. lb_emit_if(p, cond, nil_block, hash_compare_block);
  589. }
  590. lb_start_block(p, hash_compare_block);
  591. {
  592. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, h), key_compare_block, increment_block);
  593. }
  594. lb_start_block(p, key_compare_block);
  595. {
  596. lbValue element_key = lb_map_cell_index_static(p, type->Map.key, ks, lb_addr_load(p, pos));
  597. element_key = lb_emit_conv(p, element_key, ks.type);
  598. LLVM_SET_VALUE_NAME(element_key.value, "element_key_ptr");
  599. lbValue cond = lb_emit_comp(p, Token_CmpEq, lb_emit_load(p, element_key), key);
  600. lb_emit_if(p, cond, value_block, increment_block);
  601. }
  602. lb_start_block(p, value_block);
  603. {
  604. lbValue element_value = lb_map_cell_index_static(p, type->Map.value, vs, lb_addr_load(p, pos));
  605. LLVM_SET_VALUE_NAME(element_value.value, "element_value_ptr");
  606. element_value = lb_emit_conv(p, element_value, t_rawptr);
  607. LLVMBuildRet(p->builder, element_value.value);
  608. }
  609. lb_start_block(p, increment_block);
  610. {
  611. lbValue pp = lb_addr_load(p, pos);
  612. pp = lb_emit_arith(p, Token_Add, pp, one_uintptr, t_uintptr);
  613. pp = lb_emit_arith(p, Token_And, pp, mask, t_uintptr);
  614. lb_addr_store(p, pos, pp);
  615. lb_emit_increment(p, distance.addr);
  616. }
  617. lb_emit_jump(p, loop_block);
  618. lb_start_block(p, nil_block);
  619. {
  620. lbValue res = lb_const_nil(m, t_rawptr);
  621. LLVMBuildRet(p->builder, res.value);
  622. }
  623. // gb_printf_err("%s\n", LLVMPrintValueToString(p->value));
  624. return {p->value, p->type};
  625. }
  626. // gb_internal void lb_debug_print(lbProcedure *p, String const &str) {
  627. // auto args = array_make<lbValue>(heap_allocator(), 1);
  628. // args[0] = lb_const_string(p->module, str);
  629. // lb_emit_runtime_call(p, "print_string", args);
  630. // }
  631. gb_internal lbValue lb_map_set_proc_for_type(lbModule *m, Type *type) {
  632. TEMPORARY_ALLOCATOR_GUARD();
  633. GB_ASSERT(!build_context.dynamic_map_calls);
  634. type = base_type(type);
  635. GB_ASSERT(type->kind == Type_Map);
  636. String proc_name = lb_internal_gen_name_from_type("__$map_set", type);
  637. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  638. if (found) {
  639. GB_ASSERT(*found != nullptr);
  640. return {(*found)->value, (*found)->type};
  641. }
  642. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_set_proc);
  643. string_map_set(&m->gen_procs, proc_name, p);
  644. lb_begin_procedure_body(p);
  645. defer (lb_end_procedure_body(p));
  646. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  647. lb_add_attribute_to_proc(m, p->value, "nounwind");
  648. if (build_context.ODIN_DEBUG) {
  649. lb_add_attribute_to_proc(m, p->value, "noinline");
  650. }
  651. lbValue map_ptr = {LLVMGetParam(p->value, 0), t_rawptr};
  652. lbValue hash_param = {LLVMGetParam(p->value, 1), t_uintptr};
  653. lbValue key_ptr = {LLVMGetParam(p->value, 2), t_rawptr};
  654. lbValue value_ptr = {LLVMGetParam(p->value, 3), t_rawptr};
  655. lbValue location_ptr = {LLVMGetParam(p->value, 4), t_source_code_location_ptr};
  656. map_ptr = lb_emit_conv(p, map_ptr, alloc_type_pointer(type));
  657. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  658. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  659. LLVM_SET_VALUE_NAME(hash_param.value, "hash_param");
  660. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  661. LLVM_SET_VALUE_NAME(value_ptr.value, "value_ptr");
  662. LLVM_SET_VALUE_NAME(location_ptr.value, "location");
  663. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  664. lb_add_proc_attribute_at_index(p, 1+0, "noalias");
  665. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  666. if (!are_types_identical(type->Map.key, type->Map.value)) {
  667. lb_add_proc_attribute_at_index(p, 1+2, "noalias");
  668. }
  669. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  670. lb_add_proc_attribute_at_index(p, 1+3, "nonnull");
  671. if (!are_types_identical(type->Map.key, type->Map.value)) {
  672. lb_add_proc_attribute_at_index(p, 1+3, "noalias");
  673. }
  674. lb_add_proc_attribute_at_index(p, 1+3, "readonly");
  675. lb_add_proc_attribute_at_index(p, 1+4, "nonnull");
  676. lb_add_proc_attribute_at_index(p, 1+4, "noalias");
  677. lb_add_proc_attribute_at_index(p, 1+4, "readonly");
  678. lbAddr hash_addr = lb_add_local_generated(p, t_uintptr, false);
  679. lb_addr_store(p, hash_addr, hash_param);
  680. LLVM_SET_VALUE_NAME(hash_addr.addr.value, "hash");
  681. ////
  682. lbValue found_ptr = {};
  683. {
  684. lbValue map_get_proc = lb_map_get_proc_for_type(m, type);
  685. auto args = array_make<lbValue>(temporary_allocator(), 3);
  686. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  687. args[1] = lb_addr_load(p, hash_addr);
  688. args[2] = key_ptr;
  689. found_ptr = lb_emit_call(p, map_get_proc, args);
  690. }
  691. LLVM_SET_VALUE_NAME(found_ptr.value, "found_ptr");
  692. lbBlock *found_block = lb_create_block(p, "found");
  693. lbBlock *check_grow_block = lb_create_block(p, "check-grow");
  694. lbBlock *grow_fail_block = lb_create_block(p, "grow-fail");
  695. lbBlock *insert_block = lb_create_block(p, "insert");
  696. lbBlock *check_has_grown_block = lb_create_block(p, "check-has-grown");
  697. lbBlock *rehash_block = lb_create_block(p, "rehash");
  698. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, found_ptr), found_block, check_grow_block);
  699. lb_start_block(p, found_block);
  700. {
  701. lb_mem_copy_non_overlapping(p, found_ptr, value_ptr, lb_const_int(m, t_int, type_size_of(type->Map.value)));
  702. LLVMBuildRet(p->builder, lb_emit_conv(p, found_ptr, t_rawptr).value);
  703. }
  704. lb_start_block(p, check_grow_block);
  705. lbValue map_info = lb_gen_map_info_ptr(p->module, type);
  706. LLVM_SET_VALUE_NAME(map_info.value, "map_info");
  707. {
  708. auto args = array_make<lbValue>(temporary_allocator(), 3);
  709. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  710. args[1] = map_info;
  711. args[2] = lb_emit_load(p, location_ptr);
  712. lbValue grow_err_and_has_grown = lb_emit_runtime_call(p, "__dynamic_map_check_grow", args);
  713. lbValue grow_err = lb_emit_struct_ev(p, grow_err_and_has_grown, 0);
  714. lbValue has_grown = lb_emit_struct_ev(p, grow_err_and_has_grown, 1);
  715. LLVM_SET_VALUE_NAME(grow_err.value, "grow_err");
  716. LLVM_SET_VALUE_NAME(has_grown.value, "has_grown");
  717. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, grow_err), grow_fail_block, check_has_grown_block);
  718. lb_start_block(p, grow_fail_block);
  719. LLVMBuildRet(p->builder, LLVMConstNull(lb_type(m, t_rawptr)));
  720. lb_start_block(p, check_has_grown_block);
  721. lb_emit_if(p, has_grown, rehash_block, insert_block);
  722. lb_start_block(p, rehash_block);
  723. lbValue key = lb_emit_load(p, key_ptr);
  724. lbValue new_hash = lb_gen_map_key_hash(p, map_ptr, key, nullptr);
  725. LLVM_SET_VALUE_NAME(new_hash.value, "new_hash");
  726. lb_addr_store(p, hash_addr, new_hash);
  727. lb_emit_jump(p, insert_block);
  728. }
  729. lb_start_block(p, insert_block);
  730. {
  731. auto args = array_make<lbValue>(temporary_allocator(), 5);
  732. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  733. args[1] = map_info;
  734. args[2] = lb_addr_load(p, hash_addr);
  735. args[3] = lb_emit_conv(p, key_ptr, t_uintptr);
  736. args[4] = lb_emit_conv(p, value_ptr, t_uintptr);
  737. lbValue result = lb_emit_runtime_call(p, "map_insert_hash_dynamic", args);
  738. lb_emit_increment(p, lb_map_len_ptr(p, map_ptr));
  739. LLVMBuildRet(p->builder, lb_emit_conv(p, result, t_rawptr).value);
  740. }
  741. return {p->value, p->type};
  742. }
  743. gb_internal lbValue lb_gen_map_cell_info_ptr(lbModule *m, Type *type) {
  744. lbAddr *found = map_get(&m->map_cell_info_map, type);
  745. if (found) {
  746. return found->addr;
  747. }
  748. i64 size = 0, len = 0;
  749. map_cell_size_and_len(type, &size, &len);
  750. LLVMValueRef const_values[4] = {};
  751. const_values[0] = lb_const_int(m, t_uintptr, type_size_of(type)).value;
  752. const_values[1] = lb_const_int(m, t_uintptr, type_align_of(type)).value;
  753. const_values[2] = lb_const_int(m, t_uintptr, size).value;
  754. const_values[3] = lb_const_int(m, t_uintptr, len).value;
  755. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_cell_info, const_values, gb_count_of(const_values));
  756. lbValue res = {llvm_res, t_map_cell_info};
  757. lbAddr addr = lb_add_global_generated_with_name(m, t_map_cell_info, res, lb_internal_gen_name_from_type("ggv$map_cell_info", type));
  758. lb_make_global_private_const(addr);
  759. map_set(&m->map_cell_info_map, type, addr);
  760. return addr.addr;
  761. }
  762. gb_internal lbValue lb_gen_map_info_ptr(lbModule *m, Type *map_type) {
  763. map_type = base_type(map_type);
  764. GB_ASSERT(map_type->kind == Type_Map);
  765. lbAddr *found = map_get(&m->map_info_map, map_type);
  766. if (found) {
  767. return found->addr;
  768. }
  769. GB_ASSERT(t_map_info != nullptr);
  770. GB_ASSERT(t_map_cell_info != nullptr);
  771. LLVMValueRef key_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.key).value;
  772. LLVMValueRef value_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.value).value;
  773. LLVMValueRef const_values[4] = {};
  774. const_values[0] = key_cell_info;
  775. const_values[1] = value_cell_info;
  776. const_values[2] = lb_hasher_proc_for_type(m, map_type->Map.key).value;
  777. const_values[3] = lb_equal_proc_for_type(m, map_type->Map.key).value;
  778. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_info, const_values, gb_count_of(const_values));
  779. lbValue res = {llvm_res, t_map_info};
  780. lbAddr addr = lb_add_global_generated_with_name(m, t_map_info, res, lb_internal_gen_name_from_type("ggv$map_info", map_type));
  781. lb_make_global_private_const(addr);
  782. map_set(&m->map_info_map, map_type, addr);
  783. return addr.addr;
  784. }
  785. gb_internal lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  786. if (true) {
  787. return {};
  788. }
  789. lbValue hashed_key = {};
  790. #if 0
  791. if (lb_is_const(key)) {
  792. u64 hash = 0xcbf29ce484222325;
  793. if (is_type_cstring(key_type)) {
  794. size_t length = 0;
  795. char const *text = LLVMGetAsString(key.value, &length);
  796. hash = fnv64a(text, cast(isize)length);
  797. } else if (is_type_string(key_type)) {
  798. unsigned data_indices[] = {0};
  799. unsigned len_indices[] = {1};
  800. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  801. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  802. i64 length = LLVMConstIntGetSExtValue(len);
  803. char const *text = nullptr;
  804. if (false && length != 0) {
  805. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  806. return {};
  807. }
  808. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  809. size_t ulength = 0;
  810. text = LLVMGetAsString(data, &ulength);
  811. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  812. length = gb_min(length, cast(i64)ulength);
  813. }
  814. hash = fnv64a(text, cast(isize)length);
  815. } else {
  816. return {};
  817. }
  818. // TODO(bill): other const hash types
  819. if (build_context.word_size == 4) {
  820. hash &= 0xffffffffull;
  821. }
  822. hashed_key = lb_const_int(m, t_uintptr, hash);
  823. }
  824. #endif
  825. return hashed_key;
  826. }
  827. gb_internal lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue const &map_ptr, lbValue key, lbValue *key_ptr_) {
  828. TEMPORARY_ALLOCATOR_GUARD();
  829. Type* key_type = base_type(type_deref(map_ptr.type))->Map.key;
  830. lbValue real_key = lb_emit_conv(p, key, key_type);
  831. lbValue key_ptr = lb_address_from_load_or_generate_local(p, real_key);
  832. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  833. if (key_ptr_) *key_ptr_ = key_ptr;
  834. lbValue hashed_key = lb_const_hash(p->module, real_key, key_type);
  835. if (hashed_key.value == nullptr) {
  836. lbValue hasher = lb_hasher_proc_for_type(p->module, key_type);
  837. lbValue seed = {};
  838. {
  839. auto args = array_make<lbValue>(temporary_allocator(), 1);
  840. args[0] = lb_map_data_uintptr(p, lb_emit_load(p, map_ptr));
  841. seed = lb_emit_runtime_call(p, "map_seed_from_map_data", args);
  842. }
  843. auto args = array_make<lbValue>(temporary_allocator(), 2);
  844. args[0] = key_ptr;
  845. args[1] = seed;
  846. hashed_key = lb_emit_call(p, hasher, args);
  847. }
  848. return hashed_key;
  849. }
  850. gb_internal lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  851. TEMPORARY_ALLOCATOR_GUARD();
  852. Type *map_type = base_type(type_deref(map_ptr.type));
  853. GB_ASSERT(map_type->kind == Type_Map);
  854. lbValue ptr = {};
  855. lbValue key_ptr = {};
  856. lbValue hash = lb_gen_map_key_hash(p, map_ptr, key, &key_ptr);
  857. if (build_context.dynamic_map_calls) {
  858. auto args = array_make<lbValue>(temporary_allocator(), 4);
  859. args[0] = lb_emit_transmute(p, map_ptr, t_raw_map_ptr);
  860. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  861. args[2] = hash;
  862. args[3] = key_ptr;
  863. ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  864. } else {
  865. lbValue map_get_proc = lb_map_get_proc_for_type(p->module, map_type);
  866. auto args = array_make<lbValue>(temporary_allocator(), 3);
  867. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  868. args[1] = hash;
  869. args[2] = key_ptr;
  870. ptr = lb_emit_call(p, map_get_proc, args);
  871. }
  872. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  873. }
  874. gb_internal void lb_internal_dynamic_map_set(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  875. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  876. TEMPORARY_ALLOCATOR_GUARD();
  877. map_type = base_type(map_type);
  878. GB_ASSERT(map_type->kind == Type_Map);
  879. lbValue key_ptr = {};
  880. lbValue hash = lb_gen_map_key_hash(p, map_ptr, map_key, &key_ptr);
  881. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  882. lbValue value_ptr = lb_address_from_load_or_generate_local(p, v);
  883. if (build_context.dynamic_map_calls) {
  884. auto args = array_make<lbValue>(temporary_allocator(), 6);
  885. args[0] = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  886. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  887. args[2] = hash;
  888. args[3] = lb_emit_conv(p, key_ptr, t_rawptr);
  889. args[4] = lb_emit_conv(p, value_ptr, t_rawptr);
  890. args[5] = lb_emit_source_code_location_as_global(p, node);
  891. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  892. } else {
  893. lbValue map_set_proc = lb_map_set_proc_for_type(p->module, map_type);
  894. auto args = array_make<lbValue>(temporary_allocator(), 5);
  895. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  896. args[1] = hash;
  897. args[2] = lb_emit_conv(p, key_ptr, t_rawptr);
  898. args[3] = lb_emit_conv(p, value_ptr, t_rawptr);
  899. args[4] = lb_emit_source_code_location_as_global(p, node);
  900. lb_emit_call(p, map_set_proc, args);
  901. }
  902. }
  903. gb_internal lbValue lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  904. TEMPORARY_ALLOCATOR_GUARD();
  905. String proc_name = {};
  906. if (p->entity) {
  907. proc_name = p->entity->token.string;
  908. }
  909. auto args = array_make<lbValue>(temporary_allocator(), 4);
  910. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  911. args[1] = lb_gen_map_info_ptr(p->module, type_deref(map_ptr.type));
  912. args[2] = lb_const_int(p->module, t_uint, capacity);
  913. args[3] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  914. return lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  915. }
  916. gb_internal lbProcedure *lb_create_objc_names(lbModule *main_module) {
  917. if (build_context.metrics.os != TargetOs_darwin) {
  918. return nullptr;
  919. }
  920. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  921. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  922. lb_add_attribute_to_proc(p->module, p->value, "nounwind");
  923. p->is_startup = true;
  924. return p;
  925. }
  926. String lb_get_objc_type_encoding(Type *t, isize pointer_depth = 0) {
  927. // NOTE(harold): See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100
  928. // NOTE(harold): Darwin targets are always 64-bit. Should we drop this and assume "q" always?
  929. #define INT_SIZE_ENCODING (build_context.metrics.int_size == 4 ? "i" : "q")
  930. switch (t->kind) {
  931. case Type_Basic: {
  932. switch (t->Basic.kind) {
  933. case Basic_Invalid:
  934. return str_lit("?");
  935. case Basic_llvm_bool:
  936. case Basic_bool:
  937. case Basic_b8:
  938. return str_lit("B");
  939. case Basic_b16:
  940. return str_lit("C");
  941. case Basic_b32:
  942. return str_lit("I");
  943. case Basic_b64:
  944. return str_lit("q");
  945. case Basic_i8:
  946. return str_lit("c");
  947. case Basic_u8:
  948. return str_lit("C");
  949. case Basic_i16:
  950. case Basic_i16le:
  951. case Basic_i16be:
  952. return str_lit("s");
  953. case Basic_u16:
  954. case Basic_u16le:
  955. case Basic_u16be:
  956. return str_lit("S");
  957. case Basic_i32:
  958. case Basic_i32le:
  959. case Basic_i32be:
  960. return str_lit("i");
  961. case Basic_u32le:
  962. case Basic_u32:
  963. case Basic_u32be:
  964. return str_lit("I");
  965. case Basic_i64:
  966. case Basic_i64le:
  967. case Basic_i64be:
  968. return str_lit("q");
  969. case Basic_u64:
  970. case Basic_u64le:
  971. case Basic_u64be:
  972. return str_lit("Q");
  973. case Basic_i128:
  974. case Basic_i128le:
  975. case Basic_i128be:
  976. return str_lit("t");
  977. case Basic_u128:
  978. case Basic_u128le:
  979. case Basic_u128be:
  980. return str_lit("T");
  981. case Basic_rune:
  982. return str_lit("I");
  983. case Basic_f16:
  984. case Basic_f16le:
  985. case Basic_f16be:
  986. return str_lit("s"); // @harold: Closest we've got?
  987. case Basic_f32:
  988. case Basic_f32le:
  989. case Basic_f32be:
  990. return str_lit("f");
  991. case Basic_f64:
  992. case Basic_f64le:
  993. case Basic_f64be:
  994. return str_lit("d");
  995. case Basic_complex32: return str_lit("{complex32=ss}"); // No f16 encoding, so fallback to i16, as above in Basic_f16*
  996. case Basic_complex64: return str_lit("{complex64=ff}");
  997. case Basic_complex128: return str_lit("{complex128=dd}");
  998. case Basic_quaternion64: return str_lit("{quaternion64=ssss}");
  999. case Basic_quaternion128: return str_lit("{quaternion128=ffff}");
  1000. case Basic_quaternion256: return str_lit("{quaternion256=dddd}");
  1001. case Basic_int:
  1002. return str_lit(INT_SIZE_ENCODING);
  1003. case Basic_uint:
  1004. return build_context.metrics.int_size == 4 ? str_lit("I") : str_lit("Q");
  1005. case Basic_uintptr:
  1006. case Basic_rawptr:
  1007. return str_lit("^v");
  1008. case Basic_string:
  1009. return build_context.metrics.int_size == 4 ? str_lit("{string=*i}") : str_lit("{string=*q}");
  1010. case Basic_string16:
  1011. return build_context.metrics.int_size == 4 ? str_lit("{string16=*i}") : str_lit("{string16=*q}");
  1012. case Basic_cstring: return str_lit("*");
  1013. case Basic_cstring16: return str_lit("*");
  1014. case Basic_any: return str_lit("{any=^v^v}"); // rawptr + ^Type_Info
  1015. case Basic_typeid:
  1016. GB_ASSERT(t->Basic.size == 8);
  1017. return str_lit("q");
  1018. // Untyped types
  1019. case Basic_UntypedBool:
  1020. case Basic_UntypedInteger:
  1021. case Basic_UntypedFloat:
  1022. case Basic_UntypedComplex:
  1023. case Basic_UntypedQuaternion:
  1024. case Basic_UntypedString:
  1025. case Basic_UntypedRune:
  1026. case Basic_UntypedNil:
  1027. case Basic_UntypedUninit:
  1028. GB_PANIC("Untyped types cannot be @encoded()");
  1029. return str_lit("?");
  1030. }
  1031. break;
  1032. }
  1033. case Type_Named:
  1034. case Type_Struct:
  1035. case Type_Union: {
  1036. Type* base = t;
  1037. if (base->kind == Type_Named) {
  1038. base = base_type(base);
  1039. if(base->kind != Type_Struct && base->kind != Type_Union) {
  1040. return lb_get_objc_type_encoding(base, pointer_depth);
  1041. }
  1042. }
  1043. const bool is_union = base->kind == Type_Union;
  1044. if (!is_union) {
  1045. // Treat struct as an Objective-C Class?
  1046. if (has_type_got_objc_class_attribute(t) && pointer_depth == 0) {
  1047. return str_lit("#");
  1048. }
  1049. }
  1050. if (is_type_objc_object(base)) {
  1051. return str_lit("@");
  1052. }
  1053. gbString s = gb_string_make_reserve(temporary_allocator(), 16);
  1054. s = gb_string_append_length(s, is_union ? "(" :"{", 1);
  1055. if (t->kind == Type_Named) {
  1056. s = gb_string_append_length(s, t->Named.name.text, t->Named.name.len);
  1057. }
  1058. // Write fields
  1059. if (pointer_depth < 2) {
  1060. s = gb_string_append_length(s, "=", 1);
  1061. if (!is_union) {
  1062. for( auto& f : base->Struct.fields ) {
  1063. String field_type = lb_get_objc_type_encoding(f->type, pointer_depth);
  1064. s = gb_string_append_length(s, field_type.text, field_type.len);
  1065. }
  1066. } else {
  1067. for( auto& v : base->Union.variants ) {
  1068. String variant_type = lb_get_objc_type_encoding(v, pointer_depth);
  1069. s = gb_string_append_length(s, variant_type.text, variant_type.len);
  1070. }
  1071. }
  1072. }
  1073. s = gb_string_append_length(s, is_union ? ")" :"}", 1);
  1074. return make_string_c(s);
  1075. }
  1076. case Type_Generic:
  1077. GB_PANIC("Generic types cannot be @encoded()");
  1078. return str_lit("?");
  1079. case Type_Pointer: {
  1080. // NOTE: These types are pointers, so we must check here for special cases
  1081. // Check for objc_SEL
  1082. if (internal_check_is_assignable_to(t, t_objc_SEL)) {
  1083. return str_lit(":");
  1084. }
  1085. // Check for objc_Class
  1086. if (internal_check_is_assignable_to(t, t_objc_Class)) {
  1087. return str_lit("#");
  1088. }
  1089. String pointee = lb_get_objc_type_encoding(t->Pointer.elem, pointer_depth +1);
  1090. // Special case for Objective-C Objects
  1091. if (pointer_depth == 0 && pointee == "@") {
  1092. return pointee;
  1093. }
  1094. return concatenate_strings(temporary_allocator(), str_lit("^"), pointee);
  1095. }
  1096. case Type_MultiPointer:
  1097. return concatenate_strings(temporary_allocator(), str_lit("^"), lb_get_objc_type_encoding(t->Pointer.elem, pointer_depth +1));
  1098. case Type_Array: {
  1099. String type_str = lb_get_objc_type_encoding(t->Array.elem, pointer_depth);
  1100. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1101. s = gb_string_append_fmt(s, "[%lld%.*s]", t->Array.count, LIT(type_str));
  1102. return make_string_c(s);
  1103. }
  1104. case Type_EnumeratedArray: {
  1105. String type_str = lb_get_objc_type_encoding(t->EnumeratedArray.elem, pointer_depth);
  1106. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1107. s = gb_string_append_fmt(s, "[%lld%.*s]", t->EnumeratedArray.count, LIT(type_str));
  1108. return make_string_c(s);
  1109. }
  1110. case Type_Slice: {
  1111. String type_str = lb_get_objc_type_encoding(t->Slice.elem, pointer_depth);
  1112. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1113. s = gb_string_append_fmt(s, "{slice=^%.*s%s}", LIT(type_str), INT_SIZE_ENCODING);
  1114. return make_string_c(s);
  1115. }
  1116. case Type_DynamicArray: {
  1117. String type_str = lb_get_objc_type_encoding(t->DynamicArray.elem, pointer_depth);
  1118. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1119. s = gb_string_append_fmt(s, "{dynamic=^%.*s%s%sAllocator={?^v}}", LIT(type_str), INT_SIZE_ENCODING, INT_SIZE_ENCODING);
  1120. return make_string_c(s);
  1121. }
  1122. case Type_Map:
  1123. return str_lit("{^v^v{Allocator=?^v}}");
  1124. case Type_Enum:
  1125. return lb_get_objc_type_encoding(t->Enum.base_type, pointer_depth);
  1126. case Type_Tuple:
  1127. // NOTE(harold): Is this type allowed here?
  1128. return str_lit("?");
  1129. case Type_Proc:
  1130. return str_lit("?");
  1131. case Type_BitSet:
  1132. return lb_get_objc_type_encoding(t->BitSet.underlying, pointer_depth);
  1133. case Type_SimdVector: {
  1134. String type_str = lb_get_objc_type_encoding(t->SimdVector.elem, pointer_depth);
  1135. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 5);
  1136. gb_string_append_fmt(s, "[%lld%.*s]", t->SimdVector.count, LIT(type_str));
  1137. return make_string_c(s);
  1138. }
  1139. case Type_Matrix: {
  1140. String type_str = lb_get_objc_type_encoding(t->Matrix.elem, pointer_depth);
  1141. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 5);
  1142. i64 element_count = t->Matrix.column_count * t->Matrix.row_count;
  1143. gb_string_append_fmt(s, "[%lld%.*s]", element_count, LIT(type_str));
  1144. return make_string_c(s);
  1145. }
  1146. case Type_BitField:
  1147. return lb_get_objc_type_encoding(t->BitField.backing_type, pointer_depth);
  1148. case Type_SoaPointer: {
  1149. gbString s = gb_string_make_reserve(temporary_allocator(), 8);
  1150. s = gb_string_append_fmt(s, "{=^v%s}", INT_SIZE_ENCODING);
  1151. return make_string_c(s);
  1152. }
  1153. } // End switch t->kind
  1154. #undef INT_SIZE_ENCODING
  1155. GB_PANIC("Unreachable");
  1156. return str_lit("");
  1157. }
  1158. struct lbObjCGlobalClass {
  1159. lbObjCGlobal g;
  1160. lbValue class_value; // Local registered class value
  1161. };
  1162. gb_internal void lb_register_objc_thing(
  1163. StringSet &handled,
  1164. lbModule *m,
  1165. Array<lbValue> &args,
  1166. Array<lbObjCGlobalClass> &class_impls,
  1167. StringMap<lbObjCGlobalClass> &class_map,
  1168. lbProcedure *p,
  1169. lbObjCGlobal const &g,
  1170. char const *call
  1171. ) {
  1172. if (string_set_update(&handled, g.name)) {
  1173. return;
  1174. }
  1175. lbAddr addr = {};
  1176. lbValue *found = string_map_get(&m->members, g.global_name);
  1177. if (found) {
  1178. addr = lb_addr(*found);
  1179. } else {
  1180. lbValue v = {};
  1181. LLVMTypeRef t = lb_type(m, g.type);
  1182. v.value = LLVMAddGlobal(m->mod, t, g.global_name);
  1183. v.type = alloc_type_pointer(g.type);
  1184. addr = lb_addr(v);
  1185. LLVMSetInitializer(v.value, LLVMConstNull(t));
  1186. }
  1187. lbValue class_ptr = {};
  1188. lbValue class_name = lb_const_value(m, t_cstring, exact_value_string(g.name));
  1189. // If this class requires an implementation, save it for registration below.
  1190. if (g.class_impl_type != nullptr) {
  1191. // Make sure the superclass has been initialized before us
  1192. lbValue superclass_value = lb_const_nil(m, t_objc_Class);
  1193. auto &tn = g.class_impl_type->Named.type_name->TypeName;
  1194. Type *superclass = tn.objc_superclass;
  1195. if (superclass != nullptr) {
  1196. auto& superclass_global = string_map_must_get(&class_map, superclass->Named.type_name->TypeName.objc_class_name);
  1197. lb_register_objc_thing(handled, m, args, class_impls, class_map, p, superclass_global.g, call);
  1198. GB_ASSERT(superclass_global.class_value.value);
  1199. superclass_value = superclass_global.class_value;
  1200. }
  1201. args.count = 3;
  1202. args[0] = superclass_value;
  1203. args[1] = class_name;
  1204. args[2] = lb_const_int(m, t_uint, 0);
  1205. class_ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  1206. array_add(&class_impls, lbObjCGlobalClass{g, class_ptr});
  1207. }
  1208. else {
  1209. args.count = 1;
  1210. args[0] = class_name;
  1211. class_ptr = lb_emit_runtime_call(p, call, args);
  1212. }
  1213. lb_addr_store(p, addr, class_ptr);
  1214. lbObjCGlobalClass* class_global = string_map_get(&class_map, g.name);
  1215. if (class_global != nullptr) {
  1216. class_global->class_value = class_ptr;
  1217. }
  1218. }
  1219. gb_internal void lb_finalize_objc_names(lbGenerator *gen, lbProcedure *p) {
  1220. if (p == nullptr) {
  1221. return;
  1222. }
  1223. lbModule *m = p->module;
  1224. GB_ASSERT(m == &p->module->gen->default_module);
  1225. TEMPORARY_ALLOCATOR_GUARD();
  1226. StringSet handled = {};
  1227. string_set_init(&handled);
  1228. defer (string_set_destroy(&handled));
  1229. auto args = array_make<lbValue>(temporary_allocator(), 3, 8);
  1230. auto class_impls = array_make<lbObjCGlobalClass>(temporary_allocator(), 0, 16);
  1231. // Register all class implementations unconditionally, even if not statically referenced
  1232. for (Entity *e = {}; mpsc_dequeue(&gen->info->objc_class_implementations, &e); /**/) {
  1233. GB_ASSERT(e->kind == Entity_TypeName && e->TypeName.objc_is_implementation);
  1234. lb_handle_objc_find_or_register_class(p, e->TypeName.objc_class_name, e->type);
  1235. }
  1236. // Ensure classes that have been implicitly referenced through
  1237. // the objc_superclass attribute have a global variable available for them.
  1238. TypeSet class_set{};
  1239. type_set_init(&class_set, gen->objc_classes.count+16);
  1240. defer (type_set_destroy(&class_set));
  1241. auto referenced_classes = array_make<lbObjCGlobal>(temporary_allocator());
  1242. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_classes, &g); /**/) {
  1243. array_add(&referenced_classes, g);
  1244. Type *cls = g.class_impl_type;
  1245. while (cls) {
  1246. if (type_set_update(&class_set, cls)) {
  1247. break;
  1248. }
  1249. GB_ASSERT(cls->kind == Type_Named);
  1250. cls = cls->Named.type_name->TypeName.objc_superclass;
  1251. }
  1252. }
  1253. for (auto pair : class_set) {
  1254. auto& tn = pair.type->Named.type_name->TypeName;
  1255. Type *class_impl = !tn.objc_is_implementation ? nullptr : pair.type;
  1256. lb_handle_objc_find_or_register_class(p, tn.objc_class_name, class_impl);
  1257. }
  1258. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_classes, &g); /**/) {
  1259. array_add( &referenced_classes, g );
  1260. }
  1261. // Add all class globals to a map so that we can look them up dynamically
  1262. // in order to resolve out-of-order because classes that are being implemented
  1263. // require their superclasses to be registered before them.
  1264. StringMap<lbObjCGlobalClass> global_class_map{};
  1265. string_map_init(&global_class_map, (usize)gen->objc_classes.count);
  1266. defer (string_map_destroy(&global_class_map));
  1267. for (lbObjCGlobal g :referenced_classes) {
  1268. string_map_set(&global_class_map, g.name, lbObjCGlobalClass{g});
  1269. }
  1270. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  1271. lb_begin_procedure_body(p);
  1272. // Register class globals, gathering classes that must be implemented
  1273. for (auto& kv : global_class_map) {
  1274. lb_register_objc_thing(handled, m, args, class_impls, global_class_map, p, kv.value.g, "objc_lookUpClass");
  1275. }
  1276. // Prefetch selectors for implemented methods so that they can also be registered.
  1277. for (const auto& cd : class_impls) {
  1278. auto& g = cd.g;
  1279. Type *class_type = g.class_impl_type;
  1280. Array<ObjcMethodData>* methods = map_get(&m->info->objc_method_implementations, class_type);
  1281. if (!methods) {
  1282. continue;
  1283. }
  1284. for (const ObjcMethodData& md : *methods) {
  1285. lb_handle_objc_find_or_register_selector(p, md.ac.objc_selector);
  1286. }
  1287. }
  1288. // Now we can register all referenced selectors
  1289. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_selectors, &g); /**/) {
  1290. lb_register_objc_thing(handled, m, args, class_impls, global_class_map, p, g, "sel_registerName");
  1291. }
  1292. // Emit method wrapper implementations and registration
  1293. auto wrapper_args = array_make<Type *>(temporary_allocator(), 2, 8);
  1294. auto get_context_args = array_make<lbValue>(temporary_allocator(), 1);
  1295. PtrMap<Type *, lbObjCGlobal> ivar_map{};
  1296. map_init(&ivar_map, gen->objc_ivars.count);
  1297. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_ivars, &g); /**/) {
  1298. map_set(&ivar_map, g.class_impl_type, g);
  1299. }
  1300. for (const auto &cd : class_impls) {
  1301. auto &g = cd.g;
  1302. Type *class_type = g.class_impl_type;
  1303. Type *class_ptr_type = alloc_type_pointer(class_type);
  1304. lbValue class_value = cd.class_value;
  1305. Type *ivar_type = class_type->Named.type_name->TypeName.objc_ivar;
  1306. Entity *context_provider = class_type->Named.type_name->TypeName.objc_context_provider;
  1307. Type *contex_provider_self_ptr_type = nullptr;
  1308. Type *contex_provider_self_named_type = nullptr;
  1309. bool is_context_provider_ivar = false;
  1310. lbValue context_provider_proc_value{};
  1311. if (context_provider) {
  1312. context_provider_proc_value = lb_find_procedure_value_from_entity(m, context_provider);
  1313. contex_provider_self_ptr_type = base_type(context_provider->type->Proc.params->Tuple.variables[0]->type);
  1314. GB_ASSERT(contex_provider_self_ptr_type->kind == Type_Pointer);
  1315. contex_provider_self_named_type = base_named_type(type_deref(contex_provider_self_ptr_type));
  1316. is_context_provider_ivar = ivar_type != nullptr && internal_check_is_assignable_to(contex_provider_self_named_type, ivar_type);
  1317. }
  1318. Array<ObjcMethodData> *methods = map_get(&m->info->objc_method_implementations, class_type);
  1319. if (!methods) {
  1320. continue;
  1321. }
  1322. // Check if it has any class methods ahead of time so that we know to grab the meta_class
  1323. lbValue meta_class_value = {};
  1324. for (const ObjcMethodData &md : *methods) {
  1325. if (!md.ac.objc_is_class_method) {
  1326. continue;
  1327. }
  1328. // Get the meta_class
  1329. args.count = 1;
  1330. args[0] = class_value;
  1331. meta_class_value = lb_emit_runtime_call(p, "object_getClass", args);
  1332. break;
  1333. }
  1334. for (const ObjcMethodData &md : *methods) {
  1335. GB_ASSERT( md.proc_entity->kind == Entity_Procedure);
  1336. Type *method_type = md.proc_entity->type;
  1337. String proc_name = make_string_c("__$objc_method::");
  1338. proc_name = concatenate_strings(temporary_allocator(), proc_name, g.name);
  1339. proc_name = concatenate_strings(temporary_allocator(), proc_name, str_lit("::"));
  1340. proc_name = concatenate_strings( permanent_allocator(), proc_name, md.ac.objc_name);
  1341. wrapper_args.count = 2;
  1342. wrapper_args[0] = md.ac.objc_is_class_method ? t_objc_Class : class_ptr_type;
  1343. wrapper_args[1] = t_objc_SEL;
  1344. isize method_param_count = method_type->Proc.param_count;
  1345. isize method_param_offset = 0;
  1346. if (!md.ac.objc_is_class_method) {
  1347. GB_ASSERT(method_param_count >= 1);
  1348. method_param_count -= 1;
  1349. method_param_offset = 1;
  1350. }
  1351. for (isize i = 0; i < method_param_count; i++) {
  1352. array_add(&wrapper_args, method_type->Proc.params->Tuple.variables[method_param_offset+i]->type);
  1353. }
  1354. Type *wrapper_args_tuple = alloc_type_tuple_from_field_types(wrapper_args.data, wrapper_args.count, false, true);
  1355. Type *wrapper_results_tuple = nullptr;
  1356. if (method_type->Proc.result_count > 0) {
  1357. GB_ASSERT(method_type->Proc.result_count == 1);
  1358. wrapper_results_tuple = alloc_type_tuple_from_field_types(&method_type->Proc.results->Tuple.variables[0]->type, 1, false, true);
  1359. }
  1360. Type *wrapper_proc_type = alloc_type_proc(nullptr, wrapper_args_tuple, wrapper_args_tuple->Tuple.variables.count,
  1361. wrapper_results_tuple, method_type->Proc.result_count, false, ProcCC_CDecl);
  1362. lbProcedure *wrapper_proc = lb_create_dummy_procedure(m, proc_name, wrapper_proc_type);
  1363. lb_add_attribute_to_proc(wrapper_proc->module, wrapper_proc->value, "nounwind");
  1364. // Emit the wrapper
  1365. LLVMSetLinkage(wrapper_proc->value, LLVMExternalLinkage);
  1366. lb_begin_procedure_body(wrapper_proc);
  1367. {
  1368. if (method_type->Proc.calling_convention == ProcCC_Odin) {
  1369. GB_ASSERT(context_provider);
  1370. // Emit the get odin context call
  1371. get_context_args[0] = lbValue {
  1372. wrapper_proc->raw_input_parameters[0],
  1373. contex_provider_self_ptr_type,
  1374. };
  1375. if (is_context_provider_ivar) {
  1376. // The context provider takes the ivar's type.
  1377. // Emit an objc_ivar_get call and use that pointer for 'self' instead.
  1378. lbValue real_self {
  1379. wrapper_proc->raw_input_parameters[0],
  1380. class_ptr_type
  1381. };
  1382. get_context_args[0] = lb_handle_objc_ivar_for_objc_object_pointer(wrapper_proc, real_self);
  1383. }
  1384. lbValue context = lb_emit_call(wrapper_proc, context_provider_proc_value, get_context_args);
  1385. lbAddr context_addr = lb_addr(lb_address_from_load_or_generate_local(wrapper_proc, context));
  1386. lb_push_context_onto_stack(wrapper_proc, context_addr);
  1387. }
  1388. auto method_call_args = array_make<lbValue>(temporary_allocator(), method_param_count + method_param_offset);
  1389. if (!md.ac.objc_is_class_method) {
  1390. method_call_args[0] = lbValue {
  1391. wrapper_proc->raw_input_parameters[0],
  1392. class_ptr_type,
  1393. };
  1394. }
  1395. for (isize i = 0; i < method_param_count; i++) {
  1396. method_call_args[i+method_param_offset] = lbValue {
  1397. wrapper_proc->raw_input_parameters[i+2],
  1398. method_type->Proc.params->Tuple.variables[i+method_param_offset]->type,
  1399. };
  1400. }
  1401. lbValue method_proc_value = lb_find_procedure_value_from_entity(m, md.proc_entity);
  1402. // Call real procedure for method from here, passing the parameters expected, if any.
  1403. lbValue return_value = lb_emit_call(wrapper_proc, method_proc_value, method_call_args);
  1404. if (wrapper_results_tuple != nullptr) {
  1405. auto &result_var = method_type->Proc.results->Tuple.variables[0];
  1406. return_value = lb_emit_conv(wrapper_proc, return_value, result_var->type);
  1407. lb_build_return_stmt_internal(wrapper_proc, return_value, result_var->token.pos);
  1408. }
  1409. }
  1410. lb_end_procedure_body(wrapper_proc);
  1411. // Add the method to the class
  1412. String method_encoding = str_lit("v");
  1413. // TODO (harold): Checker must ensure that objc_methods have a single return value or none!
  1414. GB_ASSERT(method_type->Proc.result_count <= 1);
  1415. if (method_type->Proc.result_count != 0) {
  1416. method_encoding = lb_get_objc_type_encoding(method_type->Proc.results->Tuple.variables[0]->type);
  1417. }
  1418. if (!md.ac.objc_is_class_method) {
  1419. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, str_lit("@:"));
  1420. } else {
  1421. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, str_lit("#:"));
  1422. }
  1423. for (isize i = method_param_offset; i < method_param_count; i++) {
  1424. Type *param_type = method_type->Proc.params->Tuple.variables[i]->type;
  1425. String param_encoding = lb_get_objc_type_encoding(param_type);
  1426. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, param_encoding);
  1427. }
  1428. // Emit method registration
  1429. lbAddr* sel_address = string_map_get(&m->objc_selectors, md.ac.objc_selector);
  1430. GB_ASSERT(sel_address);
  1431. lbValue selector_value = lb_addr_load(p, *sel_address);
  1432. lbValue target_class = !md.ac.objc_is_class_method ? class_value : meta_class_value;
  1433. args.count = 4;
  1434. args[0] = target_class; // Class
  1435. args[1] = selector_value; // SEL
  1436. args[2] = lbValue { wrapper_proc->value, wrapper_proc->type };
  1437. args[3] = lb_const_value(m, t_cstring, exact_value_string(method_encoding));
  1438. // TODO(harold): Emit check BOOL result and panic if false.
  1439. lb_emit_runtime_call(p, "class_addMethod", args);
  1440. } // End methods
  1441. // Add ivar if we have one
  1442. if (ivar_type != nullptr) {
  1443. // Register a single ivar for this class
  1444. Type *ivar_base = ivar_type->Named.base;
  1445. // @note(harold): The alignment is supposed to be passed as log2(alignment): https://developer.apple.com/documentation/objectivec/class_addivar(_:_:_:_:_:)?language=objc
  1446. const i64 size = type_size_of(ivar_base);
  1447. const i64 alignment = (i64)floor_log2((u64)type_align_of(ivar_base));
  1448. // NOTE(harold): I've opted to not emit the type encoding for ivars in order to keep the data private.
  1449. // If there is desire in the future to emit the type encoding for introspection through the Obj-C runtime,
  1450. // then perhaps an option can be added for it then.
  1451. // Should we pass the actual type encoding? Might not be ideal for obfuscation.
  1452. String ivar_name = str_lit("__$ivar");
  1453. String ivar_types = str_lit("{= }"); //lb_get_objc_type_encoding(ivar_type);
  1454. args.count = 5;
  1455. args[0] = class_value;
  1456. args[1] = lb_const_value(m, t_cstring, exact_value_string(ivar_name));
  1457. args[2] = lb_const_value(m, t_uint, exact_value_u64((u64)size));
  1458. args[3] = lb_const_value(m, t_u8, exact_value_u64((u64)alignment));
  1459. args[4] = lb_const_value(m, t_cstring, exact_value_string(ivar_types));
  1460. lb_emit_runtime_call(p, "class_addIvar", args);
  1461. }
  1462. // Complete the class registration
  1463. args.count = 1;
  1464. args[0] = class_value;
  1465. lb_emit_runtime_call(p, "objc_registerClassPair", args);
  1466. }
  1467. // Register ivar offsets for any `objc_ivar_get` expressions emitted.
  1468. for (auto const& kv : ivar_map) {
  1469. lbObjCGlobal const& g = kv.value;
  1470. lbAddr ivar_addr = {};
  1471. lbValue *found = string_map_get(&m->members, g.global_name);
  1472. if (found) {
  1473. ivar_addr = lb_addr(*found);
  1474. GB_ASSERT(ivar_addr.addr.type == t_int_ptr);
  1475. } else {
  1476. // Defined in an external package, define it now in the main package
  1477. LLVMTypeRef t = lb_type(m, t_int);
  1478. lbValue global{};
  1479. global.value = LLVMAddGlobal(m->mod, t, g.global_name);
  1480. global.type = t_int_ptr;
  1481. LLVMSetInitializer(global.value, LLVMConstInt(t, 0, true));
  1482. ivar_addr = lb_addr(global);
  1483. }
  1484. String class_name = g.class_impl_type->Named.type_name->TypeName.objc_class_name;
  1485. lbValue class_value = string_map_must_get(&global_class_map, class_name).class_value;
  1486. args.count = 2;
  1487. args[0] = class_value;
  1488. args[1] = lb_const_value(m, t_cstring, exact_value_string(str_lit("__$ivar")));
  1489. lbValue ivar = lb_emit_runtime_call(p, "class_getInstanceVariable", args);
  1490. args.count = 1;
  1491. args[0] = ivar;
  1492. lbValue ivar_offset = lb_emit_runtime_call(p, "ivar_getOffset", args);
  1493. lbValue ivar_offset_int = lb_emit_conv(p, ivar_offset, t_int);
  1494. lb_addr_store(p, ivar_addr, ivar_offset_int);
  1495. }
  1496. lb_end_procedure_body(p);
  1497. }
  1498. gb_internal void lb_verify_function(lbModule *m, lbProcedure *p, bool dump_ll=false) {
  1499. if (LLVM_IGNORE_VERIFICATION) {
  1500. return;
  1501. }
  1502. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1503. char *llvm_error = nullptr;
  1504. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  1505. LLVMDumpValue(p->value);
  1506. gb_printf_err("\n");
  1507. if (dump_ll) {
  1508. gb_printf_err("\n\n\n");
  1509. String filepath_ll = lb_filepath_ll_for_module(m);
  1510. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1511. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1512. }
  1513. }
  1514. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  1515. exit_with_errors();
  1516. }
  1517. }
  1518. gb_internal WORKER_TASK_PROC(lb_llvm_module_verification_worker_proc) {
  1519. char *llvm_error = nullptr;
  1520. defer (LLVMDisposeMessage(llvm_error));
  1521. lbModule *m = cast(lbModule *)data;
  1522. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1523. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1524. if (build_context.keep_temp_files) {
  1525. TIME_SECTION("LLVM Print Module to File");
  1526. String filepath_ll = lb_filepath_ll_for_module(m);
  1527. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1528. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1529. exit_with_errors();
  1530. return false;
  1531. }
  1532. }
  1533. exit_with_errors();
  1534. return 1;
  1535. }
  1536. return 0;
  1537. }
  1538. gb_internal void lb_create_startup_runtime_generate_body(lbModule *m, lbProcedure *p) {
  1539. lb_begin_procedure_body(p);
  1540. lb_setup_type_info_data(m);
  1541. if (p->objc_names) {
  1542. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(m, p->objc_names->type), p->objc_names->value, nullptr, 0, "");
  1543. }
  1544. for (auto &var : *p->global_variables) {
  1545. if (var.is_initialized) {
  1546. continue;
  1547. }
  1548. lbModule *entity_module = m;
  1549. Entity *e = var.decl->entity;
  1550. GB_ASSERT(e->kind == Entity_Variable);
  1551. e->code_gen_module = entity_module;
  1552. Ast *init_expr = var.decl->init_expr;
  1553. if (init_expr != nullptr) {
  1554. lbValue init = lb_build_expr(p, init_expr);
  1555. if (init.value == nullptr) {
  1556. LLVMTypeRef global_type = llvm_addr_type(p->module, var.var);
  1557. if (is_type_untyped_nil(init.type)) {
  1558. LLVMSetInitializer(var.var.value, LLVMConstNull(global_type));
  1559. var.is_initialized = true;
  1560. if (e->Variable.is_rodata) {
  1561. LLVMSetGlobalConstant(var.var.value, true);
  1562. }
  1563. continue;
  1564. }
  1565. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  1566. }
  1567. if (is_type_any(e->type) || is_type_union(e->type)) {
  1568. var.init = init;
  1569. } else if (lb_is_const_or_global(init)) {
  1570. if (!var.is_initialized) {
  1571. if (is_type_proc(init.type)) {
  1572. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  1573. }
  1574. LLVMSetInitializer(var.var.value, init.value);
  1575. var.is_initialized = true;
  1576. if (e->Variable.is_rodata) {
  1577. LLVMSetGlobalConstant(var.var.value, true);
  1578. }
  1579. continue;
  1580. }
  1581. } else {
  1582. var.init = init;
  1583. }
  1584. }
  1585. if (var.init.value != nullptr) {
  1586. GB_ASSERT(!var.is_initialized);
  1587. Type *t = type_deref(var.var.type);
  1588. if (is_type_any(t)) {
  1589. // NOTE(bill): Edge case for 'any' type
  1590. Type *var_type = default_type(var.init.type);
  1591. gbString var_name = gb_string_make(permanent_allocator(), "__$global_any::");
  1592. gbString e_str = string_canonical_entity_name(temporary_allocator(), e);
  1593. var_name = gb_string_append_length(var_name, e_str, gb_strlen(e_str));
  1594. lbAddr g = lb_add_global_generated_with_name(m, var_type, {}, make_string_c(var_name));
  1595. lb_addr_store(p, g, var.init);
  1596. lbValue gp = lb_addr_get_ptr(p, g);
  1597. lbValue data = lb_emit_struct_ep(p, var.var, 0);
  1598. lbValue ti = lb_emit_struct_ep(p, var.var, 1);
  1599. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  1600. lb_emit_store(p, ti, lb_typeid(p->module, var_type));
  1601. } else {
  1602. LLVMTypeRef vt = llvm_addr_type(p->module, var.var);
  1603. lbValue src0 = lb_emit_conv(p, var.init, t);
  1604. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  1605. LLVMValueRef dst = var.var.value;
  1606. LLVMBuildStore(p->builder, src, dst);
  1607. }
  1608. var.is_initialized = true;
  1609. }
  1610. }
  1611. CheckerInfo *info = m->gen->info;
  1612. for (Entity *e : info->init_procedures) {
  1613. lbValue value = lb_find_procedure_value_from_entity(m, e);
  1614. lb_emit_call(p, value, {}, ProcInlining_none);
  1615. }
  1616. lb_end_procedure_body(p);
  1617. }
  1618. gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  1619. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  1620. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  1621. p->is_startup = true;
  1622. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1623. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1624. // Make sure shared libraries call their own runtime startup on Linux.
  1625. LLVMSetVisibility(p->value, LLVMHiddenVisibility);
  1626. LLVMSetLinkage(p->value, LLVMWeakAnyLinkage);
  1627. p->generate_body = lb_create_startup_runtime_generate_body;
  1628. p->global_variables = &global_variables;
  1629. p->objc_names = objc_names;
  1630. array_add(&main_module->procedures_to_generate, p);
  1631. return p;
  1632. }
  1633. gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // Cleanup Runtime
  1634. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  1635. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
  1636. p->is_startup = true;
  1637. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1638. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1639. // Make sure shared libraries call their own runtime cleanup on Linux.
  1640. LLVMSetVisibility(p->value, LLVMHiddenVisibility);
  1641. LLVMSetLinkage(p->value, LLVMWeakAnyLinkage);
  1642. lb_begin_procedure_body(p);
  1643. CheckerInfo *info = main_module->gen->info;
  1644. for (Entity *e : info->fini_procedures) {
  1645. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  1646. lb_emit_call(p, value, {}, ProcInlining_none);
  1647. }
  1648. lb_end_procedure_body(p);
  1649. lb_verify_function(main_module, p);
  1650. return p;
  1651. }
  1652. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p);
  1653. gb_internal WORKER_TASK_PROC(lb_generate_procedures_worker_proc) {
  1654. lbModule *m = cast(lbModule *)data;
  1655. for (isize i = 0; i < m->procedures_to_generate.count; i++) {
  1656. lbProcedure *p = m->procedures_to_generate[i];
  1657. lb_generate_procedure(p->module, p);
  1658. }
  1659. return 0;
  1660. }
  1661. struct lbGenerateProceduresWorkerData {
  1662. lbModule *m;
  1663. bool do_threading;
  1664. };
  1665. gb_internal WORKER_TASK_PROC(lb_generate_procedures_and_types_per_module) {
  1666. lbGenerateProceduresWorkerData *wd = cast(lbGenerateProceduresWorkerData *)data;
  1667. lbModule *m = wd->m;
  1668. for (Entity *e : m->global_types_to_create) {
  1669. (void)lb_get_entity_name(m, e);
  1670. (void)lb_type(m, e->type);
  1671. }
  1672. for (Entity *e : m->global_procedures_to_create) {
  1673. (void)lb_get_entity_name(m, e);
  1674. array_add(&m->procedures_to_generate, lb_create_procedure(m, e));
  1675. }
  1676. if (wd->do_threading) {
  1677. thread_pool_add_task(lb_generate_procedures_worker_proc, m);
  1678. }
  1679. return 0;
  1680. }
  1681. gb_internal GB_COMPARE_PROC(llvm_global_entity_cmp) {
  1682. Entity *x = *cast(Entity **)a;
  1683. Entity *y = *cast(Entity **)b;
  1684. if (x == y) {
  1685. return 0;
  1686. }
  1687. if (x->kind != y->kind) {
  1688. return cast(i32)(x->kind - y->kind);
  1689. }
  1690. i32 cmp = 0;
  1691. cmp = token_pos_cmp(x->token.pos, y->token.pos);
  1692. if (!cmp) {
  1693. return cmp;
  1694. }
  1695. return cmp;
  1696. }
  1697. gb_internal void lb_create_global_procedures_and_types(lbGenerator *gen, CheckerInfo *info, bool do_threading) {
  1698. for (Entity *e : info->entities) {
  1699. String name = e->token.string;
  1700. Scope * scope = e->scope;
  1701. if ((scope->flags & ScopeFlag_File) == 0) {
  1702. continue;
  1703. }
  1704. Scope *package_scope = scope->parent;
  1705. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1706. switch (e->kind) {
  1707. case Entity_Variable:
  1708. // NOTE(bill): Handled above as it requires a specific load order
  1709. continue;
  1710. case Entity_ProcGroup:
  1711. continue;
  1712. case Entity_TypeName:
  1713. case Entity_Procedure:
  1714. break;
  1715. case Entity_Constant:
  1716. if (build_context.ODIN_DEBUG) {
  1717. lb_add_debug_info_for_global_constant_from_entity(gen, e);
  1718. }
  1719. break;
  1720. }
  1721. bool polymorphic_struct = false;
  1722. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1723. Type *bt = base_type(e->type);
  1724. if (bt->kind == Type_Struct) {
  1725. polymorphic_struct = is_type_polymorphic(bt);
  1726. }
  1727. }
  1728. if (!polymorphic_struct && e->min_dep_count.load(std::memory_order_relaxed) == 0) {
  1729. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1730. continue;
  1731. }
  1732. // if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1733. // // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1734. // continue;
  1735. // }
  1736. lbModule *m = &gen->default_module;
  1737. if (USE_SEPARATE_MODULES) {
  1738. m = lb_module_of_entity(gen, e, m);
  1739. }
  1740. GB_ASSERT(m != nullptr);
  1741. if (e->kind == Entity_Procedure) {
  1742. array_add(&m->global_procedures_to_create, e);
  1743. } else if (e->kind == Entity_TypeName) {
  1744. array_add(&m->global_types_to_create, e);
  1745. }
  1746. }
  1747. for (auto const &entry : gen->modules) {
  1748. lbModule *m = entry.value;
  1749. array_sort(m->global_types_to_create, llvm_global_entity_cmp);
  1750. array_sort(m->global_procedures_to_create, llvm_global_entity_cmp);
  1751. }
  1752. if (do_threading) {
  1753. for (auto const &entry : gen->modules) {
  1754. auto wd = permanent_alloc_item<lbGenerateProceduresWorkerData>();
  1755. wd->m = entry.value;
  1756. wd->do_threading = true;
  1757. thread_pool_add_task(lb_generate_procedures_and_types_per_module, wd);
  1758. }
  1759. } else {
  1760. for (auto const &entry : gen->modules) {
  1761. auto wd = permanent_alloc_item<lbGenerateProceduresWorkerData>();
  1762. wd->m = entry.value;
  1763. wd->do_threading = false;
  1764. lb_generate_procedures_and_types_per_module(wd);
  1765. }
  1766. for (auto const &entry : gen->modules) {
  1767. lbModule *m = entry.value;
  1768. lb_generate_procedures_worker_proc(m);
  1769. }
  1770. }
  1771. thread_pool_wait();
  1772. }
  1773. gb_internal bool lb_is_module_empty(lbModule *m) {
  1774. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  1775. LLVMGetFirstGlobal(m->mod) == nullptr) {
  1776. return true;
  1777. }
  1778. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  1779. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  1780. return false;
  1781. }
  1782. }
  1783. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  1784. LLVMLinkage linkage = LLVMGetLinkage(g);
  1785. if (linkage == LLVMExternalLinkage ||
  1786. linkage == LLVMWeakAnyLinkage) {
  1787. continue;
  1788. }
  1789. if (!LLVMIsExternallyInitialized(g)) {
  1790. return false;
  1791. }
  1792. }
  1793. return true;
  1794. }
  1795. struct lbLLVMEmitWorker {
  1796. LLVMTargetMachineRef target_machine;
  1797. LLVMCodeGenFileType code_gen_file_type;
  1798. String filepath_obj;
  1799. lbModule *m;
  1800. };
  1801. gb_internal WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  1802. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  1803. char *llvm_error = nullptr;
  1804. auto wd = cast(lbLLVMEmitWorker *)data;
  1805. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  1806. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1807. exit_with_errors();
  1808. }
  1809. debugf("Generated File: %.*s\n", LIT(wd->filepath_obj));
  1810. return 0;
  1811. }
  1812. gb_internal void lb_llvm_function_pass_per_function_internal(lbModule *module, lbProcedure *p, lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default) {
  1813. LLVMPassManagerRef pass_manager = module->function_pass_managers[pass_manager_kind];
  1814. lb_run_function_pass_manager(pass_manager, p, pass_manager_kind);
  1815. }
  1816. gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
  1817. lbModule *m = cast(lbModule *)data;
  1818. {
  1819. GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
  1820. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1821. m->function_pass_managers[i] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1822. }
  1823. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1824. LLVMInitializeFunctionPassManager(m->function_pass_managers[i]);
  1825. }
  1826. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default], false, build_context.optimization_level);
  1827. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true, build_context.optimization_level);
  1828. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none], -1);
  1829. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1830. LLVMFinalizeFunctionPassManager(m->function_pass_managers[i]);
  1831. }
  1832. }
  1833. if (m == &m->gen->default_module) {
  1834. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_runtime);
  1835. lb_llvm_function_pass_per_function_internal(m, m->gen->cleanup_runtime);
  1836. lb_llvm_function_pass_per_function_internal(m, m->gen->objc_names);
  1837. }
  1838. for (lbProcedure *p : m->procedures_to_generate) {
  1839. if (p->body != nullptr) { // Build Procedure
  1840. lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
  1841. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  1842. pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
  1843. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1844. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1845. } else {
  1846. if (p->entity && p->entity->kind == Entity_Procedure) {
  1847. switch (p->entity->Procedure.optimization_mode) {
  1848. case ProcedureOptimizationMode_None:
  1849. pass_manager_kind = lbFunctionPassManager_none;
  1850. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "optnone"));
  1851. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "noinline"));
  1852. break;
  1853. case ProcedureOptimizationMode_FavorSize:
  1854. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "optsize"));
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. lb_llvm_function_pass_per_function_internal(m, p, pass_manager_kind);
  1860. }
  1861. }
  1862. for (auto const &entry : m->gen_procs) {
  1863. lbProcedure *p = entry.value;
  1864. if (string_starts_with(p->name, str_lit("__$map"))) {
  1865. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1866. } else {
  1867. lb_llvm_function_pass_per_function_internal(m, p);
  1868. }
  1869. }
  1870. return 0;
  1871. }
  1872. struct lbLLVMModulePassWorkerData {
  1873. lbModule *m;
  1874. LLVMTargetMachineRef target_machine;
  1875. bool do_threading;
  1876. };
  1877. gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  1878. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  1879. lb_run_remove_unused_function_pass(wd->m);
  1880. lb_run_remove_unused_globals_pass(wd->m);
  1881. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  1882. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  1883. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  1884. #if LB_USE_NEW_PASS_SYSTEM
  1885. auto passes = array_make<char const *>(heap_allocator(), 0, 64);
  1886. defer (array_free(&passes));
  1887. LLVMPassBuilderOptionsRef pb_options = LLVMCreatePassBuilderOptions();
  1888. defer (LLVMDisposePassBuilderOptions(pb_options));
  1889. #include "llvm_backend_passes.cpp"
  1890. // asan - Linux, Darwin, Windows
  1891. // msan - linux
  1892. // tsan - Linux, Darwin
  1893. // ubsan - Linux, Darwin, Windows (NOT SUPPORTED WITH LLVM C-API)
  1894. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  1895. array_add(&passes, "asan");
  1896. }
  1897. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  1898. array_add(&passes, "msan");
  1899. }
  1900. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  1901. array_add(&passes, "tsan");
  1902. }
  1903. if (passes.count == 0) {
  1904. array_add(&passes, "verify");
  1905. }
  1906. gbString passes_str = gb_string_make_reserve(heap_allocator(), 1024);
  1907. defer (gb_string_free(passes_str));
  1908. for_array(i, passes) {
  1909. if (i != 0) {
  1910. passes_str = gb_string_appendc(passes_str, ",");
  1911. }
  1912. passes_str = gb_string_appendc(passes_str, passes[i]);
  1913. }
  1914. for (isize i = 0; i < gb_string_length(passes_str); /**/) {
  1915. switch (passes_str[i]) {
  1916. case ' ':
  1917. case '\n':
  1918. case '\t':
  1919. gb_memmove(&passes_str[i], &passes_str[i+1], gb_string_length(passes_str)-i);
  1920. GB_STRING_HEADER(passes_str)->length -= 1;
  1921. continue;
  1922. default:
  1923. i += 1;
  1924. break;
  1925. }
  1926. }
  1927. LLVMErrorRef llvm_err = LLVMRunPasses(wd->m->mod, passes_str, wd->target_machine, pb_options);
  1928. defer (LLVMConsumeError(llvm_err));
  1929. if (llvm_err != nullptr) {
  1930. char *llvm_error = LLVMGetErrorMessage(llvm_err);
  1931. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1932. LLVMDisposeErrorMessage(llvm_error);
  1933. llvm_error = nullptr;
  1934. if (build_context.keep_temp_files) {
  1935. TIME_SECTION("LLVM Print Module to File");
  1936. String filepath_ll = lb_filepath_ll_for_module(wd->m);
  1937. if (LLVMPrintModuleToFile(wd->m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1938. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1939. }
  1940. }
  1941. exit_with_errors();
  1942. return 1;
  1943. }
  1944. #endif
  1945. if (wd->do_threading) {
  1946. thread_pool_add_task(lb_llvm_module_verification_worker_proc, wd->m);
  1947. } else {
  1948. lb_llvm_module_verification_worker_proc(wd->m);
  1949. }
  1950. return 0;
  1951. }
  1952. gb_internal WORKER_TASK_PROC(lb_generate_missing_procedures_to_check_worker_proc) {
  1953. lbModule *m = cast(lbModule *)data;
  1954. for (isize i = 0; i < m->missing_procedures_to_check.count; i++) {
  1955. lbProcedure *p = m->missing_procedures_to_check[i];
  1956. debugf("Generate missing procedure: %.*s module %p\n", LIT(p->name), m);
  1957. lb_generate_procedure(m, p);
  1958. }
  1959. return 0;
  1960. }
  1961. gb_internal void lb_generate_missing_procedures(lbGenerator *gen, bool do_threading) {
  1962. if (do_threading) {
  1963. for (auto const &entry : gen->modules) {
  1964. lbModule *m = entry.value;
  1965. // NOTE(bill): procedures may be added during generation
  1966. thread_pool_add_task(lb_generate_missing_procedures_to_check_worker_proc, m);
  1967. }
  1968. thread_pool_wait();
  1969. } else {
  1970. for (auto const &entry : gen->modules) {
  1971. lbModule *m = entry.value;
  1972. // NOTE(bill): procedures may be added during generation
  1973. lb_generate_missing_procedures_to_check_worker_proc(m);
  1974. }
  1975. }
  1976. }
  1977. gb_internal void lb_debug_info_complete_types_and_finalize(lbGenerator *gen) {
  1978. for (auto const &entry : gen->modules) {
  1979. lbModule *m = entry.value;
  1980. if (m->debug_builder != nullptr) {
  1981. LLVMDIBuilderFinalize(m->debug_builder);
  1982. }
  1983. }
  1984. }
  1985. gb_internal void lb_llvm_function_passes(lbGenerator *gen, bool do_threading) {
  1986. if (do_threading) {
  1987. for (auto const &entry : gen->modules) {
  1988. lbModule *m = entry.value;
  1989. thread_pool_add_task(lb_llvm_function_pass_per_module, m);
  1990. }
  1991. thread_pool_wait();
  1992. } else {
  1993. for (auto const &entry : gen->modules) {
  1994. lbModule *m = entry.value;
  1995. lb_llvm_function_pass_per_module(m);
  1996. }
  1997. }
  1998. }
  1999. gb_internal void lb_llvm_module_passes_and_verification(lbGenerator *gen, bool do_threading) {
  2000. if (do_threading) {
  2001. for (auto const &entry : gen->modules) {
  2002. lbModule *m = entry.value;
  2003. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  2004. wd->m = m;
  2005. wd->target_machine = m->target_machine;
  2006. wd->do_threading = true;
  2007. thread_pool_add_task(lb_llvm_module_pass_worker_proc, wd);
  2008. }
  2009. thread_pool_wait();
  2010. } else {
  2011. for (auto const &entry : gen->modules) {
  2012. lbModule *m = entry.value;
  2013. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  2014. wd->m = m;
  2015. wd->target_machine = m->target_machine;
  2016. wd->do_threading = false;
  2017. lb_llvm_module_pass_worker_proc(wd);
  2018. }
  2019. }
  2020. }
  2021. gb_internal String lb_filepath_ll_for_module(lbModule *m) {
  2022. String path = concatenate3_strings(permanent_allocator(),
  2023. build_context.build_paths[BuildPath_Output].basename,
  2024. STR_LIT("/"),
  2025. build_context.build_paths[BuildPath_Output].name
  2026. );
  2027. GB_ASSERT(m->module_name != nullptr);
  2028. String s = make_string_c(m->module_name);
  2029. String prefix = str_lit("odin_package-");
  2030. if (string_starts_with(s, prefix)) {
  2031. s.text += prefix.len;
  2032. s.len -= prefix.len;
  2033. }
  2034. path = concatenate_strings(permanent_allocator(), path, s);
  2035. path = concatenate_strings(permanent_allocator(), s, STR_LIT(".ll"));
  2036. return path;
  2037. }
  2038. gb_internal String lb_filepath_obj_for_module(lbModule *m) {
  2039. String basename = build_context.build_paths[BuildPath_Output].basename;
  2040. String name = build_context.build_paths[BuildPath_Output].name;
  2041. bool use_temporary_directory = false;
  2042. if (USE_SEPARATE_MODULES && build_context.build_mode == BuildMode_Executable) {
  2043. // NOTE(bill): use a temporary directory
  2044. String dir = temporary_directory(permanent_allocator());
  2045. if (dir.len != 0) {
  2046. basename = dir;
  2047. use_temporary_directory = true;
  2048. }
  2049. }
  2050. gbString path = gb_string_make_length(heap_allocator(), basename.text, basename.len);
  2051. path = gb_string_appendc(path, "/");
  2052. if (USE_SEPARATE_MODULES) {
  2053. GB_ASSERT(m->module_name != nullptr);
  2054. String s = make_string_c(m->module_name);
  2055. String prefix = str_lit("odin_package");
  2056. if (string_starts_with(s, prefix)) {
  2057. s.text += prefix.len;
  2058. s.len -= prefix.len;
  2059. }
  2060. path = gb_string_append_length(path, s.text, s.len);
  2061. } else {
  2062. path = gb_string_append_length(path, name.text, name.len);
  2063. }
  2064. if (use_temporary_directory) {
  2065. // NOTE(bill): this must be suffixed to ensure it is not conflicting with anything else in the temporary directory
  2066. path = gb_string_append_fmt(path, "-%p", m);
  2067. }
  2068. String ext = {};
  2069. if (build_context.build_mode == BuildMode_Assembly) {
  2070. ext = STR_LIT("S");
  2071. } else if (build_context.build_mode == BuildMode_Object) {
  2072. // Allow a user override for the object extension.
  2073. ext = build_context.build_paths[BuildPath_Output].ext;
  2074. } else {
  2075. ext = infer_object_extension_from_build_context();
  2076. }
  2077. path = gb_string_append_length(path, ".", 1);
  2078. path = gb_string_append_length(path, ext.text, ext.len);
  2079. return make_string(cast(u8 *)path, gb_string_length(path));
  2080. }
  2081. gb_internal void lb_add_foreign_library_paths(lbGenerator *gen) {
  2082. for (auto const &entry : gen->modules) {
  2083. lbModule *m = entry.value;
  2084. for (Entity *e : m->info->required_foreign_imports_through_force) {
  2085. lb_add_foreign_library_path(m, e);
  2086. }
  2087. if (lb_is_module_empty(m)) {
  2088. continue;
  2089. }
  2090. }
  2091. }
  2092. gb_internal bool lb_llvm_object_generation(lbGenerator *gen, bool do_threading) {
  2093. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  2094. if (build_context.build_mode == BuildMode_Assembly) {
  2095. code_gen_file_type = LLVMAssemblyFile;
  2096. }
  2097. char *llvm_error = nullptr;
  2098. defer (LLVMDisposeMessage(llvm_error));
  2099. if (do_threading) {
  2100. for (auto const &entry : gen->modules) {
  2101. lbModule *m = entry.value;
  2102. if (lb_is_module_empty(m)) {
  2103. continue;
  2104. }
  2105. String filepath_ll = lb_filepath_ll_for_module(m);
  2106. String filepath_obj = lb_filepath_obj_for_module(m);
  2107. array_add(&gen->output_object_paths, filepath_obj);
  2108. array_add(&gen->output_temp_paths, filepath_ll);
  2109. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  2110. wd->target_machine = m->target_machine;
  2111. wd->code_gen_file_type = code_gen_file_type;
  2112. wd->filepath_obj = filepath_obj;
  2113. wd->m = m;
  2114. thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  2115. }
  2116. thread_pool_wait(&global_thread_pool);
  2117. } else {
  2118. for (auto const &entry : gen->modules) {
  2119. lbModule *m = entry.value;
  2120. if (lb_is_module_empty(m)) {
  2121. continue;
  2122. }
  2123. String filepath_obj = lb_filepath_obj_for_module(m);
  2124. array_add(&gen->output_object_paths, filepath_obj);
  2125. String short_name = remove_directory_from_path(filepath_obj);
  2126. gbString section_name = gb_string_make(permanent_allocator(), "LLVM Generate Object: ");
  2127. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  2128. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  2129. if (LLVMTargetMachineEmitToFile(m->target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  2130. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2131. exit_with_errors();
  2132. return false;
  2133. }
  2134. debugf("Generated File: %.*s\n", LIT(filepath_obj));
  2135. }
  2136. }
  2137. return true;
  2138. }
  2139. gb_internal lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime, lbProcedure *cleanup_runtime) {
  2140. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  2141. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  2142. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  2143. Type *params = alloc_type_tuple();
  2144. Type *results = alloc_type_tuple();
  2145. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  2146. bool call_cleanup = true;
  2147. bool has_args = false;
  2148. bool is_dll_main = false;
  2149. String name = str_lit("main");
  2150. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  2151. is_dll_main = true;
  2152. name = str_lit("DllMain");
  2153. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  2154. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  2155. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  2156. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  2157. call_cleanup = false;
  2158. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  2159. name = str_lit("mainCRTStartup");
  2160. } else if (is_arch_wasm()) {
  2161. name = str_lit("_start");
  2162. call_cleanup = false;
  2163. } else {
  2164. has_args = true;
  2165. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  2166. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  2167. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  2168. }
  2169. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  2170. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  2171. Type *proc_type = alloc_type_proc(nullptr,
  2172. params, params->Tuple.variables.count,
  2173. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  2174. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  2175. p->is_startup = true;
  2176. lb_begin_procedure_body(p);
  2177. if (has_args) { // initialize `runtime.args__`
  2178. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  2179. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  2180. LLVMSetValueName2(argc.value, "argc", 4);
  2181. LLVMSetValueName2(argv.value, "argv", 4);
  2182. argc = lb_emit_conv(p, argc, t_int);
  2183. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  2184. lb_fill_slice(p, args, argv, argc);
  2185. }
  2186. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  2187. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none);
  2188. if (build_context.command_kind == Command_test) {
  2189. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  2190. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  2191. Type *slice_type = alloc_type_slice(t_Internal_Test);
  2192. lbAddr all_tests_array_addr = lb_add_global_generated_with_name(p->module, array_type, {}, str_lit("__$all_tests_array"));
  2193. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  2194. LLVMValueRef indices[2] = {};
  2195. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  2196. isize testing_proc_index = 0;
  2197. for (Entity *testing_proc : m->info->testing_procedures) {
  2198. String name = testing_proc->token.string;
  2199. String pkg_name = {};
  2200. if (testing_proc->pkg != nullptr) {
  2201. pkg_name = testing_proc->pkg->name;
  2202. }
  2203. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name, false);
  2204. lbValue v_name = lb_find_or_add_entity_string(m, name, false);
  2205. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  2206. indices[1] = LLVMConstInt(lb_type(m, t_int), testing_proc_index++, false);
  2207. LLVMValueRef vals[3] = {};
  2208. vals[0] = v_pkg.value;
  2209. vals[1] = v_name.value;
  2210. vals[2] = v_proc.value;
  2211. GB_ASSERT(LLVMIsConstant(vals[0]));
  2212. GB_ASSERT(LLVMIsConstant(vals[1]));
  2213. GB_ASSERT(LLVMIsConstant(vals[2]));
  2214. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  2215. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  2216. LLVMBuildStore(p->builder, src, dst);
  2217. }
  2218. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  2219. lb_fill_slice(p, all_tests_slice,
  2220. lb_array_elem(p, all_tests_array),
  2221. lb_const_int(m, t_int, m->info->testing_procedures.count));
  2222. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  2223. TEMPORARY_ALLOCATOR_GUARD();
  2224. auto args = array_make<lbValue>(temporary_allocator(), 1);
  2225. args[0] = lb_addr_load(p, all_tests_slice);
  2226. lbValue result = lb_emit_call(p, runner, args);
  2227. lbValue exit_runner = lb_find_package_value(m, str_lit("os"), str_lit("exit"));
  2228. auto exit_args = array_make<lbValue>(temporary_allocator(), 1);
  2229. exit_args[0] = lb_emit_select(p, result, lb_const_int(m, t_int, 0), lb_const_int(m, t_int, 1));
  2230. lb_emit_call(p, exit_runner, exit_args, ProcInlining_none);
  2231. } else {
  2232. if (m->info->entry_point != nullptr) {
  2233. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  2234. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  2235. }
  2236. if (call_cleanup) {
  2237. lbValue cleanup_runtime_value = {cleanup_runtime->value, cleanup_runtime->type};
  2238. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none);
  2239. }
  2240. if (is_dll_main) {
  2241. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  2242. } else {
  2243. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  2244. }
  2245. }
  2246. lb_end_procedure_body(p);
  2247. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2248. if (is_arch_wasm()) {
  2249. lb_set_wasm_export_attributes(p->value, p->name);
  2250. }
  2251. lb_verify_function(m, p);
  2252. lb_run_function_pass_manager(default_function_pass_manager, p, lbFunctionPassManager_default);
  2253. return p;
  2254. }
  2255. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  2256. if (p->is_done) {
  2257. return;
  2258. }
  2259. if (p->body != nullptr) { // Build Procedure
  2260. m->curr_procedure = p;
  2261. lb_begin_procedure_body(p);
  2262. lb_build_stmt(p, p->body);
  2263. lb_end_procedure_body(p);
  2264. p->is_done = true;
  2265. m->curr_procedure = nullptr;
  2266. } else if (p->generate_body != nullptr) {
  2267. p->generate_body(m, p);
  2268. }
  2269. // Add Flags
  2270. if (p->entity && p->entity->kind == Entity_Procedure && p->entity->Procedure.is_memcpy_like) {
  2271. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  2272. }
  2273. lb_verify_function(m, p, true);
  2274. }
  2275. gb_internal bool lb_generate_code(lbGenerator *gen) {
  2276. TIME_SECTION("LLVM Initializtion");
  2277. isize thread_count = gb_max(build_context.thread_count, 1);
  2278. isize worker_count = thread_count-1;
  2279. bool do_threading = !!(LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  2280. lbModule *default_module = &gen->default_module;
  2281. CheckerInfo *info = gen->info;
  2282. switch (build_context.metrics.arch) {
  2283. case TargetArch_amd64:
  2284. case TargetArch_i386:
  2285. LLVMInitializeX86TargetInfo();
  2286. LLVMInitializeX86Target();
  2287. LLVMInitializeX86TargetMC();
  2288. LLVMInitializeX86AsmPrinter();
  2289. LLVMInitializeX86AsmParser();
  2290. LLVMInitializeX86Disassembler();
  2291. break;
  2292. case TargetArch_arm64:
  2293. LLVMInitializeAArch64TargetInfo();
  2294. LLVMInitializeAArch64Target();
  2295. LLVMInitializeAArch64TargetMC();
  2296. LLVMInitializeAArch64AsmPrinter();
  2297. LLVMInitializeAArch64AsmParser();
  2298. LLVMInitializeAArch64Disassembler();
  2299. break;
  2300. case TargetArch_wasm32:
  2301. case TargetArch_wasm64p32:
  2302. LLVMInitializeWebAssemblyTargetInfo();
  2303. LLVMInitializeWebAssemblyTarget();
  2304. LLVMInitializeWebAssemblyTargetMC();
  2305. LLVMInitializeWebAssemblyAsmPrinter();
  2306. LLVMInitializeWebAssemblyAsmParser();
  2307. LLVMInitializeWebAssemblyDisassembler();
  2308. break;
  2309. case TargetArch_riscv64:
  2310. LLVMInitializeRISCVTargetInfo();
  2311. LLVMInitializeRISCVTarget();
  2312. LLVMInitializeRISCVTargetMC();
  2313. LLVMInitializeRISCVAsmPrinter();
  2314. LLVMInitializeRISCVAsmParser();
  2315. LLVMInitializeRISCVDisassembler();
  2316. break;
  2317. case TargetArch_arm32:
  2318. LLVMInitializeARMTargetInfo();
  2319. LLVMInitializeARMTarget();
  2320. LLVMInitializeARMTargetMC();
  2321. LLVMInitializeARMAsmPrinter();
  2322. LLVMInitializeARMAsmParser();
  2323. LLVMInitializeARMDisassembler();
  2324. break;
  2325. default:
  2326. GB_PANIC("Unimplemented LLVM target initialization");
  2327. break;
  2328. }
  2329. if (build_context.microarch == "native") {
  2330. LLVMInitializeNativeTarget();
  2331. }
  2332. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  2333. for (auto const &entry : gen->modules) {
  2334. LLVMSetTarget(entry.value->mod, target_triple);
  2335. }
  2336. LLVMTargetRef target = {};
  2337. char *llvm_error = nullptr;
  2338. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  2339. GB_ASSERT(target != nullptr);
  2340. TIME_SECTION("LLVM Create Target Machine");
  2341. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  2342. if (is_arch_wasm()) {
  2343. code_mode = LLVMCodeModelJITDefault;
  2344. } else if (is_arch_x86() && build_context.metrics.os == TargetOs_freestanding) {
  2345. code_mode = LLVMCodeModelKernel;
  2346. }
  2347. String llvm_cpu = get_final_microarchitecture();
  2348. gbString llvm_features = gb_string_make(temporary_allocator(), "");
  2349. String_Iterator it = {build_context.target_features_string, 0};
  2350. bool first = true;
  2351. for (;;) {
  2352. String str = string_split_iterator(&it, ',');
  2353. if (str == "") break;
  2354. if (!first) {
  2355. llvm_features = gb_string_appendc(llvm_features, ",");
  2356. }
  2357. first = false;
  2358. llvm_features = gb_string_appendc(llvm_features, "+");
  2359. llvm_features = gb_string_append_length(llvm_features, str.text, str.len);
  2360. }
  2361. debugf("CPU: %.*s, Features: %s\n", LIT(llvm_cpu), llvm_features);
  2362. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  2363. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  2364. if (!LB_USE_NEW_PASS_SYSTEM) {
  2365. build_context.optimization_level = gb_clamp(build_context.optimization_level, -1, 2);
  2366. }
  2367. switch (build_context.optimization_level) {
  2368. default:/*fallthrough*/
  2369. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  2370. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  2371. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  2372. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  2373. }
  2374. // NOTE(bill): Target Machine Creation
  2375. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  2376. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), 0, gen->modules.count);
  2377. // NOTE(dweiler): Dynamic libraries require position-independent code.
  2378. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  2379. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  2380. reloc_mode = LLVMRelocPIC;
  2381. }
  2382. switch (build_context.reloc_mode) {
  2383. case RelocMode_Default:
  2384. if (build_context.metrics.os == TargetOs_openbsd || build_context.metrics.os == TargetOs_haiku) {
  2385. // Always use PIC for OpenBSD and Haiku: they default to PIE
  2386. reloc_mode = LLVMRelocPIC;
  2387. }
  2388. if (build_context.metrics.arch == TargetArch_riscv64) {
  2389. // NOTE(laytan): didn't seem to work without this.
  2390. reloc_mode = LLVMRelocPIC;
  2391. }
  2392. break;
  2393. case RelocMode_Static:
  2394. reloc_mode = LLVMRelocStatic;
  2395. break;
  2396. case RelocMode_PIC:
  2397. reloc_mode = LLVMRelocPIC;
  2398. break;
  2399. case RelocMode_DynamicNoPIC:
  2400. reloc_mode = LLVMRelocDynamicNoPic;
  2401. break;
  2402. }
  2403. for (auto const &entry : gen->modules) {
  2404. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  2405. target, target_triple, (const char *)llvm_cpu.text,
  2406. llvm_features,
  2407. code_gen_level,
  2408. reloc_mode,
  2409. code_mode);
  2410. lbModule *m = entry.value;
  2411. m->target_machine = target_machine;
  2412. LLVMSetModuleDataLayout(m->mod, LLVMCreateTargetDataLayout(target_machine));
  2413. #if LLVM_VERSION_MAJOR >= 18
  2414. if (build_context.fast_isel) {
  2415. LLVMSetTargetMachineFastISel(m->target_machine, true);
  2416. }
  2417. #endif
  2418. array_add(&target_machines, target_machine);
  2419. }
  2420. for (auto const &entry : gen->modules) {
  2421. lbModule *m = entry.value;
  2422. if (m->debug_builder) { // Debug Info
  2423. for (auto const &file_entry : info->files) {
  2424. AstFile *f = file_entry.value;
  2425. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  2426. cast(char const *)f->filename.text, f->filename.len,
  2427. cast(char const *)f->directory.text, f->directory.len);
  2428. lb_set_llvm_metadata(m, f, res);
  2429. }
  2430. TEMPORARY_ALLOCATOR_GUARD();
  2431. gbString producer = gb_string_make(temporary_allocator(), "odin");
  2432. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  2433. // #ifdef NIGHTLY
  2434. // producer = gb_string_appendc(producer, "-nightly");
  2435. // #endif
  2436. // #ifdef GIT_SHA
  2437. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  2438. // #endif
  2439. gbString split_name = gb_string_make(temporary_allocator(), "");
  2440. LLVMBool is_optimized = build_context.optimization_level > 0;
  2441. AstFile *init_file = m->info->init_package->files[0];
  2442. if (Entity *entry_point = m->info->entry_point) {
  2443. if (Ast *ident = entry_point->identifier.load()) {
  2444. if (ident->file_id) {
  2445. init_file = ident->file();
  2446. }
  2447. }
  2448. }
  2449. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  2450. LLVMBool debug_info_for_profiling = false;
  2451. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  2452. lb_get_llvm_metadata(m, init_file),
  2453. producer, gb_string_length(producer),
  2454. is_optimized, "", 0,
  2455. 1, split_name, gb_string_length(split_name),
  2456. LLVMDWARFEmissionFull,
  2457. 0, split_debug_inlining,
  2458. debug_info_for_profiling,
  2459. "", 0, // sys_root
  2460. "", 0 // SDK
  2461. );
  2462. GB_ASSERT(m->debug_compile_unit != nullptr);
  2463. }
  2464. }
  2465. TIME_SECTION("LLVM Global Variables");
  2466. if (!build_context.no_rtti) {
  2467. lbModule *m = default_module;
  2468. { // Add type info data
  2469. // GB_ASSERT_MSG(info->minimum_dependency_type_info_index_map.count == info->type_info_types.count, "%tu vs %tu", info->minimum_dependency_type_info_index_map.count, info->type_info_types.count);
  2470. // isize max_type_info_count = info->minimum_dependency_type_info_index_map.count+1;
  2471. isize max_type_info_count = info->type_info_types_hash_map.count;
  2472. Type *t = alloc_type_array(t_type_info_ptr, max_type_info_count);
  2473. // IMPORTANT NOTE(bill): As LLVM does not have a union type, an array of unions cannot be initialized
  2474. // at compile time without cheating in some way. This means to emulate an array of unions is to use
  2475. // a giant packed struct of "corrected" data types.
  2476. LLVMTypeRef internal_llvm_type = lb_type(m, t);
  2477. LLVMValueRef g = LLVMAddGlobal(m->mod, internal_llvm_type, LB_TYPE_INFO_DATA_NAME);
  2478. LLVMSetInitializer(g, LLVMConstNull(internal_llvm_type));
  2479. LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2480. // LLVMSetUnnamedAddress(g, LLVMGlobalUnnamedAddr);
  2481. LLVMSetGlobalConstant(g, true);
  2482. lbValue value = {};
  2483. value.value = g;
  2484. value.type = alloc_type_pointer(t);
  2485. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  2486. lb_add_entity(m, lb_global_type_info_data_entity, value);
  2487. }
  2488. { // Type info member buffer
  2489. // NOTE(bill): Removes need for heap allocation by making it global memory
  2490. isize count = 0;
  2491. isize offsets_extra = 0;
  2492. for (auto const &tt : m->info->type_info_types_hash_map) {
  2493. Type *t = tt.type;
  2494. if (t == nullptr) {
  2495. continue;
  2496. }
  2497. isize index = lb_type_info_index(m->info, t, false);
  2498. if (index < 0) {
  2499. continue;
  2500. }
  2501. switch (t->kind) {
  2502. case Type_Union:
  2503. count += t->Union.variants.count;
  2504. break;
  2505. case Type_Struct:
  2506. count += t->Struct.fields.count;
  2507. break;
  2508. case Type_Tuple:
  2509. count += t->Tuple.variables.count;
  2510. break;
  2511. case Type_BitField:
  2512. count += t->BitField.fields.count;
  2513. // Twice is needed for the bit_offsets
  2514. offsets_extra += t->BitField.fields.count;
  2515. break;
  2516. }
  2517. }
  2518. auto const global_type_info_make = [](lbModule *m, char const *name, Type *elem_type, i64 count) -> lbAddr {
  2519. Type *t = alloc_type_array(elem_type, count);
  2520. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2521. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2522. LLVMSetLinkage(g, LLVMInternalLinkage);
  2523. lb_make_global_private_const(g);
  2524. lb_set_odin_rtti_section(g);
  2525. return lb_addr({g, alloc_type_pointer(t)});
  2526. };
  2527. lb_global_type_info_member_types = global_type_info_make(m, LB_TYPE_INFO_TYPES_NAME, t_type_info_ptr, count);
  2528. lb_global_type_info_member_names = global_type_info_make(m, LB_TYPE_INFO_NAMES_NAME, t_string, count);
  2529. lb_global_type_info_member_offsets = global_type_info_make(m, LB_TYPE_INFO_OFFSETS_NAME, t_uintptr, count+offsets_extra);
  2530. lb_global_type_info_member_usings = global_type_info_make(m, LB_TYPE_INFO_USINGS_NAME, t_bool, count);
  2531. lb_global_type_info_member_tags = global_type_info_make(m, LB_TYPE_INFO_TAGS_NAME, t_string, count);
  2532. }
  2533. }
  2534. isize global_variable_max_count = 0;
  2535. bool already_has_entry_point = false;
  2536. for (Entity *e : info->entities) {
  2537. String name = e->token.string;
  2538. if (e->kind == Entity_Variable) {
  2539. global_variable_max_count++;
  2540. } else if (e->kind == Entity_Procedure) {
  2541. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  2542. GB_ASSERT(e == info->entry_point);
  2543. }
  2544. if (build_context.command_kind == Command_test &&
  2545. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  2546. String link_name = e->Procedure.link_name;
  2547. if (e->pkg->kind == Package_Runtime) {
  2548. if (link_name == "main" ||
  2549. link_name == "DllMain" ||
  2550. link_name == "WinMain" ||
  2551. link_name == "wWinMain" ||
  2552. link_name == "mainCRTStartup" ||
  2553. link_name == "_start") {
  2554. already_has_entry_point = true;
  2555. }
  2556. }
  2557. }
  2558. }
  2559. }
  2560. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  2561. for (DeclInfo *d : info->variable_init_order) {
  2562. Entity *e = d->entity;
  2563. if ((e->scope->flags & ScopeFlag_File) == 0) {
  2564. continue;
  2565. }
  2566. if (e->min_dep_count.load(std::memory_order_relaxed) == 0) {
  2567. continue;
  2568. }
  2569. // if (!ptr_set_exists(min_dep_set, e)) {
  2570. // continue;
  2571. // }
  2572. DeclInfo *decl = decl_info_of_entity(e);
  2573. if (decl == nullptr) {
  2574. continue;
  2575. }
  2576. GB_ASSERT(e->kind == Entity_Variable);
  2577. bool is_foreign = e->Variable.is_foreign;
  2578. bool is_export = e->Variable.is_export;
  2579. lbModule *m = &gen->default_module;
  2580. String name = lb_get_entity_name(m, e);
  2581. lbValue g = {};
  2582. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2583. g.type = alloc_type_pointer(e->type);
  2584. lb_apply_thread_local_model(g.value, e->Variable.thread_local_model);
  2585. if (is_foreign) {
  2586. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2587. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  2588. LLVMSetExternallyInitialized(g.value, true);
  2589. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  2590. } else {
  2591. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  2592. }
  2593. if (is_export) {
  2594. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  2595. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  2596. } else if (!is_foreign) {
  2597. LLVMSetLinkage(g.value, USE_SEPARATE_MODULES ? LLVMWeakAnyLinkage : LLVMInternalLinkage);
  2598. }
  2599. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  2600. LLVMSetAlignment(g.value, cast(u32)type_align_of(e->type));
  2601. if (e->Variable.link_section.len > 0) {
  2602. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  2603. }
  2604. lbGlobalVariable var = {};
  2605. var.var = g;
  2606. var.decl = decl;
  2607. if (decl->init_expr != nullptr) {
  2608. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  2609. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  2610. if (tav.mode != Addressing_Invalid) {
  2611. if (tav.value.kind != ExactValue_Invalid) {
  2612. auto cc = LB_CONST_CONTEXT_DEFAULT;
  2613. cc.is_rodata = e->kind == Entity_Variable && e->Variable.is_rodata;
  2614. cc.allow_local = false;
  2615. cc.link_section = e->Variable.link_section;
  2616. ExactValue v = tav.value;
  2617. lbValue init = lb_const_value(m, tav.type, v, cc);
  2618. LLVMSetInitializer(g.value, init.value);
  2619. var.is_initialized = true;
  2620. if (cc.is_rodata) {
  2621. LLVMSetGlobalConstant(g.value, true);
  2622. }
  2623. }
  2624. }
  2625. }
  2626. if (!var.is_initialized && is_type_untyped_nil(tav.type)) {
  2627. var.is_initialized = true;
  2628. if (e->kind == Entity_Variable && e->Variable.is_rodata) {
  2629. LLVMSetGlobalConstant(g.value, true);
  2630. }
  2631. }
  2632. } else if (e->kind == Entity_Variable && e->Variable.is_rodata) {
  2633. LLVMSetGlobalConstant(g.value, true);
  2634. }
  2635. if (e->flags & EntityFlag_Require) {
  2636. lb_append_to_compiler_used(m, g.value);
  2637. }
  2638. array_add(&global_variables, var);
  2639. lb_add_entity(m, e, g);
  2640. lb_add_member(m, name, g);
  2641. if (m->debug_builder) {
  2642. String global_name = e->token.string;
  2643. if (global_name.len != 0 && global_name != "_") {
  2644. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  2645. LLVMMetadataRef llvm_scope = llvm_file;
  2646. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  2647. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2648. LLVMMetadataRef llvm_decl = nullptr;
  2649. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  2650. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  2651. m->debug_builder, llvm_scope,
  2652. cast(char const *)global_name.text, global_name.len,
  2653. "", 0, // linkage
  2654. llvm_file, e->token.pos.line,
  2655. lb_debug_type(m, e->type),
  2656. local_to_unit,
  2657. llvm_expr,
  2658. llvm_decl,
  2659. align_in_bits
  2660. );
  2661. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  2662. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  2663. }
  2664. }
  2665. }
  2666. if (build_context.ODIN_DEBUG) {
  2667. // Custom `.raddbg` section for its debugger
  2668. if (build_context.metrics.os == TargetOs_windows) {
  2669. lbModule *m = default_module;
  2670. LLVMModuleRef mod = m->mod;
  2671. LLVMContextRef ctx = m->ctx;
  2672. {
  2673. LLVMTypeRef type = LLVMArrayType(LLVMInt8TypeInContext(ctx), 1);
  2674. LLVMValueRef global = LLVMAddGlobal(mod, type, "raddbg_is_attached_byte_marker");
  2675. LLVMSetInitializer(global, LLVMConstNull(type));
  2676. LLVMSetSection(global, ".raddbg");
  2677. }
  2678. if (gen->info->entry_point) {
  2679. String mangled_name = lb_get_entity_name(m, gen->info->entry_point);
  2680. char const *str = alloc_cstring(temporary_allocator(), mangled_name);
  2681. lb_add_raddbg_string(m, "entry_point: \"", str, "\"");
  2682. }
  2683. }
  2684. }
  2685. TIME_SECTION("LLVM Runtime Objective-C Names Creation");
  2686. gen->objc_names = lb_create_objc_names(default_module);
  2687. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables & @(init))");
  2688. gen->startup_runtime = lb_create_startup_runtime(default_module, gen->objc_names, global_variables);
  2689. TIME_SECTION("LLVM Runtime Cleanup Creation & @(fini)");
  2690. gen->cleanup_runtime = lb_create_cleanup_runtime(default_module);
  2691. if (build_context.ODIN_DEBUG) {
  2692. for (auto const &entry : builtin_pkg->scope->elements) {
  2693. Entity *e = entry.value;
  2694. lb_add_debug_info_for_global_constant_from_entity(gen, e);
  2695. }
  2696. }
  2697. if (gen->modules.count <= 1) {
  2698. do_threading = false;
  2699. }
  2700. TIME_SECTION("LLVM Global Procedures and Types + Procedure Generation");
  2701. lb_create_global_procedures_and_types(gen, info, do_threading);
  2702. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  2703. TIME_SECTION("LLVM main");
  2704. lb_create_main_procedure(default_module, gen->startup_runtime, gen->cleanup_runtime);
  2705. }
  2706. TIME_SECTION("LLVM Procedure Generation (missing)");
  2707. lb_generate_missing_procedures(gen, do_threading);
  2708. if (gen->objc_names) {
  2709. TIME_SECTION("Finalize objc names");
  2710. lb_finalize_objc_names(gen, gen->objc_names);
  2711. }
  2712. if (build_context.ODIN_DEBUG) {
  2713. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  2714. lb_debug_info_complete_types_and_finalize(gen);
  2715. // Custom `.raddbg` section for its debugger
  2716. if (build_context.metrics.os == TargetOs_windows) {
  2717. lbModule *m = default_module;
  2718. LLVMModuleRef mod = m->mod;
  2719. LLVMContextRef ctx = m->ctx;
  2720. lb_add_raddbg_string(m, "type_view: {type: \"[]?\", expr: \"array(data, len)\"}");
  2721. lb_add_raddbg_string(m, "type_view: {type: \"string\", expr: \"array(data, len)\"}");
  2722. lb_add_raddbg_string(m, "type_view: {type: \"[dynamic]?\", expr: \"rows($, array(data, len), len, cap, allocator)\"}");
  2723. // column major matrices
  2724. lb_add_raddbg_string(m, "type_view: {type: \"matrix[1, ?]?\", expr: \"columns($.data, $[0])\"}");
  2725. lb_add_raddbg_string(m, "type_view: {type: \"matrix[2, ?]?\", expr: \"columns($.data, $[0], $[1])\"}");
  2726. lb_add_raddbg_string(m, "type_view: {type: \"matrix[3, ?]?\", expr: \"columns($.data, $[0], $[1], $[2])\"}");
  2727. lb_add_raddbg_string(m, "type_view: {type: \"matrix[4, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3])\"}");
  2728. lb_add_raddbg_string(m, "type_view: {type: \"matrix[5, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4])\"}");
  2729. lb_add_raddbg_string(m, "type_view: {type: \"matrix[6, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5])\"}");
  2730. lb_add_raddbg_string(m, "type_view: {type: \"matrix[7, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6])\"}");
  2731. lb_add_raddbg_string(m, "type_view: {type: \"matrix[8, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7])\"}");
  2732. lb_add_raddbg_string(m, "type_view: {type: \"matrix[9, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8])\"}");
  2733. lb_add_raddbg_string(m, "type_view: {type: \"matrix[10, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9])\"}");
  2734. lb_add_raddbg_string(m, "type_view: {type: \"matrix[11, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10])\"}");
  2735. lb_add_raddbg_string(m, "type_view: {type: \"matrix[12, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11])\"}");
  2736. lb_add_raddbg_string(m, "type_view: {type: \"matrix[13, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12])\"}");
  2737. lb_add_raddbg_string(m, "type_view: {type: \"matrix[14, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13])\"}");
  2738. lb_add_raddbg_string(m, "type_view: {type: \"matrix[15, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14])\"}");
  2739. lb_add_raddbg_string(m, "type_view: {type: \"matrix[16, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14], $[15])\"}");
  2740. // row major matrices
  2741. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 1]?\", expr: \"columns($.data, $[0])\"}");
  2742. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 2]?\", expr: \"columns($.data, $[0], $[1])\"}");
  2743. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 3]?\", expr: \"columns($.data, $[0], $[1], $[2])\"}");
  2744. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 4]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3])\"}");
  2745. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 5]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4])\"}");
  2746. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 6]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5])\"}");
  2747. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 7]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6])\"}");
  2748. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 8]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7])\"}");
  2749. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 9]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8])\"}");
  2750. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 10]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9])\"}");
  2751. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 11]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10])\"}");
  2752. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 12]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11])\"}");
  2753. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 13]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12])\"}");
  2754. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 14]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13])\"}");
  2755. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 15]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14])\"}");
  2756. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 16]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14], $[15])\"}");
  2757. TEMPORARY_ALLOCATOR_GUARD();
  2758. for (RaddbgTypeView const &type_view : gen->info->raddbg_type_views) {
  2759. if (type_view.type == nullptr) {
  2760. continue;
  2761. }
  2762. if (type_view.view.len == 0) {
  2763. continue;
  2764. }
  2765. String t_str = type_to_canonical_string(temporary_allocator(), type_view.type);
  2766. gbString s = gb_string_make(temporary_allocator(), "");
  2767. s = gb_string_appendc(s, "type_view: {type: \"");
  2768. s = gb_string_append_length(s, t_str.text, t_str.len);
  2769. s = gb_string_appendc(s, "\", expr: \"");
  2770. s = gb_string_append_length(s, type_view.view.text, type_view.view.len);
  2771. s = gb_string_appendc(s, "\"}");
  2772. lb_add_raddbg_string(m, s);
  2773. }
  2774. TEMPORARY_ALLOCATOR_GUARD();
  2775. u32 global_name_index = 0;
  2776. for (String str = {}; mpsc_dequeue(&gen->raddebug_section_strings, &str); /**/) {
  2777. LLVMValueRef data = LLVMConstStringInContext(ctx, cast(char const *)str.text, cast(unsigned)str.len, false);
  2778. LLVMTypeRef type = LLVMTypeOf(data);
  2779. gbString global_name = gb_string_make(temporary_allocator(), "raddbg_data__");
  2780. global_name = gb_string_append_fmt(global_name, "%u", global_name_index);
  2781. global_name_index += 1;
  2782. LLVMValueRef global = LLVMAddGlobal(mod, type, global_name);
  2783. LLVMSetInitializer(global, data);
  2784. LLVMSetAlignment(global, 1);
  2785. LLVMSetSection(global, ".raddbg");
  2786. }
  2787. }
  2788. }
  2789. if (do_threading) {
  2790. isize non_empty_module_count = 0;
  2791. for (auto const &entry : gen->modules) {
  2792. lbModule *m = entry.value;
  2793. if (!lb_is_module_empty(m)) {
  2794. non_empty_module_count += 1;
  2795. }
  2796. }
  2797. if (non_empty_module_count <= 1) {
  2798. do_threading = false;
  2799. }
  2800. }
  2801. TIME_SECTION("LLVM Function Pass");
  2802. lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
  2803. TIME_SECTION("LLVM Module Pass and Verification");
  2804. lb_llvm_module_passes_and_verification(gen, do_threading);
  2805. if (gen->module_verification_failed.load(std::memory_order_relaxed)) {
  2806. return false;
  2807. }
  2808. llvm_error = nullptr;
  2809. defer (LLVMDisposeMessage(llvm_error));
  2810. if (build_context.keep_temp_files ||
  2811. build_context.build_mode == BuildMode_LLVM_IR) {
  2812. TIME_SECTION("LLVM Print Module to File");
  2813. for (auto const &entry : gen->modules) {
  2814. lbModule *m = entry.value;
  2815. if (lb_is_module_empty(m)) {
  2816. continue;
  2817. }
  2818. String filepath_ll = lb_filepath_ll_for_module(m);
  2819. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2820. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2821. exit_with_errors();
  2822. return false;
  2823. }
  2824. array_add(&gen->output_temp_paths, filepath_ll);
  2825. }
  2826. if (build_context.build_mode == BuildMode_LLVM_IR) {
  2827. return true;
  2828. }
  2829. }
  2830. TIME_SECTION("LLVM Add Foreign Library Paths");
  2831. lb_add_foreign_library_paths(gen);
  2832. TIME_SECTION("LLVM Correct Entity Linkage");
  2833. lb_correct_entity_linkage(gen);
  2834. ////////////////////////////////////////////
  2835. for (auto const &entry: gen->modules) {
  2836. lbModule *m = entry.value;
  2837. if (!lb_is_module_empty(m)) {
  2838. gen->used_module_count += 1;
  2839. }
  2840. }
  2841. gbString label_object_generation = gb_string_make(heap_allocator(), "LLVM Object Generation");
  2842. if (gen->used_module_count > 1) {
  2843. label_object_generation = gb_string_append_fmt(label_object_generation, " (%td used modules)", gen->used_module_count);
  2844. }
  2845. TIME_SECTION_WITH_LEN(label_object_generation, gb_string_length(label_object_generation));
  2846. if (build_context.ignore_llvm_build) {
  2847. gb_printf_err("LLVM object generation has been ignored!\n");
  2848. return false;
  2849. }
  2850. if (!lb_llvm_object_generation(gen, do_threading)) {
  2851. return false;
  2852. }
  2853. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  2854. switch (build_context.metrics.os) {
  2855. case TargetOs_windows: {
  2856. auto paths = array_make<String>(heap_allocator(), 0, 1);
  2857. String path = concatenate_strings(permanent_allocator(), build_context.ODIN_ROOT, str_lit("\\bin\\llvm\\windows\\clang_rt.asan-x86_64.lib"));
  2858. array_add(&paths, path);
  2859. Entity *lib = alloc_entity_library_name(nullptr, make_token_ident("asan_lib"), nullptr, slice_from_array(paths), str_lit("asan_lib"));
  2860. array_add(&gen->foreign_libraries, lib);
  2861. } break;
  2862. case TargetOs_darwin:
  2863. case TargetOs_linux:
  2864. case TargetOs_freebsd:
  2865. if (!build_context.extra_linker_flags.text) {
  2866. build_context.extra_linker_flags = str_lit("-fsanitize=address");
  2867. } else {
  2868. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=address"));
  2869. }
  2870. break;
  2871. }
  2872. }
  2873. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  2874. switch (build_context.metrics.os) {
  2875. case TargetOs_linux:
  2876. case TargetOs_freebsd:
  2877. if (!build_context.extra_linker_flags.text) {
  2878. build_context.extra_linker_flags = str_lit("-fsanitize=memory");
  2879. } else {
  2880. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=memory"));
  2881. }
  2882. break;
  2883. }
  2884. }
  2885. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  2886. switch (build_context.metrics.os) {
  2887. case TargetOs_darwin:
  2888. case TargetOs_linux:
  2889. case TargetOs_freebsd:
  2890. if (!build_context.extra_linker_flags.text) {
  2891. build_context.extra_linker_flags = str_lit("-fsanitize=thread");
  2892. } else {
  2893. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=thread"));
  2894. }
  2895. break;
  2896. }
  2897. }
  2898. array_sort(gen->foreign_libraries, foreign_library_cmp);
  2899. return true;
  2900. }