llvm_backend_utility.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  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_string(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_string;
  175. res.value = llvm_const_named_struct(p->module, t_string, values, gb_count_of(values));
  176. return res;
  177. } else {
  178. lbAddr res = lb_add_local_generated(p, t_string, 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_transmute(lbProcedure *p, lbValue value, Type *t) {
  185. Type *src_type = value.type;
  186. if (are_types_identical(t, src_type)) {
  187. return value;
  188. }
  189. lbValue res = {};
  190. res.type = t;
  191. Type *src = base_type(src_type);
  192. Type *dst = base_type(t);
  193. lbModule *m = p->module;
  194. i64 sz = type_size_of(src);
  195. i64 dz = type_size_of(dst);
  196. if (sz != dz) {
  197. LLVMTypeRef s = lb_type(m, src);
  198. LLVMTypeRef d = lb_type(m, dst);
  199. i64 llvm_sz = lb_sizeof(s);
  200. i64 llvm_dz = lb_sizeof(d);
  201. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  202. }
  203. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  204. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  205. if (is_type_internally_pointer_like(src)) {
  206. if (is_type_integer(dst)) {
  207. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  208. return res;
  209. } else if (is_type_internally_pointer_like(dst)) {
  210. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  211. return res;
  212. } else if (is_type_float(dst)) {
  213. LLVMValueRef the_int = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t_uintptr), "");
  214. res.value = LLVMBuildBitCast(p->builder, the_int, lb_type(m, t), "");
  215. return res;
  216. }
  217. }
  218. if (is_type_internally_pointer_like(dst)) {
  219. if (is_type_uintptr(src) && is_type_internally_pointer_like(dst)) {
  220. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  221. return res;
  222. } else if (is_type_integer(src) && is_type_internally_pointer_like(dst)) {
  223. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  224. return res;
  225. } else if (is_type_float(src)) {
  226. LLVMValueRef the_int = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t_uintptr), "");
  227. res.value = LLVMBuildIntToPtr(p->builder, the_int, lb_type(m, t), "");
  228. return res;
  229. }
  230. }
  231. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  232. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  233. return res;
  234. } else if (is_type_array_like(src) && (is_type_simd_vector(dst) || is_type_integer_128bit(dst))) {
  235. unsigned align = cast(unsigned)gb_max(type_align_of(src), type_align_of(dst));
  236. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  237. if (lb_try_update_alignment(ptr, align)) {
  238. LLVMTypeRef result_type = lb_type(p->module, t);
  239. res.value = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(result_type, 0), "");
  240. res.value = OdinLLVMBuildLoad(p, result_type, res.value);
  241. return res;
  242. }
  243. lbAddr addr = lb_add_local_generated(p, t, false);
  244. lbValue ap = lb_addr_get_ptr(p, addr);
  245. ap = lb_emit_conv(p, ap, alloc_type_pointer(value.type));
  246. lb_emit_store(p, ap, value);
  247. return lb_addr_load(p, addr);
  248. } else if (is_type_map(src) && are_types_identical(t_raw_map, t)) {
  249. res.value = value.value;
  250. res.type = t;
  251. return res;
  252. } else if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  253. lbValue s = lb_address_from_load_or_generate_local(p, value);
  254. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  255. return lb_emit_load(p, d);
  256. }
  257. res.value = OdinLLVMBuildTransmute(p, value.value, lb_type(m, res.type));
  258. return res;
  259. }
  260. gb_internal lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  261. i64 type_alignment = type_align_of(new_type);
  262. if (alignment < type_alignment) {
  263. alignment = type_alignment;
  264. }
  265. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  266. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  267. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  268. lb_addr_store(p, ptr, val);
  269. // ptr.kind = lbAddr_Context;
  270. return ptr.addr;
  271. }
  272. gb_internal lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  273. GB_ASSERT(ce->args.count > 0);
  274. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  275. for_array(i, slices) {
  276. Ast *arg = ce->args[i];
  277. if (arg->kind == Ast_FieldValue) {
  278. arg = arg->FieldValue.value;
  279. }
  280. slices[i] = lb_build_expr(p, arg);
  281. }
  282. lbValue len = lb_slice_len(p, slices[0]);
  283. for (isize i = 1; i < slices.count; i++) {
  284. lbValue other_len = lb_slice_len(p, slices[i]);
  285. len = lb_emit_min(p, t_int, len, other_len);
  286. }
  287. GB_ASSERT(is_type_soa_struct(tv.type));
  288. lbAddr res = lb_add_local_generated(p, tv.type, true);
  289. for_array(i, slices) {
  290. lbValue src = lb_slice_elem(p, slices[i]);
  291. src = lb_emit_conv(p, src, alloc_type_pointer_to_multi_pointer(src.type));
  292. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  293. lb_emit_store(p, dst, src);
  294. }
  295. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  296. lb_emit_store(p, len_dst, len);
  297. return lb_addr_load(p, res);
  298. }
  299. gb_internal lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  300. GB_ASSERT(ce->args.count == 1);
  301. lbValue arg = lb_build_expr(p, ce->args[0]);
  302. Type *t = base_type(arg.type);
  303. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  304. lbValue len = lb_soa_struct_len(p, arg);
  305. lbAddr res = lb_add_local_generated(p, tv.type, true);
  306. if (is_type_tuple(tv.type)) {
  307. lbValue rp = lb_addr_get_ptr(p, res);
  308. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  309. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  310. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  311. lb_fill_slice(p, dst, ptr, len);
  312. }
  313. } else {
  314. GB_ASSERT(is_type_slice(tv.type));
  315. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  316. lb_fill_slice(p, res, ptr, len);
  317. }
  318. return lb_addr_load(p, res);
  319. }
  320. gb_internal void lb_emit_try_lhs_rhs(lbProcedure *p, Ast *arg, TypeAndValue const &tv, lbValue *lhs_, lbValue *rhs_) {
  321. lbValue lhs = {};
  322. lbValue rhs = {};
  323. lbValue value = lb_build_expr(p, arg);
  324. if (is_type_tuple(value.type)) {
  325. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  326. if (value.type->Tuple.variables.count == 2) {
  327. lhs = lb_emit_tuple_ev(p, value, 0);
  328. } else {
  329. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  330. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  331. for (i32 i = 0; i < n; i++) {
  332. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_tuple_ev(p, value, i));
  333. }
  334. lhs = lb_addr_load(p, lhs_addr);
  335. }
  336. rhs = lb_emit_tuple_ev(p, value, n);
  337. } else {
  338. rhs = value;
  339. }
  340. GB_ASSERT(rhs.value != nullptr);
  341. if (lhs_) *lhs_ = lhs;
  342. if (rhs_) *rhs_ = rhs;
  343. }
  344. gb_internal lbValue lb_emit_try_has_value(lbProcedure *p, lbValue rhs) {
  345. lbValue has_value = {};
  346. if (is_type_boolean(rhs.type)) {
  347. has_value = rhs;
  348. } else {
  349. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  350. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  351. }
  352. GB_ASSERT(has_value.value != nullptr);
  353. return has_value;
  354. }
  355. gb_internal lbValue lb_emit_or_else(lbProcedure *p, Ast *arg, Ast *else_expr, TypeAndValue const &tv) {
  356. if (arg->state_flags & StateFlag_DirectiveWasFalse) {
  357. return lb_build_expr(p, else_expr);
  358. }
  359. lbValue lhs = {};
  360. lbValue rhs = {};
  361. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  362. GB_ASSERT(else_expr != nullptr);
  363. Type *type = default_type(tv.type);
  364. if (is_diverging_expr(else_expr)) {
  365. lbBlock *then = lb_create_block(p, "or_else.then");
  366. lbBlock *else_ = lb_create_block(p, "or_else.else");
  367. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  368. // NOTE(bill): else block needs to be straight afterwards to make sure that the actual value is used
  369. // from the then block
  370. lb_start_block(p, else_);
  371. lb_build_expr(p, else_expr);
  372. lb_emit_unreachable(p); // add just in case
  373. lb_start_block(p, then);
  374. return lb_emit_conv(p, lhs, type);
  375. } else {
  376. LLVMValueRef incoming_values[2] = {};
  377. LLVMBasicBlockRef incoming_blocks[2] = {};
  378. lbBlock *then = lb_create_block(p, "or_else.then");
  379. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  380. lbBlock *else_ = lb_create_block(p, "or_else.else");
  381. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  382. lb_start_block(p, then);
  383. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  384. lb_emit_jump(p, done);
  385. lb_start_block(p, else_);
  386. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_expr), type).value;
  387. lb_emit_jump(p, done);
  388. lb_start_block(p, done);
  389. lbValue res = {};
  390. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  391. res.type = type;
  392. GB_ASSERT(p->curr_block->preds.count >= 2);
  393. incoming_blocks[0] = p->curr_block->preds[0]->block;
  394. incoming_blocks[1] = p->curr_block->preds[1]->block;
  395. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  396. return res;
  397. }
  398. }
  399. gb_internal void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results, TokenPos pos);
  400. gb_internal void lb_build_return_stmt_internal(lbProcedure *p, lbValue res, TokenPos pos);
  401. gb_internal lbValue lb_emit_or_return(lbProcedure *p, Ast *arg, TypeAndValue const &tv) {
  402. lbValue lhs = {};
  403. lbValue rhs = {};
  404. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  405. lbBlock *return_block = lb_create_block(p, "or_return.return");
  406. lbBlock *continue_block = lb_create_block(p, "or_return.continue");
  407. lb_emit_if(p, lb_emit_try_has_value(p, rhs), continue_block, return_block);
  408. lb_start_block(p, return_block);
  409. {
  410. Type *proc_type = base_type(p->type);
  411. Type *results = proc_type->Proc.results;
  412. GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  413. TypeTuple *tuple = &results->Tuple;
  414. GB_ASSERT(tuple->variables.count != 0);
  415. Entity *end_entity = tuple->variables[tuple->variables.count-1];
  416. rhs = lb_emit_conv(p, rhs, end_entity->type);
  417. if (p->type->Proc.has_named_results) {
  418. GB_ASSERT(end_entity->token.string.len != 0);
  419. // NOTE(bill): store the named values before returning
  420. lbValue found = map_must_get(&p->module->values, end_entity);
  421. lb_emit_store(p, found, rhs);
  422. lb_build_return_stmt(p, {}, ast_token(arg).pos);
  423. } else {
  424. GB_ASSERT(tuple->variables.count == 1);
  425. lb_build_return_stmt_internal(p, rhs, ast_token(arg).pos);
  426. }
  427. }
  428. lb_start_block(p, continue_block);
  429. if (tv.type != nullptr) {
  430. return lb_emit_conv(p, lhs, tv.type);
  431. }
  432. return {};
  433. }
  434. gb_internal void lb_emit_increment(lbProcedure *p, lbValue addr) {
  435. GB_ASSERT(is_type_pointer(addr.type));
  436. Type *type = type_deref(addr.type);
  437. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  438. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  439. }
  440. gb_internal lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  441. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  442. if (type_size_of(value.type) < 2) {
  443. return value;
  444. }
  445. Type *original_type = value.type;
  446. if (is_type_float(original_type)) {
  447. i64 sz = type_size_of(original_type);
  448. Type *integer_type = nullptr;
  449. switch (sz) {
  450. case 2: integer_type = t_u16; break;
  451. case 4: integer_type = t_u32; break;
  452. case 8: integer_type = t_u64; break;
  453. }
  454. GB_ASSERT(integer_type != nullptr);
  455. value = lb_emit_transmute(p, value, integer_type);
  456. }
  457. char const *name = "llvm.bswap";
  458. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  459. LLVMValueRef args[1] = { value.value };
  460. lbValue res = {};
  461. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  462. res.type = value.type;
  463. if (is_type_float(original_type)) {
  464. res = lb_emit_transmute(p, res, original_type);
  465. }
  466. res.type = end_type;
  467. return res;
  468. }
  469. gb_internal lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  470. x = lb_emit_conv(p, x, type);
  471. char const *name = "llvm.ctpop";
  472. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  473. LLVMValueRef args[1] = { x.value };
  474. lbValue res = {};
  475. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  476. res.type = type;
  477. return res;
  478. }
  479. gb_internal lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  480. Type *elem = base_array_type(type);
  481. i64 sz = 8*type_size_of(elem);
  482. lbValue size = lb_const_int(p->module, elem, cast(u64)sz);
  483. size = lb_emit_conv(p, size, type);
  484. lbValue count = lb_emit_count_ones(p, x, type);
  485. return lb_emit_arith(p, Token_Sub, size, count, type);
  486. }
  487. gb_internal lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  488. x = lb_emit_conv(p, x, type);
  489. char const *name = "llvm.cttz";
  490. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  491. LLVMValueRef args[2] = {
  492. x.value,
  493. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  494. lbValue res = {};
  495. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  496. res.type = type;
  497. return res;
  498. }
  499. gb_internal lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  500. x = lb_emit_conv(p, x, type);
  501. char const *name = "llvm.ctlz";
  502. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  503. LLVMValueRef args[2] = {
  504. x.value,
  505. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  506. lbValue res = {};
  507. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  508. res.type = type;
  509. return res;
  510. }
  511. gb_internal lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  512. x = lb_emit_conv(p, x, type);
  513. char const *name = "llvm.bitreverse";
  514. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  515. LLVMValueRef args[1] = { x.value };
  516. lbValue res = {};
  517. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  518. res.type = type;
  519. return res;
  520. }
  521. gb_internal lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  522. GB_ASSERT(is_type_tuple(type));
  523. lbModule *m = p->module;
  524. Type *src_type = value.type;
  525. bool is_ptr = is_type_pointer(src_type);
  526. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  527. // so when it does an assignment, it complete ignores the value.
  528. // Just make it two booleans and ignore the first one
  529. //
  530. // _, ok := x.(T);
  531. //
  532. Type *ok_type = type->Tuple.variables[1]->type;
  533. Type *gen_tuple_types[2] = {};
  534. gen_tuple_types[0] = ok_type;
  535. gen_tuple_types[1] = ok_type;
  536. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  537. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  538. if (is_ptr) {
  539. value = lb_emit_load(p, value);
  540. }
  541. Type *src = base_type(type_deref(src_type));
  542. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  543. Type *dst = type->Tuple.variables[0]->type;
  544. lbValue cond = {};
  545. if (is_type_union_maybe_pointer(src)) {
  546. lbValue data = lb_emit_transmute(p, value, dst);
  547. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  548. } else {
  549. lbValue tag = lb_emit_union_tag_value(p, value);
  550. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  551. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  552. }
  553. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  554. lb_emit_store(p, gep1, cond);
  555. return lb_addr_load(p, v);
  556. }
  557. gb_internal lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  558. lbModule *m = p->module;
  559. Type *src_type = value.type;
  560. bool is_ptr = is_type_pointer(src_type);
  561. bool is_tuple = true;
  562. Type *tuple = type;
  563. if (type->kind != Type_Tuple) {
  564. is_tuple = false;
  565. tuple = make_optional_ok_type(type);
  566. }
  567. lbAddr v = lb_add_local_generated(p, tuple, true);
  568. if (is_ptr) {
  569. value = lb_emit_load(p, value);
  570. }
  571. Type *src = base_type(type_deref(src_type));
  572. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  573. Type *dst = tuple->Tuple.variables[0]->type;
  574. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  575. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  576. // just do a bit cast of the data at the front
  577. lbValue ptr = lb_emit_conv(p, value_, alloc_type_pointer(type));
  578. return lb_emit_load(p, ptr);
  579. }
  580. lbValue tag = {};
  581. lbValue dst_tag = {};
  582. lbValue cond = {};
  583. lbValue data = {};
  584. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  585. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  586. if (is_type_union_maybe_pointer(src)) {
  587. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  588. } else {
  589. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  590. dst_tag = lb_const_union_tag(m, src, dst);
  591. }
  592. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  593. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  594. if (data.value != nullptr) {
  595. GB_ASSERT(is_type_union_maybe_pointer(src));
  596. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  597. } else {
  598. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  599. }
  600. lb_emit_if(p, cond, ok_block, end_block);
  601. lb_start_block(p, ok_block);
  602. if (data.value == nullptr) {
  603. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  604. }
  605. lb_emit_store(p, gep0, data);
  606. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  607. lb_emit_jump(p, end_block);
  608. lb_start_block(p, end_block);
  609. if (!is_tuple) {
  610. if (!build_context.no_type_assert) {
  611. GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0);
  612. // NOTE(bill): Panic on invalid conversion
  613. Type *dst_type = tuple->Tuple.variables[0]->type;
  614. isize arg_count = 7;
  615. if (build_context.no_rtti) {
  616. arg_count = 4;
  617. }
  618. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  619. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  620. args[0] = ok;
  621. lb_set_file_line_col(p, array_slice(args, 1, args.count), pos);
  622. if (!build_context.no_rtti) {
  623. args[4] = lb_typeid(m, src_type);
  624. args[5] = lb_typeid(m, dst_type);
  625. args[6] = lb_emit_conv(p, value_, t_rawptr);
  626. }
  627. lb_emit_runtime_call(p, "type_assertion_check2", args);
  628. }
  629. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  630. }
  631. return lb_addr_load(p, v);
  632. }
  633. gb_internal lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  634. lbModule *m = p->module;
  635. Type *src_type = value.type;
  636. if (is_type_pointer(src_type)) {
  637. value = lb_emit_load(p, value);
  638. }
  639. bool is_tuple = true;
  640. Type *tuple = type;
  641. if (type->kind != Type_Tuple) {
  642. is_tuple = false;
  643. tuple = make_optional_ok_type(type);
  644. }
  645. Type *dst_type = tuple->Tuple.variables[0]->type;
  646. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  647. // just do a bit cast of the data at the front
  648. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  649. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(type));
  650. return lb_addr(ptr);
  651. }
  652. lbAddr v = lb_add_local_generated(p, tuple, true);
  653. lbValue dst_typeid = lb_typeid(m, dst_type);
  654. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  655. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  656. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  657. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  658. lb_emit_if(p, cond, ok_block, end_block);
  659. lb_start_block(p, ok_block);
  660. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  661. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  662. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  663. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  664. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  665. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  666. lb_emit_jump(p, end_block);
  667. lb_start_block(p, end_block);
  668. if (!is_tuple) {
  669. // NOTE(bill): Panic on invalid conversion
  670. if (!build_context.no_type_assert) {
  671. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  672. isize arg_count = 7;
  673. if (build_context.no_rtti) {
  674. arg_count = 4;
  675. }
  676. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  677. args[0] = ok;
  678. lb_set_file_line_col(p, array_slice(args, 1, args.count), pos);
  679. if (!build_context.no_rtti) {
  680. args[4] = any_typeid;
  681. args[5] = dst_typeid;
  682. args[6] = lb_emit_struct_ev(p, value, 0);
  683. }
  684. lb_emit_runtime_call(p, "type_assertion_check2", args);
  685. }
  686. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  687. }
  688. return v;
  689. }
  690. gb_internal lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  691. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  692. }
  693. gb_internal lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  694. if (p->context_stack.count > 0) {
  695. return p->context_stack[p->context_stack.count-1].ctx;
  696. }
  697. Type *pt = base_type(p->type);
  698. GB_ASSERT(pt->kind == Type_Proc);
  699. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  700. lbAddr c = lb_add_local_generated(p, t_context, true);
  701. c.kind = lbAddr_Context;
  702. lb_emit_init_context(p, c);
  703. lb_push_context_onto_stack(p, c);
  704. lb_add_debug_context_variable(p, c);
  705. return c;
  706. }
  707. gb_internal lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  708. if (LLVMIsALoadInst(value.value)) {
  709. lbValue res = {};
  710. res.value = LLVMGetOperand(value.value, 0);
  711. res.type = alloc_type_pointer(value.type);
  712. return res;
  713. }
  714. GB_ASSERT(is_type_typed(value.type));
  715. lbAddr res = lb_add_local_generated(p, value.type, false);
  716. lb_addr_store(p, res, value);
  717. return res.addr;
  718. }
  719. gb_internal lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  720. if (LLVMIsALoadInst(value.value)) {
  721. lbValue res = {};
  722. res.value = LLVMGetOperand(value.value, 0);
  723. res.type = alloc_type_pointer(value.type);
  724. return res;
  725. }
  726. GB_PANIC("lb_address_from_load");
  727. return {};
  728. }
  729. gb_internal lbValue lb_address_from_load_if_readonly_parameter(lbProcedure *p, lbValue x) {
  730. if (!LLVMIsALoadInst(x.value)) {
  731. return {};
  732. }
  733. LLVMValueRef optr = LLVMGetOperand(x.value, 0);
  734. while (optr && LLVMIsABitCastInst(optr)) {
  735. optr = LLVMGetOperand(optr, 0);
  736. }
  737. LLVMAttributeIndex param_index = 1;
  738. if (p->return_ptr.addr.value) {
  739. param_index++;
  740. }
  741. bool is_parameter = false;
  742. for (LLVMValueRef param : p->raw_input_parameters) {
  743. if (param == optr) {
  744. is_parameter = true;
  745. break;
  746. }
  747. param_index++;
  748. }
  749. if (is_parameter) {
  750. unsigned readonly_attr_kind = LLVMGetEnumAttributeKindForName("readonly", 8);
  751. unsigned n = LLVMGetAttributeCountAtIndex(p->value, param_index);
  752. if (n) {
  753. TEMPORARY_ALLOCATOR_GUARD();
  754. LLVMAttributeRef *attrs = gb_alloc_array(temporary_allocator(), LLVMAttributeRef, n);
  755. LLVMGetAttributesAtIndex(p->value, param_index, attrs);
  756. for (unsigned i = 0; i < n; i++) {
  757. if (LLVMGetEnumAttributeKind(attrs[i]) == readonly_attr_kind) {
  758. return lb_address_from_load_or_generate_local(p, x);
  759. }
  760. }
  761. }
  762. }
  763. return {};
  764. }
  765. gb_internal lbStructFieldRemapping lb_get_struct_remapping(lbModule *m, Type *t) {
  766. t = base_type(t);
  767. LLVMTypeRef struct_type = lb_type(m, t);
  768. mutex_lock(&m->types_mutex);
  769. auto *field_remapping = map_get(&m->struct_field_remapping, cast(void *)struct_type);
  770. if (field_remapping == nullptr) {
  771. field_remapping = map_get(&m->struct_field_remapping, cast(void *)t);
  772. }
  773. mutex_unlock(&m->types_mutex);
  774. GB_ASSERT_MSG(field_remapping != nullptr, "%s", type_to_string(t));
  775. return *field_remapping;
  776. }
  777. gb_internal i32 lb_convert_struct_index(lbModule *m, Type *t, i32 index) {
  778. if (t->kind == Type_Struct) {
  779. auto field_remapping = lb_get_struct_remapping(m, t);
  780. return field_remapping[index];
  781. } else if (is_type_any(t) && build_context.ptr_size == 4) {
  782. GB_ASSERT(t->kind == Type_Basic);
  783. GB_ASSERT(t->Basic.kind == Basic_any);
  784. switch (index) {
  785. case 0: return 0; // data
  786. case 1: return 2; // id
  787. }
  788. } else if (build_context.ptr_size != build_context.int_size) {
  789. switch (t->kind) {
  790. case Type_Basic:
  791. if (t->Basic.kind != Basic_string &&
  792. t->Basic.kind != Basic_string16) {
  793. break;
  794. }
  795. /*fallthrough*/
  796. case Type_Slice:
  797. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  798. switch (index) {
  799. case 0: return 0; // data
  800. case 1: return 2; // len
  801. }
  802. break;
  803. case Type_DynamicArray:
  804. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  805. switch (index) {
  806. case 0: return 0; // data
  807. case 1: return 2; // len
  808. case 2: return 3; // cap
  809. case 3: return 4; // allocator
  810. }
  811. break;
  812. case Type_SoaPointer:
  813. GB_ASSERT(build_context.ptr_size*2 == build_context.int_size);
  814. switch (index) {
  815. case 0: return 0; // data
  816. case 1: return 2; // offset
  817. }
  818. break;
  819. }
  820. }
  821. return index;
  822. }
  823. gb_internal LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 padding_align) {
  824. MUTEX_GUARD(&m->pad_types_mutex);
  825. if (padding % padding_align == 0) {
  826. for (auto pd : m->pad_types) {
  827. if (pd.padding == padding && pd.padding_align == padding_align) {
  828. return pd.type;
  829. }
  830. }
  831. } else {
  832. for (auto pd : m->pad_types) {
  833. if (pd.padding == padding && pd.padding_align == 1) {
  834. return pd.type;
  835. }
  836. }
  837. }
  838. // NOTE(bill): limit to `[N x u64]` to prevent ABI issues
  839. padding_align = gb_clamp(padding_align, 1, 8);
  840. if (padding % padding_align == 0) {
  841. LLVMTypeRef elem = nullptr;
  842. isize len = padding/padding_align;
  843. switch (padding_align) {
  844. case 1: elem = lb_type(m, t_u8); break;
  845. case 2: elem = lb_type(m, t_u16); break;
  846. case 4: elem = lb_type(m, t_u32); break;
  847. case 8: elem = lb_type(m, t_u64); break;
  848. }
  849. GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
  850. LLVMTypeRef type = nullptr;
  851. if (len != 1) {
  852. type = llvm_array_type(elem, len);
  853. } else {
  854. type = elem;
  855. }
  856. array_add(&m->pad_types, lbPadType{padding, padding_align, type});
  857. return type;
  858. } else {
  859. LLVMTypeRef type = llvm_array_type(lb_type(m, t_u8), padding);
  860. array_add(&m->pad_types, lbPadType{padding, 1, type});
  861. return type;
  862. }
  863. }
  864. gb_global char const *llvm_type_kinds[] = {
  865. "LLVMVoidTypeKind",
  866. "LLVMHalfTypeKind",
  867. "LLVMFloatTypeKind",
  868. "LLVMDoubleTypeKind",
  869. "LLVMX86_FP80TypeKind",
  870. "LLVMFP128TypeKind",
  871. "LLVMPPC_FP128TypeKind",
  872. "LLVMLabelTypeKind",
  873. "LLVMIntegerTypeKind",
  874. "LLVMFunctionTypeKind",
  875. "LLVMStructTypeKind",
  876. "LLVMArrayTypeKind",
  877. "LLVMPointerTypeKind",
  878. "LLVMVectorTypeKind",
  879. "LLVMMetadataTypeKind",
  880. "LLVMX86_MMXTypeKind",
  881. "LLVMTokenTypeKind",
  882. "LLVMScalableVectorTypeKind",
  883. "LLVMBFloatTypeKind",
  884. };
  885. gb_internal lbValue lb_emit_struct_ep_internal(lbProcedure *p, lbValue s, i32 index, Type *result_type) {
  886. Type *t = base_type(type_deref(s.type));
  887. i32 original_index = index;
  888. index = lb_convert_struct_index(p->module, t, index);
  889. if (lb_is_const(s)) {
  890. // NOTE(bill): this cannot be replaced with lb_emit_epi
  891. lbModule *m = p->module;
  892. lbValue res = {};
  893. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  894. res.value = LLVMConstGEP2(lb_type(m, type_deref(s.type)), s.value, indices, gb_count_of(indices));
  895. res.type = alloc_type_pointer(result_type);
  896. return res;
  897. } else {
  898. lbValue res = {};
  899. LLVMTypeRef st = lb_type(p->module, type_deref(s.type));
  900. // gb_printf_err("%s\n", type_to_string(s.type));
  901. // gb_printf_err("%s\n", LLVMPrintTypeToString(LLVMTypeOf(s.value)));
  902. // gb_printf_err("%d\n", index);
  903. GB_ASSERT_MSG(LLVMGetTypeKind(st) == LLVMStructTypeKind, "%s", llvm_type_kinds[LLVMGetTypeKind(st)]);
  904. unsigned count = LLVMCountStructElementTypes(st);
  905. GB_ASSERT_MSG(count >= cast(unsigned)index, "%u %d %d", count, index, original_index);
  906. res.value = LLVMBuildStructGEP2(p->builder, st, s.value, cast(unsigned)index, "");
  907. res.type = alloc_type_pointer(result_type);
  908. return res;
  909. }
  910. }
  911. gb_internal lbValue lb_emit_tuple_ep(lbProcedure *p, lbValue ptr, i32 index) {
  912. Type *t = type_deref(ptr.type);
  913. GB_ASSERT(is_type_tuple(t));
  914. Type *result_type = t->Tuple.variables[index]->type;
  915. lbValue res = {};
  916. lbTupleFix *tf = map_get(&p->tuple_fix_map, ptr.value);
  917. if (tf) {
  918. res = tf->values[index];
  919. GB_ASSERT(are_types_identical(res.type, result_type));
  920. res = lb_address_from_load_or_generate_local(p, res);
  921. } else {
  922. res = lb_emit_struct_ep_internal(p, ptr, index, result_type);
  923. }
  924. return res;
  925. }
  926. gb_internal lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  927. GB_ASSERT(is_type_pointer(s.type));
  928. Type *t = base_type(type_deref(s.type));
  929. Type *result_type = nullptr;
  930. if (is_type_struct(t)) {
  931. result_type = get_struct_field_type(t, index);
  932. } else if (is_type_union(t)) {
  933. GB_ASSERT(index == -1);
  934. return lb_emit_union_tag_ptr(p, s);
  935. } else if (is_type_tuple(t)) {
  936. return lb_emit_tuple_ep(p, s, index);
  937. } else if (is_type_complex(t)) {
  938. Type *ft = base_complex_elem_type(t);
  939. switch (index) {
  940. case 0: result_type = ft; break;
  941. case 1: result_type = ft; break;
  942. }
  943. } else if (is_type_quaternion(t)) {
  944. Type *ft = base_complex_elem_type(t);
  945. switch (index) {
  946. case 0: result_type = ft; break;
  947. case 1: result_type = ft; break;
  948. case 2: result_type = ft; break;
  949. case 3: result_type = ft; break;
  950. }
  951. } else if (is_type_slice(t)) {
  952. switch (index) {
  953. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  954. case 1: result_type = t_int; break;
  955. }
  956. } else if (is_type_string16(t)) {
  957. switch (index) {
  958. case 0: result_type = t_u16_ptr; break;
  959. case 1: result_type = t_int; break;
  960. }
  961. } else if (is_type_string(t)) {
  962. switch (index) {
  963. case 0: result_type = t_u8_ptr; break;
  964. case 1: result_type = t_int; break;
  965. }
  966. } else if (is_type_any(t)) {
  967. switch (index) {
  968. case 0: result_type = t_rawptr; break;
  969. case 1: result_type = t_typeid; break;
  970. }
  971. } else if (is_type_dynamic_array(t)) {
  972. switch (index) {
  973. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  974. case 1: result_type = t_int; break;
  975. case 2: result_type = t_int; break;
  976. case 3: result_type = t_allocator; break;
  977. }
  978. } else if (is_type_map(t)) {
  979. init_map_internal_debug_types(t);
  980. Type *itp = alloc_type_pointer(t_raw_map);
  981. s = lb_emit_transmute(p, s, itp);
  982. switch (index) {
  983. case 0: result_type = get_struct_field_type(t_raw_map, 0); break;
  984. case 1: result_type = get_struct_field_type(t_raw_map, 1); break;
  985. case 2: result_type = get_struct_field_type(t_raw_map, 2); break;
  986. }
  987. } else if (is_type_array(t)) {
  988. return lb_emit_array_epi(p, s, index);
  989. } else if (is_type_soa_pointer(t)) {
  990. switch (index) {
  991. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  992. case 1: result_type = t_int; break;
  993. }
  994. } else {
  995. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  996. }
  997. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  998. lbValue gep = lb_emit_struct_ep_internal(p, s, index, result_type);
  999. Type *bt = base_type(t);
  1000. if (bt->kind == Type_Struct) {
  1001. if (bt->Struct.is_packed) {
  1002. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_IS_PACKED, 1);
  1003. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_IS_PACKED) == 1);
  1004. }
  1005. u64 align_max = bt->Struct.custom_max_field_align;
  1006. u64 align_min = bt->Struct.custom_min_field_align;
  1007. GB_ASSERT(align_min == 0 || align_max == 0 || align_min <= align_max);
  1008. if (align_max) {
  1009. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MAX_ALIGN, align_max);
  1010. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MAX_ALIGN) == align_max);
  1011. }
  1012. if (align_min) {
  1013. lb_set_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MIN_ALIGN, align_min);
  1014. GB_ASSERT(lb_get_metadata_custom_u64(p->module, gep.value, ODIN_METADATA_MIN_ALIGN) == align_min);
  1015. }
  1016. }
  1017. return gep;
  1018. }
  1019. gb_internal lbValue lb_emit_tuple_ev(lbProcedure *p, lbValue value, i32 index) {
  1020. Type *t = value.type;
  1021. GB_ASSERT(is_type_tuple(t));
  1022. Type *result_type = t->Tuple.variables[index]->type;
  1023. lbValue res = {};
  1024. lbTupleFix *tf = map_get(&p->tuple_fix_map, value.value);
  1025. if (tf) {
  1026. res = tf->values[index];
  1027. GB_ASSERT(are_types_identical(res.type, result_type));
  1028. } else {
  1029. if (t->Tuple.variables.count == 1) {
  1030. GB_ASSERT(index == 0);
  1031. // value.type = result_type;
  1032. return value;
  1033. }
  1034. if (LLVMIsALoadInst(value.value)) {
  1035. lbValue res = {};
  1036. res.value = LLVMGetOperand(value.value, 0);
  1037. res.type = alloc_type_pointer(value.type);
  1038. lbValue ptr = lb_emit_struct_ep(p, res, index);
  1039. return lb_emit_load(p, ptr);
  1040. }
  1041. res.value = LLVMBuildExtractValue(p->builder, value.value, cast(unsigned)index, "");
  1042. res.type = result_type;
  1043. }
  1044. return res;
  1045. }
  1046. gb_internal lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  1047. Type *t = base_type(s.type);
  1048. if (is_type_tuple(t)) {
  1049. return lb_emit_tuple_ev(p, s, index);
  1050. }
  1051. if (LLVMIsALoadInst(s.value)) {
  1052. lbValue res = {};
  1053. res.value = LLVMGetOperand(s.value, 0);
  1054. res.type = alloc_type_pointer(s.type);
  1055. lbValue ptr = lb_emit_struct_ep(p, res, index);
  1056. return lb_emit_load(p, ptr);
  1057. }
  1058. Type *result_type = nullptr;
  1059. switch (t->kind) {
  1060. case Type_Basic:
  1061. switch (t->Basic.kind) {
  1062. case Basic_string16:
  1063. switch (index) {
  1064. case 0: result_type = t_u16_ptr; break;
  1065. case 1: result_type = t_int; break;
  1066. }
  1067. break;
  1068. case Basic_string:
  1069. switch (index) {
  1070. case 0: result_type = t_u8_ptr; break;
  1071. case 1: result_type = t_int; break;
  1072. }
  1073. break;
  1074. case Basic_any:
  1075. switch (index) {
  1076. case 0: result_type = t_rawptr; break;
  1077. case 1: result_type = t_typeid; break;
  1078. }
  1079. break;
  1080. case Basic_complex32:
  1081. case Basic_complex64:
  1082. case Basic_complex128:
  1083. {
  1084. Type *ft = base_complex_elem_type(t);
  1085. switch (index) {
  1086. case 0: result_type = ft; break;
  1087. case 1: result_type = ft; break;
  1088. }
  1089. break;
  1090. }
  1091. case Basic_quaternion64:
  1092. case Basic_quaternion128:
  1093. case Basic_quaternion256:
  1094. {
  1095. Type *ft = base_complex_elem_type(t);
  1096. switch (index) {
  1097. case 0: result_type = ft; break;
  1098. case 1: result_type = ft; break;
  1099. case 2: result_type = ft; break;
  1100. case 3: result_type = ft; break;
  1101. }
  1102. break;
  1103. }
  1104. }
  1105. break;
  1106. case Type_Struct:
  1107. result_type = get_struct_field_type(t, index);
  1108. break;
  1109. case Type_Union:
  1110. GB_ASSERT(index == -1);
  1111. // return lb_emit_union_tag_value(p, s);
  1112. GB_PANIC("lb_emit_union_tag_value");
  1113. case Type_Tuple:
  1114. return lb_emit_tuple_ev(p, s, index);
  1115. case Type_Slice:
  1116. switch (index) {
  1117. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  1118. case 1: result_type = t_int; break;
  1119. }
  1120. break;
  1121. case Type_DynamicArray:
  1122. switch (index) {
  1123. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  1124. case 1: result_type = t_int; break;
  1125. case 2: result_type = t_int; break;
  1126. case 3: result_type = t_allocator; break;
  1127. }
  1128. break;
  1129. case Type_Map:
  1130. {
  1131. init_map_internal_debug_types(t);
  1132. switch (index) {
  1133. case 0: result_type = get_struct_field_type(t_raw_map, 0); break;
  1134. case 1: result_type = get_struct_field_type(t_raw_map, 1); break;
  1135. case 2: result_type = get_struct_field_type(t_raw_map, 2); break;
  1136. }
  1137. }
  1138. break;
  1139. case Type_Array:
  1140. result_type = t->Array.elem;
  1141. break;
  1142. case Type_SoaPointer:
  1143. switch (index) {
  1144. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  1145. case 1: result_type = t_int; break;
  1146. }
  1147. break;
  1148. default:
  1149. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  1150. break;
  1151. }
  1152. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  1153. index = lb_convert_struct_index(p->module, t, index);
  1154. lbValue res = {};
  1155. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  1156. res.type = result_type;
  1157. return res;
  1158. }
  1159. gb_internal lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  1160. GB_ASSERT(sel.index.count > 0);
  1161. Type *type = type_deref(e.type);
  1162. for_array(i, sel.index) {
  1163. i32 index = cast(i32)sel.index[i];
  1164. if (is_type_pointer(type)) {
  1165. type = type_deref(type);
  1166. e = lb_emit_load(p, e);
  1167. }
  1168. type = core_type(type);
  1169. if (type->kind == Type_SoaPointer) {
  1170. lbValue addr = lb_emit_struct_ep(p, e, 0);
  1171. lbValue index = lb_emit_struct_ep(p, e, 1);
  1172. addr = lb_emit_load(p, addr);
  1173. index = lb_emit_load(p, index);
  1174. i32 first_index = sel.index[0];
  1175. Selection sub_sel = sel;
  1176. sub_sel.index.data += 1;
  1177. sub_sel.index.count -= 1;
  1178. lbValue arr = lb_emit_struct_ep(p, addr, first_index);
  1179. Type *t = base_type(type_deref(addr.type));
  1180. GB_ASSERT(is_type_soa_struct(t));
  1181. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1182. e = lb_emit_array_ep(p, arr, index);
  1183. } else {
  1184. e = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  1185. }
  1186. e.type = alloc_type_multi_pointer_to_pointer(e.type);
  1187. } else if (is_type_quaternion(type)) {
  1188. e = lb_emit_struct_ep(p, e, index);
  1189. } else if (is_type_raw_union(type)) {
  1190. type = get_struct_field_type(type, index);
  1191. GB_ASSERT(is_type_pointer(e.type));
  1192. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  1193. } else if (is_type_struct(type)) {
  1194. type = get_struct_field_type(type, index);
  1195. e = lb_emit_struct_ep(p, e, index);
  1196. } else if (type->kind == Type_Union) {
  1197. GB_ASSERT(index == -1);
  1198. type = t_type_info_ptr;
  1199. e = lb_emit_struct_ep(p, e, index);
  1200. } else if (type->kind == Type_Tuple) {
  1201. type = type->Tuple.variables[index]->type;
  1202. e = lb_emit_struct_ep(p, e, index);
  1203. } else if (type->kind == Type_Basic) {
  1204. switch (type->Basic.kind) {
  1205. case Basic_any: {
  1206. if (index == 0) {
  1207. type = t_rawptr;
  1208. } else if (index == 1) {
  1209. type = t_typeid;
  1210. }
  1211. e = lb_emit_struct_ep(p, e, index);
  1212. break;
  1213. }
  1214. case Basic_string:
  1215. e = lb_emit_struct_ep(p, e, index);
  1216. break;
  1217. case Basic_string16:
  1218. e = lb_emit_struct_ep(p, e, index);
  1219. break;
  1220. default:
  1221. GB_PANIC("un-gep-able type %s", type_to_string(type));
  1222. break;
  1223. }
  1224. } else if (type->kind == Type_Slice) {
  1225. e = lb_emit_struct_ep(p, e, index);
  1226. } else if (type->kind == Type_DynamicArray) {
  1227. e = lb_emit_struct_ep(p, e, index);
  1228. } else if (type->kind == Type_Array) {
  1229. e = lb_emit_array_epi(p, e, index);
  1230. } else if (type->kind == Type_Map) {
  1231. e = lb_emit_struct_ep(p, e, index);
  1232. } else {
  1233. GB_PANIC("un-gep-able type %s", type_to_string(type));
  1234. }
  1235. }
  1236. return e;
  1237. }
  1238. gb_internal lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  1239. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  1240. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  1241. return lb_emit_load(p, res);
  1242. }
  1243. gb_internal lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  1244. Type *t = s.type;
  1245. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  1246. Type *st = base_type(type_deref(t));
  1247. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1248. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  1249. LLVMValueRef indices[2] = {};
  1250. indices[0] = llvm_zero(p->module);
  1251. indices[1] = lb_emit_conv(p, index, t_int).value;
  1252. Type *ptr = base_array_type(st);
  1253. lbValue res = {};
  1254. if (LLVMIsConstant(s.value) && LLVMIsConstant(index.value)) {
  1255. res.value = LLVMConstGEP2(lb_type(p->module, st), s.value, indices, gb_count_of(indices));
  1256. } else {
  1257. res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, st), s.value, indices, gb_count_of(indices), "");
  1258. }
  1259. res.type = alloc_type_pointer(ptr);
  1260. return res;
  1261. }
  1262. gb_internal lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  1263. Type *t = s.type;
  1264. GB_ASSERT(is_type_pointer(t));
  1265. Type *st = base_type(type_deref(t));
  1266. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1267. GB_ASSERT(0 <= index);
  1268. return lb_emit_epi(p, s, index);
  1269. }
  1270. gb_internal lbValue lb_emit_array_epi(lbModule *m, lbValue s, isize index) {
  1271. Type *t = s.type;
  1272. GB_ASSERT(is_type_pointer(t));
  1273. Type *st = base_type(type_deref(t));
  1274. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1275. GB_ASSERT(0 <= index);
  1276. return lb_emit_epi(m, s, index);
  1277. }
  1278. gb_internal lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  1279. index = lb_emit_conv(p, index, t_int);
  1280. LLVMValueRef indices[1] = {index.value};
  1281. lbValue res = {};
  1282. res.type = ptr.type;
  1283. LLVMTypeRef type = lb_type(p->module, type_deref(res.type, true));
  1284. if (lb_is_const(ptr) && lb_is_const(index)) {
  1285. res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
  1286. } else {
  1287. res.value = LLVMBuildGEP2(p->builder, type, ptr.value, indices, 1, "");
  1288. }
  1289. return res;
  1290. }
  1291. gb_internal lbValue lb_const_ptr_offset(lbModule *m, lbValue ptr, lbValue index) {
  1292. LLVMValueRef indices[1] = {index.value};
  1293. lbValue res = {};
  1294. res.type = ptr.type;
  1295. LLVMTypeRef type = lb_type(m, type_deref(res.type, true));
  1296. GB_ASSERT(lb_is_const(ptr) && lb_is_const(index));
  1297. res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
  1298. return res;
  1299. }
  1300. gb_internal lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
  1301. Type *t = s.type;
  1302. GB_ASSERT(is_type_pointer(t));
  1303. Type *mt = base_type(type_deref(t));
  1304. if (!mt->Matrix.is_row_major) {
  1305. if (column == 0) {
  1306. GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt));
  1307. return lb_emit_epi(p, s, row);
  1308. } else if (row == 0 && is_type_array_like(mt)) {
  1309. return lb_emit_epi(p, s, column);
  1310. }
  1311. }
  1312. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1313. isize offset = matrix_indices_to_offset(mt, row, column);
  1314. return lb_emit_epi(p, s, offset);
  1315. }
  1316. gb_internal lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) {
  1317. Type *t = s.type;
  1318. GB_ASSERT(is_type_pointer(t));
  1319. Type *mt = base_type(type_deref(t));
  1320. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1321. Type *ptr = base_array_type(mt);
  1322. LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value;
  1323. row = lb_emit_conv(p, row, t_int);
  1324. column = lb_emit_conv(p, column, t_int);
  1325. LLVMValueRef index = nullptr;
  1326. if (mt->Matrix.is_row_major) {
  1327. index = LLVMBuildAdd(p->builder, column.value, LLVMBuildMul(p->builder, row.value, stride_elems, ""), "");
  1328. } else {
  1329. index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), "");
  1330. }
  1331. LLVMValueRef indices[2] = {
  1332. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1333. index,
  1334. };
  1335. LLVMTypeRef type = lb_type(p->module, mt);
  1336. lbValue res = {};
  1337. if (lb_is_const(s)) {
  1338. res.value = LLVMConstGEP2(type, s.value, indices, gb_count_of(indices));
  1339. } else {
  1340. res.value = LLVMBuildGEP2(p->builder, type, s.value, indices, gb_count_of(indices), "");
  1341. }
  1342. res.type = alloc_type_pointer(ptr);
  1343. return res;
  1344. }
  1345. gb_internal lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) {
  1346. Type *st = base_type(s.type);
  1347. GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st));
  1348. lbValue value = lb_address_from_load_or_generate_local(p, s);
  1349. lbValue ptr = lb_emit_matrix_epi(p, value, row, column);
  1350. return lb_emit_load(p, ptr);
  1351. }
  1352. gb_internal void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  1353. Type *t = lb_addr_type(slice);
  1354. GB_ASSERT(is_type_slice(t));
  1355. lbValue ptr = lb_addr_get_ptr(p, slice);
  1356. lbValue data = lb_emit_struct_ep(p, ptr, 0);
  1357. if (are_types_identical(type_deref(base_elem.type, true), type_deref(type_deref(data.type), true))) {
  1358. base_elem = lb_emit_conv(p, base_elem, type_deref(data.type));
  1359. }
  1360. lb_emit_store(p, data, base_elem);
  1361. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1362. }
  1363. gb_internal void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  1364. Type *t = lb_addr_type(string);
  1365. GB_ASSERT(is_type_string(t));
  1366. lbValue ptr = lb_addr_get_ptr(p, string);
  1367. lbValue data = lb_emit_struct_ep(p, ptr, 0);
  1368. if (are_types_identical(type_deref(base_elem.type, true), type_deref(type_deref(data.type), true))) {
  1369. base_elem = lb_emit_conv(p, base_elem, type_deref(data.type));
  1370. }
  1371. lb_emit_store(p, data, base_elem);
  1372. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1373. }
  1374. gb_internal lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  1375. Type *t = base_type(string.type);
  1376. if (t->kind == Type_Basic && t->Basic.kind == Basic_string16) {
  1377. return lb_emit_struct_ev(p, string, 0);
  1378. }
  1379. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  1380. return lb_emit_struct_ev(p, string, 0);
  1381. }
  1382. gb_internal lbValue lb_string_len(lbProcedure *p, lbValue string) {
  1383. Type *t = base_type(string.type);
  1384. if (t->kind == Type_Basic && t->Basic.kind == Basic_string16) {
  1385. return lb_emit_struct_ev(p, string, 1);
  1386. }
  1387. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  1388. return lb_emit_struct_ev(p, string, 1);
  1389. }
  1390. gb_internal lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  1391. GB_ASSERT(is_type_cstring(value.type));
  1392. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1393. args[0] = lb_emit_conv(p, value, t_cstring);
  1394. return lb_emit_runtime_call(p, "cstring_len", args);
  1395. }
  1396. gb_internal lbValue lb_cstring16_len(lbProcedure *p, lbValue value) {
  1397. GB_ASSERT(is_type_cstring16(value.type));
  1398. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1399. args[0] = lb_emit_conv(p, value, t_cstring16);
  1400. return lb_emit_runtime_call(p, "cstring16_len", args);
  1401. }
  1402. gb_internal lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  1403. Type *t = type_deref(array_ptr.type);
  1404. GB_ASSERT(is_type_array(t));
  1405. return lb_emit_struct_ep(p, array_ptr, 0);
  1406. }
  1407. gb_internal lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  1408. GB_ASSERT(is_type_slice(slice.type));
  1409. return lb_emit_struct_ev(p, slice, 0);
  1410. }
  1411. gb_internal lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  1412. GB_ASSERT(is_type_slice(slice.type));
  1413. return lb_emit_struct_ev(p, slice, 1);
  1414. }
  1415. gb_internal lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  1416. GB_ASSERT(is_type_dynamic_array(da.type));
  1417. return lb_emit_struct_ev(p, da, 0);
  1418. }
  1419. gb_internal lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  1420. GB_ASSERT(is_type_dynamic_array(da.type));
  1421. return lb_emit_struct_ev(p, da, 1);
  1422. }
  1423. gb_internal lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  1424. GB_ASSERT(is_type_dynamic_array(da.type));
  1425. return lb_emit_struct_ev(p, da, 2);
  1426. }
  1427. gb_internal lbValue lb_map_len(lbProcedure *p, lbValue value) {
  1428. GB_ASSERT_MSG(is_type_map(value.type) || are_types_identical(value.type, t_raw_map), "%s", type_to_string(value.type));
  1429. lbValue len = lb_emit_struct_ev(p, value, 1);
  1430. return lb_emit_conv(p, len, t_int);
  1431. }
  1432. gb_internal lbValue lb_map_len_ptr(lbProcedure *p, lbValue map_ptr) {
  1433. Type *type = map_ptr.type;
  1434. GB_ASSERT(is_type_pointer(type));
  1435. type = type_deref(type);
  1436. GB_ASSERT_MSG(is_type_map(type) || are_types_identical(type, t_raw_map), "%s", type_to_string(type));
  1437. return lb_emit_struct_ep(p, map_ptr, 1);
  1438. }
  1439. gb_internal lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  1440. GB_ASSERT_MSG(is_type_map(value.type) || are_types_identical(value.type, t_raw_map), "%s", type_to_string(value.type));
  1441. lbValue zero = lb_const_int(p->module, t_uintptr, 0);
  1442. lbValue one = lb_const_int(p->module, t_uintptr, 1);
  1443. lbValue mask = lb_const_int(p->module, t_uintptr, MAP_CACHE_LINE_SIZE-1);
  1444. lbValue data = lb_emit_struct_ev(p, value, 0);
  1445. lbValue log2_cap = lb_emit_arith(p, Token_And, data, mask, t_uintptr);
  1446. lbValue cap = lb_emit_arith(p, Token_Shl, one, log2_cap, t_uintptr);
  1447. lbValue cmp = lb_emit_comp(p, Token_CmpEq, data, zero);
  1448. return lb_emit_conv(p, lb_emit_select(p, cmp, zero, cap), t_int);
  1449. }
  1450. gb_internal lbValue lb_map_data_uintptr(lbProcedure *p, lbValue value) {
  1451. GB_ASSERT(is_type_map(value.type) || are_types_identical(value.type, t_raw_map));
  1452. lbValue data = lb_emit_struct_ev(p, value, 0);
  1453. u64 mask_value = 0;
  1454. if (build_context.ptr_size == 4) {
  1455. mask_value = 0xfffffffful & ~(MAP_CACHE_LINE_SIZE-1);
  1456. } else {
  1457. mask_value = 0xffffffffffffffffull & ~(MAP_CACHE_LINE_SIZE-1);
  1458. }
  1459. lbValue mask = lb_const_int(p->module, t_uintptr, mask_value);
  1460. return lb_emit_arith(p, Token_And, data, mask, t_uintptr);
  1461. }
  1462. gb_internal lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  1463. Type *t = base_type(value.type);
  1464. bool is_ptr = false;
  1465. if (is_type_pointer(t)) {
  1466. is_ptr = true;
  1467. t = base_type(type_deref(t));
  1468. }
  1469. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1470. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1471. }
  1472. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  1473. t->Struct.soa_kind == StructSoa_Dynamic);
  1474. isize n = 0;
  1475. Type *elem = base_type(t->Struct.soa_elem);
  1476. if (elem->kind == Type_Struct) {
  1477. n = cast(isize)elem->Struct.fields.count;
  1478. } else if (elem->kind == Type_Array) {
  1479. n = cast(isize)elem->Array.count;
  1480. } else {
  1481. GB_PANIC("Unreachable");
  1482. }
  1483. if (is_ptr) {
  1484. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1485. return lb_emit_load(p, v);
  1486. }
  1487. return lb_emit_struct_ev(p, value, cast(i32)n);
  1488. }
  1489. gb_internal lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  1490. Type *t = base_type(value.type);
  1491. bool is_ptr = false;
  1492. if (is_type_pointer(t)) {
  1493. is_ptr = true;
  1494. t = base_type(type_deref(t));
  1495. }
  1496. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1497. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1498. }
  1499. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  1500. isize n = 0;
  1501. Type *elem = base_type(t->Struct.soa_elem);
  1502. if (elem->kind == Type_Struct) {
  1503. n = cast(isize)elem->Struct.fields.count+1;
  1504. } else if (elem->kind == Type_Array) {
  1505. n = cast(isize)elem->Array.count+1;
  1506. } else {
  1507. GB_PANIC("Unreachable");
  1508. }
  1509. if (is_ptr) {
  1510. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1511. return lb_emit_load(p, v);
  1512. }
  1513. return lb_emit_struct_ev(p, value, cast(i32)n);
  1514. }
  1515. gb_internal lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) {
  1516. lbModule *m = p->module;
  1517. a = lb_emit_conv(p, a, t);
  1518. b = lb_emit_conv(p, b, t);
  1519. c = lb_emit_conv(p, c, t);
  1520. bool is_possible = !is_type_different_to_arch_endianness(t) && is_type_float(t);
  1521. if (is_possible) {
  1522. switch (build_context.metrics.arch) {
  1523. case TargetArch_amd64:
  1524. // NOTE: using the intrinsic when not supported causes slow codegen (See #2928).
  1525. if (type_size_of(t) == 2 || !check_target_feature_is_enabled(str_lit("fma"), nullptr)) {
  1526. is_possible = false;
  1527. }
  1528. break;
  1529. case TargetArch_arm64:
  1530. // possible
  1531. break;
  1532. case TargetArch_i386:
  1533. case TargetArch_wasm32:
  1534. case TargetArch_wasm64p32:
  1535. is_possible = false;
  1536. break;
  1537. }
  1538. }
  1539. if (is_possible) {
  1540. char const *name = "llvm.fma";
  1541. LLVMTypeRef types[1] = { lb_type(m, t) };
  1542. LLVMValueRef values[3] = {
  1543. a.value,
  1544. b.value,
  1545. c.value };
  1546. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1547. return {call, t};
  1548. } else {
  1549. lbValue x = lb_emit_arith(p, Token_Mul, a, b, t);
  1550. lbValue y = lb_emit_arith(p, Token_Add, x, c, t);
  1551. return y;
  1552. }
  1553. }
  1554. gb_internal LLVMValueRef llvm_mask_iota(lbModule *m, unsigned start, unsigned count) {
  1555. auto iota = slice_make<LLVMValueRef>(temporary_allocator(), count);
  1556. for (unsigned i = 0; i < count; i++) {
  1557. iota[i] = lb_const_int(m, t_u32, start+i).value;
  1558. }
  1559. return LLVMConstVector(iota.data, count);
  1560. }
  1561. gb_internal LLVMValueRef llvm_mask_zero(lbModule *m, unsigned count) {
  1562. return LLVMConstNull(LLVMVectorType(lb_type(m, t_u32), count));
  1563. }
  1564. #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMGetUndef((type))
  1565. // #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMConstNull((type))
  1566. gb_internal LLVMValueRef llvm_basic_shuffle(lbProcedure *p, LLVMValueRef vector, LLVMValueRef mask) {
  1567. return LLVMBuildShuffleVector(p->builder, vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask, "");
  1568. }
  1569. gb_internal LLVMValueRef llvm_basic_const_shuffle(LLVMValueRef vector, LLVMValueRef mask) {
  1570. return LLVMConstShuffleVector(vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask);
  1571. }
  1572. gb_internal LLVMValueRef llvm_vector_broadcast(lbProcedure *p, LLVMValueRef value, unsigned count) {
  1573. GB_ASSERT(count > 0);
  1574. if (LLVMIsConstant(value)) {
  1575. LLVMValueRef single = LLVMConstVector(&value, 1);
  1576. if (count == 1) {
  1577. return single;
  1578. }
  1579. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1580. return llvm_basic_const_shuffle(single, mask);
  1581. }
  1582. LLVMTypeRef single_type = LLVMVectorType(LLVMTypeOf(value), 1);
  1583. LLVMValueRef single = LLVMBuildBitCast(p->builder, value, single_type, "");
  1584. if (count == 1) {
  1585. return single;
  1586. }
  1587. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1588. return llvm_basic_shuffle(p, single, mask);
  1589. }
  1590. gb_internal LLVMValueRef llvm_vector_shuffle_reduction(lbProcedure *p, LLVMValueRef value, LLVMOpcode op_code) {
  1591. LLVMTypeRef original_vector_type = LLVMTypeOf(value);
  1592. GB_ASSERT(LLVMGetTypeKind(original_vector_type) == LLVMVectorTypeKind);
  1593. unsigned len = LLVMGetVectorSize(original_vector_type);
  1594. LLVMValueRef v_zero32 = lb_const_int(p->module, t_u32, 0).value;
  1595. if (len == 1) {
  1596. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1597. }
  1598. GB_ASSERT((len & (len-1)) == 0);
  1599. for (unsigned i = len; i != 1; i >>= 1) {
  1600. unsigned mask_len = i/2;
  1601. LLVMValueRef lhs_mask = llvm_mask_iota(p->module, 0, mask_len);
  1602. LLVMValueRef rhs_mask = llvm_mask_iota(p->module, mask_len, mask_len);
  1603. GB_ASSERT(LLVMTypeOf(lhs_mask) == LLVMTypeOf(rhs_mask));
  1604. LLVMValueRef lhs = llvm_basic_shuffle(p, value, lhs_mask);
  1605. LLVMValueRef rhs = llvm_basic_shuffle(p, value, rhs_mask);
  1606. GB_ASSERT(LLVMTypeOf(lhs) == LLVMTypeOf(rhs));
  1607. value = LLVMBuildBinOp(p->builder, op_code, lhs, rhs, "");
  1608. }
  1609. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1610. }
  1611. gb_internal LLVMValueRef llvm_vector_expand_to_power_of_two(lbProcedure *p, LLVMValueRef value) {
  1612. LLVMTypeRef vector_type = LLVMTypeOf(value);
  1613. unsigned len = LLVMGetVectorSize(vector_type);
  1614. if (len == 1) {
  1615. return value;
  1616. }
  1617. if ((len & (len-1)) == 0) {
  1618. return value;
  1619. }
  1620. unsigned expanded_len = cast(unsigned)next_pow2(cast(i64)len);
  1621. LLVMValueRef mask = llvm_mask_iota(p->module, 0, expanded_len);
  1622. return LLVMBuildShuffleVector(p->builder, value, LLVMConstNull(vector_type), mask, "");
  1623. }
  1624. gb_internal LLVMValueRef llvm_vector_reduce_add(lbProcedure *p, LLVMValueRef value) {
  1625. LLVMTypeRef type = LLVMTypeOf(value);
  1626. GB_ASSERT(LLVMGetTypeKind(type) == LLVMVectorTypeKind);
  1627. LLVMTypeRef elem = OdinLLVMGetVectorElementType(type);
  1628. unsigned len = LLVMGetVectorSize(type);
  1629. if (len == 0) {
  1630. return LLVMConstNull(type);
  1631. }
  1632. char const *name = nullptr;
  1633. i32 value_offset = 0;
  1634. i32 value_count = 0;
  1635. switch (LLVMGetTypeKind(elem)) {
  1636. case LLVMHalfTypeKind:
  1637. case LLVMFloatTypeKind:
  1638. case LLVMDoubleTypeKind:
  1639. name = "llvm.vector.reduce.fadd";
  1640. value_offset = 0;
  1641. value_count = 2;
  1642. break;
  1643. case LLVMIntegerTypeKind:
  1644. name = "llvm.vector.reduce.add";
  1645. value_offset = 1;
  1646. value_count = 1;
  1647. break;
  1648. default:
  1649. GB_PANIC("invalid vector type %s", LLVMPrintTypeToString(type));
  1650. break;
  1651. }
  1652. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1653. if (id != 0 && false) {
  1654. LLVMTypeRef types[1] = { type };
  1655. LLVMValueRef values[2] = { LLVMConstNull(elem), value };
  1656. return lb_call_intrinsic(p, name, values + value_offset, value_count, types, gb_count_of(types));
  1657. }
  1658. // Manual reduce
  1659. #if 0
  1660. LLVMValueRef sum = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, 0).value, "");
  1661. for (unsigned i = 0; i < len; i++) {
  1662. LLVMValueRef val = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, i).value, "");
  1663. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1664. sum = LLVMBuildAdd(p->builder, sum, val, "");
  1665. } else {
  1666. sum = LLVMBuildFAdd(p->builder, sum, val, "");
  1667. }
  1668. }
  1669. return sum;
  1670. #else
  1671. LLVMOpcode op_code = LLVMFAdd;
  1672. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1673. op_code = LLVMAdd;
  1674. }
  1675. unsigned len_pow_2 = prev_pow2(len);
  1676. if (len_pow_2 == len) {
  1677. return llvm_vector_shuffle_reduction(p, value, op_code);
  1678. } else {
  1679. GB_ASSERT(len_pow_2 < len);
  1680. LLVMValueRef lower_mask = llvm_mask_iota(p->module, 0, len_pow_2);
  1681. LLVMValueRef upper_mask = llvm_mask_iota(p->module, len_pow_2, len-len_pow_2);
  1682. LLVMValueRef lower = llvm_basic_shuffle(p, value, lower_mask);
  1683. LLVMValueRef upper = llvm_basic_shuffle(p, value, upper_mask);
  1684. upper = llvm_vector_expand_to_power_of_two(p, upper);
  1685. LLVMValueRef lower_reduced = llvm_vector_shuffle_reduction(p, lower, op_code);
  1686. LLVMValueRef upper_reduced = llvm_vector_shuffle_reduction(p, upper, op_code);
  1687. GB_ASSERT(LLVMTypeOf(lower_reduced) == LLVMTypeOf(upper_reduced));
  1688. return LLVMBuildBinOp(p->builder, op_code, lower_reduced, upper_reduced, "");
  1689. }
  1690. #endif
  1691. }
  1692. gb_internal LLVMValueRef llvm_vector_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1693. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1694. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1695. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1696. return LLVMBuildAdd(p->builder, a, b, "");
  1697. }
  1698. return LLVMBuildFAdd(p->builder, a, b, "");
  1699. }
  1700. gb_internal LLVMValueRef llvm_vector_mul(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1701. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1702. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1703. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1704. return LLVMBuildMul(p->builder, a, b, "");
  1705. }
  1706. return LLVMBuildFMul(p->builder, a, b, "");
  1707. }
  1708. gb_internal LLVMValueRef llvm_vector_dot(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1709. return llvm_vector_reduce_add(p, llvm_vector_mul(p, a, b));
  1710. }
  1711. gb_internal LLVMValueRef llvm_vector_mul_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, LLVMValueRef c) {
  1712. LLVMTypeRef t = LLVMTypeOf(a);
  1713. GB_ASSERT(t == LLVMTypeOf(b));
  1714. GB_ASSERT(t == LLVMTypeOf(c));
  1715. GB_ASSERT(LLVMGetTypeKind(t) == LLVMVectorTypeKind);
  1716. LLVMTypeRef elem = OdinLLVMGetVectorElementType(t);
  1717. bool is_possible = false;
  1718. switch (LLVMGetTypeKind(elem)) {
  1719. case LLVMHalfTypeKind:
  1720. is_possible = true;
  1721. break;
  1722. case LLVMFloatTypeKind:
  1723. case LLVMDoubleTypeKind:
  1724. is_possible = true;
  1725. break;
  1726. }
  1727. if (is_possible) {
  1728. char const *name = "llvm.fmuladd";
  1729. LLVMTypeRef types[1] = { t };
  1730. LLVMValueRef values[3] = { a, b, c};
  1731. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1732. return call;
  1733. } else {
  1734. LLVMValueRef x = llvm_vector_mul(p, a, b);
  1735. LLVMValueRef y = llvm_vector_add(p, x, c);
  1736. return y;
  1737. }
  1738. }
  1739. 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) {
  1740. return LLVMGetInlineAsm(func_type,
  1741. cast(char *)str.text, cast(size_t)str.len,
  1742. cast(char *)clobbers.text, cast(size_t)clobbers.len,
  1743. has_side_effects, is_align_stack,
  1744. dialect
  1745. #if LLVM_VERSION_MAJOR >= 13
  1746. , /*CanThrow*/false
  1747. #endif
  1748. );
  1749. }
  1750. gb_internal void lb_set_wasm_procedure_import_attributes(LLVMValueRef value, Entity *entity, String import_name) {
  1751. if (!is_arch_wasm()) {
  1752. return;
  1753. }
  1754. String module_name = str_lit("env");
  1755. if (entity->Procedure.foreign_library != nullptr) {
  1756. Entity *foreign_library = entity->Procedure.foreign_library;
  1757. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1758. GB_ASSERT(foreign_library->LibraryName.paths.count == 1);
  1759. module_name = foreign_library->LibraryName.paths[0];
  1760. if (string_ends_with(module_name, str_lit(".o"))) {
  1761. return;
  1762. }
  1763. if (string_starts_with(import_name, module_name)) {
  1764. import_name = substring(import_name, module_name.len+WASM_MODULE_NAME_SEPARATOR.len, import_name.len);
  1765. }
  1766. }
  1767. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-module", alloc_cstring(permanent_allocator(), module_name));
  1768. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-name", alloc_cstring(permanent_allocator(), import_name));
  1769. }
  1770. gb_internal void lb_set_wasm_export_attributes(LLVMValueRef value, String export_name) {
  1771. if (!is_arch_wasm()) {
  1772. return;
  1773. }
  1774. LLVMSetLinkage(value, LLVMDLLExportLinkage);
  1775. LLVMSetDLLStorageClass(value, LLVMDLLExportStorageClass);
  1776. LLVMSetVisibility(value, LLVMDefaultVisibility);
  1777. LLVMAddTargetDependentFunctionAttr(value, "wasm-export-name", alloc_cstring(permanent_allocator(), export_name));
  1778. }
  1779. gb_internal lbAddr lb_handle_objc_find_or_register_selector(lbProcedure *p, String const &name) {
  1780. lbModule *m = p->module;
  1781. lbAddr *found = string_map_get(&m->objc_selectors, name);
  1782. if (found) {
  1783. return *found;
  1784. }
  1785. lbModule *default_module = &p->module->gen->default_module;
  1786. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_SEL::");
  1787. global_name = gb_string_append_length(global_name, name.text, name.len);
  1788. LLVMTypeRef t = lb_type(m, t_objc_SEL);
  1789. lbValue g = {};
  1790. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1791. g.type = alloc_type_pointer(t_objc_SEL);
  1792. if (default_module == m) {
  1793. LLVMSetInitializer(g.value, LLVMConstNull(t));
  1794. lb_add_member(m, make_string_c(global_name), g);
  1795. } else {
  1796. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1797. }
  1798. mpsc_enqueue(&m->gen->objc_selectors, lbObjCGlobal{m, global_name, name, t_objc_SEL});
  1799. lbAddr addr = lb_addr(g);
  1800. string_map_set(&m->objc_selectors, name, addr);
  1801. return addr;
  1802. }
  1803. gb_internal lbAddr lb_handle_objc_find_or_register_class(lbProcedure *p, String const &name, Type *class_impl_type) {
  1804. lbModule *m = p->module;
  1805. lbAddr *found = string_map_get(&m->objc_classes, name);
  1806. if (found) {
  1807. return *found;
  1808. }
  1809. lbModule *default_module = &p->module->gen->default_module;
  1810. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_Class::");
  1811. global_name = gb_string_append_length(global_name, name.text, name.len);
  1812. LLVMTypeRef t = lb_type(m, t_objc_Class);
  1813. lbValue g = {};
  1814. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1815. g.type = alloc_type_pointer(t_objc_Class);
  1816. if (default_module == m) {
  1817. LLVMSetInitializer(g.value, LLVMConstNull(t));
  1818. lb_add_member(m, make_string_c(global_name), g);
  1819. } else {
  1820. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1821. }
  1822. mpsc_enqueue(&m->gen->objc_classes, lbObjCGlobal{m, global_name, name, t_objc_Class, class_impl_type});
  1823. lbAddr addr = lb_addr(g);
  1824. string_map_set(&m->objc_classes, name, addr);
  1825. return addr;
  1826. }
  1827. gb_internal lbAddr lb_handle_objc_find_or_register_ivar(lbModule *m, Type *self_type) {
  1828. String name = self_type->Named.type_name->TypeName.objc_class_name;
  1829. GB_ASSERT(name != "");
  1830. lbAddr *found = string_map_get(&m->objc_ivars, name);
  1831. if (found) {
  1832. return *found;
  1833. }
  1834. lbModule *default_module = &m->gen->default_module;
  1835. gbString global_name = gb_string_make(permanent_allocator(), "__$objc_ivar::");
  1836. global_name = gb_string_append_length(global_name, name.text, name.len);
  1837. // Create a global variable to store offset of the ivar in an instance of an object
  1838. LLVMTypeRef t = lb_type(m, t_int);
  1839. lbValue g = {};
  1840. g.value = LLVMAddGlobal(m->mod, t, global_name);
  1841. g.type = t_int_ptr;
  1842. if (default_module == m) {
  1843. LLVMSetInitializer(g.value, LLVMConstInt(t, 0, true));
  1844. lb_add_member(m, make_string_c(global_name), g);
  1845. } else {
  1846. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1847. }
  1848. mpsc_enqueue(&m->gen->objc_ivars, lbObjCGlobal{m, global_name, name, t_int, self_type});
  1849. lbAddr addr = lb_addr(g);
  1850. string_map_set(&m->objc_ivars, name, addr);
  1851. return addr;
  1852. }
  1853. gb_internal lbValue lb_handle_objc_ivar_for_objc_object_pointer(lbProcedure *p, lbValue self) {
  1854. GB_ASSERT(self.type->kind == Type_Pointer && self.type->Pointer.elem->kind == Type_Named);
  1855. Type *self_type = self.type->Pointer.elem;
  1856. lbValue self_uptr = lb_emit_conv(p, self, t_uintptr);
  1857. lbValue ivar_offset = lb_addr_load(p, lb_handle_objc_find_or_register_ivar(p->module, self_type));
  1858. lbValue ivar_offset_uptr = lb_emit_conv(p, ivar_offset, t_uintptr);
  1859. lbValue ivar_uptr = lb_emit_arith(p, Token_Add, self_uptr, ivar_offset_uptr, t_uintptr);
  1860. Type *ivar_type = self_type->Named.type_name->TypeName.objc_ivar;
  1861. return lb_emit_conv(p, ivar_uptr, alloc_type_pointer(ivar_type));
  1862. }
  1863. gb_internal lbValue lb_handle_objc_ivar_get(lbProcedure *p, Ast *expr) {
  1864. ast_node(ce, CallExpr, expr);
  1865. GB_ASSERT(ce->args[0]->tav.type->kind == Type_Pointer);
  1866. lbValue self = lb_build_expr(p, ce->args[0]);
  1867. return lb_handle_objc_ivar_for_objc_object_pointer(p, self);
  1868. }
  1869. gb_internal lbValue lb_handle_objc_find_selector(lbProcedure *p, Ast *expr) {
  1870. ast_node(ce, CallExpr, expr);
  1871. auto tav = ce->args[0]->tav;
  1872. GB_ASSERT(tav.value.kind == ExactValue_String);
  1873. String name = tav.value.value_string;
  1874. return lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, name));
  1875. }
  1876. gb_internal lbValue lb_handle_objc_register_selector(lbProcedure *p, Ast *expr) {
  1877. ast_node(ce, CallExpr, expr);
  1878. lbModule *m = p->module;
  1879. auto tav = ce->args[0]->tav;
  1880. GB_ASSERT(tav.value.kind == ExactValue_String);
  1881. String name = tav.value.value_string;
  1882. lbAddr dst = lb_handle_objc_find_or_register_selector(p, name);
  1883. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1884. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  1885. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  1886. lb_addr_store(p, dst, ptr);
  1887. return lb_addr_load(p, dst);
  1888. }
  1889. gb_internal lbValue lb_handle_objc_find_class(lbProcedure *p, Ast *expr) {
  1890. ast_node(ce, CallExpr, expr);
  1891. auto tav = ce->args[0]->tav;
  1892. GB_ASSERT(tav.value.kind == ExactValue_String);
  1893. String name = tav.value.value_string;
  1894. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name, nullptr));
  1895. }
  1896. gb_internal lbValue lb_handle_objc_register_class(lbProcedure *p, Ast *expr) {
  1897. ast_node(ce, CallExpr, expr);
  1898. lbModule *m = p->module;
  1899. auto tav = ce->args[0]->tav;
  1900. GB_ASSERT(tav.value.kind == ExactValue_String);
  1901. String name = tav.value.value_string;
  1902. lbAddr dst = lb_handle_objc_find_or_register_class(p, name, nullptr);
  1903. auto args = array_make<lbValue>(permanent_allocator(), 3);
  1904. args[0] = lb_const_nil(m, t_objc_Class);
  1905. args[1] = lb_const_nil(m, t_objc_Class);
  1906. args[2] = lb_const_int(m, t_uint, 0);
  1907. lbValue ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  1908. lb_addr_store(p, dst, ptr);
  1909. return lb_addr_load(p, dst);
  1910. }
  1911. gb_internal lbValue lb_handle_objc_id(lbProcedure *p, Ast *expr) {
  1912. TypeAndValue const &tav = type_and_value_of_expr(expr);
  1913. if (tav.mode == Addressing_Type) {
  1914. Type *type = tav.type;
  1915. GB_ASSERT_MSG(type->kind == Type_Named, "%s", type_to_string(type));
  1916. Entity *e = type->Named.type_name;
  1917. GB_ASSERT(e->kind == Entity_TypeName);
  1918. String name = e->TypeName.objc_class_name;
  1919. Type *class_impl_type = e->TypeName.objc_is_implementation ? type : nullptr;
  1920. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name, class_impl_type));
  1921. }
  1922. return lb_build_expr(p, expr);
  1923. }
  1924. gb_internal lbValue lb_handle_objc_send(lbProcedure *p, Ast *expr) {
  1925. ast_node(ce, CallExpr, expr);
  1926. lbModule *m = p->module;
  1927. CheckerInfo *info = m->info;
  1928. ObjcMsgData data = map_must_get(&info->objc_msgSend_types, expr);
  1929. GB_ASSERT(data.proc_type != nullptr);
  1930. GB_ASSERT(ce->args.count >= 3);
  1931. auto args = array_make<lbValue>(permanent_allocator(), 0, ce->args.count-1);
  1932. lbValue id = lb_handle_objc_id(p, ce->args[1]);
  1933. Ast *sel_expr = ce->args[2];
  1934. GB_ASSERT(sel_expr->tav.value.kind == ExactValue_String);
  1935. lbValue sel = lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, sel_expr->tav.value.value_string));
  1936. array_add(&args, id);
  1937. array_add(&args, sel);
  1938. for (isize i = 3; i < ce->args.count; i++) {
  1939. lbValue arg = lb_build_expr(p, ce->args[i]);
  1940. array_add(&args, arg);
  1941. }
  1942. lbValue the_proc = {};
  1943. switch (data.kind) {
  1944. default:
  1945. GB_PANIC("unhandled ObjcMsgKind %u", data.kind);
  1946. break;
  1947. case ObjcMsg_normal: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend")); break;
  1948. case ObjcMsg_fpret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fpret")); break;
  1949. case ObjcMsg_fp2ret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fp2ret")); break;
  1950. case ObjcMsg_stret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_stret")); break;
  1951. }
  1952. the_proc = lb_emit_conv(p, the_proc, data.proc_type);
  1953. return lb_emit_call(p, the_proc, args);
  1954. }
  1955. gb_internal LLVMAtomicOrdering llvm_atomic_ordering_from_odin(ExactValue const &value) {
  1956. GB_ASSERT(value.kind == ExactValue_Integer);
  1957. i64 v = exact_value_to_i64(value);
  1958. switch (v) {
  1959. case OdinAtomicMemoryOrder_relaxed: return LLVMAtomicOrderingMonotonic;
  1960. case OdinAtomicMemoryOrder_consume: return LLVMAtomicOrderingAcquire;
  1961. case OdinAtomicMemoryOrder_acquire: return LLVMAtomicOrderingAcquire;
  1962. case OdinAtomicMemoryOrder_release: return LLVMAtomicOrderingRelease;
  1963. case OdinAtomicMemoryOrder_acq_rel: return LLVMAtomicOrderingAcquireRelease;
  1964. case OdinAtomicMemoryOrder_seq_cst: return LLVMAtomicOrderingSequentiallyConsistent;
  1965. }
  1966. GB_PANIC("Unknown atomic ordering");
  1967. return LLVMAtomicOrderingSequentiallyConsistent;
  1968. }
  1969. gb_internal LLVMAtomicOrdering llvm_atomic_ordering_from_odin(Ast *expr) {
  1970. ExactValue value = type_and_value_of_expr(expr).value;
  1971. return llvm_atomic_ordering_from_odin(value);
  1972. }