llvm_backend_utility.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078
  1. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name);
  2. gb_internal bool lb_is_type_aggregate(Type *t) {
  3. t = base_type(t);
  4. switch (t->kind) {
  5. case Type_Basic:
  6. switch (t->Basic.kind) {
  7. case Basic_string:
  8. case Basic_string16:
  9. case Basic_any:
  10. return true;
  11. case Basic_complex32:
  12. case Basic_complex64:
  13. case Basic_complex128:
  14. case Basic_quaternion64:
  15. case Basic_quaternion128:
  16. case Basic_quaternion256:
  17. return true;
  18. }
  19. break;
  20. case Type_Pointer:
  21. return false;
  22. case Type_Array:
  23. case Type_Slice:
  24. case Type_Struct:
  25. case Type_Union:
  26. case Type_Tuple:
  27. case Type_DynamicArray:
  28. case Type_Map:
  29. case Type_SimdVector:
  30. return true;
  31. case Type_Named:
  32. return lb_is_type_aggregate(t->Named.base);
  33. }
  34. return false;
  35. }
  36. gb_internal void lb_emit_unreachable(lbProcedure *p) {
  37. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  38. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  39. lb_call_intrinsic(p, "llvm.trap", nullptr, 0, nullptr, 0);
  40. LLVMBuildUnreachable(p->builder);
  41. }
  42. }
  43. gb_internal lbValue lb_correct_endianness(lbProcedure *p, lbValue value) {
  44. Type *src = core_type(value.type);
  45. GB_ASSERT(is_type_integer(src) || is_type_float(src));
  46. if (is_type_different_to_arch_endianness(src)) {
  47. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  48. value = lb_emit_byte_swap(p, value, platform_src_type);
  49. }
  50. return value;
  51. }
  52. gb_internal void lb_set_metadata_custom_u64(lbModule *m, LLVMValueRef v_ref, String name, u64 value) {
  53. unsigned md_id = LLVMGetMDKindIDInContext(m->ctx, cast(char const *)name.text, cast(unsigned)name.len);
  54. LLVMMetadataRef md = LLVMValueAsMetadata(LLVMConstInt(lb_type(m, t_u64), value, false));
  55. LLVMValueRef node = LLVMMetadataAsValue(m->ctx, LLVMMDNodeInContext2(m->ctx, &md, 1));
  56. LLVMSetMetadata(v_ref, md_id, node);
  57. }
  58. gb_internal u64 lb_get_metadata_custom_u64(lbModule *m, LLVMValueRef v_ref, String name) {
  59. unsigned md_id = LLVMGetMDKindIDInContext(m->ctx, cast(char const *)name.text, cast(unsigned)name.len);
  60. LLVMValueRef v_md = LLVMGetMetadata(v_ref, md_id);
  61. if (v_md == nullptr) {
  62. return 0;
  63. }
  64. unsigned node_count = LLVMGetMDNodeNumOperands(v_md);
  65. if (node_count == 0) {
  66. return 0;
  67. }
  68. GB_ASSERT(node_count == 1);
  69. LLVMValueRef value = nullptr;
  70. LLVMGetMDNodeOperands(v_md, &value);
  71. return LLVMConstIntGetZExtValue(value);
  72. }
  73. gb_internal LLVMValueRef lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, usize len, unsigned alignment, bool is_volatile) {
  74. return lb_mem_zero_ptr_internal(p, ptr, LLVMConstInt(lb_type(p->module, t_uint), len, false), alignment, is_volatile);
  75. }
  76. gb_internal LLVMValueRef lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment, bool is_volatile) {
  77. bool is_inlinable = false;
  78. i64 const_len = 0;
  79. if (LLVMIsConstant(len)) {
  80. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  81. // TODO(bill): Determine when it is better to do the `*.inline` versions
  82. if (const_len <= lb_max_zero_init_size()) {
  83. is_inlinable = true;
  84. }
  85. }
  86. char const *name = "llvm.memset";
  87. if (is_inlinable) {
  88. name = "llvm.memset.inline";
  89. }
  90. LLVMTypeRef types[2] = {
  91. lb_type(p->module, t_rawptr),
  92. lb_type(p->module, t_int)
  93. };
  94. LLVMValueRef args[4] = {};
  95. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  96. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  97. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  98. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), is_volatile, false);
  99. return lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  100. }
  101. gb_internal void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  102. LLVMTypeRef llvm_type = lb_type(p->module, type);
  103. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  104. i64 sz = type_size_of(type);
  105. switch (kind) {
  106. case LLVMStructTypeKind:
  107. case LLVMArrayTypeKind:
  108. if (is_type_tuple(type)) {
  109. // NOTE(bill): even though this should be safe, to keep ASAN happy, do not zero the implicit padding at the end
  110. GB_ASSERT(type->kind == Type_Tuple);
  111. i64 n = type->Tuple.variables.count-1;
  112. i64 end_offset = type->Tuple.offsets[n] + type_size_of(type->Tuple.variables[n]->type);
  113. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, end_offset).value, alignment, false);
  114. } else {
  115. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  116. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment, false);
  117. }
  118. break;
  119. default:
  120. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  121. break;
  122. }
  123. }
  124. gb_internal lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  125. cond = lb_emit_conv(p, cond, t_llvm_bool);
  126. lbValue res = {};
  127. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  128. res.type = x.type;
  129. return res;
  130. }
  131. gb_internal lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  132. x = lb_emit_conv(p, x, t);
  133. y = lb_emit_conv(p, y, t);
  134. bool use_llvm_intrinsic = !is_arch_wasm() && (is_type_float(t) || (is_type_simd_vector(t) && is_type_float(base_array_type(t))));
  135. if (use_llvm_intrinsic) {
  136. LLVMValueRef args[2] = {x.value, y.value};
  137. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  138. // NOTE(bill): f either operand is a NaN, returns NaN. Otherwise returns the lesser of the two arguments.
  139. // -0.0 is considered to be less than +0.0 for this intrinsic.
  140. // These semantics are specified by IEEE 754-2008.
  141. LLVMValueRef v = lb_call_intrinsic(p, "llvm.minnum", args, gb_count_of(args), types, gb_count_of(types));
  142. return {v, t};
  143. }
  144. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  145. }
  146. gb_internal lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  147. x = lb_emit_conv(p, x, t);
  148. y = lb_emit_conv(p, y, t);
  149. bool use_llvm_intrinsic = !is_arch_wasm() && (is_type_float(t) || (is_type_simd_vector(t) && is_type_float(base_array_type(t))));
  150. if (use_llvm_intrinsic) {
  151. LLVMValueRef args[2] = {x.value, y.value};
  152. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  153. // NOTE(bill): If either operand is a NaN, returns NaN. Otherwise returns the greater of the two arguments.
  154. // -0.0 is considered to be less than +0.0 for this intrinsic.
  155. // These semantics are specified by IEEE 754-2008.
  156. LLVMValueRef v = lb_call_intrinsic(p, "llvm.maxnum", args, gb_count_of(args), types, gb_count_of(types));
  157. return {v, t};
  158. }
  159. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  160. }
  161. gb_internal lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  162. lbValue z = {};
  163. z = lb_emit_max(p, t, x, min);
  164. z = lb_emit_min(p, t, z, max);
  165. return z;
  166. }
  167. gb_internal lbValue lb_emit_string16(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  168. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  169. LLVMValueRef values[2] = {
  170. str_elem.value,
  171. str_len.value,
  172. };
  173. lbValue res = {};
  174. res.type = t_string16;
  175. res.value = llvm_const_named_struct(p->module, t_string16, values, gb_count_of(values));
  176. return res;
  177. } else {
  178. lbAddr res = lb_add_local_generated(p, t_string16, false);
  179. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  180. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  181. return lb_addr_load(p, res);
  182. }
  183. }
  184. gb_internal lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  185. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  186. LLVMValueRef values[2] = {
  187. str_elem.value,
  188. str_len.value,
  189. };
  190. lbValue res = {};
  191. res.type = t_string;
  192. res.value = llvm_const_named_struct(p->module, t_string, values, gb_count_of(values));
  193. return res;
  194. } else {
  195. lbAddr res = lb_add_local_generated(p, t_string, false);
  196. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  197. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  198. return lb_addr_load(p, res);
  199. }
  200. }
  201. gb_internal lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  202. Type *src_type = value.type;
  203. if (are_types_identical(t, src_type)) {
  204. return value;
  205. }
  206. lbValue res = {};
  207. res.type = t;
  208. Type *src = base_type(src_type);
  209. Type *dst = base_type(t);
  210. lbModule *m = p->module;
  211. i64 sz = type_size_of(src);
  212. i64 dz = type_size_of(dst);
  213. if (sz != dz) {
  214. LLVMTypeRef s = lb_type(m, src);
  215. LLVMTypeRef d = lb_type(m, dst);
  216. i64 llvm_sz = lb_sizeof(s);
  217. i64 llvm_dz = lb_sizeof(d);
  218. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  219. }
  220. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  221. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  222. if (is_type_internally_pointer_like(src)) {
  223. if (is_type_integer(dst)) {
  224. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  225. return res;
  226. } else if (is_type_internally_pointer_like(dst)) {
  227. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  228. return res;
  229. } else if (is_type_float(dst)) {
  230. LLVMValueRef the_int = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t_uintptr), "");
  231. res.value = LLVMBuildBitCast(p->builder, the_int, lb_type(m, t), "");
  232. return res;
  233. }
  234. }
  235. if (is_type_internally_pointer_like(dst)) {
  236. if (is_type_uintptr(src) && is_type_internally_pointer_like(dst)) {
  237. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  238. return res;
  239. } else if (is_type_integer(src) && is_type_internally_pointer_like(dst)) {
  240. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  241. return res;
  242. } else if (is_type_float(src)) {
  243. LLVMValueRef the_int = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t_uintptr), "");
  244. res.value = LLVMBuildIntToPtr(p->builder, the_int, lb_type(m, t), "");
  245. return res;
  246. }
  247. }
  248. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  249. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  250. return res;
  251. } else if (is_type_array_like(src) && (is_type_simd_vector(dst) || is_type_integer_128bit(dst))) {
  252. unsigned align = cast(unsigned)gb_max(type_align_of(src), type_align_of(dst));
  253. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  254. if (lb_try_update_alignment(ptr, align)) {
  255. LLVMTypeRef result_type = lb_type(p->module, t);
  256. res.value = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(result_type, 0), "");
  257. res.value = OdinLLVMBuildLoad(p, result_type, res.value);
  258. return res;
  259. }
  260. lbAddr addr = lb_add_local_generated(p, t, false);
  261. lbValue ap = lb_addr_get_ptr(p, addr);
  262. ap = lb_emit_conv(p, ap, alloc_type_pointer(value.type));
  263. lb_emit_store(p, ap, value);
  264. return lb_addr_load(p, addr);
  265. } else if (is_type_map(src) && are_types_identical(t_raw_map, t)) {
  266. res.value = value.value;
  267. res.type = t;
  268. return res;
  269. } else if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  270. lbValue s = lb_address_from_load_or_generate_local(p, value);
  271. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  272. return lb_emit_load(p, d);
  273. }
  274. res.value = OdinLLVMBuildTransmute(p, value.value, lb_type(m, res.type));
  275. return res;
  276. }
  277. gb_internal lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  278. i64 type_alignment = type_align_of(new_type);
  279. if (alignment < type_alignment) {
  280. alignment = type_alignment;
  281. }
  282. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  283. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  284. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  285. lb_addr_store(p, ptr, val);
  286. // ptr.kind = lbAddr_Context;
  287. return ptr.addr;
  288. }
  289. gb_internal lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  290. GB_ASSERT(ce->args.count > 0);
  291. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  292. for_array(i, slices) {
  293. Ast *arg = ce->args[i];
  294. if (arg->kind == Ast_FieldValue) {
  295. arg = arg->FieldValue.value;
  296. }
  297. slices[i] = lb_build_expr(p, arg);
  298. }
  299. lbValue len = lb_slice_len(p, slices[0]);
  300. for (isize i = 1; i < slices.count; i++) {
  301. lbValue other_len = lb_slice_len(p, slices[i]);
  302. len = lb_emit_min(p, t_int, len, other_len);
  303. }
  304. GB_ASSERT(is_type_soa_struct(tv.type));
  305. lbAddr res = lb_add_local_generated(p, tv.type, true);
  306. for_array(i, slices) {
  307. lbValue src = lb_slice_elem(p, slices[i]);
  308. src = lb_emit_conv(p, src, alloc_type_pointer_to_multi_pointer(src.type));
  309. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  310. lb_emit_store(p, dst, src);
  311. }
  312. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  313. lb_emit_store(p, len_dst, len);
  314. return lb_addr_load(p, res);
  315. }
  316. gb_internal lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  317. GB_ASSERT(ce->args.count == 1);
  318. lbValue arg = lb_build_expr(p, ce->args[0]);
  319. Type *t = base_type(arg.type);
  320. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  321. lbValue len = lb_soa_struct_len(p, arg);
  322. lbAddr res = lb_add_local_generated(p, tv.type, true);
  323. if (is_type_tuple(tv.type)) {
  324. lbValue rp = lb_addr_get_ptr(p, res);
  325. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  326. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  327. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  328. lb_fill_slice(p, dst, ptr, len);
  329. }
  330. } else {
  331. GB_ASSERT(is_type_slice(tv.type));
  332. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  333. lb_fill_slice(p, res, ptr, len);
  334. }
  335. return lb_addr_load(p, res);
  336. }
  337. gb_internal void lb_emit_try_lhs_rhs(lbProcedure *p, Ast *arg, TypeAndValue const &tv, lbValue *lhs_, lbValue *rhs_) {
  338. lbValue lhs = {};
  339. lbValue rhs = {};
  340. lbValue value = lb_build_expr(p, arg);
  341. if (is_type_tuple(value.type)) {
  342. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  343. if (value.type->Tuple.variables.count == 2) {
  344. lhs = lb_emit_tuple_ev(p, value, 0);
  345. } else {
  346. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  347. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  348. for (i32 i = 0; i < n; i++) {
  349. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_tuple_ev(p, value, i));
  350. }
  351. lhs = lb_addr_load(p, lhs_addr);
  352. }
  353. rhs = lb_emit_tuple_ev(p, value, n);
  354. } else {
  355. rhs = value;
  356. }
  357. GB_ASSERT(rhs.value != nullptr);
  358. if (lhs_) *lhs_ = lhs;
  359. if (rhs_) *rhs_ = rhs;
  360. }
  361. gb_internal lbValue lb_emit_try_has_value(lbProcedure *p, lbValue rhs) {
  362. lbValue has_value = {};
  363. if (is_type_boolean(rhs.type)) {
  364. has_value = rhs;
  365. } else {
  366. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  367. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  368. }
  369. GB_ASSERT(has_value.value != nullptr);
  370. return has_value;
  371. }
  372. gb_internal lbValue lb_emit_or_else(lbProcedure *p, Ast *arg, Ast *else_expr, TypeAndValue const &tv) {
  373. if (arg->state_flags & StateFlag_DirectiveWasFalse) {
  374. return lb_build_expr(p, else_expr);
  375. }
  376. lbValue lhs = {};
  377. lbValue rhs = {};
  378. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  379. GB_ASSERT(else_expr != nullptr);
  380. Type *type = default_type(tv.type);
  381. if (is_diverging_expr(else_expr)) {
  382. lbBlock *then = lb_create_block(p, "or_else.then");
  383. lbBlock *else_ = lb_create_block(p, "or_else.else");
  384. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  385. // NOTE(bill): else block needs to be straight afterwards to make sure that the actual value is used
  386. // from the then block
  387. lb_start_block(p, else_);
  388. lb_build_expr(p, else_expr);
  389. lb_emit_unreachable(p); // add just in case
  390. lb_start_block(p, then);
  391. return lb_emit_conv(p, lhs, type);
  392. } else {
  393. LLVMValueRef incoming_values[2] = {};
  394. LLVMBasicBlockRef incoming_blocks[2] = {};
  395. lbBlock *then = lb_create_block(p, "or_else.then");
  396. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  397. lbBlock *else_ = lb_create_block(p, "or_else.else");
  398. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  399. lb_start_block(p, then);
  400. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  401. lb_emit_jump(p, done);
  402. lb_start_block(p, else_);
  403. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_expr), type).value;
  404. lb_emit_jump(p, done);
  405. lb_start_block(p, done);
  406. lbValue res = {};
  407. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  408. res.type = type;
  409. GB_ASSERT(p->curr_block->preds.count >= 2);
  410. incoming_blocks[0] = p->curr_block->preds[0]->block;
  411. incoming_blocks[1] = p->curr_block->preds[1]->block;
  412. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  413. return res;
  414. }
  415. }
  416. gb_internal void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results, TokenPos pos);
  417. gb_internal void lb_build_return_stmt_internal(lbProcedure *p, lbValue res, TokenPos pos);
  418. gb_internal lbValue lb_emit_or_return(lbProcedure *p, Ast *arg, TypeAndValue const &tv) {
  419. lbValue lhs = {};
  420. lbValue rhs = {};
  421. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  422. lbBlock *return_block = lb_create_block(p, "or_return.return");
  423. lbBlock *continue_block = lb_create_block(p, "or_return.continue");
  424. lb_emit_if(p, lb_emit_try_has_value(p, rhs), continue_block, return_block);
  425. lb_start_block(p, return_block);
  426. {
  427. Type *proc_type = base_type(p->type);
  428. Type *results = proc_type->Proc.results;
  429. GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  430. TypeTuple *tuple = &results->Tuple;
  431. GB_ASSERT(tuple->variables.count != 0);
  432. Entity *end_entity = tuple->variables[tuple->variables.count-1];
  433. rhs = lb_emit_conv(p, rhs, end_entity->type);
  434. if (p->type->Proc.has_named_results) {
  435. GB_ASSERT(end_entity->token.string.len != 0);
  436. // NOTE(bill): store the named values before returning
  437. lbValue found = map_must_get(&p->module->values, end_entity);
  438. lb_emit_store(p, found, rhs);
  439. lb_build_return_stmt(p, {}, ast_token(arg).pos);
  440. } else {
  441. GB_ASSERT(tuple->variables.count == 1);
  442. lb_build_return_stmt_internal(p, rhs, ast_token(arg).pos);
  443. }
  444. }
  445. lb_start_block(p, continue_block);
  446. if (tv.type != nullptr) {
  447. return lb_emit_conv(p, lhs, tv.type);
  448. }
  449. return {};
  450. }
  451. gb_internal void lb_emit_increment(lbProcedure *p, lbValue addr) {
  452. GB_ASSERT(is_type_pointer(addr.type));
  453. Type *type = type_deref(addr.type);
  454. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  455. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  456. }
  457. gb_internal lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  458. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  459. if (type_size_of(value.type) < 2) {
  460. return value;
  461. }
  462. Type *original_type = value.type;
  463. if (is_type_float(original_type)) {
  464. i64 sz = type_size_of(original_type);
  465. Type *integer_type = nullptr;
  466. switch (sz) {
  467. case 2: integer_type = t_u16; break;
  468. case 4: integer_type = t_u32; break;
  469. case 8: integer_type = t_u64; break;
  470. }
  471. GB_ASSERT(integer_type != nullptr);
  472. value = lb_emit_transmute(p, value, integer_type);
  473. }
  474. char const *name = "llvm.bswap";
  475. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  476. LLVMValueRef args[1] = { value.value };
  477. lbValue res = {};
  478. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  479. res.type = value.type;
  480. if (is_type_float(original_type)) {
  481. res = lb_emit_transmute(p, res, original_type);
  482. }
  483. res.type = end_type;
  484. return res;
  485. }
  486. gb_internal lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  487. x = lb_emit_conv(p, x, type);
  488. char const *name = "llvm.ctpop";
  489. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  490. LLVMValueRef args[1] = { x.value };
  491. lbValue res = {};
  492. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  493. res.type = type;
  494. return res;
  495. }
  496. gb_internal lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  497. Type *elem = base_array_type(type);
  498. i64 sz = 8*type_size_of(elem);
  499. lbValue size = lb_const_int(p->module, elem, cast(u64)sz);
  500. size = lb_emit_conv(p, size, type);
  501. lbValue count = lb_emit_count_ones(p, x, type);
  502. return lb_emit_arith(p, Token_Sub, size, count, type);
  503. }
  504. gb_internal lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  505. x = lb_emit_conv(p, x, type);
  506. char const *name = "llvm.cttz";
  507. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  508. LLVMValueRef args[2] = {
  509. x.value,
  510. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  511. lbValue res = {};
  512. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  513. res.type = type;
  514. return res;
  515. }
  516. gb_internal lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  517. x = lb_emit_conv(p, x, type);
  518. char const *name = "llvm.ctlz";
  519. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  520. LLVMValueRef args[2] = {
  521. x.value,
  522. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  523. lbValue res = {};
  524. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  525. res.type = type;
  526. return res;
  527. }
  528. gb_internal lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  529. x = lb_emit_conv(p, x, type);
  530. char const *name = "llvm.bitreverse";
  531. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  532. LLVMValueRef args[1] = { x.value };
  533. lbValue res = {};
  534. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  535. res.type = type;
  536. return res;
  537. }
  538. gb_internal lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  539. GB_ASSERT(is_type_tuple(type));
  540. lbModule *m = p->module;
  541. Type *src_type = value.type;
  542. bool is_ptr = is_type_pointer(src_type);
  543. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  544. // so when it does an assignment, it complete ignores the value.
  545. // Just make it two booleans and ignore the first one
  546. //
  547. // _, ok := x.(T);
  548. //
  549. Type *ok_type = type->Tuple.variables[1]->type;
  550. Type *gen_tuple_types[2] = {};
  551. gen_tuple_types[0] = ok_type;
  552. gen_tuple_types[1] = ok_type;
  553. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  554. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  555. if (is_ptr) {
  556. value = lb_emit_load(p, value);
  557. }
  558. Type *src = base_type(type_deref(src_type));
  559. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  560. Type *dst = type->Tuple.variables[0]->type;
  561. lbValue cond = {};
  562. if (is_type_union_maybe_pointer(src)) {
  563. lbValue data = lb_emit_transmute(p, value, dst);
  564. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  565. } else {
  566. lbValue tag = lb_emit_union_tag_value(p, value);
  567. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  568. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  569. }
  570. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  571. lb_emit_store(p, gep1, cond);
  572. return lb_addr_load(p, v);
  573. }
  574. gb_internal lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  575. lbModule *m = p->module;
  576. Type *src_type = value.type;
  577. bool is_ptr = is_type_pointer(src_type);
  578. bool is_tuple = true;
  579. Type *tuple = type;
  580. if (type->kind != Type_Tuple) {
  581. is_tuple = false;
  582. tuple = make_optional_ok_type(type);
  583. }
  584. lbAddr v = lb_add_local_generated(p, tuple, true);
  585. if (is_ptr) {
  586. value = lb_emit_load(p, value);
  587. }
  588. Type *src = base_type(type_deref(src_type));
  589. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  590. Type *dst = tuple->Tuple.variables[0]->type;
  591. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  592. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  593. // just do a bit cast of the data at the front
  594. lbValue ptr = lb_emit_conv(p, value_, alloc_type_pointer(type));
  595. return lb_emit_load(p, ptr);
  596. }
  597. lbValue tag = {};
  598. lbValue dst_tag = {};
  599. lbValue cond = {};
  600. lbValue data = {};
  601. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  602. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  603. if (is_type_union_maybe_pointer(src)) {
  604. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  605. } else {
  606. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  607. dst_tag = lb_const_union_tag(m, src, dst);
  608. }
  609. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  610. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  611. if (data.value != nullptr) {
  612. GB_ASSERT(is_type_union_maybe_pointer(src));
  613. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  614. } else {
  615. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  616. }
  617. lb_emit_if(p, cond, ok_block, end_block);
  618. lb_start_block(p, ok_block);
  619. if (data.value == nullptr) {
  620. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  621. }
  622. lb_emit_store(p, gep0, data);
  623. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  624. lb_emit_jump(p, end_block);
  625. lb_start_block(p, end_block);
  626. if (!is_tuple) {
  627. if (!build_context.no_type_assert) {
  628. GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0);
  629. // NOTE(bill): Panic on invalid conversion
  630. Type *dst_type = tuple->Tuple.variables[0]->type;
  631. isize arg_count = 7;
  632. if (build_context.no_rtti) {
  633. arg_count = 4;
  634. }
  635. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  636. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  637. args[0] = ok;
  638. lb_set_file_line_col(p, array_slice(args, 1, args.count), pos);
  639. if (!build_context.no_rtti) {
  640. args[4] = lb_typeid(m, src_type);
  641. args[5] = lb_typeid(m, dst_type);
  642. args[6] = lb_emit_conv(p, value_, t_rawptr);
  643. }
  644. lb_emit_runtime_call(p, "type_assertion_check2", args);
  645. }
  646. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  647. }
  648. return lb_addr_load(p, v);
  649. }
  650. gb_internal lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  651. lbModule *m = p->module;
  652. Type *src_type = value.type;
  653. if (is_type_pointer(src_type)) {
  654. value = lb_emit_load(p, value);
  655. }
  656. bool is_tuple = true;
  657. Type *tuple = type;
  658. if (type->kind != Type_Tuple) {
  659. is_tuple = false;
  660. tuple = make_optional_ok_type(type);
  661. }
  662. Type *dst_type = tuple->Tuple.variables[0]->type;
  663. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  664. // just do a bit cast of the data at the front
  665. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  666. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(type));
  667. return lb_addr(ptr);
  668. }
  669. lbAddr v = lb_add_local_generated(p, tuple, true);
  670. lbValue dst_typeid = lb_typeid(m, dst_type);
  671. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  672. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  673. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  674. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  675. lb_emit_if(p, cond, ok_block, end_block);
  676. lb_start_block(p, ok_block);
  677. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  678. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  679. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  680. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  681. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  682. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  683. lb_emit_jump(p, end_block);
  684. lb_start_block(p, end_block);
  685. if (!is_tuple) {
  686. // NOTE(bill): Panic on invalid conversion
  687. if (!build_context.no_type_assert) {
  688. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  689. isize arg_count = 7;
  690. if (build_context.no_rtti) {
  691. arg_count = 4;
  692. }
  693. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  694. args[0] = ok;
  695. lb_set_file_line_col(p, array_slice(args, 1, args.count), pos);
  696. if (!build_context.no_rtti) {
  697. args[4] = any_typeid;
  698. args[5] = dst_typeid;
  699. args[6] = lb_emit_struct_ev(p, value, 0);
  700. }
  701. lb_emit_runtime_call(p, "type_assertion_check2", args);
  702. }
  703. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  704. }
  705. return v;
  706. }
  707. gb_internal lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  708. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  709. }
  710. gb_internal lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  711. if (p->context_stack.count > 0) {
  712. return p->context_stack[p->context_stack.count-1].ctx;
  713. }
  714. Type *pt = base_type(p->type);
  715. GB_ASSERT(pt->kind == Type_Proc);
  716. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  717. lbAddr c = lb_add_local_generated(p, t_context, true);
  718. c.kind = lbAddr_Context;
  719. lb_emit_init_context(p, c);
  720. lb_push_context_onto_stack(p, c);
  721. lb_add_debug_context_variable(p, c);
  722. return c;
  723. }
  724. gb_internal lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  725. if (LLVMIsALoadInst(value.value)) {
  726. lbValue res = {};
  727. res.value = LLVMGetOperand(value.value, 0);
  728. res.type = alloc_type_pointer(value.type);
  729. return res;
  730. }
  731. GB_ASSERT(is_type_typed(value.type));
  732. lbAddr res = lb_add_local_generated(p, value.type, false);
  733. lb_addr_store(p, res, value);
  734. return res.addr;
  735. }
  736. gb_internal lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  737. if (LLVMIsALoadInst(value.value)) {
  738. lbValue res = {};
  739. res.value = LLVMGetOperand(value.value, 0);
  740. res.type = alloc_type_pointer(value.type);
  741. return res;
  742. }
  743. GB_PANIC("lb_address_from_load");
  744. return {};
  745. }
  746. gb_internal lbValue lb_address_from_load_if_readonly_parameter(lbProcedure *p, lbValue x) {
  747. if (!LLVMIsALoadInst(x.value)) {
  748. return {};
  749. }
  750. LLVMValueRef optr = LLVMGetOperand(x.value, 0);
  751. while (optr && LLVMIsABitCastInst(optr)) {
  752. optr = LLVMGetOperand(optr, 0);
  753. }
  754. LLVMAttributeIndex param_index = 1;
  755. if (p->return_ptr.addr.value) {
  756. param_index++;
  757. }
  758. bool is_parameter = false;
  759. for (LLVMValueRef param : p->raw_input_parameters) {
  760. if (param == optr) {
  761. is_parameter = true;
  762. break;
  763. }
  764. param_index++;
  765. }
  766. if (is_parameter) {
  767. unsigned readonly_attr_kind = LLVMGetEnumAttributeKindForName("readonly", 8);
  768. unsigned n = LLVMGetAttributeCountAtIndex(p->value, param_index);
  769. if (n) {
  770. TEMPORARY_ALLOCATOR_GUARD();
  771. LLVMAttributeRef *attrs = gb_alloc_array(temporary_allocator(), LLVMAttributeRef, n);
  772. LLVMGetAttributesAtIndex(p->value, param_index, attrs);
  773. for (unsigned i = 0; i < n; i++) {
  774. if (LLVMGetEnumAttributeKind(attrs[i]) == readonly_attr_kind) {
  775. return lb_address_from_load_or_generate_local(p, x);
  776. }
  777. }
  778. }
  779. }
  780. return {};
  781. }
  782. gb_internal lbStructFieldRemapping lb_get_struct_remapping(lbModule *m, Type *t) {
  783. t = base_type(t);
  784. LLVMTypeRef struct_type = lb_type(m, t);
  785. mutex_lock(&m->types_mutex);
  786. auto *field_remapping = map_get(&m->struct_field_remapping, cast(void *)struct_type);
  787. if (field_remapping == nullptr) {
  788. field_remapping = map_get(&m->struct_field_remapping, cast(void *)t);
  789. }
  790. mutex_unlock(&m->types_mutex);
  791. GB_ASSERT_MSG(field_remapping != nullptr, "%s", type_to_string(t));
  792. return *field_remapping;
  793. }
  794. gb_internal i32 lb_convert_struct_index(lbModule *m, Type *t, i32 index) {
  795. if (t->kind == Type_Struct) {
  796. auto field_remapping = lb_get_struct_remapping(m, t);
  797. return field_remapping[index];
  798. } else if (is_type_any(t) && build_context.ptr_size == 4) {
  799. GB_ASSERT(t->kind == Type_Basic);
  800. GB_ASSERT(t->Basic.kind == Basic_any);
  801. switch (index) {
  802. case 0: return 0; // data
  803. case 1: return 2; // id
  804. }
  805. } else if (build_context.ptr_size != build_context.int_size) {
  806. switch (t->kind) {
  807. case Type_Basic:
  808. if (t->Basic.kind != Basic_string &&
  809. t->Basic.kind != Basic_string16) {
  810. break;
  811. }
  812. /*fallthrough*/
  813. case Type_Slice:
  814. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  815. switch (index) {
  816. case 0: return 0; // data
  817. case 1: return 2; // len
  818. }
  819. break;
  820. case Type_DynamicArray:
  821. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  822. switch (index) {
  823. case 0: return 0; // data
  824. case 1: return 2; // len
  825. case 2: return 3; // cap
  826. case 3: return 4; // allocator
  827. }
  828. break;
  829. case Type_SoaPointer:
  830. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  831. switch (index) {
  832. case 0: return 0; // data
  833. case 1: return 2; // offset
  834. }
  835. break;
  836. }
  837. }
  838. return index;
  839. }
  840. gb_internal LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 padding_align) {
  841. MUTEX_GUARD(&m->pad_types_mutex);
  842. if (padding % padding_align == 0) {
  843. for (auto pd : m->pad_types) {
  844. if (pd.padding == padding && pd.padding_align == padding_align) {
  845. return pd.type;
  846. }
  847. }
  848. } else {
  849. for (auto pd : m->pad_types) {
  850. if (pd.padding == padding && pd.padding_align == 1) {
  851. return pd.type;
  852. }
  853. }
  854. }
  855. // NOTE(bill): limit to `[N x u64]` to prevent ABI issues
  856. padding_align = gb_clamp(padding_align, 1, 8);
  857. if (padding % padding_align == 0) {
  858. LLVMTypeRef elem = nullptr;
  859. isize len = padding/padding_align;
  860. switch (padding_align) {
  861. case 1: elem = lb_type(m, t_u8); break;
  862. case 2: elem = lb_type(m, t_u16); break;
  863. case 4: elem = lb_type(m, t_u32); break;
  864. case 8: elem = lb_type(m, t_u64); break;
  865. }
  866. GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
  867. LLVMTypeRef type = nullptr;
  868. if (len != 1) {
  869. type = llvm_array_type(elem, len);
  870. } else {
  871. type = elem;
  872. }
  873. array_add(&m->pad_types, lbPadType{padding, padding_align, type});
  874. return type;
  875. } else {
  876. LLVMTypeRef type = llvm_array_type(lb_type(m, t_u8), padding);
  877. array_add(&m->pad_types, lbPadType{padding, 1, type});
  878. return type;
  879. }
  880. }
  881. gb_global char const *llvm_type_kinds[] = {
  882. "LLVMVoidTypeKind",
  883. "LLVMHalfTypeKind",
  884. "LLVMFloatTypeKind",
  885. "LLVMDoubleTypeKind",
  886. "LLVMX86_FP80TypeKind",
  887. "LLVMFP128TypeKind",
  888. "LLVMPPC_FP128TypeKind",
  889. "LLVMLabelTypeKind",
  890. "LLVMIntegerTypeKind",
  891. "LLVMFunctionTypeKind",
  892. "LLVMStructTypeKind",
  893. "LLVMArrayTypeKind",
  894. "LLVMPointerTypeKind",
  895. "LLVMVectorTypeKind",
  896. "LLVMMetadataTypeKind",
  897. "LLVMX86_MMXTypeKind",
  898. "LLVMTokenTypeKind",
  899. "LLVMScalableVectorTypeKind",
  900. "LLVMBFloatTypeKind",
  901. };
  902. gb_internal lbValue lb_emit_struct_ep_internal(lbProcedure *p, lbValue s, i32 index, Type *result_type) {
  903. Type *t = base_type(type_deref(s.type));
  904. i32 original_index = index;
  905. index = lb_convert_struct_index(p->module, t, index);
  906. if (lb_is_const(s)) {
  907. // NOTE(bill): this cannot be replaced with lb_emit_epi
  908. lbModule *m = p->module;
  909. lbValue res = {};
  910. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  911. res.value = LLVMConstGEP2(lb_type(m, type_deref(s.type)), s.value, indices, gb_count_of(indices));
  912. res.type = alloc_type_pointer(result_type);
  913. return res;
  914. } else {
  915. lbValue res = {};
  916. LLVMTypeRef st = lb_type(p->module, type_deref(s.type));
  917. // gb_printf_err("%s\n", type_to_string(s.type));
  918. // gb_printf_err("%s\n", LLVMPrintTypeToString(LLVMTypeOf(s.value)));
  919. // gb_printf_err("%d\n", index);
  920. GB_ASSERT_MSG(LLVMGetTypeKind(st) == LLVMStructTypeKind, "%s", llvm_type_kinds[LLVMGetTypeKind(st)]);
  921. unsigned count = LLVMCountStructElementTypes(st);
  922. GB_ASSERT_MSG(count >= cast(unsigned)index, "%u %d %d", count, index, original_index);
  923. res.value = LLVMBuildStructGEP2(p->builder, st, s.value, cast(unsigned)index, "");
  924. res.type = alloc_type_pointer(result_type);
  925. return res;
  926. }
  927. }
  928. gb_internal lbValue lb_emit_tuple_ep(lbProcedure *p, lbValue ptr, i32 index) {
  929. Type *t = type_deref(ptr.type);
  930. GB_ASSERT(is_type_tuple(t));
  931. Type *result_type = t->Tuple.variables[index]->type;
  932. lbValue res = {};
  933. lbTupleFix *tf = map_get(&p->tuple_fix_map, ptr.value);
  934. if (tf) {
  935. res = tf->values[index];
  936. GB_ASSERT(are_types_identical(res.type, result_type));
  937. res = lb_address_from_load_or_generate_local(p, res);
  938. } else {
  939. res = lb_emit_struct_ep_internal(p, ptr, index, result_type);
  940. }
  941. return res;
  942. }
  943. gb_internal lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  944. GB_ASSERT(is_type_pointer(s.type));
  945. Type *t = base_type(type_deref(s.type));
  946. Type *result_type = nullptr;
  947. if (is_type_struct(t)) {
  948. result_type = get_struct_field_type(t, index);
  949. } else if (is_type_union(t)) {
  950. GB_ASSERT(index == -1);
  951. return lb_emit_union_tag_ptr(p, s);
  952. } else if (is_type_tuple(t)) {
  953. return lb_emit_tuple_ep(p, s, index);
  954. } else if (is_type_complex(t)) {
  955. Type *ft = base_complex_elem_type(t);
  956. switch (index) {
  957. case 0: result_type = ft; break;
  958. case 1: result_type = ft; break;
  959. }
  960. } else if (is_type_quaternion(t)) {
  961. Type *ft = base_complex_elem_type(t);
  962. switch (index) {
  963. case 0: result_type = ft; break;
  964. case 1: result_type = ft; break;
  965. case 2: result_type = ft; break;
  966. case 3: result_type = ft; break;
  967. }
  968. } else if (is_type_slice(t)) {
  969. switch (index) {
  970. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  971. case 1: result_type = t_int; break;
  972. }
  973. } else if (is_type_string16(t)) {
  974. switch (index) {
  975. case 0: result_type = t_u16_ptr; break;
  976. case 1: result_type = t_int; break;
  977. }
  978. } else if (is_type_string(t)) {
  979. switch (index) {
  980. case 0: result_type = t_u8_ptr; break;
  981. case 1: result_type = t_int; break;
  982. }
  983. } else if (is_type_any(t)) {
  984. switch (index) {
  985. case 0: result_type = t_rawptr; break;
  986. case 1: result_type = t_typeid; break;
  987. }
  988. } else if (is_type_dynamic_array(t)) {
  989. switch (index) {
  990. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  991. case 1: result_type = t_int; break;
  992. case 2: result_type = t_int; break;
  993. case 3: result_type = t_allocator; break;
  994. }
  995. } else if (is_type_map(t)) {
  996. init_map_internal_debug_types(t);
  997. Type *itp = alloc_type_pointer(t_raw_map);
  998. s = lb_emit_transmute(p, s, itp);
  999. switch (index) {
  1000. case 0: result_type = get_struct_field_type(t_raw_map, 0); break;
  1001. case 1: result_type = get_struct_field_type(t_raw_map, 1); break;
  1002. case 2: result_type = get_struct_field_type(t_raw_map, 2); break;
  1003. }
  1004. } else if (is_type_array(t)) {
  1005. return lb_emit_array_epi(p, s, index);
  1006. } else if (is_type_soa_pointer(t)) {
  1007. switch (index) {
  1008. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  1009. case 1: result_type = t_int; break;
  1010. }
  1011. } else {
  1012. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  1013. }
  1014. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  1015. lbValue gep = lb_emit_struct_ep_internal(p, s, index, result_type);
  1016. Type *bt = base_type(t);
  1017. if (bt->kind == Type_Struct) {
  1018. if (bt->Struct.is_packed) {
  1019. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_IS_PACKED, 1);
  1020. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_IS_PACKED) == 1);
  1021. }
  1022. u64 align_max = bt->Struct.custom_max_field_align;
  1023. u64 align_min = bt->Struct.custom_min_field_align;
  1024. GB_ASSERT(align_min == 0 || align_max == 0 || align_min <= align_max);
  1025. if (align_max) {
  1026. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MAX_ALIGN, align_max);
  1027. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MAX_ALIGN) == align_max);
  1028. }
  1029. if (align_min) {
  1030. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MIN_ALIGN, align_min);
  1031. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MIN_ALIGN) == align_min);
  1032. }
  1033. }
  1034. return gep;
  1035. }
  1036. gb_internal lbValue lb_emit_tuple_ev(lbProcedure *p, lbValue value, i32 index) {
  1037. Type *t = value.type;
  1038. GB_ASSERT(is_type_tuple(t));
  1039. Type *result_type = t->Tuple.variables[index]->type;
  1040. lbValue res = {};
  1041. lbTupleFix *tf = map_get(&p->tuple_fix_map, value.value);
  1042. if (tf) {
  1043. res = tf->values[index];
  1044. GB_ASSERT(are_types_identical(res.type, result_type));
  1045. } else {
  1046. if (t->Tuple.variables.count == 1) {
  1047. GB_ASSERT(index == 0);
  1048. // value.type = result_type;
  1049. return value;
  1050. }
  1051. if (LLVMIsALoadInst(value.value)) {
  1052. lbValue res = {};
  1053. res.value = LLVMGetOperand(value.value, 0);
  1054. res.type = alloc_type_pointer(value.type);
  1055. lbValue ptr = lb_emit_struct_ep(p, res, index);
  1056. return lb_emit_load(p, ptr);
  1057. }
  1058. res.value = LLVMBuildExtractValue(p->builder, value.value, cast(unsigned)index, "");
  1059. res.type = result_type;
  1060. }
  1061. return res;
  1062. }
  1063. gb_internal lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  1064. Type *t = base_type(s.type);
  1065. if (is_type_tuple(t)) {
  1066. return lb_emit_tuple_ev(p, s, index);
  1067. }
  1068. if (LLVMIsALoadInst(s.value)) {
  1069. lbValue res = {};
  1070. res.value = LLVMGetOperand(s.value, 0);
  1071. res.type = alloc_type_pointer(s.type);
  1072. lbValue ptr = lb_emit_struct_ep(p, res, index);
  1073. return lb_emit_load(p, ptr);
  1074. }
  1075. Type *result_type = nullptr;
  1076. switch (t->kind) {
  1077. case Type_Basic:
  1078. switch (t->Basic.kind) {
  1079. case Basic_string16:
  1080. switch (index) {
  1081. case 0: result_type = t_u16_ptr; break;
  1082. case 1: result_type = t_int; break;
  1083. }
  1084. break;
  1085. case Basic_string:
  1086. switch (index) {
  1087. case 0: result_type = t_u8_ptr; break;
  1088. case 1: result_type = t_int; break;
  1089. }
  1090. break;
  1091. case Basic_any:
  1092. switch (index) {
  1093. case 0: result_type = t_rawptr; break;
  1094. case 1: result_type = t_typeid; break;
  1095. }
  1096. break;
  1097. case Basic_complex32:
  1098. case Basic_complex64:
  1099. case Basic_complex128:
  1100. {
  1101. Type *ft = base_complex_elem_type(t);
  1102. switch (index) {
  1103. case 0: result_type = ft; break;
  1104. case 1: result_type = ft; break;
  1105. }
  1106. break;
  1107. }
  1108. case Basic_quaternion64:
  1109. case Basic_quaternion128:
  1110. case Basic_quaternion256:
  1111. {
  1112. Type *ft = base_complex_elem_type(t);
  1113. switch (index) {
  1114. case 0: result_type = ft; break;
  1115. case 1: result_type = ft; break;
  1116. case 2: result_type = ft; break;
  1117. case 3: result_type = ft; break;
  1118. }
  1119. break;
  1120. }
  1121. }
  1122. break;
  1123. case Type_Struct:
  1124. result_type = get_struct_field_type(t, index);
  1125. break;
  1126. case Type_Union:
  1127. GB_ASSERT(index == -1);
  1128. // return lb_emit_union_tag_value(p, s);
  1129. GB_PANIC("lb_emit_union_tag_value");
  1130. case Type_Tuple:
  1131. return lb_emit_tuple_ev(p, s, index);
  1132. case Type_Slice:
  1133. switch (index) {
  1134. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  1135. case 1: result_type = t_int; break;
  1136. }
  1137. break;
  1138. case Type_DynamicArray:
  1139. switch (index) {
  1140. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  1141. case 1: result_type = t_int; break;
  1142. case 2: result_type = t_int; break;
  1143. case 3: result_type = t_allocator; break;
  1144. }
  1145. break;
  1146. case Type_Map:
  1147. {
  1148. init_map_internal_debug_types(t);
  1149. switch (index) {
  1150. case 0: result_type = get_struct_field_type(t_raw_map, 0); break;
  1151. case 1: result_type = get_struct_field_type(t_raw_map, 1); break;
  1152. case 2: result_type = get_struct_field_type(t_raw_map, 2); break;
  1153. }
  1154. }
  1155. break;
  1156. case Type_Array:
  1157. result_type = t->Array.elem;
  1158. break;
  1159. case Type_SoaPointer:
  1160. switch (index) {
  1161. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  1162. case 1: result_type = t_int; break;
  1163. }
  1164. break;
  1165. default:
  1166. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  1167. break;
  1168. }
  1169. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  1170. index = lb_convert_struct_index(p->module, t, index);
  1171. lbValue res = {};
  1172. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  1173. res.type = result_type;
  1174. return res;
  1175. }
  1176. gb_internal lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  1177. GB_ASSERT(sel.index.count > 0);
  1178. Type *type = type_deref(e.type);
  1179. for_array(i, sel.index) {
  1180. i32 index = cast(i32)sel.index[i];
  1181. if (is_type_pointer(type)) {
  1182. type = type_deref(type);
  1183. e = lb_emit_load(p, e);
  1184. }
  1185. type = core_type(type);
  1186. if (type->kind == Type_SoaPointer) {
  1187. lbValue addr = lb_emit_struct_ep(p, e, 0);
  1188. lbValue index = lb_emit_struct_ep(p, e, 1);
  1189. addr = lb_emit_load(p, addr);
  1190. index = lb_emit_load(p, index);
  1191. i32 first_index = sel.index[0];
  1192. Selection sub_sel = sel;
  1193. sub_sel.index.data += 1;
  1194. sub_sel.index.count -= 1;
  1195. lbValue arr = lb_emit_struct_ep(p, addr, first_index);
  1196. Type *t = base_type(type_deref(addr.type));
  1197. GB_ASSERT(is_type_soa_struct(t));
  1198. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1199. e = lb_emit_array_ep(p, arr, index);
  1200. } else {
  1201. e = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  1202. }
  1203. e.type = alloc_type_multi_pointer_to_pointer(e.type);
  1204. } else if (is_type_quaternion(type)) {
  1205. e = lb_emit_struct_ep(p, e, index);
  1206. } else if (is_type_raw_union(type)) {
  1207. type = get_struct_field_type(type, index);
  1208. GB_ASSERT(is_type_pointer(e.type));
  1209. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  1210. } else if (is_type_struct(type)) {
  1211. type = get_struct_field_type(type, index);
  1212. e = lb_emit_struct_ep(p, e, index);
  1213. } else if (type->kind == Type_Union) {
  1214. GB_ASSERT(index == -1);
  1215. type = t_type_info_ptr;
  1216. e = lb_emit_struct_ep(p, e, index);
  1217. } else if (type->kind == Type_Tuple) {
  1218. type = type->Tuple.variables[index]->type;
  1219. e = lb_emit_struct_ep(p, e, index);
  1220. } else if (type->kind == Type_Basic) {
  1221. switch (type->Basic.kind) {
  1222. case Basic_any: {
  1223. if (index == 0) {
  1224. type = t_rawptr;
  1225. } else if (index == 1) {
  1226. type = t_typeid;
  1227. }
  1228. e = lb_emit_struct_ep(p, e, index);
  1229. break;
  1230. }
  1231. case Basic_string:
  1232. e = lb_emit_struct_ep(p, e, index);
  1233. break;
  1234. case Basic_string16:
  1235. e = lb_emit_struct_ep(p, e, index);
  1236. break;
  1237. default:
  1238. GB_PANIC("un-gep-able type %s", type_to_string(type));
  1239. break;
  1240. }
  1241. } else if (type->kind == Type_Slice) {
  1242. e = lb_emit_struct_ep(p, e, index);
  1243. } else if (type->kind == Type_DynamicArray) {
  1244. e = lb_emit_struct_ep(p, e, index);
  1245. } else if (type->kind == Type_Array) {
  1246. e = lb_emit_array_epi(p, e, index);
  1247. } else if (type->kind == Type_Map) {
  1248. e = lb_emit_struct_ep(p, e, index);
  1249. } else {
  1250. GB_PANIC("un-gep-able type %s", type_to_string(type));
  1251. }
  1252. }
  1253. return e;
  1254. }
  1255. gb_internal lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  1256. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  1257. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  1258. return lb_emit_load(p, res);
  1259. }
  1260. gb_internal lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  1261. Type *t = s.type;
  1262. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  1263. Type *st = base_type(type_deref(t));
  1264. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1265. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  1266. LLVMValueRef indices[2] = {};
  1267. indices[0] = llvm_zero(p->module);
  1268. indices[1] = lb_emit_conv(p, index, t_int).value;
  1269. Type *ptr = base_array_type(st);
  1270. lbValue res = {};
  1271. if (LLVMIsConstant(s.value) && LLVMIsConstant(index.value)) {
  1272. res.value = LLVMConstGEP2(lb_type(p->module, st), s.value, indices, gb_count_of(indices));
  1273. } else {
  1274. res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, st), s.value, indices, gb_count_of(indices), "");
  1275. }
  1276. res.type = alloc_type_pointer(ptr);
  1277. return res;
  1278. }
  1279. gb_internal lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  1280. Type *t = s.type;
  1281. GB_ASSERT(is_type_pointer(t));
  1282. Type *st = base_type(type_deref(t));
  1283. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1284. GB_ASSERT(0 <= index);
  1285. return lb_emit_epi(p, s, index);
  1286. }
  1287. gb_internal lbValue lb_emit_array_epi(lbModule *m, lbValue s, isize index) {
  1288. Type *t = s.type;
  1289. GB_ASSERT(is_type_pointer(t));
  1290. Type *st = base_type(type_deref(t));
  1291. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1292. GB_ASSERT(0 <= index);
  1293. return lb_emit_epi(m, s, index);
  1294. }
  1295. gb_internal lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  1296. index = lb_emit_conv(p, index, t_int);
  1297. LLVMValueRef indices[1] = {index.value};
  1298. lbValue res = {};
  1299. res.type = ptr.type;
  1300. LLVMTypeRef type = lb_type(p->module, type_deref(res.type, true));
  1301. if (lb_is_const(ptr) && lb_is_const(index)) {
  1302. res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
  1303. } else {
  1304. res.value = LLVMBuildGEP2(p->builder, type, ptr.value, indices, 1, "");
  1305. }
  1306. return res;
  1307. }
  1308. gb_internal lbValue lb_const_ptr_offset(lbModule *m, lbValue ptr, lbValue index) {
  1309. LLVMValueRef indices[1] = {index.value};
  1310. lbValue res = {};
  1311. res.type = ptr.type;
  1312. LLVMTypeRef type = lb_type(m, type_deref(res.type, true));
  1313. GB_ASSERT(lb_is_const(ptr) && lb_is_const(index));
  1314. res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
  1315. return res;
  1316. }
  1317. gb_internal lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
  1318. Type *t = s.type;
  1319. GB_ASSERT(is_type_pointer(t));
  1320. Type *mt = base_type(type_deref(t));
  1321. if (!mt->Matrix.is_row_major) {
  1322. if (column == 0) {
  1323. GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt));
  1324. return lb_emit_epi(p, s, row);
  1325. } else if (row == 0 && is_type_array_like(mt)) {
  1326. return lb_emit_epi(p, s, column);
  1327. }
  1328. }
  1329. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1330. isize offset = matrix_indices_to_offset(mt, row, column);
  1331. return lb_emit_epi(p, s, offset);
  1332. }
  1333. gb_internal lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) {
  1334. Type *t = s.type;
  1335. GB_ASSERT(is_type_pointer(t));
  1336. Type *mt = base_type(type_deref(t));
  1337. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1338. Type *ptr = base_array_type(mt);
  1339. LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value;
  1340. row = lb_emit_conv(p, row, t_int);
  1341. column = lb_emit_conv(p, column, t_int);
  1342. LLVMValueRef index = nullptr;
  1343. if (mt->Matrix.is_row_major) {
  1344. index = LLVMBuildAdd(p->builder, column.value, LLVMBuildMul(p->builder, row.value, stride_elems, ""), "");
  1345. } else {
  1346. index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), "");
  1347. }
  1348. LLVMValueRef indices[2] = {
  1349. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1350. index,
  1351. };
  1352. LLVMTypeRef type = lb_type(p->module, mt);
  1353. lbValue res = {};
  1354. if (lb_is_const(s)) {
  1355. res.value = LLVMConstGEP2(type, s.value, indices, gb_count_of(indices));
  1356. } else {
  1357. res.value = LLVMBuildGEP2(p->builder, type, s.value, indices, gb_count_of(indices), "");
  1358. }
  1359. res.type = alloc_type_pointer(ptr);
  1360. return res;
  1361. }
  1362. gb_internal lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) {
  1363. Type *st = base_type(s.type);
  1364. GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st));
  1365. lbValue value = lb_address_from_load_or_generate_local(p, s);
  1366. lbValue ptr = lb_emit_matrix_epi(p, value, row, column);
  1367. return lb_emit_load(p, ptr);
  1368. }
  1369. gb_internal void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  1370. Type *t = lb_addr_type(slice);
  1371. GB_ASSERT(is_type_slice(t));
  1372. lbValue ptr = lb_addr_get_ptr(p, slice);
  1373. lbValue data = lb_emit_struct_ep(p, ptr, 0);
  1374. if (are_types_identical(type_deref(base_elem.type, true), type_deref(type_deref(data.type), true))) {
  1375. base_elem = lb_emit_conv(p, base_elem, type_deref(data.type));
  1376. }
  1377. lb_emit_store(p, data, base_elem);
  1378. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1379. }
  1380. gb_internal void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  1381. Type *t = lb_addr_type(string);
  1382. GB_ASSERT(is_type_string(t));
  1383. lbValue ptr = lb_addr_get_ptr(p, string);
  1384. lbValue data = lb_emit_struct_ep(p, ptr, 0);
  1385. if (are_types_identical(type_deref(base_elem.type, true), type_deref(type_deref(data.type), true))) {
  1386. base_elem = lb_emit_conv(p, base_elem, type_deref(data.type));
  1387. }
  1388. lb_emit_store(p, data, base_elem);
  1389. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1390. }
  1391. gb_internal lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  1392. Type *t = base_type(string.type);
  1393. if (t->kind == Type_Basic && t->Basic.kind == Basic_string16) {
  1394. return lb_emit_struct_ev(p, string, 0);
  1395. }
  1396. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  1397. return lb_emit_struct_ev(p, string, 0);
  1398. }
  1399. gb_internal lbValue lb_string_len(lbProcedure *p, lbValue string) {
  1400. Type *t = base_type(string.type);
  1401. if (t->kind == Type_Basic && t->Basic.kind == Basic_string16) {
  1402. return lb_emit_struct_ev(p, string, 1);
  1403. }
  1404. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  1405. return lb_emit_struct_ev(p, string, 1);
  1406. }
  1407. gb_internal lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  1408. GB_ASSERT(is_type_cstring(value.type));
  1409. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1410. args[0] = lb_emit_conv(p, value, t_cstring);
  1411. return lb_emit_runtime_call(p, "cstring_len", args);
  1412. }
  1413. gb_internal lbValue lb_cstring16_len(lbProcedure *p, lbValue value) {
  1414. GB_ASSERT(is_type_cstring16(value.type));
  1415. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1416. args[0] = lb_emit_conv(p, value, t_cstring16);
  1417. return lb_emit_runtime_call(p, "cstring16_len", args);
  1418. }
  1419. gb_internal lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  1420. Type *t = type_deref(array_ptr.type);
  1421. GB_ASSERT(is_type_array(t));
  1422. return lb_emit_struct_ep(p, array_ptr, 0);
  1423. }
  1424. gb_internal lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  1425. GB_ASSERT(is_type_slice(slice.type));
  1426. return lb_emit_struct_ev(p, slice, 0);
  1427. }
  1428. gb_internal lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  1429. GB_ASSERT(is_type_slice(slice.type));
  1430. return lb_emit_struct_ev(p, slice, 1);
  1431. }
  1432. gb_internal lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  1433. GB_ASSERT(is_type_dynamic_array(da.type));
  1434. return lb_emit_struct_ev(p, da, 0);
  1435. }
  1436. gb_internal lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  1437. GB_ASSERT(is_type_dynamic_array(da.type));
  1438. return lb_emit_struct_ev(p, da, 1);
  1439. }
  1440. gb_internal lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  1441. GB_ASSERT(is_type_dynamic_array(da.type));
  1442. return lb_emit_struct_ev(p, da, 2);
  1443. }
  1444. gb_internal lbValue lb_map_len(lbProcedure *p, lbValue value) {
  1445. GB_ASSERT_MSG(is_type_map(value.type) || are_types_identical(value.type, t_raw_map), "%s", type_to_string(value.type));
  1446. lbValue len = lb_emit_struct_ev(p, value, 1);
  1447. return lb_emit_conv(p, len, t_int);
  1448. }
  1449. gb_internal lbValue lb_map_len_ptr(lbProcedure *p, lbValue map_ptr) {
  1450. Type *type = map_ptr.type;
  1451. GB_ASSERT(is_type_pointer(type));
  1452. type = type_deref(type);
  1453. GB_ASSERT_MSG(is_type_map(type) || are_types_identical(type, t_raw_map), "%s", type_to_string(type));
  1454. return lb_emit_struct_ep(p, map_ptr, 1);
  1455. }
  1456. gb_internal lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  1457. GB_ASSERT_MSG(is_type_map(value.type) || are_types_identical(value.type, t_raw_map), "%s", type_to_string(value.type));
  1458. lbValue zero = lb_const_int(p->module, t_uintptr, 0);
  1459. lbValue one = lb_const_int(p->module, t_uintptr, 1);
  1460. lbValue mask = lb_const_int(p->module, t_uintptr, MAP_CACHE_LINE_SIZE-1);
  1461. lbValue data = lb_emit_struct_ev(p, value, 0);
  1462. lbValue log2_cap = lb_emit_arith(p, Token_And, data, mask, t_uintptr);
  1463. lbValue cap = lb_emit_arith(p, Token_Shl, one, log2_cap, t_uintptr);
  1464. lbValue cmp = lb_emit_comp(p, Token_CmpEq, data, zero);
  1465. return lb_emit_conv(p, lb_emit_select(p, cmp, zero, cap), t_int);
  1466. }
  1467. gb_internal lbValue lb_map_data_uintptr(lbProcedure *p, lbValue value) {
  1468. GB_ASSERT(is_type_map(value.type) || are_types_identical(value.type, t_raw_map));
  1469. lbValue data = lb_emit_struct_ev(p, value, 0);
  1470. u64 mask_value = 0;
  1471. if (build_context.ptr_size == 4) {
  1472. mask_value = 0xfffffffful & ~(MAP_CACHE_LINE_SIZE-1);
  1473. } else {
  1474. mask_value = 0xffffffffffffffffull & ~(MAP_CACHE_LINE_SIZE-1);
  1475. }
  1476. lbValue mask = lb_const_int(p->module, t_uintptr, mask_value);
  1477. return lb_emit_arith(p, Token_And, data, mask, t_uintptr);
  1478. }
  1479. gb_internal lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  1480. Type *t = base_type(value.type);
  1481. bool is_ptr = false;
  1482. if (is_type_pointer(t)) {
  1483. is_ptr = true;
  1484. t = base_type(type_deref(t));
  1485. }
  1486. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1487. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1488. }
  1489. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  1490. t->Struct.soa_kind == StructSoa_Dynamic);
  1491. isize n = 0;
  1492. Type *elem = base_type(t->Struct.soa_elem);
  1493. if (elem->kind == Type_Struct) {
  1494. n = cast(isize)elem->Struct.fields.count;
  1495. } else if (elem->kind == Type_Array) {
  1496. n = cast(isize)elem->Array.count;
  1497. } else {
  1498. GB_PANIC("Unreachable");
  1499. }
  1500. if (is_ptr) {
  1501. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1502. return lb_emit_load(p, v);
  1503. }
  1504. return lb_emit_struct_ev(p, value, cast(i32)n);
  1505. }
  1506. gb_internal lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  1507. Type *t = base_type(value.type);
  1508. bool is_ptr = false;
  1509. if (is_type_pointer(t)) {
  1510. is_ptr = true;
  1511. t = base_type(type_deref(t));
  1512. }
  1513. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1514. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1515. }
  1516. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  1517. isize n = 0;
  1518. Type *elem = base_type(t->Struct.soa_elem);
  1519. if (elem->kind == Type_Struct) {
  1520. n = cast(isize)elem->Struct.fields.count+1;
  1521. } else if (elem->kind == Type_Array) {
  1522. n = cast(isize)elem->Array.count+1;
  1523. } else {
  1524. GB_PANIC("Unreachable");
  1525. }
  1526. if (is_ptr) {
  1527. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1528. return lb_emit_load(p, v);
  1529. }
  1530. return lb_emit_struct_ev(p, value, cast(i32)n);
  1531. }
  1532. gb_internal lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) {
  1533. lbModule *m = p->module;
  1534. a = lb_emit_conv(p, a, t);
  1535. b = lb_emit_conv(p, b, t);
  1536. c = lb_emit_conv(p, c, t);
  1537. bool is_possible = !is_type_different_to_arch_endianness(t) && is_type_float(t);
  1538. if (is_possible) {
  1539. switch (build_context.metrics.arch) {
  1540. case TargetArch_amd64:
  1541. // NOTE: using the intrinsic when not supported causes slow codegen (See #2928).
  1542. if (type_size_of(t) == 2 || !check_target_feature_is_enabled(str_lit("fma"), nullptr)) {
  1543. is_possible = false;
  1544. }
  1545. break;
  1546. case TargetArch_arm64:
  1547. // possible
  1548. break;
  1549. case TargetArch_i386:
  1550. case TargetArch_wasm32:
  1551. case TargetArch_wasm64p32:
  1552. is_possible = false;
  1553. break;
  1554. }
  1555. }
  1556. if (is_possible) {
  1557. char const *name = "llvm.fma";
  1558. LLVMTypeRef types[1] = { lb_type(m, t) };
  1559. LLVMValueRef values[3] = {
  1560. a.value,
  1561. b.value,
  1562. c.value };
  1563. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1564. return {call, t};
  1565. } else {
  1566. lbValue x = lb_emit_arith(p, Token_Mul, a, b, t);
  1567. lbValue y = lb_emit_arith(p, Token_Add, x, c, t);
  1568. return y;
  1569. }
  1570. }
  1571. gb_internal LLVMValueRef llvm_mask_iota(lbModule *m, unsigned start, unsigned count) {
  1572. auto iota = slice_make<LLVMValueRef>(temporary_allocator(), count);
  1573. for (unsigned i = 0; i < count; i++) {
  1574. iota[i] = lb_const_int(m, t_u32, start+i).value;
  1575. }
  1576. return LLVMConstVector(iota.data, count);
  1577. }
  1578. gb_internal LLVMValueRef llvm_mask_zero(lbModule *m, unsigned count) {
  1579. return LLVMConstNull(LLVMVectorType(lb_type(m, t_u32), count));
  1580. }
  1581. #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMGetUndef((type))
  1582. // #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMConstNull((type))
  1583. gb_internal LLVMValueRef llvm_basic_shuffle(lbProcedure *p, LLVMValueRef vector, LLVMValueRef mask) {
  1584. return LLVMBuildShuffleVector(p->builder, vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask, "");
  1585. }
  1586. gb_internal LLVMValueRef llvm_basic_const_shuffle(LLVMValueRef vector, LLVMValueRef mask) {
  1587. return LLVMConstShuffleVector(vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask);
  1588. }
  1589. gb_internal LLVMValueRef llvm_vector_broadcast(lbProcedure *p, LLVMValueRef value, unsigned count) {
  1590. GB_ASSERT(count > 0);
  1591. if (LLVMIsConstant(value)) {
  1592. LLVMValueRef single = LLVMConstVector(&value, 1);
  1593. if (count == 1) {
  1594. return single;
  1595. }
  1596. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1597. return llvm_basic_const_shuffle(single, mask);
  1598. }
  1599. LLVMTypeRef single_type = LLVMVectorType(LLVMTypeOf(value), 1);
  1600. LLVMValueRef single = LLVMBuildBitCast(p->builder, value, single_type, "");
  1601. if (count == 1) {
  1602. return single;
  1603. }
  1604. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1605. return llvm_basic_shuffle(p, single, mask);
  1606. }
  1607. gb_internal LLVMValueRef llvm_vector_shuffle_reduction(lbProcedure *p, LLVMValueRef value, LLVMOpcode op_code) {
  1608. LLVMTypeRef original_vector_type = LLVMTypeOf(value);
  1609. GB_ASSERT(LLVMGetTypeKind(original_vector_type) == LLVMVectorTypeKind);
  1610. unsigned len = LLVMGetVectorSize(original_vector_type);
  1611. LLVMValueRef v_zero32 = lb_const_int(p->module, t_u32, 0).value;
  1612. if (len == 1) {
  1613. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1614. }
  1615. GB_ASSERT((len & (len-1)) == 0);
  1616. for (unsigned i = len; i != 1; i >>= 1) {
  1617. unsigned mask_len = i/2;
  1618. LLVMValueRef lhs_mask = llvm_mask_iota(p->module, 0, mask_len);
  1619. LLVMValueRef rhs_mask = llvm_mask_iota(p->module, mask_len, mask_len);
  1620. GB_ASSERT(LLVMTypeOf(lhs_mask) == LLVMTypeOf(rhs_mask));
  1621. LLVMValueRef lhs = llvm_basic_shuffle(p, value, lhs_mask);
  1622. LLVMValueRef rhs = llvm_basic_shuffle(p, value, rhs_mask);
  1623. GB_ASSERT(LLVMTypeOf(lhs) == LLVMTypeOf(rhs));
  1624. value = LLVMBuildBinOp(p->builder, op_code, lhs, rhs, "");
  1625. }
  1626. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1627. }
  1628. gb_internal LLVMValueRef llvm_vector_expand_to_power_of_two(lbProcedure *p, LLVMValueRef value) {
  1629. LLVMTypeRef vector_type = LLVMTypeOf(value);
  1630. unsigned len = LLVMGetVectorSize(vector_type);
  1631. if (len == 1) {
  1632. return value;
  1633. }
  1634. if ((len & (len-1)) == 0) {
  1635. return value;
  1636. }
  1637. unsigned expanded_len = cast(unsigned)next_pow2(cast(i64)len);
  1638. LLVMValueRef mask = llvm_mask_iota(p->module, 0, expanded_len);
  1639. return LLVMBuildShuffleVector(p->builder, value, LLVMConstNull(vector_type), mask, "");
  1640. }
  1641. gb_internal LLVMValueRef llvm_vector_reduce_add(lbProcedure *p, LLVMValueRef value) {
  1642. LLVMTypeRef type = LLVMTypeOf(value);
  1643. GB_ASSERT(LLVMGetTypeKind(type) == LLVMVectorTypeKind);
  1644. LLVMTypeRef elem = OdinLLVMGetVectorElementType(type);
  1645. unsigned len = LLVMGetVectorSize(type);
  1646. if (len == 0) {
  1647. return LLVMConstNull(type);
  1648. }
  1649. char const *name = nullptr;
  1650. i32 value_offset = 0;
  1651. i32 value_count = 0;
  1652. switch (LLVMGetTypeKind(elem)) {
  1653. case LLVMHalfTypeKind:
  1654. case LLVMFloatTypeKind:
  1655. case LLVMDoubleTypeKind:
  1656. name = "llvm.vector.reduce.fadd";
  1657. value_offset = 0;
  1658. value_count = 2;
  1659. break;
  1660. case LLVMIntegerTypeKind:
  1661. name = "llvm.vector.reduce.add";
  1662. value_offset = 1;
  1663. value_count = 1;
  1664. break;
  1665. default:
  1666. GB_PANIC("invalid vector type %s", LLVMPrintTypeToString(type));
  1667. break;
  1668. }
  1669. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1670. if (id != 0 && false) {
  1671. LLVMTypeRef types[1] = { type };
  1672. LLVMValueRef values[2] = { LLVMConstNull(elem), value };
  1673. return lb_call_intrinsic(p, name, values + value_offset, value_count, types, gb_count_of(types));
  1674. }
  1675. // Manual reduce
  1676. #if 0
  1677. LLVMValueRef sum = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, 0).value, "");
  1678. for (unsigned i = 0; i < len; i++) {
  1679. LLVMValueRef val = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, i).value, "");
  1680. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1681. sum = LLVMBuildAdd(p->builder, sum, val, "");
  1682. } else {
  1683. sum = LLVMBuildFAdd(p->builder, sum, val, "");
  1684. }
  1685. }
  1686. return sum;
  1687. #else
  1688. LLVMOpcode op_code = LLVMFAdd;
  1689. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1690. op_code = LLVMAdd;
  1691. }
  1692. unsigned len_pow_2 = prev_pow2(len);
  1693. if (len_pow_2 == len) {
  1694. return llvm_vector_shuffle_reduction(p, value, op_code);
  1695. } else {
  1696. GB_ASSERT(len_pow_2 < len);
  1697. LLVMValueRef lower_mask = llvm_mask_iota(p->module, 0, len_pow_2);
  1698. LLVMValueRef upper_mask = llvm_mask_iota(p->module, len_pow_2, len-len_pow_2);
  1699. LLVMValueRef lower = llvm_basic_shuffle(p, value, lower_mask);
  1700. LLVMValueRef upper = llvm_basic_shuffle(p, value, upper_mask);
  1701. upper = llvm_vector_expand_to_power_of_two(p, upper);
  1702. LLVMValueRef lower_reduced = llvm_vector_shuffle_reduction(p, lower, op_code);
  1703. LLVMValueRef upper_reduced = llvm_vector_shuffle_reduction(p, upper, op_code);
  1704. GB_ASSERT(LLVMTypeOf(lower_reduced) == LLVMTypeOf(upper_reduced));
  1705. return LLVMBuildBinOp(p->builder, op_code, lower_reduced, upper_reduced, "");
  1706. }
  1707. #endif
  1708. }
  1709. gb_internal LLVMValueRef llvm_vector_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1710. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1711. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1712. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1713. return LLVMBuildAdd(p->builder, a, b, "");
  1714. }
  1715. return LLVMBuildFAdd(p->builder, a, b, "");
  1716. }
  1717. gb_internal LLVMValueRef llvm_vector_mul(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1718. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1719. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1720. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1721. return LLVMBuildMul(p->builder, a, b, "");
  1722. }
  1723. return LLVMBuildFMul(p->builder, a, b, "");
  1724. }
  1725. gb_internal LLVMValueRef llvm_vector_dot(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1726. return llvm_vector_reduce_add(p, llvm_vector_mul(p, a, b));
  1727. }
  1728. gb_internal LLVMValueRef llvm_vector_mul_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, LLVMValueRef c) {
  1729. LLVMTypeRef t = LLVMTypeOf(a);
  1730. GB_ASSERT(t == LLVMTypeOf(b));
  1731. GB_ASSERT(t == LLVMTypeOf(c));
  1732. GB_ASSERT(LLVMGetTypeKind(t) == LLVMVectorTypeKind);
  1733. LLVMTypeRef elem = OdinLLVMGetVectorElementType(t);
  1734. bool is_possible = false;
  1735. switch (LLVMGetTypeKind(elem)) {
  1736. case LLVMHalfTypeKind:
  1737. is_possible = true;
  1738. break;
  1739. case LLVMFloatTypeKind:
  1740. case LLVMDoubleTypeKind:
  1741. is_possible = true;
  1742. break;
  1743. }
  1744. if (is_possible) {
  1745. char const *name = "llvm.fmuladd";
  1746. LLVMTypeRef types[1] = { t };
  1747. LLVMValueRef values[3] = { a, b, c};
  1748. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1749. return call;
  1750. } else {
  1751. LLVMValueRef x = llvm_vector_mul(p, a, b);
  1752. LLVMValueRef y = llvm_vector_add(p, x, c);
  1753. return y;
  1754. }
  1755. }
  1756. gb_internal LLVMValueRef llvm_get_inline_asm(LLVMTypeRef func_type, String const &str, String const &clobbers, bool has_side_effects=true, bool is_align_stack=false, LLVMInlineAsmDialect dialect=LLVMInlineAsmDialectATT) {
  1757. return LLVMGetInlineAsm(func_type,
  1758. cast(char *)str.text, cast(size_t)str.len,
  1759. cast(char *)clobbers.text, cast(size_t)clobbers.len,
  1760. has_side_effects, is_align_stack,
  1761. dialect
  1762. #if LLVM_VERSION_MAJOR >= 13
  1763. , /*CanThrow*/false
  1764. #endif
  1765. );
  1766. }
  1767. gb_internal void lb_set_wasm_procedure_import_attributes(LLVMValueRef value, Entity *entity, String import_name) {
  1768. if (!is_arch_wasm()) {
  1769. return;
  1770. }
  1771. String module_name = str_lit("env");
  1772. if (entity->Procedure.foreign_library != nullptr) {
  1773. Entity *foreign_library = entity->Procedure.foreign_library;
  1774. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1775. GB_ASSERT(foreign_library->LibraryName.paths.count == 1);
  1776. module_name = foreign_library->LibraryName.paths[0];
  1777. if (string_ends_with(module_name, str_lit(".o"))) {
  1778. return;
  1779. }
  1780. if (string_starts_with(import_name, module_name)) {
  1781. import_name = substring(import_name, module_name.len+WASM_MODULE_NAME_SEPARATOR.len, import_name.len);
  1782. }
  1783. }
  1784. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-module", alloc_cstring(permanent_allocator(), module_name));
  1785. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-name", alloc_cstring(permanent_allocator(), import_name));
  1786. }
  1787. gb_internal void lb_set_wasm_export_attributes(LLVMValueRef value, String export_name) {
  1788. if (!is_arch_wasm()) {
  1789. return;
  1790. }
  1791. LLVMSetLinkage(value, LLVMDLLExportLinkage);
  1792. LLVMSetDLLStorageClass(value, LLVMDLLExportStorageClass);
  1793. LLVMSetVisibility(value, LLVMDefaultVisibility);
  1794. LLVMAddTargetDependentFunctionAttr(value, "wasm-export-name", alloc_cstring(permanent_allocator(), export_name));
  1795. }
  1796. gb_internal lbAddr lb_handle_objc_find_or_register_selector(lbProcedure *p, String const &name) {
  1797. lbModule *m = p->module;
  1798. lbAddr *found = string_map_get(&m->objc_selectors, name);
  1799. if (found) {
  1800. return *found;
  1801. }
  1802. lbModule *default_module = &p->module->gen->default_module;
  1803. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_SEL::");
  1804. global_name = gb_string_append_length(global_name, name.text, name.len);
  1805. LLVMTypeRef t = lb_type(m, t_objc_SEL);
  1806. lbValue g = {};
  1807. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1808. g.type = alloc_type_pointer(t_objc_SEL);
  1809. if (default_module == m) {
  1810. LLVMSetInitializer(g.value, LLVMConstNull(t));
  1811. lb_add_member(m, make_string_c(global_name), g);
  1812. } else {
  1813. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1814. }
  1815. mpsc_enqueue(&m->gen->objc_selectors, lbObjCGlobal{m, global_name, name, t_objc_SEL});
  1816. lbAddr addr = lb_addr(g);
  1817. string_map_set(&m->objc_selectors, name, addr);
  1818. return addr;
  1819. }
  1820. gb_internal lbAddr lb_handle_objc_find_or_register_class(lbProcedure *p, String const &name, Type *class_impl_type) {
  1821. lbModule *m = p->module;
  1822. lbAddr *found = string_map_get(&m->objc_classes, name);
  1823. if (found) {
  1824. return *found;
  1825. }
  1826. lbModule *default_module = &p->module->gen->default_module;
  1827. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_Class::");
  1828. global_name = gb_string_append_length(global_name, name.text, name.len);
  1829. LLVMTypeRef t = lb_type(m, t_objc_Class);
  1830. lbValue g = {};
  1831. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1832. g.type = alloc_type_pointer(t_objc_Class);
  1833. if (default_module == m) {
  1834. LLVMSetInitializer(g.value, LLVMConstNull(t));
  1835. lb_add_member(m, make_string_c(global_name), g);
  1836. } else {
  1837. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1838. }
  1839. mpsc_enqueue(&m->gen->objc_classes, lbObjCGlobal{m, global_name, name, t_objc_Class, class_impl_type});
  1840. lbAddr addr = lb_addr(g);
  1841. string_map_set(&m->objc_classes, name, addr);
  1842. return addr;
  1843. }
  1844. gb_internal lbAddr lb_handle_objc_find_or_register_ivar(lbModule *m, Type *self_type) {
  1845. String name = self_type->Named.type_name->TypeName.objc_class_name;
  1846. GB_ASSERT(name != "");
  1847. lbAddr *found = string_map_get(&m->objc_ivars, name);
  1848. if (found) {
  1849. return *found;
  1850. }
  1851. lbModule *default_module = &m->gen->default_module;
  1852. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_ivar::");
  1853. global_name = gb_string_append_length(global_name, name.text, name.len);
  1854. // Create a global variable to store offset of the ivar in an instance of an object
  1855. LLVMTypeRef t = lb_type(m, t_int);
  1856. lbValue g = {};
  1857. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1858. g.type = t_int_ptr;
  1859. if (default_module == m) {
  1860. LLVMSetInitializer(g.value, LLVMConstInt(t, 0, true));
  1861. lb_add_member(m, make_string_c(global_name), g);
  1862. } else {
  1863. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1864. }
  1865. mpsc_enqueue(&m->gen->objc_ivars, lbObjCGlobal{m, global_name, name, t_int, self_type});
  1866. lbAddr addr = lb_addr(g);
  1867. string_map_set(&m->objc_ivars, name, addr);
  1868. return addr;
  1869. }
  1870. gb_internal lbValue lb_handle_objc_ivar_for_objc_object_pointer(lbProcedure *p, lbValue self) {
  1871. GB_ASSERT(self.type->kind == Type_Pointer && self.type->Pointer.elem->kind == Type_Named);
  1872. Type *self_type = self.type->Pointer.elem;
  1873. lbValue self_uptr = lb_emit_conv(p, self, t_uintptr);
  1874. lbValue ivar_offset = lb_addr_load(p, lb_handle_objc_find_or_register_ivar(p->module, self_type));
  1875. lbValue ivar_offset_uptr = lb_emit_conv(p, ivar_offset, t_uintptr);
  1876. lbValue ivar_uptr = lb_emit_arith(p, Token_Add, self_uptr, ivar_offset_uptr, t_uintptr);
  1877. Type *ivar_type = self_type->Named.type_name->TypeName.objc_ivar;
  1878. return lb_emit_conv(p, ivar_uptr, alloc_type_pointer(ivar_type));
  1879. }
  1880. gb_internal lbValue lb_handle_objc_ivar_get(lbProcedure *p, Ast *expr) {
  1881. ast_node(ce, CallExpr, expr);
  1882. GB_ASSERT(ce->args[0]->tav.type->kind == Type_Pointer);
  1883. lbValue self = lb_build_expr(p, ce->args[0]);
  1884. return lb_handle_objc_ivar_for_objc_object_pointer(p, self);
  1885. }
  1886. gb_internal void lb_create_objc_block_helper_procs(
  1887. lbModule *m, LLVMTypeRef block_lit_type, isize capture_field_offset,
  1888. Slice<lbValue> capture_values, Slice<isize> objc_object_indices,
  1889. lbProcedure *&out_copy_helper, lbProcedure *&out_dispose_helper
  1890. ) {
  1891. gbString copy_helper_name = gb_string_append_fmt(gb_string_make(temporary_allocator(), ""), "__$objc_block_copy_helper_%lld", m->objc_next_block_id);
  1892. gbString dispose_helper_name = gb_string_append_fmt(gb_string_make(temporary_allocator(), ""), "__$objc_block_dispose_helper_%lld", m->objc_next_block_id);
  1893. // copy: Block_Literal *dst, Block_Literal *src, i32 field_apropos
  1894. // dispose: Block_Literal *src, i32 field_apropos
  1895. Type *types[3] = { t_rawptr, t_rawptr, t_i32 };
  1896. Type *copy_tuple = alloc_type_tuple_from_field_types(types, 3, false, true);
  1897. Type *dispose_tuple = alloc_type_tuple_from_field_types(&types[1], 2, false, true);
  1898. Type *copy_proc_type = alloc_type_proc(nullptr, copy_tuple, 3, nullptr, 0, false, ProcCC_CDecl);
  1899. Type *dispose_proc_type = alloc_type_proc(nullptr, dispose_tuple, 2, nullptr, 0, false, ProcCC_CDecl);
  1900. lbProcedure *copy_proc = lb_create_dummy_procedure(m, make_string((u8*)copy_helper_name, gb_string_length(copy_helper_name)), copy_proc_type);
  1901. lbProcedure *dispose_proc = lb_create_dummy_procedure(m, make_string((u8*)dispose_helper_name, gb_string_length(dispose_helper_name)), dispose_proc_type);
  1902. LLVMSetLinkage(copy_proc->value, LLVMPrivateLinkage);
  1903. LLVMSetLinkage(dispose_proc->value, LLVMPrivateLinkage);
  1904. const int BLOCK_FIELD_IS_OBJECT = 3; // id, NSObject, __attribute__((NSObject)), block, ...
  1905. const int BLOCK_FIELD_IS_BLOCK = 7; // a block variable
  1906. Type *block_base_type = find_core_type(m->info->checker, str_lit("Objc_Block"));
  1907. auto is_object_objc_block = [](Type *type, Type *block_base_type) -> bool {
  1908. Type *base = base_type(type_deref(type));
  1909. GB_ASSERT(base->kind == Type_Struct);
  1910. while (is_type_polymorphic_record_specialized(base)) {
  1911. if (base->Struct.polymorphic_parent) {
  1912. base = base->Struct.polymorphic_parent;
  1913. if (base == block_base_type) {
  1914. return true;
  1915. }
  1916. base = base_type(base);
  1917. GB_ASSERT(base->kind == Type_Struct);
  1918. }
  1919. }
  1920. return false;
  1921. };
  1922. lb_begin_procedure_body(copy_proc);
  1923. lb_begin_procedure_body(dispose_proc);
  1924. {
  1925. for (isize object_index : objc_object_indices) {
  1926. const auto field_offset = unsigned(capture_field_offset+object_index);
  1927. Type *field_type = capture_values[object_index].type;
  1928. LLVMTypeRef field_raw_type = lb_type(m, field_type);
  1929. GB_ASSERT(is_type_objc_object(field_type));
  1930. bool is_block_obj = is_object_objc_block(field_type, block_base_type);
  1931. auto copy_args = array_make<lbValue>(temporary_allocator(), 3, 3);
  1932. auto dispose_args = array_make<lbValue>(temporary_allocator(), 2, 2);
  1933. // Copy helper
  1934. {
  1935. LLVMValueRef dst_field = LLVMBuildStructGEP2(copy_proc->builder, block_lit_type, copy_proc->raw_input_parameters[0], field_offset, "");
  1936. LLVMValueRef src_field = LLVMBuildStructGEP2(copy_proc->builder, block_lit_type, copy_proc->raw_input_parameters[1], field_offset, "");
  1937. lbValue dst_value = {}, src_value = {};
  1938. dst_value.type = alloc_type_pointer(field_type);
  1939. dst_value.value = dst_field;
  1940. src_value.type = field_type;
  1941. src_value.value = LLVMBuildLoad2(copy_proc->builder, field_raw_type, src_field, "");
  1942. copy_args[0] = dst_value;
  1943. copy_args[1] = src_value;
  1944. copy_args[2] = lb_const_int(m, t_i32, u64(is_block_obj ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT));
  1945. lb_emit_runtime_call(copy_proc, "_Block_object_assign", copy_args);
  1946. }
  1947. // Dispose helper
  1948. {
  1949. LLVMValueRef src_field = LLVMBuildStructGEP2(dispose_proc->builder, block_lit_type, dispose_proc->raw_input_parameters[0], field_offset, "");
  1950. lbValue src_value = {};
  1951. src_value.type = field_type;
  1952. src_value.value = LLVMBuildLoad2(dispose_proc->builder, field_raw_type, src_field, "");
  1953. dispose_args[0] = src_value;
  1954. dispose_args[1] = lb_const_int(m, t_i32, u64(is_block_obj ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT));
  1955. lb_emit_runtime_call(dispose_proc, "_Block_object_dispose", dispose_args);
  1956. }
  1957. }
  1958. }
  1959. lb_end_procedure_body(copy_proc);
  1960. lb_end_procedure_body(dispose_proc);
  1961. out_copy_helper = copy_proc;
  1962. out_dispose_helper = dispose_proc;
  1963. }
  1964. gb_internal lbValue lb_handle_objc_block(lbProcedure *p, Ast *expr) {
  1965. /// #See: https://clang.llvm.org/docs/Block-ABI-Apple.html
  1966. /// https://www.newosxbook.com/src.php?tree=xnu&file=/libkern/libkern/Block_private.h
  1967. /// https://github.com/llvm/llvm-project/blob/21f1f9558df3830ffa637def364e3c0cb0dbb3c0/compiler-rt/lib/BlocksRuntime/Block_private.h
  1968. /// https://github.com/apple-oss-distributions/libclosure/blob/3668b0837f47be3cc1c404fb5e360f4ff178ca13/runtime.cpp
  1969. ast_node(ce, CallExpr, expr);
  1970. GB_ASSERT(ce->args.count > 0);
  1971. lbModule *m = p->module;
  1972. m->objc_next_block_id += 1;
  1973. const isize capture_arg_count = ce->args.count - 1;
  1974. Type *block_result_type = type_of_expr(expr);
  1975. GB_ASSERT(block_result_type != nullptr && block_result_type->kind == Type_Pointer);
  1976. LLVMTypeRef lb_type_rawptr = lb_type(m, t_rawptr);
  1977. LLVMTypeRef lb_type_i32 = lb_type(m, t_i32);
  1978. LLVMTypeRef lb_type_int = lb_type(m, t_int);
  1979. // Build user proc
  1980. // Type * user_proc_type = type_of_expr(ce->args[capture_arg_count]);
  1981. lbValue user_proc_value = lb_build_expr(p, ce->args[capture_arg_count]);
  1982. auto& user_proc = user_proc_value.type->Proc;
  1983. GB_ASSERT(user_proc_value.type->kind == Type_Proc);
  1984. const bool is_global = capture_arg_count == 0 && user_proc.calling_convention != ProcCC_Odin;
  1985. const isize block_forward_args = user_proc.param_count - capture_arg_count;
  1986. const isize capture_fields_offset = user_proc.calling_convention != ProcCC_Odin ? 5 : 6;
  1987. Ast *proc_lit = unparen_expr(ce->args[capture_arg_count]);
  1988. if (proc_lit->kind == Ast_Ident) {
  1989. proc_lit = proc_lit->Ident.entity->decl_info->proc_lit;
  1990. }
  1991. GB_ASSERT(proc_lit->kind == Ast_ProcLit);
  1992. lbProcedure *copy_helper = {}, *dispose_helper = {};
  1993. // Build captured arguments & collect the ones that are Objective-C objects
  1994. auto captured_values = array_make<lbValue>(temporary_allocator(), capture_arg_count, capture_arg_count);
  1995. auto objc_captures = array_make<isize>(temporary_allocator());
  1996. for (isize i = 0; i < capture_arg_count; i++) {
  1997. captured_values[i] = lb_build_expr(p, ce->args[i]);
  1998. if (is_type_pointer(captured_values[i].type) && is_type_objc_object(captured_values[i].type)) {
  1999. array_add(&objc_captures, i);
  2000. }
  2001. }
  2002. const bool has_objc_fields = objc_captures.count > 0;
  2003. // Create proc with the block signature
  2004. // (takes a block literal pointer as the first parameter, followed by any expected ones from the user's proc)
  2005. gbString block_invoker_name = gb_string_append_fmt(gb_string_make(permanent_allocator(), ""), "__$objc_block_invoker_%lld", m->objc_next_block_id);
  2006. // Add + 1 because the first parameter received is the block literal pointer itself
  2007. auto invoker_args = array_make<Type *>(temporary_allocator(), block_forward_args + 1, block_forward_args + 1);
  2008. invoker_args[0] = t_rawptr;
  2009. GB_ASSERT(block_forward_args <= user_proc.param_count);
  2010. if (user_proc.param_count > 0) {
  2011. Slice<Entity *> user_proc_param_types = user_proc.params->Tuple.variables;
  2012. for (isize i = 0; i < block_forward_args; i++) {
  2013. invoker_args[i+1] = user_proc_param_types[i]->type;
  2014. }
  2015. }
  2016. GB_ASSERT(user_proc.result_count <= 1);
  2017. Type *invoker_args_tuple = alloc_type_tuple_from_field_types(invoker_args.data, invoker_args.count, false, true);
  2018. Type *invoker_results_tuple = nullptr;
  2019. if (user_proc.result_count > 0) {
  2020. invoker_results_tuple = alloc_type_tuple_from_field_types(&user_proc.results->Tuple.variables[0]->type, 1, false, true);
  2021. }
  2022. Type *invoker_proc_type = alloc_type_proc(nullptr, invoker_args_tuple, invoker_args_tuple->Tuple.variables.count,
  2023. invoker_results_tuple, user_proc.result_count, false, ProcCC_CDecl);
  2024. lbProcedure *invoker_proc = lb_create_dummy_procedure(m, make_string((u8*)block_invoker_name,
  2025. gb_string_length(block_invoker_name)), invoker_proc_type);
  2026. LLVMSetLinkage(invoker_proc->value, LLVMPrivateLinkage);
  2027. // Create the block descriptor and block literal
  2028. gbString block_lit_type_name = gb_string_make(temporary_allocator(), "__$ObjC_Block_Literal_");
  2029. block_lit_type_name = gb_string_append_fmt(block_lit_type_name, "%lld", m->objc_next_block_id);
  2030. gbString block_desc_type_name = gb_string_make(temporary_allocator(), "__$ObjC_Block_Descriptor_");
  2031. block_desc_type_name = gb_string_append_fmt(block_desc_type_name, "%lld", m->objc_next_block_id);
  2032. LLVMTypeRef block_lit_type = {};
  2033. LLVMTypeRef block_desc_type = {};
  2034. LLVMValueRef block_desc_initializer = {};
  2035. {
  2036. block_desc_type = LLVMStructCreateNamed(m->ctx, block_desc_type_name);
  2037. LLVMTypeRef fields_types[4] = {
  2038. lb_type_int, // Reserved
  2039. lb_type_int, // Block size
  2040. lb_type_rawptr, // Copy helper func pointer
  2041. lb_type_rawptr, // Dispose helper func pointer
  2042. };
  2043. LLVMStructSetBody(block_desc_type, fields_types, has_objc_fields ? 4 : 2, false);
  2044. }
  2045. {
  2046. block_lit_type = LLVMStructCreateNamed(m->ctx, block_lit_type_name);
  2047. auto fields = array_make<LLVMTypeRef>(temporary_allocator());
  2048. array_add(&fields, lb_type_rawptr); // isa
  2049. array_add(&fields, lb_type_i32); // flags
  2050. array_add(&fields, lb_type_i32); // reserved
  2051. array_add(&fields, lb_type_rawptr); // invoke
  2052. array_add(&fields, block_desc_type); // descriptor
  2053. if (user_proc.calling_convention == ProcCC_Odin) {
  2054. array_add(&fields, lb_type(m, t_context)); // context
  2055. }
  2056. // From here on, fields for the captured vars are added
  2057. for (lbValue cap_arg : captured_values) {
  2058. array_add(&fields, lb_type(m, cap_arg.type));
  2059. }
  2060. LLVMStructSetBody(block_lit_type, fields.data, (unsigned)fields.count, false);
  2061. }
  2062. // Generate copy and dispose helper functions for captured params that are Objective-C objects (or a Block)
  2063. if (has_objc_fields) {
  2064. lb_create_objc_block_helper_procs(m, block_lit_type, capture_fields_offset,
  2065. slice(captured_values, 0, captured_values.count),
  2066. slice(objc_captures, 0, objc_captures.count),
  2067. copy_helper, dispose_helper);
  2068. }
  2069. {
  2070. LLVMValueRef fields_values[4] = {
  2071. lb_const_int(m, t_int, 0).value, // Reserved
  2072. lb_const_int(m, t_int, u64(lb_sizeof(block_lit_type))).value, // Block size
  2073. has_objc_fields ? copy_helper->value : nullptr, // Copy helper
  2074. has_objc_fields ? dispose_helper->value : nullptr, // Dispose helper
  2075. };
  2076. block_desc_initializer = LLVMConstNamedStruct(block_desc_type, fields_values, has_objc_fields ? 4 : 2);
  2077. }
  2078. // Create global block descriptor
  2079. gbString desc_global_name = gb_string_make(temporary_allocator(), "__$objc_block_desc_");
  2080. desc_global_name = gb_string_append_fmt(desc_global_name, "%lld", m->objc_next_block_id);
  2081. LLVMValueRef p_descriptor = LLVMAddGlobal(m->mod, block_desc_type, desc_global_name);
  2082. LLVMSetInitializer(p_descriptor, block_desc_initializer);
  2083. /// Invoker body
  2084. lb_begin_procedure_body(invoker_proc);
  2085. {
  2086. auto call_args = array_make<lbValue>(temporary_allocator(), user_proc.param_count, user_proc.param_count);
  2087. for (isize i = 1; i < invoker_proc->raw_input_parameters.count; i++) {
  2088. lbValue arg = {};
  2089. arg.type = invoker_args[i];
  2090. arg.value = invoker_proc->raw_input_parameters[i],
  2091. call_args[i-1] = arg;
  2092. }
  2093. LLVMValueRef block_literal = invoker_proc->raw_input_parameters[0];
  2094. // Push context, if needed
  2095. if (user_proc.calling_convention == ProcCC_Odin) {
  2096. LLVMValueRef p_context = LLVMBuildStructGEP2(invoker_proc->builder, block_lit_type, block_literal, 5, "context");
  2097. lbValue ctx_val = {};
  2098. ctx_val.type = t_context_ptr;
  2099. ctx_val.value = p_context;
  2100. lb_push_context_onto_stack(invoker_proc, lb_addr(ctx_val));
  2101. }
  2102. // Copy capture parameters from the block literal
  2103. for (isize i = 0; i < capture_arg_count; i++) {
  2104. LLVMValueRef cap_value = LLVMBuildStructGEP2(invoker_proc->builder, block_lit_type, block_literal, unsigned(capture_fields_offset + i), "");
  2105. lbValue cap_arg = {};
  2106. cap_arg.value = cap_value;
  2107. cap_arg.type = alloc_type_pointer(captured_values[i].type);
  2108. lbValue arg = lb_emit_load(invoker_proc, cap_arg);
  2109. call_args[block_forward_args+i] = arg;
  2110. }
  2111. lbValue result = lb_emit_call(invoker_proc, user_proc_value, call_args, proc_lit->ProcLit.inlining);
  2112. GB_ASSERT(user_proc.result_count <= 1);
  2113. if (user_proc.result_count > 0) {
  2114. GB_ASSERT(result.value != nullptr);
  2115. LLVMBuildRet(p->builder, result.value);
  2116. }
  2117. }
  2118. lb_end_procedure_body(invoker_proc);
  2119. /// Create local block literal
  2120. const int BLOCK_HAS_COPY_DISPOSE = (1 << 25);
  2121. const int BLOCK_IS_GLOBAL = (1 << 28);
  2122. int raw_flags = is_global ? BLOCK_IS_GLOBAL : 0;
  2123. if (has_objc_fields) {
  2124. raw_flags |= BLOCK_HAS_COPY_DISPOSE;
  2125. }
  2126. gbString block_var_name = gb_string_make(temporary_allocator(), "__$objc_block_literal_");
  2127. block_var_name = gb_string_append_fmt(block_var_name, "%lld", m->objc_next_block_id);
  2128. lbValue result = {};
  2129. result.type = block_result_type;
  2130. lbValue isa_val = lb_find_runtime_value(m, is_global ? str_lit("_NSConcreteGlobalBlock") : str_lit("_NSConcreteStackBlock"));
  2131. lbValue flags_val = lb_const_int(m, t_i32, (u64)raw_flags);
  2132. lbValue reserved_val = lb_const_int(m, t_i32, 0);
  2133. if (is_global) {
  2134. LLVMValueRef p_block_lit = LLVMAddGlobal(m->mod, block_lit_type, block_var_name);
  2135. result.value = p_block_lit;
  2136. LLVMValueRef fields_values[5] = {
  2137. isa_val.value, // isa
  2138. flags_val.value, // flags
  2139. reserved_val.value, // reserved
  2140. invoker_proc->value, // invoke
  2141. p_descriptor // descriptor
  2142. };
  2143. LLVMValueRef g_block_lit_initializer = LLVMConstNamedStruct(block_lit_type, fields_values, gb_count_of(fields_values));
  2144. LLVMSetInitializer(p_block_lit, g_block_lit_initializer);
  2145. } else {
  2146. LLVMValueRef p_block_lit = llvm_alloca(p, block_lit_type, lb_alignof(block_lit_type), block_var_name);
  2147. result.value = p_block_lit;
  2148. // Initialize it
  2149. LLVMValueRef f_isa = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 0, "isa");
  2150. LLVMValueRef f_flags = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 1, "flags");
  2151. LLVMValueRef f_reserved = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 2, "reserved");
  2152. LLVMValueRef f_invoke = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 3, "invoke");
  2153. LLVMValueRef f_descriptor = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 4, "descriptor");
  2154. LLVMBuildStore(p->builder, isa_val.value, f_isa);
  2155. LLVMBuildStore(p->builder, flags_val.value, f_flags);
  2156. LLVMBuildStore(p->builder, reserved_val.value, f_reserved);
  2157. LLVMBuildStore(p->builder, invoker_proc->value, f_invoke);
  2158. LLVMBuildStore(p->builder, p_descriptor, f_descriptor);
  2159. // Store current context, if there is one
  2160. if (user_proc.calling_convention == ProcCC_Odin) {
  2161. LLVMValueRef f_context = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, 5, "context");
  2162. lbAddr p_current_context = lb_find_or_generate_context_ptr(p);
  2163. LLVMValueRef context_size = LLVMConstInt(LLVMInt64TypeInContext(m->ctx), (u64)lb_sizeof(lb_type(m, t_context)), false);
  2164. LLVMBuildMemCpy(p->builder, f_context, lb_try_get_alignment(f_context, 1),
  2165. p_current_context.addr.value, lb_try_get_alignment(p_current_context.addr.value, 1), context_size);
  2166. }
  2167. // Store captured args into the block
  2168. for (isize i = 0; i < captured_values.count; i++) {
  2169. lbValue capture_arg = captured_values[i];
  2170. unsigned field_index = unsigned(capture_fields_offset + i);
  2171. LLVMValueRef f_capture = LLVMBuildStructGEP2(p->builder, block_lit_type, p_block_lit, field_index, "capture_arg");
  2172. lbValue f_capture_val = {};
  2173. f_capture_val.type = alloc_type_pointer(capture_arg.type);
  2174. f_capture_val.value = f_capture;
  2175. lb_emit_store(p, f_capture_val, capture_arg);
  2176. }
  2177. }
  2178. return result;
  2179. }
  2180. gb_internal lbValue lb_handle_objc_find_selector(lbProcedure *p, Ast *expr) {
  2181. ast_node(ce, CallExpr, expr);
  2182. auto tav = ce->args[0]->tav;
  2183. GB_ASSERT(tav.value.kind == ExactValue_String);
  2184. String name = tav.value.value_string;
  2185. return lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, name));
  2186. }
  2187. gb_internal lbValue lb_handle_objc_register_selector(lbProcedure *p, Ast *expr) {
  2188. ast_node(ce, CallExpr, expr);
  2189. lbModule *m = p->module;
  2190. auto tav = ce->args[0]->tav;
  2191. GB_ASSERT(tav.value.kind == ExactValue_String);
  2192. String name = tav.value.value_string;
  2193. lbAddr dst = lb_handle_objc_find_or_register_selector(p, name);
  2194. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2195. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  2196. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  2197. lb_addr_store(p, dst, ptr);
  2198. return lb_addr_load(p, dst);
  2199. }
  2200. gb_internal lbValue lb_handle_objc_find_class(lbProcedure *p, Ast *expr) {
  2201. ast_node(ce, CallExpr, expr);
  2202. auto tav = ce->args[0]->tav;
  2203. GB_ASSERT(tav.value.kind == ExactValue_String);
  2204. String name = tav.value.value_string;
  2205. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name, nullptr));
  2206. }
  2207. gb_internal lbValue lb_handle_objc_register_class(lbProcedure *p, Ast *expr) {
  2208. ast_node(ce, CallExpr, expr);
  2209. lbModule *m = p->module;
  2210. auto tav = ce->args[0]->tav;
  2211. GB_ASSERT(tav.value.kind == ExactValue_String);
  2212. String name = tav.value.value_string;
  2213. lbAddr dst = lb_handle_objc_find_or_register_class(p, name, nullptr);
  2214. auto args = array_make<lbValue>(permanent_allocator(), 3);
  2215. args[0] = lb_const_nil(m, t_objc_Class);
  2216. args[1] = lb_const_nil(m, t_objc_Class);
  2217. args[2] = lb_const_int(m, t_uint, 0);
  2218. lbValue ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  2219. lb_addr_store(p, dst, ptr);
  2220. return lb_addr_load(p, dst);
  2221. }
  2222. gb_internal lbValue lb_handle_objc_id(lbProcedure *p, Ast *expr) {
  2223. TypeAndValue const &tav = type_and_value_of_expr(expr);
  2224. if (tav.mode == Addressing_Type) {
  2225. Type *type = tav.type;
  2226. GB_ASSERT_MSG(type->kind == Type_Named, "%s", type_to_string(type));
  2227. Entity *e = type->Named.type_name;
  2228. GB_ASSERT(e->kind == Entity_TypeName);
  2229. String name = e->TypeName.objc_class_name;
  2230. Type *class_impl_type = e->TypeName.objc_is_implementation ? type : nullptr;
  2231. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name, class_impl_type));
  2232. }
  2233. return lb_build_expr(p, expr);
  2234. }
  2235. gb_internal lbValue lb_handle_objc_send(lbProcedure *p, Ast *expr) {
  2236. ast_node(ce, CallExpr, expr);
  2237. lbModule *m = p->module;
  2238. CheckerInfo *info = m->info;
  2239. ObjcMsgData data = map_must_get(&info->objc_msgSend_types, expr);
  2240. GB_ASSERT(data.proc_type != nullptr);
  2241. GB_ASSERT(ce->args.count >= 3);
  2242. auto args = array_make<lbValue>(permanent_allocator(), 0, ce->args.count-1);
  2243. lbValue id = lb_handle_objc_id(p, ce->args[1]);
  2244. Ast *sel_expr = ce->args[2];
  2245. GB_ASSERT(sel_expr->tav.value.kind == ExactValue_String);
  2246. lbValue sel = lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, sel_expr->tav.value.value_string));
  2247. array_add(&args, id);
  2248. array_add(&args, sel);
  2249. for (isize i = 3; i < ce->args.count; i++) {
  2250. lbValue arg = lb_build_expr(p, ce->args[i]);
  2251. array_add(&args, arg);
  2252. }
  2253. lbValue the_proc = {};
  2254. switch (data.kind) {
  2255. default:
  2256. GB_PANIC("unhandled ObjcMsgKind %u", data.kind);
  2257. break;
  2258. case ObjcMsg_normal: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend")); break;
  2259. case ObjcMsg_fpret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fpret")); break;
  2260. case ObjcMsg_fp2ret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fp2ret")); break;
  2261. case ObjcMsg_stret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_stret")); break;
  2262. }
  2263. the_proc = lb_emit_conv(p, the_proc, data.proc_type);
  2264. return lb_emit_call(p, the_proc, args);
  2265. }
  2266. gb_internal LLVMAtomicOrdering llvm_atomic_ordering_from_odin(ExactValue const &value) {
  2267. GB_ASSERT(value.kind == ExactValue_Integer);
  2268. i64 v = exact_value_to_i64(value);
  2269. switch (v) {
  2270. case OdinAtomicMemoryOrder_relaxed: return LLVMAtomicOrderingMonotonic;
  2271. case OdinAtomicMemoryOrder_consume: return LLVMAtomicOrderingAcquire;
  2272. case OdinAtomicMemoryOrder_acquire: return LLVMAtomicOrderingAcquire;
  2273. case OdinAtomicMemoryOrder_release: return LLVMAtomicOrderingRelease;
  2274. case OdinAtomicMemoryOrder_acq_rel: return LLVMAtomicOrderingAcquireRelease;
  2275. case OdinAtomicMemoryOrder_seq_cst: return LLVMAtomicOrderingSequentiallyConsistent;
  2276. }
  2277. GB_PANIC("Unknown atomic ordering");
  2278. return LLVMAtomicOrderingSequentiallyConsistent;
  2279. }
  2280. gb_internal LLVMAtomicOrdering llvm_atomic_ordering_from_odin(Ast *expr) {
  2281. ExactValue value = type_and_value_of_expr(expr).value;
  2282. return llvm_atomic_ordering_from_odin(value);
  2283. }
  2284. struct lbDiagParaPolyEntry {
  2285. Entity *entity;
  2286. String canonical_name;
  2287. isize count;
  2288. isize total_code_size;
  2289. };
  2290. gb_internal isize lb_total_code_size(lbProcedure *p) {
  2291. isize instruction_count = 0;
  2292. LLVMBasicBlockRef first = LLVMGetFirstBasicBlock(p->value);
  2293. for (LLVMBasicBlockRef block = first; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2294. for (LLVMValueRef instr = LLVMGetFirstInstruction(block); instr != nullptr; instr = LLVMGetNextInstruction(instr)) {
  2295. instruction_count += 1;
  2296. }
  2297. }
  2298. return instruction_count;
  2299. }
  2300. gb_internal void lb_do_para_poly_diagnostics(lbGenerator *gen) {
  2301. PtrMap<Entity * /* Parent */, lbDiagParaPolyEntry> procs = {};
  2302. map_init(&procs);
  2303. defer (map_destroy(&procs));
  2304. for (auto &entry : gen->modules) {
  2305. lbModule *m = entry.value;
  2306. for (lbProcedure *p : m->generated_procedures) {
  2307. Entity *e = p->entity;
  2308. if (e == nullptr) {
  2309. continue;
  2310. }
  2311. if (p->builder == nullptr) {
  2312. continue;
  2313. }
  2314. DeclInfo *d = e->decl_info;
  2315. Entity *para_poly_parent = d->para_poly_original;
  2316. if (para_poly_parent == nullptr) {
  2317. continue;
  2318. }
  2319. lbDiagParaPolyEntry *entry = map_get(&procs, para_poly_parent);
  2320. if (entry == nullptr) {
  2321. lbDiagParaPolyEntry entry = {};
  2322. entry.entity = para_poly_parent;
  2323. entry.count = 0;
  2324. gbString w = string_canonical_entity_name(permanent_allocator(), entry.entity);
  2325. String name = make_string_c(w);
  2326. for (isize i = 0; i < name.len; i++) {
  2327. String s = substring(name, i, name.len);
  2328. if (string_starts_with(s, str_lit(":proc"))) {
  2329. name = substring(name, 0, i);
  2330. break;
  2331. }
  2332. }
  2333. entry.canonical_name = name;
  2334. map_set(&procs, para_poly_parent, entry);
  2335. }
  2336. entry = map_get(&procs, para_poly_parent);
  2337. GB_ASSERT(entry != nullptr);
  2338. entry->count += 1;
  2339. entry->total_code_size += lb_total_code_size(p);
  2340. }
  2341. }
  2342. auto entries = array_make<lbDiagParaPolyEntry>(heap_allocator(), 0, procs.count);
  2343. defer (array_free(&entries));
  2344. for (auto &entry : procs) {
  2345. array_add(&entries, entry.value);
  2346. }
  2347. array_sort(entries, [](void const *a, void const *b) -> int {
  2348. lbDiagParaPolyEntry *x = cast(lbDiagParaPolyEntry *)a;
  2349. lbDiagParaPolyEntry *y = cast(lbDiagParaPolyEntry *)b;
  2350. if (x->total_code_size > y->total_code_size) {
  2351. return -1;
  2352. }
  2353. if (x->total_code_size < y->total_code_size) {
  2354. return +1;
  2355. }
  2356. return string_compare(x->canonical_name, y->canonical_name);
  2357. });
  2358. gb_printf("Parametric Polymorphic Procedure Diagnostics\n");
  2359. gb_printf("------------------------------------------------------------------------------------------\n");
  2360. gb_printf("Sorted by Total Instruction Count Descending (Top 100)\n\n");
  2361. gb_printf("Total Instruction Count | Instantiation Count | Average Instruction Count | Procedure Name\n");
  2362. isize max_count = 100;
  2363. for (auto &entry : entries) {
  2364. isize code_size = entry.total_code_size;
  2365. isize count = entry.count;
  2366. String name = entry.canonical_name;
  2367. f64 average = cast(f64)code_size / cast(f64)gb_max(count, 1);
  2368. gb_printf("%23td | %19td | %25.2f | %.*s\n", code_size, count, average, LIT(name));
  2369. if (max_count-- <= 0) {
  2370. break;
  2371. }
  2372. }
  2373. gb_printf("------------------------------------------------------------------------------------------\n");
  2374. array_sort(entries, [](void const *a, void const *b) -> int {
  2375. lbDiagParaPolyEntry *x = cast(lbDiagParaPolyEntry *)a;
  2376. lbDiagParaPolyEntry *y = cast(lbDiagParaPolyEntry *)b;
  2377. if (x->count > y->count) {
  2378. return -1;
  2379. }
  2380. if (x->count < y->count) {
  2381. return +1;
  2382. }
  2383. return string_compare(x->canonical_name, y->canonical_name);
  2384. });
  2385. gb_printf("Sorted by Total Instantiation Count Descending (Top 100)\n\n");
  2386. gb_printf("Instantiation Count | Total Instruction Count | Average Instruction Count | Procedure Name\n");
  2387. max_count = 100;
  2388. for (auto &entry : entries) {
  2389. isize code_size = entry.total_code_size;
  2390. isize count = entry.count;
  2391. String name = entry.canonical_name;
  2392. f64 average = cast(f64)code_size / cast(f64)gb_max(count, 1);
  2393. gb_printf("%19td | %23td | %25.2f | %.*s\n", count, code_size, average, LIT(name));
  2394. if (max_count-- <= 0) {
  2395. break;
  2396. }
  2397. }
  2398. gb_printf("------------------------------------------------------------------------------------------\n");
  2399. array_sort(entries, [](void const *a, void const *b) -> int {
  2400. lbDiagParaPolyEntry *x = cast(lbDiagParaPolyEntry *)a;
  2401. lbDiagParaPolyEntry *y = cast(lbDiagParaPolyEntry *)b;
  2402. if (x->count < y->count) {
  2403. return -1;
  2404. }
  2405. if (x->count > y->count) {
  2406. return +1;
  2407. }
  2408. if (x->total_code_size > y->total_code_size) {
  2409. return -1;
  2410. }
  2411. if (x->total_code_size < y->total_code_size) {
  2412. return +1;
  2413. }
  2414. return string_compare(x->canonical_name, y->canonical_name);
  2415. });
  2416. gb_printf("Single Instanced Parametric Polymorphic Procedures\n\n");
  2417. gb_printf("Instruction Count | Procedure Name\n");
  2418. for (auto &entry : entries) {
  2419. isize code_size = entry.total_code_size;
  2420. isize count = entry.count;
  2421. String name = entry.canonical_name;
  2422. if (count != 1) {
  2423. break;
  2424. }
  2425. gb_printf("%17td | %.*s\n", code_size, LIT(name));
  2426. }
  2427. }
  2428. struct lbDiagModuleEntry {
  2429. lbModule *m;
  2430. String name;
  2431. isize global_internal_count;
  2432. isize global_external_count;
  2433. isize proc_internal_count;
  2434. isize proc_external_count;
  2435. isize total_instruction_count;
  2436. };
  2437. gb_internal void lb_do_module_diagnostics(lbGenerator *gen) {
  2438. Array<lbDiagModuleEntry> modules = {};
  2439. array_init(&modules, heap_allocator());
  2440. defer (array_free(&modules));
  2441. for (auto &em : gen->modules) {
  2442. lbModule *m = em.value;
  2443. {
  2444. lbDiagModuleEntry entry = {};
  2445. entry.m = m;
  2446. entry.name = make_string_c(m->module_name);
  2447. array_add(&modules, entry);
  2448. }
  2449. lbDiagModuleEntry &entry = modules[modules.count-1];
  2450. for (LLVMValueRef p = LLVMGetFirstFunction(m->mod); p != nullptr; p = LLVMGetNextFunction(p)) {
  2451. LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(p);
  2452. if (block == nullptr) {
  2453. entry.proc_external_count += 1;
  2454. } else {
  2455. entry.proc_internal_count += 1;
  2456. for (; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2457. for (LLVMValueRef i = LLVMGetFirstInstruction(block); i != nullptr; i = LLVMGetNextInstruction(i)) {
  2458. entry.total_instruction_count += 1;
  2459. }
  2460. }
  2461. }
  2462. }
  2463. for (LLVMValueRef g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  2464. LLVMLinkage linkage = LLVMGetLinkage(g);
  2465. if (linkage == LLVMExternalLinkage) {
  2466. entry.global_external_count += 1;
  2467. } else {
  2468. entry.global_internal_count += 1;
  2469. }
  2470. }
  2471. }
  2472. array_sort(modules, [](void const *a, void const *b) -> int {
  2473. lbDiagModuleEntry *x = cast(lbDiagModuleEntry *)a;
  2474. lbDiagModuleEntry *y = cast(lbDiagModuleEntry *)b;
  2475. if (x->total_instruction_count > y->total_instruction_count) {
  2476. return -1;
  2477. }
  2478. if (x->total_instruction_count < y->total_instruction_count) {
  2479. return +1;
  2480. }
  2481. return string_compare(x->name, y->name);
  2482. });
  2483. gb_printf("Module Diagnostics\n\n");
  2484. gb_printf("Total Instructions | Global Internals | Global Externals | Proc Internals | Proc Externals | Files | Instructions/File | Instructions/Proc | Module Name\n");
  2485. gb_printf("-------------------+------------------+------------------+----------------+----------------+-------+-------------------+-------------------+------------\n");
  2486. for (auto &entry : modules) {
  2487. isize file_count = 1;
  2488. if (entry.m->file != nullptr) {
  2489. file_count = 1;
  2490. } else if (entry.m->pkg) {
  2491. file_count = entry.m->pkg->files.count;
  2492. }
  2493. f64 instructions_per_file = cast(f64)entry.total_instruction_count / gb_max(1.0, cast(f64)file_count);
  2494. f64 instructions_per_proc = cast(f64)entry.total_instruction_count / gb_max(1.0, cast(f64)entry.proc_internal_count);
  2495. gb_printf("%18td | %16td | %16td | %14td | %14td | %5td | %17.1f | %17.1f | %s \n",
  2496. entry.total_instruction_count,
  2497. entry.global_internal_count,
  2498. entry.global_external_count,
  2499. entry.proc_internal_count,
  2500. entry.proc_external_count,
  2501. file_count,
  2502. instructions_per_file,
  2503. instructions_per_proc,
  2504. entry.m->module_name);
  2505. }
  2506. }
  2507. gb_internal void lb_do_build_diagnostics(lbGenerator *gen) {
  2508. lb_do_para_poly_diagnostics(gen);
  2509. gb_printf("------------------------------------------------------------------------------------------\n");
  2510. gb_printf("------------------------------------------------------------------------------------------\n\n");
  2511. lb_do_module_diagnostics(gen);
  2512. gb_printf("------------------------------------------------------------------------------------------\n");
  2513. gb_printf("------------------------------------------------------------------------------------------\n\n");
  2514. }