llvm_backend.cpp 96 KB

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