llvm_backend_utility.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  1. bool lb_is_type_aggregate(Type *t) {
  2. t = base_type(t);
  3. switch (t->kind) {
  4. case Type_Basic:
  5. switch (t->Basic.kind) {
  6. case Basic_string:
  7. case Basic_any:
  8. return true;
  9. case Basic_complex32:
  10. case Basic_complex64:
  11. case Basic_complex128:
  12. case Basic_quaternion64:
  13. case Basic_quaternion128:
  14. case Basic_quaternion256:
  15. return true;
  16. }
  17. break;
  18. case Type_Pointer:
  19. return false;
  20. case Type_Array:
  21. case Type_Slice:
  22. case Type_Struct:
  23. case Type_Union:
  24. case Type_Tuple:
  25. case Type_DynamicArray:
  26. case Type_Map:
  27. case Type_SimdVector:
  28. return true;
  29. case Type_Named:
  30. return lb_is_type_aggregate(t->Named.base);
  31. }
  32. return false;
  33. }
  34. lbValue lb_correct_endianness(lbProcedure *p, lbValue value) {
  35. Type *src = core_type(value.type);
  36. GB_ASSERT(is_type_integer(src) || is_type_float(src));
  37. if (is_type_different_to_arch_endianness(src)) {
  38. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  39. value = lb_emit_byte_swap(p, value, platform_src_type);
  40. }
  41. return value;
  42. }
  43. void lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment, bool is_volatile) {
  44. bool is_inlinable = false;
  45. i64 const_len = 0;
  46. if (LLVMIsConstant(len)) {
  47. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  48. // TODO(bill): Determine when it is better to do the `*.inline` versions
  49. if (const_len <= 4*build_context.word_size) {
  50. is_inlinable = true;
  51. }
  52. }
  53. char const *name = "llvm.memset";
  54. if (is_inlinable) {
  55. name = "llvm.memset.inline";
  56. }
  57. LLVMTypeRef types[2] = {
  58. lb_type(p->module, t_rawptr),
  59. lb_type(p->module, t_int)
  60. };
  61. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  62. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]));
  63. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  64. LLVMValueRef args[4] = {};
  65. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  66. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  67. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  68. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), is_volatile, false);
  69. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  70. }
  71. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  72. LLVMTypeRef llvm_type = lb_type(p->module, type);
  73. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  74. switch (kind) {
  75. case LLVMStructTypeKind:
  76. case LLVMArrayTypeKind:
  77. {
  78. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  79. i32 sz = cast(i32)type_size_of(type);
  80. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment, false);
  81. }
  82. break;
  83. default:
  84. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  85. break;
  86. }
  87. }
  88. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  89. cond = lb_emit_conv(p, cond, t_llvm_bool);
  90. lbValue res = {};
  91. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  92. res.type = x.type;
  93. return res;
  94. }
  95. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  96. x = lb_emit_conv(p, x, t);
  97. y = lb_emit_conv(p, y, t);
  98. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  99. }
  100. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  101. x = lb_emit_conv(p, x, t);
  102. y = lb_emit_conv(p, y, t);
  103. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  104. }
  105. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  106. lbValue z = {};
  107. z = lb_emit_max(p, t, x, min);
  108. z = lb_emit_min(p, t, z, max);
  109. return z;
  110. }
  111. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  112. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  113. LLVMValueRef values[2] = {
  114. str_elem.value,
  115. str_len.value,
  116. };
  117. lbValue res = {};
  118. res.type = t_string;
  119. res.value = llvm_const_named_struct(p->module, t_string, values, gb_count_of(values));
  120. return res;
  121. } else {
  122. lbAddr res = lb_add_local_generated(p, t_string, false);
  123. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  124. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  125. return lb_addr_load(p, res);
  126. }
  127. }
  128. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  129. Type *src_type = value.type;
  130. if (are_types_identical(t, src_type)) {
  131. return value;
  132. }
  133. lbValue res = {};
  134. res.type = t;
  135. Type *src = base_type(src_type);
  136. Type *dst = base_type(t);
  137. lbModule *m = p->module;
  138. i64 sz = type_size_of(src);
  139. i64 dz = type_size_of(dst);
  140. if (sz != dz) {
  141. LLVMTypeRef s = lb_type(m, src);
  142. LLVMTypeRef d = lb_type(m, dst);
  143. i64 llvm_sz = lb_sizeof(s);
  144. i64 llvm_dz = lb_sizeof(d);
  145. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  146. }
  147. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  148. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  149. if (is_type_uintptr(src) && is_type_internally_pointer_like(dst)) {
  150. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  151. return res;
  152. }
  153. if (is_type_internally_pointer_like(src) && is_type_uintptr(dst)) {
  154. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  155. return res;
  156. }
  157. if (is_type_integer(src) && is_type_internally_pointer_like(dst)) {
  158. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  159. return res;
  160. } else if (is_type_internally_pointer_like(src) && is_type_integer(dst)) {
  161. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  162. return res;
  163. }
  164. if (is_type_internally_pointer_like(src) && is_type_internally_pointer_like(dst)) {
  165. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  166. return res;
  167. }
  168. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  169. lbValue s = lb_address_from_load_or_generate_local(p, value);
  170. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  171. return lb_emit_load(p, d);
  172. }
  173. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  174. return res;
  175. }
  176. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  177. i64 type_alignment = type_align_of(new_type);
  178. if (alignment < type_alignment) {
  179. alignment = type_alignment;
  180. }
  181. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  182. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  183. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  184. lb_addr_store(p, ptr, val);
  185. // ptr.kind = lbAddr_Context;
  186. return ptr.addr;
  187. }
  188. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  189. GB_ASSERT(ce->args.count > 0);
  190. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  191. for_array(i, slices) {
  192. Ast *arg = ce->args[i];
  193. if (arg->kind == Ast_FieldValue) {
  194. arg = arg->FieldValue.value;
  195. }
  196. slices[i] = lb_build_expr(p, arg);
  197. }
  198. lbValue len = lb_slice_len(p, slices[0]);
  199. for (isize i = 1; i < slices.count; i++) {
  200. lbValue other_len = lb_slice_len(p, slices[i]);
  201. len = lb_emit_min(p, t_int, len, other_len);
  202. }
  203. GB_ASSERT(is_type_soa_struct(tv.type));
  204. lbAddr res = lb_add_local_generated(p, tv.type, true);
  205. for_array(i, slices) {
  206. lbValue src = lb_slice_elem(p, slices[i]);
  207. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  208. lb_emit_store(p, dst, src);
  209. }
  210. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  211. lb_emit_store(p, len_dst, len);
  212. return lb_addr_load(p, res);
  213. }
  214. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  215. GB_ASSERT(ce->args.count == 1);
  216. lbValue arg = lb_build_expr(p, ce->args[0]);
  217. Type *t = base_type(arg.type);
  218. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  219. lbValue len = lb_soa_struct_len(p, arg);
  220. lbAddr res = lb_add_local_generated(p, tv.type, true);
  221. if (is_type_tuple(tv.type)) {
  222. lbValue rp = lb_addr_get_ptr(p, res);
  223. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  224. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  225. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  226. lb_fill_slice(p, dst, ptr, len);
  227. }
  228. } else {
  229. GB_ASSERT(is_type_slice(tv.type));
  230. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  231. lb_fill_slice(p, res, ptr, len);
  232. }
  233. return lb_addr_load(p, res);
  234. }
  235. void lb_emit_try_lhs_rhs(lbProcedure *p, Ast *arg, TypeAndValue const &tv, lbValue *lhs_, lbValue *rhs_) {
  236. lbValue lhs = {};
  237. lbValue rhs = {};
  238. lbValue value = lb_build_expr(p, arg);
  239. if (is_type_tuple(value.type)) {
  240. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  241. if (value.type->Tuple.variables.count == 2) {
  242. lhs = lb_emit_struct_ev(p, value, 0);
  243. } else {
  244. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  245. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  246. for (i32 i = 0; i < n; i++) {
  247. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_struct_ev(p, value, i));
  248. }
  249. lhs = lb_addr_load(p, lhs_addr);
  250. }
  251. rhs = lb_emit_struct_ev(p, value, n);
  252. } else {
  253. rhs = value;
  254. }
  255. GB_ASSERT(rhs.value != nullptr);
  256. if (lhs_) *lhs_ = lhs;
  257. if (rhs_) *rhs_ = rhs;
  258. }
  259. lbValue lb_emit_try_has_value(lbProcedure *p, lbValue rhs) {
  260. lbValue has_value = {};
  261. if (is_type_boolean(rhs.type)) {
  262. has_value = rhs;
  263. } else {
  264. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  265. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  266. }
  267. GB_ASSERT(has_value.value != nullptr);
  268. return has_value;
  269. }
  270. lbValue lb_emit_or_else(lbProcedure *p, Ast *arg, Ast *else_expr, TypeAndValue const &tv) {
  271. lbValue lhs = {};
  272. lbValue rhs = {};
  273. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  274. LLVMValueRef incoming_values[2] = {};
  275. LLVMBasicBlockRef incoming_blocks[2] = {};
  276. GB_ASSERT(else_expr != nullptr);
  277. lbBlock *then = lb_create_block(p, "or_else.then");
  278. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  279. lbBlock *else_ = lb_create_block(p, "or_else.else");
  280. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  281. lb_start_block(p, then);
  282. Type *type = default_type(tv.type);
  283. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  284. lb_emit_jump(p, done);
  285. lb_start_block(p, else_);
  286. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_expr), type).value;
  287. lb_emit_jump(p, done);
  288. lb_start_block(p, done);
  289. lbValue res = {};
  290. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  291. res.type = type;
  292. GB_ASSERT(p->curr_block->preds.count >= 2);
  293. incoming_blocks[0] = p->curr_block->preds[0]->block;
  294. incoming_blocks[1] = p->curr_block->preds[1]->block;
  295. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  296. return res;
  297. }
  298. void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results);
  299. void lb_build_return_stmt_internal(lbProcedure *p, lbValue const &res);
  300. lbValue lb_emit_or_return(lbProcedure *p, Ast *arg, TypeAndValue const &tv) {
  301. lbValue lhs = {};
  302. lbValue rhs = {};
  303. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  304. lbBlock *return_block = lb_create_block(p, "or_return.return");
  305. lbBlock *continue_block = lb_create_block(p, "or_return.continue");
  306. lb_emit_if(p, lb_emit_try_has_value(p, rhs), continue_block, return_block);
  307. lb_start_block(p, return_block);
  308. {
  309. Type *proc_type = base_type(p->type);
  310. Type *results = proc_type->Proc.results;
  311. GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  312. TypeTuple *tuple = &results->Tuple;
  313. GB_ASSERT(tuple->variables.count != 0);
  314. Entity *end_entity = tuple->variables[tuple->variables.count-1];
  315. rhs = lb_emit_conv(p, rhs, end_entity->type);
  316. if (p->type->Proc.has_named_results) {
  317. GB_ASSERT(end_entity->token.string.len != 0);
  318. // NOTE(bill): store the named values before returning
  319. lbValue found = map_must_get(&p->module->values, end_entity);
  320. lb_emit_store(p, found, rhs);
  321. lb_build_return_stmt(p, {});
  322. } else {
  323. GB_ASSERT(tuple->variables.count == 1);
  324. lb_build_return_stmt_internal(p, rhs);
  325. }
  326. }
  327. lb_start_block(p, continue_block);
  328. if (tv.type != nullptr) {
  329. return lb_emit_conv(p, lhs, tv.type);
  330. }
  331. return {};
  332. }
  333. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  334. GB_ASSERT(is_type_pointer(addr.type));
  335. Type *type = type_deref(addr.type);
  336. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  337. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  338. }
  339. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  340. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  341. if (type_size_of(value.type) < 2) {
  342. return value;
  343. }
  344. Type *original_type = value.type;
  345. if (is_type_float(original_type)) {
  346. i64 sz = type_size_of(original_type);
  347. Type *integer_type = nullptr;
  348. switch (sz) {
  349. case 2: integer_type = t_u16; break;
  350. case 4: integer_type = t_u32; break;
  351. case 8: integer_type = t_u64; break;
  352. }
  353. GB_ASSERT(integer_type != nullptr);
  354. value = lb_emit_transmute(p, value, integer_type);
  355. }
  356. char const *name = "llvm.bswap";
  357. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  358. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  359. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  360. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  361. LLVMValueRef args[1] = {};
  362. args[0] = value.value;
  363. lbValue res = {};
  364. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  365. res.type = value.type;
  366. if (is_type_float(original_type)) {
  367. res = lb_emit_transmute(p, res, original_type);
  368. }
  369. res.type = end_type;
  370. return res;
  371. }
  372. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  373. x = lb_emit_conv(p, x, type);
  374. char const *name = "llvm.ctpop";
  375. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  376. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  377. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  378. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  379. LLVMValueRef args[1] = {};
  380. args[0] = x.value;
  381. lbValue res = {};
  382. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  383. res.type = type;
  384. return res;
  385. }
  386. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  387. i64 sz = 8*type_size_of(type);
  388. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  389. lbValue count = lb_emit_count_ones(p, x, type);
  390. return lb_emit_arith(p, Token_Sub, size, count, type);
  391. }
  392. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  393. x = lb_emit_conv(p, x, type);
  394. char const *name = "llvm.cttz";
  395. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  396. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  397. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  398. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  399. LLVMValueRef args[2] = {};
  400. args[0] = x.value;
  401. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  402. lbValue res = {};
  403. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  404. res.type = type;
  405. return res;
  406. }
  407. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  408. x = lb_emit_conv(p, x, type);
  409. char const *name = "llvm.ctlz";
  410. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  411. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  412. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  413. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  414. LLVMValueRef args[2] = {};
  415. args[0] = x.value;
  416. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  417. lbValue res = {};
  418. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  419. res.type = type;
  420. return res;
  421. }
  422. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  423. x = lb_emit_conv(p, x, type);
  424. char const *name = "llvm.bitreverse";
  425. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  426. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  427. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  428. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  429. LLVMValueRef args[1] = {};
  430. args[0] = x.value;
  431. lbValue res = {};
  432. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  433. res.type = type;
  434. return res;
  435. }
  436. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  437. GB_ASSERT(is_type_bit_set(x.type));
  438. Type *underlying = bit_set_to_int(x.type);
  439. lbValue card = lb_emit_count_ones(p, x, underlying);
  440. return lb_emit_conv(p, card, t_int);
  441. }
  442. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  443. GB_ASSERT(is_type_tuple(type));
  444. lbModule *m = p->module;
  445. Type *src_type = value.type;
  446. bool is_ptr = is_type_pointer(src_type);
  447. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  448. // so when it does an assignment, it complete ignores the value.
  449. // Just make it two booleans and ignore the first one
  450. //
  451. // _, ok := x.(T);
  452. //
  453. Type *ok_type = type->Tuple.variables[1]->type;
  454. Type *gen_tuple_types[2] = {};
  455. gen_tuple_types[0] = ok_type;
  456. gen_tuple_types[1] = ok_type;
  457. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  458. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  459. if (is_ptr) {
  460. value = lb_emit_load(p, value);
  461. }
  462. Type *src = base_type(type_deref(src_type));
  463. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  464. Type *dst = type->Tuple.variables[0]->type;
  465. lbValue cond = {};
  466. if (is_type_union_maybe_pointer(src)) {
  467. lbValue data = lb_emit_transmute(p, value, dst);
  468. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  469. } else {
  470. lbValue tag = lb_emit_union_tag_value(p, value);
  471. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  472. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  473. }
  474. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  475. lb_emit_store(p, gep1, cond);
  476. return lb_addr_load(p, v);
  477. }
  478. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  479. lbModule *m = p->module;
  480. Type *src_type = value.type;
  481. bool is_ptr = is_type_pointer(src_type);
  482. bool is_tuple = true;
  483. Type *tuple = type;
  484. if (type->kind != Type_Tuple) {
  485. is_tuple = false;
  486. tuple = make_optional_ok_type(type);
  487. }
  488. lbAddr v = lb_add_local_generated(p, tuple, true);
  489. if (is_ptr) {
  490. value = lb_emit_load(p, value);
  491. }
  492. Type *src = base_type(type_deref(src_type));
  493. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  494. Type *dst = tuple->Tuple.variables[0]->type;
  495. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  496. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  497. // just do a bit cast of the data at the front
  498. lbValue ptr = lb_emit_conv(p, value_, alloc_type_pointer(type));
  499. return lb_emit_load(p, ptr);
  500. }
  501. lbValue tag = {};
  502. lbValue dst_tag = {};
  503. lbValue cond = {};
  504. lbValue data = {};
  505. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  506. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  507. if (is_type_union_maybe_pointer(src)) {
  508. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  509. } else {
  510. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  511. dst_tag = lb_const_union_tag(m, src, dst);
  512. }
  513. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  514. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  515. if (data.value != nullptr) {
  516. GB_ASSERT(is_type_union_maybe_pointer(src));
  517. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  518. } else {
  519. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  520. }
  521. lb_emit_if(p, cond, ok_block, end_block);
  522. lb_start_block(p, ok_block);
  523. if (data.value == nullptr) {
  524. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  525. }
  526. lb_emit_store(p, gep0, data);
  527. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  528. lb_emit_jump(p, end_block);
  529. lb_start_block(p, end_block);
  530. if (!is_tuple) {
  531. GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0);
  532. // NOTE(bill): Panic on invalid conversion
  533. Type *dst_type = tuple->Tuple.variables[0]->type;
  534. isize arg_count = 7;
  535. if (build_context.disallow_rtti) {
  536. arg_count = 4;
  537. }
  538. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  539. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  540. args[0] = ok;
  541. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  542. args[2] = lb_const_int(m, t_i32, pos.line);
  543. args[3] = lb_const_int(m, t_i32, pos.column);
  544. if (!build_context.disallow_rtti) {
  545. args[4] = lb_typeid(m, src_type);
  546. args[5] = lb_typeid(m, dst_type);
  547. args[6] = lb_emit_conv(p, value_, t_rawptr);
  548. }
  549. lb_emit_runtime_call(p, "type_assertion_check2", args);
  550. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  551. }
  552. return lb_addr_load(p, v);
  553. }
  554. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  555. lbModule *m = p->module;
  556. Type *src_type = value.type;
  557. if (is_type_pointer(src_type)) {
  558. value = lb_emit_load(p, value);
  559. }
  560. bool is_tuple = true;
  561. Type *tuple = type;
  562. if (type->kind != Type_Tuple) {
  563. is_tuple = false;
  564. tuple = make_optional_ok_type(type);
  565. }
  566. Type *dst_type = tuple->Tuple.variables[0]->type;
  567. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  568. // just do a bit cast of the data at the front
  569. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  570. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(type));
  571. return lb_addr(ptr);
  572. }
  573. lbAddr v = lb_add_local_generated(p, tuple, true);
  574. lbValue dst_typeid = lb_typeid(m, dst_type);
  575. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  576. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  577. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  578. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  579. lb_emit_if(p, cond, ok_block, end_block);
  580. lb_start_block(p, ok_block);
  581. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  582. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  583. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  584. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  585. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  586. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  587. lb_emit_jump(p, end_block);
  588. lb_start_block(p, end_block);
  589. if (!is_tuple) {
  590. // NOTE(bill): Panic on invalid conversion
  591. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  592. isize arg_count = 7;
  593. if (build_context.disallow_rtti) {
  594. arg_count = 4;
  595. }
  596. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  597. args[0] = ok;
  598. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  599. args[2] = lb_const_int(m, t_i32, pos.line);
  600. args[3] = lb_const_int(m, t_i32, pos.column);
  601. if (!build_context.disallow_rtti) {
  602. args[4] = any_typeid;
  603. args[5] = dst_typeid;
  604. args[6] = lb_emit_struct_ev(p, value, 0);
  605. }
  606. lb_emit_runtime_call(p, "type_assertion_check2", args);
  607. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  608. }
  609. return v;
  610. }
  611. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  612. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  613. }
  614. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  615. if (p->context_stack.count > 0) {
  616. return p->context_stack[p->context_stack.count-1].ctx;
  617. }
  618. Type *pt = base_type(p->type);
  619. GB_ASSERT(pt->kind == Type_Proc);
  620. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  621. lbAddr c = lb_add_local_generated(p, t_context, true);
  622. c.kind = lbAddr_Context;
  623. lb_emit_init_context(p, c);
  624. lb_push_context_onto_stack(p, c);
  625. lb_add_debug_context_variable(p, c);
  626. return c;
  627. }
  628. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  629. if (LLVMIsALoadInst(value.value)) {
  630. lbValue res = {};
  631. res.value = LLVMGetOperand(value.value, 0);
  632. res.type = alloc_type_pointer(value.type);
  633. return res;
  634. }
  635. GB_ASSERT(is_type_typed(value.type));
  636. lbAddr res = lb_add_local_generated(p, value.type, false);
  637. lb_addr_store(p, res, value);
  638. return res.addr;
  639. }
  640. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  641. if (LLVMIsALoadInst(value.value)) {
  642. lbValue res = {};
  643. res.value = LLVMGetOperand(value.value, 0);
  644. res.type = alloc_type_pointer(value.type);
  645. return res;
  646. }
  647. GB_PANIC("lb_address_from_load");
  648. return {};
  649. }
  650. lbStructFieldRemapping lb_get_struct_remapping(lbModule *m, Type *t) {
  651. t = base_type(t);
  652. LLVMTypeRef struct_type = lb_type(m, t);
  653. auto *field_remapping = map_get(&m->struct_field_remapping, cast(void *)struct_type);
  654. if (field_remapping == nullptr) {
  655. field_remapping = map_get(&m->struct_field_remapping, cast(void *)t);
  656. }
  657. GB_ASSERT(field_remapping != nullptr);
  658. return *field_remapping;
  659. }
  660. i32 lb_convert_struct_index(lbModule *m, Type *t, i32 index) {
  661. if (t->kind == Type_Struct) {
  662. auto field_remapping = lb_get_struct_remapping(m, t);
  663. index = field_remapping[index];
  664. }
  665. return index;
  666. }
  667. LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 padding_align) {
  668. // NOTE(bill): limit to `[N x u64]` to prevent ABI issues
  669. padding_align = gb_clamp(padding_align, 1, 8);
  670. if (padding % padding_align == 0) {
  671. LLVMTypeRef elem = nullptr;
  672. isize len = padding/padding_align;
  673. switch (padding_align) {
  674. case 1: elem = lb_type(m, t_u8); break;
  675. case 2: elem = lb_type(m, t_u16); break;
  676. case 4: elem = lb_type(m, t_u32); break;
  677. case 8: elem = lb_type(m, t_u64); break;
  678. }
  679. GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
  680. if (len != 1) {
  681. return LLVMArrayType(elem, cast(unsigned)len);
  682. } else {
  683. return elem;
  684. }
  685. } else {
  686. return LLVMArrayType(lb_type(m, t_u8), cast(unsigned)padding);
  687. }
  688. }
  689. char const *llvm_type_kinds[] = {
  690. "LLVMVoidTypeKind",
  691. "LLVMHalfTypeKind",
  692. "LLVMFloatTypeKind",
  693. "LLVMDoubleTypeKind",
  694. "LLVMX86_FP80TypeKind",
  695. "LLVMFP128TypeKind",
  696. "LLVMPPC_FP128TypeKind",
  697. "LLVMLabelTypeKind",
  698. "LLVMIntegerTypeKind",
  699. "LLVMFunctionTypeKind",
  700. "LLVMStructTypeKind",
  701. "LLVMArrayTypeKind",
  702. "LLVMPointerTypeKind",
  703. "LLVMVectorTypeKind",
  704. "LLVMMetadataTypeKind",
  705. "LLVMX86_MMXTypeKind",
  706. "LLVMTokenTypeKind",
  707. "LLVMScalableVectorTypeKind",
  708. "LLVMBFloatTypeKind",
  709. };
  710. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  711. GB_ASSERT(is_type_pointer(s.type));
  712. Type *t = base_type(type_deref(s.type));
  713. Type *result_type = nullptr;
  714. if (is_type_relative_pointer(t)) {
  715. s = lb_addr_get_ptr(p, lb_addr(s));
  716. }
  717. if (is_type_struct(t)) {
  718. result_type = get_struct_field_type(t, index);
  719. } else if (is_type_union(t)) {
  720. GB_ASSERT(index == -1);
  721. return lb_emit_union_tag_ptr(p, s);
  722. } else if (is_type_tuple(t)) {
  723. GB_ASSERT(t->Tuple.variables.count > 0);
  724. result_type = t->Tuple.variables[index]->type;
  725. } else if (is_type_complex(t)) {
  726. Type *ft = base_complex_elem_type(t);
  727. switch (index) {
  728. case 0: result_type = ft; break;
  729. case 1: result_type = ft; break;
  730. }
  731. } else if (is_type_quaternion(t)) {
  732. Type *ft = base_complex_elem_type(t);
  733. switch (index) {
  734. case 0: result_type = ft; break;
  735. case 1: result_type = ft; break;
  736. case 2: result_type = ft; break;
  737. case 3: result_type = ft; break;
  738. }
  739. } else if (is_type_slice(t)) {
  740. switch (index) {
  741. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  742. case 1: result_type = t_int; break;
  743. }
  744. } else if (is_type_string(t)) {
  745. switch (index) {
  746. case 0: result_type = t_u8_ptr; break;
  747. case 1: result_type = t_int; break;
  748. }
  749. } else if (is_type_any(t)) {
  750. switch (index) {
  751. case 0: result_type = t_rawptr; break;
  752. case 1: result_type = t_typeid; break;
  753. }
  754. } else if (is_type_dynamic_array(t)) {
  755. switch (index) {
  756. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  757. case 1: result_type = t_int; break;
  758. case 2: result_type = t_int; break;
  759. case 3: result_type = t_allocator; break;
  760. }
  761. } else if (is_type_map(t)) {
  762. init_map_internal_types(t);
  763. Type *itp = alloc_type_pointer(t->Map.internal_type);
  764. s = lb_emit_transmute(p, s, itp);
  765. Type *gst = t->Map.internal_type;
  766. GB_ASSERT(gst->kind == Type_Struct);
  767. switch (index) {
  768. case 0: result_type = get_struct_field_type(gst, 0); break;
  769. case 1: result_type = get_struct_field_type(gst, 1); break;
  770. }
  771. } else if (is_type_array(t)) {
  772. return lb_emit_array_epi(p, s, index);
  773. } else if (is_type_relative_slice(t)) {
  774. switch (index) {
  775. case 0: result_type = t->RelativeSlice.base_integer; break;
  776. case 1: result_type = t->RelativeSlice.base_integer; break;
  777. }
  778. } else {
  779. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  780. }
  781. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  782. i32 original_index = index;
  783. index = lb_convert_struct_index(p->module, t, index);
  784. if (lb_is_const(s)) {
  785. lbModule *m = p->module;
  786. lbValue res = {};
  787. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  788. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  789. res.type = alloc_type_pointer(result_type);
  790. return res;
  791. } else {
  792. lbValue res = {};
  793. LLVMTypeRef st = LLVMGetElementType(LLVMTypeOf(s.value));
  794. // gb_printf_err("%s\n", type_to_string(s.type));
  795. // gb_printf_err("%s\n", LLVMPrintTypeToString(LLVMTypeOf(s.value)));
  796. // gb_printf_err("%d\n", index);
  797. GB_ASSERT_MSG(LLVMGetTypeKind(st) == LLVMStructTypeKind, "%s", llvm_type_kinds[LLVMGetTypeKind(st)]);
  798. unsigned count = LLVMCountStructElementTypes(st);
  799. GB_ASSERT_MSG(count >= cast(unsigned)index, "%u %d %d", count, index, original_index);
  800. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  801. res.type = alloc_type_pointer(result_type);
  802. return res;
  803. }
  804. }
  805. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  806. if (LLVMIsALoadInst(s.value)) {
  807. lbValue res = {};
  808. res.value = LLVMGetOperand(s.value, 0);
  809. res.type = alloc_type_pointer(s.type);
  810. lbValue ptr = lb_emit_struct_ep(p, res, index);
  811. return lb_emit_load(p, ptr);
  812. }
  813. Type *t = base_type(s.type);
  814. Type *result_type = nullptr;
  815. switch (t->kind) {
  816. case Type_Basic:
  817. switch (t->Basic.kind) {
  818. case Basic_string:
  819. switch (index) {
  820. case 0: result_type = t_u8_ptr; break;
  821. case 1: result_type = t_int; break;
  822. }
  823. break;
  824. case Basic_any:
  825. switch (index) {
  826. case 0: result_type = t_rawptr; break;
  827. case 1: result_type = t_typeid; break;
  828. }
  829. break;
  830. case Basic_complex32:
  831. case Basic_complex64:
  832. case Basic_complex128:
  833. {
  834. Type *ft = base_complex_elem_type(t);
  835. switch (index) {
  836. case 0: result_type = ft; break;
  837. case 1: result_type = ft; break;
  838. }
  839. break;
  840. }
  841. case Basic_quaternion64:
  842. case Basic_quaternion128:
  843. case Basic_quaternion256:
  844. {
  845. Type *ft = base_complex_elem_type(t);
  846. switch (index) {
  847. case 0: result_type = ft; break;
  848. case 1: result_type = ft; break;
  849. case 2: result_type = ft; break;
  850. case 3: result_type = ft; break;
  851. }
  852. break;
  853. }
  854. }
  855. break;
  856. case Type_Struct:
  857. result_type = get_struct_field_type(t, index);
  858. break;
  859. case Type_Union:
  860. GB_ASSERT(index == -1);
  861. // return lb_emit_union_tag_value(p, s);
  862. GB_PANIC("lb_emit_union_tag_value");
  863. case Type_Tuple:
  864. GB_ASSERT(t->Tuple.variables.count > 0);
  865. result_type = t->Tuple.variables[index]->type;
  866. if (t->Tuple.variables.count == 1) {
  867. return s;
  868. }
  869. break;
  870. case Type_Slice:
  871. switch (index) {
  872. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  873. case 1: result_type = t_int; break;
  874. }
  875. break;
  876. case Type_DynamicArray:
  877. switch (index) {
  878. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  879. case 1: result_type = t_int; break;
  880. case 2: result_type = t_int; break;
  881. case 3: result_type = t_allocator; break;
  882. }
  883. break;
  884. case Type_Map:
  885. {
  886. init_map_internal_types(t);
  887. Type *gst = t->Map.generated_struct_type;
  888. switch (index) {
  889. case 0: result_type = get_struct_field_type(gst, 0); break;
  890. case 1: result_type = get_struct_field_type(gst, 1); break;
  891. }
  892. }
  893. break;
  894. case Type_Array:
  895. result_type = t->Array.elem;
  896. break;
  897. default:
  898. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  899. break;
  900. }
  901. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  902. index = lb_convert_struct_index(p->module, t, index);
  903. lbValue res = {};
  904. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  905. res.type = result_type;
  906. return res;
  907. }
  908. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  909. GB_ASSERT(sel.index.count > 0);
  910. Type *type = type_deref(e.type);
  911. for_array(i, sel.index) {
  912. i32 index = cast(i32)sel.index[i];
  913. if (is_type_pointer(type)) {
  914. type = type_deref(type);
  915. e = lb_emit_load(p, e);
  916. }
  917. type = core_type(type);
  918. if (is_type_quaternion(type)) {
  919. e = lb_emit_struct_ep(p, e, index);
  920. } else if (is_type_raw_union(type)) {
  921. type = get_struct_field_type(type, index);
  922. GB_ASSERT(is_type_pointer(e.type));
  923. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  924. } else if (is_type_struct(type)) {
  925. type = get_struct_field_type(type, index);
  926. e = lb_emit_struct_ep(p, e, index);
  927. } else if (type->kind == Type_Union) {
  928. GB_ASSERT(index == -1);
  929. type = t_type_info_ptr;
  930. e = lb_emit_struct_ep(p, e, index);
  931. } else if (type->kind == Type_Tuple) {
  932. type = type->Tuple.variables[index]->type;
  933. e = lb_emit_struct_ep(p, e, index);
  934. } else if (type->kind == Type_Basic) {
  935. switch (type->Basic.kind) {
  936. case Basic_any: {
  937. if (index == 0) {
  938. type = t_rawptr;
  939. } else if (index == 1) {
  940. type = t_type_info_ptr;
  941. }
  942. e = lb_emit_struct_ep(p, e, index);
  943. break;
  944. }
  945. case Basic_string:
  946. e = lb_emit_struct_ep(p, e, index);
  947. break;
  948. default:
  949. GB_PANIC("un-gep-able type %s", type_to_string(type));
  950. break;
  951. }
  952. } else if (type->kind == Type_Slice) {
  953. e = lb_emit_struct_ep(p, e, index);
  954. } else if (type->kind == Type_DynamicArray) {
  955. e = lb_emit_struct_ep(p, e, index);
  956. } else if (type->kind == Type_Array) {
  957. e = lb_emit_array_epi(p, e, index);
  958. } else if (type->kind == Type_Map) {
  959. e = lb_emit_struct_ep(p, e, index);
  960. } else if (type->kind == Type_RelativePointer) {
  961. e = lb_emit_struct_ep(p, e, index);
  962. } else {
  963. GB_PANIC("un-gep-able type %s", type_to_string(type));
  964. }
  965. }
  966. return e;
  967. }
  968. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  969. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  970. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  971. return lb_emit_load(p, res);
  972. }
  973. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  974. Type *t = s.type;
  975. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  976. Type *st = base_type(type_deref(t));
  977. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  978. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  979. LLVMValueRef indices[2] = {};
  980. indices[0] = llvm_zero(p->module);
  981. indices[1] = lb_emit_conv(p, index, t_int).value;
  982. Type *ptr = base_array_type(st);
  983. lbValue res = {};
  984. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  985. res.type = alloc_type_pointer(ptr);
  986. return res;
  987. }
  988. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  989. Type *t = s.type;
  990. GB_ASSERT(is_type_pointer(t));
  991. Type *st = base_type(type_deref(t));
  992. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  993. GB_ASSERT(0 <= index);
  994. Type *ptr = base_array_type(st);
  995. LLVMValueRef indices[2] = {
  996. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  997. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  998. };
  999. lbValue res = {};
  1000. if (lb_is_const(s)) {
  1001. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1002. } else {
  1003. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1004. }
  1005. res.type = alloc_type_pointer(ptr);
  1006. return res;
  1007. }
  1008. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  1009. index = lb_emit_conv(p, index, t_int);
  1010. LLVMValueRef indices[1] = {index.value};
  1011. lbValue res = {};
  1012. res.type = ptr.type;
  1013. if (lb_is_const(ptr) && lb_is_const(index)) {
  1014. res.value = LLVMConstGEP(ptr.value, indices, 1);
  1015. } else {
  1016. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  1017. }
  1018. return res;
  1019. }
  1020. lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
  1021. Type *t = s.type;
  1022. GB_ASSERT(is_type_pointer(t));
  1023. Type *mt = base_type(type_deref(t));
  1024. Type *ptr = base_array_type(mt);
  1025. if (column == 0) {
  1026. GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt));
  1027. LLVMValueRef indices[2] = {
  1028. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1029. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)row, false),
  1030. };
  1031. lbValue res = {};
  1032. if (lb_is_const(s)) {
  1033. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1034. } else {
  1035. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1036. }
  1037. Type *ptr = base_array_type(mt);
  1038. res.type = alloc_type_pointer(ptr);
  1039. return res;
  1040. } else if (row == 0 && is_type_array_like(mt)) {
  1041. LLVMValueRef indices[2] = {
  1042. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1043. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)column, false),
  1044. };
  1045. lbValue res = {};
  1046. if (lb_is_const(s)) {
  1047. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1048. } else {
  1049. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1050. }
  1051. Type *ptr = base_array_type(mt);
  1052. res.type = alloc_type_pointer(ptr);
  1053. return res;
  1054. }
  1055. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1056. isize offset = matrix_indices_to_offset(mt, row, column);
  1057. LLVMValueRef indices[2] = {
  1058. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1059. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)offset, false),
  1060. };
  1061. lbValue res = {};
  1062. if (lb_is_const(s)) {
  1063. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1064. } else {
  1065. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1066. }
  1067. res.type = alloc_type_pointer(ptr);
  1068. return res;
  1069. }
  1070. lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) {
  1071. Type *t = s.type;
  1072. GB_ASSERT(is_type_pointer(t));
  1073. Type *mt = base_type(type_deref(t));
  1074. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1075. Type *ptr = base_array_type(mt);
  1076. LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value;
  1077. row = lb_emit_conv(p, row, t_int);
  1078. column = lb_emit_conv(p, column, t_int);
  1079. LLVMValueRef index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), "");
  1080. LLVMValueRef indices[2] = {
  1081. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1082. index,
  1083. };
  1084. lbValue res = {};
  1085. if (lb_is_const(s)) {
  1086. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1087. } else {
  1088. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1089. }
  1090. res.type = alloc_type_pointer(ptr);
  1091. return res;
  1092. }
  1093. lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) {
  1094. Type *st = base_type(s.type);
  1095. GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st));
  1096. lbValue value = lb_address_from_load_or_generate_local(p, s);
  1097. lbValue ptr = lb_emit_matrix_epi(p, value, row, column);
  1098. return lb_emit_load(p, ptr);
  1099. }
  1100. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  1101. Type *t = lb_addr_type(slice);
  1102. GB_ASSERT(is_type_slice(t));
  1103. lbValue ptr = lb_addr_get_ptr(p, slice);
  1104. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1105. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1106. }
  1107. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  1108. Type *t = lb_addr_type(string);
  1109. GB_ASSERT(is_type_string(t));
  1110. lbValue ptr = lb_addr_get_ptr(p, string);
  1111. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1112. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1113. }
  1114. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  1115. Type *t = base_type(string.type);
  1116. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  1117. return lb_emit_struct_ev(p, string, 0);
  1118. }
  1119. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  1120. Type *t = base_type(string.type);
  1121. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  1122. return lb_emit_struct_ev(p, string, 1);
  1123. }
  1124. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  1125. GB_ASSERT(is_type_cstring(value.type));
  1126. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1127. args[0] = lb_emit_conv(p, value, t_cstring);
  1128. return lb_emit_runtime_call(p, "cstring_len", args);
  1129. }
  1130. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  1131. Type *t = type_deref(array_ptr.type);
  1132. GB_ASSERT(is_type_array(t));
  1133. return lb_emit_struct_ep(p, array_ptr, 0);
  1134. }
  1135. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  1136. GB_ASSERT(is_type_slice(slice.type));
  1137. return lb_emit_struct_ev(p, slice, 0);
  1138. }
  1139. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  1140. GB_ASSERT(is_type_slice(slice.type) || is_type_relative_slice(slice.type));
  1141. return lb_emit_struct_ev(p, slice, 1);
  1142. }
  1143. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  1144. GB_ASSERT(is_type_dynamic_array(da.type));
  1145. return lb_emit_struct_ev(p, da, 0);
  1146. }
  1147. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  1148. GB_ASSERT(is_type_dynamic_array(da.type));
  1149. return lb_emit_struct_ev(p, da, 1);
  1150. }
  1151. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  1152. GB_ASSERT(is_type_dynamic_array(da.type));
  1153. return lb_emit_struct_ev(p, da, 2);
  1154. }
  1155. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  1156. GB_ASSERT(is_type_dynamic_array(da.type));
  1157. return lb_emit_struct_ev(p, da, 3);
  1158. }
  1159. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  1160. Type *t = base_type(value.type);
  1161. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1162. init_map_internal_types(t);
  1163. i32 index = 1;
  1164. lbValue entries = lb_emit_struct_ev(p, value, index);
  1165. return entries;
  1166. }
  1167. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  1168. Type *t = base_type(type_deref(value.type));
  1169. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1170. init_map_internal_types(t);
  1171. i32 index = 1;
  1172. lbValue entries = lb_emit_struct_ep(p, value, index);
  1173. return entries;
  1174. }
  1175. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  1176. lbValue entries = lb_map_entries(p, value);
  1177. return lb_dynamic_array_len(p, entries);
  1178. }
  1179. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  1180. lbValue entries = lb_map_entries(p, value);
  1181. return lb_dynamic_array_cap(p, entries);
  1182. }
  1183. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  1184. Type *t = base_type(value.type);
  1185. bool is_ptr = false;
  1186. if (is_type_pointer(t)) {
  1187. is_ptr = true;
  1188. t = base_type(type_deref(t));
  1189. }
  1190. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1191. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1192. }
  1193. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  1194. t->Struct.soa_kind == StructSoa_Dynamic);
  1195. isize n = 0;
  1196. Type *elem = base_type(t->Struct.soa_elem);
  1197. if (elem->kind == Type_Struct) {
  1198. n = cast(isize)elem->Struct.fields.count;
  1199. } else if (elem->kind == Type_Array) {
  1200. n = cast(isize)elem->Array.count;
  1201. } else {
  1202. GB_PANIC("Unreachable");
  1203. }
  1204. if (is_ptr) {
  1205. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1206. return lb_emit_load(p, v);
  1207. }
  1208. return lb_emit_struct_ev(p, value, cast(i32)n);
  1209. }
  1210. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  1211. Type *t = base_type(value.type);
  1212. bool is_ptr = false;
  1213. if (is_type_pointer(t)) {
  1214. is_ptr = true;
  1215. t = base_type(type_deref(t));
  1216. }
  1217. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1218. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1219. }
  1220. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  1221. isize n = 0;
  1222. Type *elem = base_type(t->Struct.soa_elem);
  1223. if (elem->kind == Type_Struct) {
  1224. n = cast(isize)elem->Struct.fields.count+1;
  1225. } else if (elem->kind == Type_Array) {
  1226. n = cast(isize)elem->Array.count+1;
  1227. } else {
  1228. GB_PANIC("Unreachable");
  1229. }
  1230. if (is_ptr) {
  1231. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1232. return lb_emit_load(p, v);
  1233. }
  1234. return lb_emit_struct_ev(p, value, cast(i32)n);
  1235. }
  1236. lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) {
  1237. lbModule *m = p->module;
  1238. a = lb_emit_conv(p, a, t);
  1239. b = lb_emit_conv(p, b, t);
  1240. c = lb_emit_conv(p, c, t);
  1241. bool is_possible = !is_type_different_to_arch_endianness(t) && is_type_float(t);
  1242. if (is_possible) {
  1243. switch (build_context.metrics.arch) {
  1244. case TargetArch_amd64:
  1245. if (type_size_of(t) == 2) {
  1246. is_possible = false;
  1247. }
  1248. break;
  1249. case TargetArch_arm64:
  1250. // possible
  1251. break;
  1252. case TargetArch_i386:
  1253. case TargetArch_wasm32:
  1254. case TargetArch_wasm64:
  1255. is_possible = false;
  1256. break;
  1257. }
  1258. }
  1259. if (is_possible) {
  1260. char const *name = "llvm.fma";
  1261. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1262. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1263. LLVMTypeRef types[1] = {};
  1264. types[0] = lb_type(m, t);
  1265. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types));
  1266. LLVMValueRef values[3] = {};
  1267. values[0] = a.value;
  1268. values[1] = b.value;
  1269. values[2] = c.value;
  1270. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), "");
  1271. return {call, t};
  1272. } else {
  1273. lbValue x = lb_emit_arith(p, Token_Mul, a, b, t);
  1274. lbValue y = lb_emit_arith(p, Token_Add, x, c, t);
  1275. return y;
  1276. }
  1277. }
  1278. LLVMValueRef llvm_mask_iota(lbModule *m, unsigned start, unsigned count) {
  1279. auto iota = slice_make<LLVMValueRef>(temporary_allocator(), count);
  1280. for (unsigned i = 0; i < count; i++) {
  1281. iota[i] = lb_const_int(m, t_u32, start+i).value;
  1282. }
  1283. return LLVMConstVector(iota.data, count);
  1284. }
  1285. LLVMValueRef llvm_mask_zero(lbModule *m, unsigned count) {
  1286. return LLVMConstNull(LLVMVectorType(lb_type(m, t_u32), count));
  1287. }
  1288. #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMGetUndef((type))
  1289. // #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMConstNull((type))
  1290. LLVMValueRef llvm_basic_shuffle(lbProcedure *p, LLVMValueRef vector, LLVMValueRef mask) {
  1291. return LLVMBuildShuffleVector(p->builder, vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask, "");
  1292. }
  1293. LLVMValueRef llvm_basic_const_shuffle(LLVMValueRef vector, LLVMValueRef mask) {
  1294. return LLVMConstShuffleVector(vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask);
  1295. }
  1296. LLVMValueRef llvm_vector_broadcast(lbProcedure *p, LLVMValueRef value, unsigned count) {
  1297. GB_ASSERT(count > 0);
  1298. if (LLVMIsConstant(value)) {
  1299. LLVMValueRef single = LLVMConstVector(&value, 1);
  1300. if (count == 1) {
  1301. return single;
  1302. }
  1303. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1304. return llvm_basic_const_shuffle(single, mask);
  1305. }
  1306. LLVMTypeRef single_type = LLVMVectorType(LLVMTypeOf(value), 1);
  1307. LLVMValueRef single = LLVMBuildBitCast(p->builder, value, single_type, "");
  1308. if (count == 1) {
  1309. return single;
  1310. }
  1311. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1312. return llvm_basic_shuffle(p, single, mask);
  1313. }
  1314. LLVMValueRef llvm_vector_shuffle_reduction(lbProcedure *p, LLVMValueRef value, LLVMOpcode op_code) {
  1315. LLVMTypeRef original_vector_type = LLVMTypeOf(value);
  1316. GB_ASSERT(LLVMGetTypeKind(original_vector_type) == LLVMVectorTypeKind);
  1317. unsigned len = LLVMGetVectorSize(original_vector_type);
  1318. LLVMValueRef v_zero32 = lb_const_int(p->module, t_u32, 0).value;
  1319. if (len == 1) {
  1320. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1321. }
  1322. GB_ASSERT((len & (len-1)) == 0);
  1323. for (unsigned i = len; i != 1; i >>= 1) {
  1324. unsigned mask_len = i/2;
  1325. LLVMValueRef lhs_mask = llvm_mask_iota(p->module, 0, mask_len);
  1326. LLVMValueRef rhs_mask = llvm_mask_iota(p->module, mask_len, mask_len);
  1327. GB_ASSERT(LLVMTypeOf(lhs_mask) == LLVMTypeOf(rhs_mask));
  1328. LLVMValueRef lhs = llvm_basic_shuffle(p, value, lhs_mask);
  1329. LLVMValueRef rhs = llvm_basic_shuffle(p, value, rhs_mask);
  1330. GB_ASSERT(LLVMTypeOf(lhs) == LLVMTypeOf(rhs));
  1331. value = LLVMBuildBinOp(p->builder, op_code, lhs, rhs, "");
  1332. }
  1333. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1334. }
  1335. LLVMValueRef llvm_vector_expand_to_power_of_two(lbProcedure *p, LLVMValueRef value) {
  1336. LLVMTypeRef vector_type = LLVMTypeOf(value);
  1337. unsigned len = LLVMGetVectorSize(vector_type);
  1338. if (len == 1) {
  1339. return value;
  1340. }
  1341. if ((len & (len-1)) == 0) {
  1342. return value;
  1343. }
  1344. unsigned expanded_len = cast(unsigned)next_pow2(cast(i64)len);
  1345. LLVMValueRef mask = llvm_mask_iota(p->module, 0, expanded_len);
  1346. return LLVMBuildShuffleVector(p->builder, value, LLVMConstNull(vector_type), mask, "");
  1347. }
  1348. LLVMValueRef llvm_vector_reduce_add(lbProcedure *p, LLVMValueRef value) {
  1349. LLVMTypeRef type = LLVMTypeOf(value);
  1350. GB_ASSERT(LLVMGetTypeKind(type) == LLVMVectorTypeKind);
  1351. LLVMTypeRef elem = LLVMGetElementType(type);
  1352. unsigned len = LLVMGetVectorSize(type);
  1353. if (len == 0) {
  1354. return LLVMConstNull(type);
  1355. }
  1356. char const *name = nullptr;
  1357. i32 value_offset = 0;
  1358. i32 value_count = 0;
  1359. switch (LLVMGetTypeKind(elem)) {
  1360. case LLVMHalfTypeKind:
  1361. case LLVMFloatTypeKind:
  1362. case LLVMDoubleTypeKind:
  1363. name = "llvm.vector.reduce.fadd";
  1364. value_offset = 0;
  1365. value_count = 2;
  1366. break;
  1367. case LLVMIntegerTypeKind:
  1368. name = "llvm.vector.reduce.add";
  1369. value_offset = 1;
  1370. value_count = 1;
  1371. break;
  1372. default:
  1373. GB_PANIC("invalid vector type %s", LLVMPrintTypeToString(type));
  1374. break;
  1375. }
  1376. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1377. if (id != 0 && false) {
  1378. LLVMTypeRef types[1] = {};
  1379. types[0] = type;
  1380. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1381. LLVMValueRef values[2] = {};
  1382. values[0] = LLVMConstNull(elem);
  1383. values[1] = value;
  1384. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values+value_offset, value_count, "");
  1385. return call;
  1386. }
  1387. // Manual reduce
  1388. #if 0
  1389. LLVMValueRef sum = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, 0).value, "");
  1390. for (unsigned i = 0; i < len; i++) {
  1391. LLVMValueRef val = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, i).value, "");
  1392. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1393. sum = LLVMBuildAdd(p->builder, sum, val, "");
  1394. } else {
  1395. sum = LLVMBuildFAdd(p->builder, sum, val, "");
  1396. }
  1397. }
  1398. return sum;
  1399. #else
  1400. LLVMOpcode op_code = LLVMFAdd;
  1401. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1402. op_code = LLVMAdd;
  1403. }
  1404. unsigned len_pow_2 = prev_pow2(len);
  1405. if (len_pow_2 == len) {
  1406. return llvm_vector_shuffle_reduction(p, value, op_code);
  1407. } else {
  1408. GB_ASSERT(len_pow_2 < len);
  1409. LLVMValueRef lower_mask = llvm_mask_iota(p->module, 0, len_pow_2);
  1410. LLVMValueRef upper_mask = llvm_mask_iota(p->module, len_pow_2, len-len_pow_2);
  1411. LLVMValueRef lower = llvm_basic_shuffle(p, value, lower_mask);
  1412. LLVMValueRef upper = llvm_basic_shuffle(p, value, upper_mask);
  1413. upper = llvm_vector_expand_to_power_of_two(p, upper);
  1414. LLVMValueRef lower_reduced = llvm_vector_shuffle_reduction(p, lower, op_code);
  1415. LLVMValueRef upper_reduced = llvm_vector_shuffle_reduction(p, upper, op_code);
  1416. GB_ASSERT(LLVMTypeOf(lower_reduced) == LLVMTypeOf(upper_reduced));
  1417. return LLVMBuildBinOp(p->builder, op_code, lower_reduced, upper_reduced, "");
  1418. }
  1419. #endif
  1420. }
  1421. LLVMValueRef llvm_vector_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1422. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1423. LLVMTypeRef elem = LLVMGetElementType(LLVMTypeOf(a));
  1424. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1425. return LLVMBuildAdd(p->builder, a, b, "");
  1426. }
  1427. return LLVMBuildFAdd(p->builder, a, b, "");
  1428. }
  1429. LLVMValueRef llvm_vector_mul(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1430. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1431. LLVMTypeRef elem = LLVMGetElementType(LLVMTypeOf(a));
  1432. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1433. return LLVMBuildMul(p->builder, a, b, "");
  1434. }
  1435. return LLVMBuildFMul(p->builder, a, b, "");
  1436. }
  1437. LLVMValueRef llvm_vector_dot(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1438. return llvm_vector_reduce_add(p, llvm_vector_mul(p, a, b));
  1439. }
  1440. LLVMValueRef llvm_vector_mul_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, LLVMValueRef c) {
  1441. lbModule *m = p->module;
  1442. LLVMTypeRef t = LLVMTypeOf(a);
  1443. GB_ASSERT(t == LLVMTypeOf(b));
  1444. GB_ASSERT(t == LLVMTypeOf(c));
  1445. GB_ASSERT(LLVMGetTypeKind(t) == LLVMVectorTypeKind);
  1446. LLVMTypeRef elem = LLVMGetElementType(t);
  1447. bool is_possible = false;
  1448. switch (LLVMGetTypeKind(elem)) {
  1449. case LLVMHalfTypeKind:
  1450. is_possible = true;
  1451. break;
  1452. case LLVMFloatTypeKind:
  1453. case LLVMDoubleTypeKind:
  1454. is_possible = true;
  1455. break;
  1456. }
  1457. if (is_possible) {
  1458. char const *name = "llvm.fmuladd";
  1459. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1460. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1461. LLVMTypeRef types[1] = {};
  1462. types[0] = t;
  1463. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types));
  1464. LLVMValueRef values[3] = {};
  1465. values[0] = a;
  1466. values[1] = b;
  1467. values[2] = c;
  1468. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), "");
  1469. return call;
  1470. } else {
  1471. LLVMValueRef x = llvm_vector_mul(p, a, b);
  1472. LLVMValueRef y = llvm_vector_add(p, x, c);
  1473. return y;
  1474. }
  1475. }
  1476. 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) {
  1477. return LLVMGetInlineAsm(func_type,
  1478. cast(char *)str.text, cast(size_t)str.len,
  1479. cast(char *)clobbers.text, cast(size_t)clobbers.len,
  1480. has_side_effects, is_align_stack,
  1481. dialect
  1482. #if LLVM_VERSION_MAJOR >= 13
  1483. , /*CanThrow*/false
  1484. #endif
  1485. );
  1486. }
  1487. void lb_set_wasm_import_attributes(LLVMValueRef value, Entity *entity, String import_name) {
  1488. if (!is_arch_wasm()) {
  1489. return;
  1490. }
  1491. String module_name = str_lit("env");
  1492. if (entity->Procedure.foreign_library != nullptr) {
  1493. Entity *foreign_library = entity->Procedure.foreign_library;
  1494. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1495. GB_ASSERT(foreign_library->LibraryName.paths.count == 1);
  1496. module_name = foreign_library->LibraryName.paths[0];
  1497. if (string_starts_with(import_name, module_name)) {
  1498. import_name = substring(import_name, module_name.len+WASM_MODULE_NAME_SEPARATOR.len, import_name.len);
  1499. }
  1500. }
  1501. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-module", alloc_cstring(permanent_allocator(), module_name));
  1502. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-name", alloc_cstring(permanent_allocator(), import_name));
  1503. }
  1504. void lb_set_wasm_export_attributes(LLVMValueRef value, String export_name) {
  1505. if (!is_arch_wasm()) {
  1506. return;
  1507. }
  1508. LLVMSetLinkage(value, LLVMDLLExportLinkage);
  1509. LLVMSetDLLStorageClass(value, LLVMDLLExportStorageClass);
  1510. LLVMSetVisibility(value, LLVMDefaultVisibility);
  1511. LLVMAddTargetDependentFunctionAttr(value, "wasm-export-name", alloc_cstring(permanent_allocator(), export_name));
  1512. }
  1513. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name);
  1514. lbAddr lb_handle_objc_find_or_register_selector(lbProcedure *p, String const &name) {
  1515. lbAddr *found = string_map_get(&p->module->objc_selectors, name);
  1516. if (found) {
  1517. return *found;
  1518. } else {
  1519. lbModule *default_module = &p->module->gen->default_module;
  1520. Entity *e = nullptr;
  1521. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_SEL, {}, &e);
  1522. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1523. lbAddr local_addr = lb_addr(ptr);
  1524. string_map_set(&default_module->objc_selectors, name, default_addr);
  1525. if (default_module != p->module) {
  1526. string_map_set(&p->module->objc_selectors, name, local_addr);
  1527. }
  1528. return local_addr;
  1529. }
  1530. }
  1531. lbValue lb_handle_objc_find_selector(lbProcedure *p, Ast *expr) {
  1532. ast_node(ce, CallExpr, expr);
  1533. auto tav = ce->args[0]->tav;
  1534. GB_ASSERT(tav.value.kind == ExactValue_String);
  1535. String name = tav.value.value_string;
  1536. return lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, name));
  1537. }
  1538. lbValue lb_handle_objc_register_selector(lbProcedure *p, Ast *expr) {
  1539. ast_node(ce, CallExpr, expr);
  1540. lbModule *m = p->module;
  1541. auto tav = ce->args[0]->tav;
  1542. GB_ASSERT(tav.value.kind == ExactValue_String);
  1543. String name = tav.value.value_string;
  1544. lbAddr dst = lb_handle_objc_find_or_register_selector(p, name);
  1545. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1546. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  1547. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  1548. lb_addr_store(p, dst, ptr);
  1549. return lb_addr_load(p, dst);
  1550. }
  1551. lbAddr lb_handle_objc_find_or_register_class(lbProcedure *p, String const &name) {
  1552. lbAddr *found = string_map_get(&p->module->objc_classes, name);
  1553. if (found) {
  1554. return *found;
  1555. } else {
  1556. lbModule *default_module = &p->module->gen->default_module;
  1557. Entity *e = nullptr;
  1558. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_SEL, {}, &e);
  1559. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1560. lbAddr local_addr = lb_addr(ptr);
  1561. string_map_set(&default_module->objc_classes, name, default_addr);
  1562. if (default_module != p->module) {
  1563. string_map_set(&p->module->objc_classes, name, local_addr);
  1564. }
  1565. return local_addr;
  1566. }
  1567. }
  1568. lbValue lb_handle_objc_find_class(lbProcedure *p, Ast *expr) {
  1569. ast_node(ce, CallExpr, expr);
  1570. auto tav = ce->args[0]->tav;
  1571. GB_ASSERT(tav.value.kind == ExactValue_String);
  1572. String name = tav.value.value_string;
  1573. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name));
  1574. }
  1575. lbValue lb_handle_objc_register_class(lbProcedure *p, Ast *expr) {
  1576. ast_node(ce, CallExpr, expr);
  1577. lbModule *m = p->module;
  1578. auto tav = ce->args[0]->tav;
  1579. GB_ASSERT(tav.value.kind == ExactValue_String);
  1580. String name = tav.value.value_string;
  1581. lbAddr dst = lb_handle_objc_find_or_register_class(p, name);
  1582. auto args = array_make<lbValue>(permanent_allocator(), 3);
  1583. args[0] = lb_const_nil(m, t_objc_Class);
  1584. args[1] = lb_const_nil(m, t_objc_Class);
  1585. args[2] = lb_const_int(m, t_uint, 0);
  1586. lbValue ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  1587. lb_addr_store(p, dst, ptr);
  1588. return lb_addr_load(p, dst);
  1589. }
  1590. lbValue lb_handle_objc_id(lbProcedure *p, Ast *expr) {
  1591. TypeAndValue const &tav = type_and_value_of_expr(expr);
  1592. if (tav.mode == Addressing_Type) {
  1593. Type *type = tav.type;
  1594. GB_ASSERT_MSG(type->kind == Type_Named, "%s", type_to_string(type));
  1595. Entity *e = type->Named.type_name;
  1596. GB_ASSERT(e->kind == Entity_TypeName);
  1597. String name = e->TypeName.objc_class_name;
  1598. lbAddr *found = string_map_get(&p->module->objc_classes, name);
  1599. if (found) {
  1600. return lb_addr_load(p, *found);
  1601. } else {
  1602. lbModule *default_module = &p->module->gen->default_module;
  1603. Entity *e = nullptr;
  1604. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_Class, {}, &e);
  1605. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1606. lbAddr local_addr = lb_addr(ptr);
  1607. string_map_set(&default_module->objc_classes, name, default_addr);
  1608. if (default_module != p->module) {
  1609. string_map_set(&p->module->objc_classes, name, local_addr);
  1610. }
  1611. return lb_addr_load(p, local_addr);
  1612. }
  1613. }
  1614. return lb_build_expr(p, expr);
  1615. }
  1616. lbValue lb_handle_objc_send(lbProcedure *p, Ast *expr) {
  1617. ast_node(ce, CallExpr, expr);
  1618. lbModule *m = p->module;
  1619. CheckerInfo *info = m->info;
  1620. ObjcMsgData data = map_must_get(&info->objc_msgSend_types, expr);
  1621. GB_ASSERT(data.proc_type != nullptr);
  1622. GB_ASSERT(ce->args.count >= 3);
  1623. auto args = array_make<lbValue>(permanent_allocator(), 0, ce->args.count-1);
  1624. lbValue id = lb_handle_objc_id(p, ce->args[1]);
  1625. Ast *sel_expr = ce->args[2];
  1626. GB_ASSERT(sel_expr->tav.value.kind == ExactValue_String);
  1627. lbValue sel = lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, sel_expr->tav.value.value_string));
  1628. array_add(&args, id);
  1629. array_add(&args, sel);
  1630. for (isize i = 3; i < ce->args.count; i++) {
  1631. lbValue arg = lb_build_expr(p, ce->args[i]);
  1632. array_add(&args, arg);
  1633. }
  1634. lbValue the_proc = {};
  1635. switch (data.kind) {
  1636. default:
  1637. GB_PANIC("unhandled ObjcMsgKind %u", data.kind);
  1638. break;
  1639. case ObjcMsg_normal: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend")); break;
  1640. case ObjcMsg_fpret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fpret")); break;
  1641. case ObjcMsg_fp2ret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fp2ret")); break;
  1642. case ObjcMsg_stret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_stret")); break;
  1643. }
  1644. the_proc = lb_emit_conv(p, the_proc, data.proc_type);
  1645. return lb_emit_call(p, the_proc, args);
  1646. }