llvm_backend_utility.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  535. auto args = array_make<lbValue>(permanent_allocator(), 7);
  536. args[0] = ok;
  537. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  538. args[2] = lb_const_int(m, t_i32, pos.line);
  539. args[3] = lb_const_int(m, t_i32, pos.column);
  540. args[4] = lb_typeid(m, src_type);
  541. args[5] = lb_typeid(m, dst_type);
  542. args[6] = lb_emit_conv(p, value_, t_rawptr);
  543. lb_emit_runtime_call(p, "type_assertion_check2", args);
  544. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  545. }
  546. return lb_addr_load(p, v);
  547. }
  548. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  549. lbModule *m = p->module;
  550. Type *src_type = value.type;
  551. if (is_type_pointer(src_type)) {
  552. value = lb_emit_load(p, value);
  553. }
  554. bool is_tuple = true;
  555. Type *tuple = type;
  556. if (type->kind != Type_Tuple) {
  557. is_tuple = false;
  558. tuple = make_optional_ok_type(type);
  559. }
  560. Type *dst_type = tuple->Tuple.variables[0]->type;
  561. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  562. // just do a bit cast of the data at the front
  563. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  564. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(type));
  565. return lb_addr(ptr);
  566. }
  567. lbAddr v = lb_add_local_generated(p, tuple, true);
  568. lbValue dst_typeid = lb_typeid(m, dst_type);
  569. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  570. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  571. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  572. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  573. lb_emit_if(p, cond, ok_block, end_block);
  574. lb_start_block(p, ok_block);
  575. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  576. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  577. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  578. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  579. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  580. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  581. lb_emit_jump(p, end_block);
  582. lb_start_block(p, end_block);
  583. if (!is_tuple) {
  584. // NOTE(bill): Panic on invalid conversion
  585. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  586. auto args = array_make<lbValue>(permanent_allocator(), 7);
  587. args[0] = ok;
  588. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  589. args[2] = lb_const_int(m, t_i32, pos.line);
  590. args[3] = lb_const_int(m, t_i32, pos.column);
  591. args[4] = any_typeid;
  592. args[5] = dst_typeid;
  593. args[6] = lb_emit_struct_ev(p, value, 0);;
  594. lb_emit_runtime_call(p, "type_assertion_check2", args);
  595. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  596. }
  597. return v;
  598. }
  599. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  600. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  601. }
  602. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  603. if (p->context_stack.count > 0) {
  604. return p->context_stack[p->context_stack.count-1].ctx;
  605. }
  606. Type *pt = base_type(p->type);
  607. GB_ASSERT(pt->kind == Type_Proc);
  608. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  609. lbAddr c = lb_add_local_generated(p, t_context, true);
  610. c.kind = lbAddr_Context;
  611. lb_emit_init_context(p, c);
  612. lb_push_context_onto_stack(p, c);
  613. lb_add_debug_context_variable(p, c);
  614. return c;
  615. }
  616. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  617. if (LLVMIsALoadInst(value.value)) {
  618. lbValue res = {};
  619. res.value = LLVMGetOperand(value.value, 0);
  620. res.type = alloc_type_pointer(value.type);
  621. return res;
  622. }
  623. GB_ASSERT(is_type_typed(value.type));
  624. lbAddr res = lb_add_local_generated(p, value.type, false);
  625. lb_addr_store(p, res, value);
  626. return res.addr;
  627. }
  628. lbValue lb_address_from_load(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_PANIC("lb_address_from_load");
  636. return {};
  637. }
  638. lbStructFieldRemapping lb_get_struct_remapping(lbModule *m, Type *t) {
  639. t = base_type(t);
  640. LLVMTypeRef struct_type = lb_type(m, t);
  641. auto *field_remapping = map_get(&m->struct_field_remapping, cast(void *)struct_type);
  642. if (field_remapping == nullptr) {
  643. field_remapping = map_get(&m->struct_field_remapping, cast(void *)t);
  644. }
  645. GB_ASSERT(field_remapping != nullptr);
  646. return *field_remapping;
  647. }
  648. i32 lb_convert_struct_index(lbModule *m, Type *t, i32 index) {
  649. if (t->kind == Type_Struct) {
  650. auto field_remapping = lb_get_struct_remapping(m, t);
  651. index = field_remapping[index];
  652. }
  653. return index;
  654. }
  655. LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 padding_align) {
  656. // NOTE(bill): limit to `[N x u64]` to prevent ABI issues
  657. padding_align = gb_clamp(padding_align, 1, 8);
  658. if (padding % padding_align == 0) {
  659. LLVMTypeRef elem = nullptr;
  660. isize len = padding/padding_align;
  661. switch (padding_align) {
  662. case 1: elem = lb_type(m, t_u8); break;
  663. case 2: elem = lb_type(m, t_u16); break;
  664. case 4: elem = lb_type(m, t_u32); break;
  665. case 8: elem = lb_type(m, t_u64); break;
  666. }
  667. GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
  668. if (len != 1) {
  669. return LLVMArrayType(elem, cast(unsigned)len);
  670. } else {
  671. return elem;
  672. }
  673. } else {
  674. return LLVMArrayType(lb_type(m, t_u8), cast(unsigned)padding);
  675. }
  676. }
  677. char const *llvm_type_kinds[] = {
  678. "LLVMVoidTypeKind",
  679. "LLVMHalfTypeKind",
  680. "LLVMFloatTypeKind",
  681. "LLVMDoubleTypeKind",
  682. "LLVMX86_FP80TypeKind",
  683. "LLVMFP128TypeKind",
  684. "LLVMPPC_FP128TypeKind",
  685. "LLVMLabelTypeKind",
  686. "LLVMIntegerTypeKind",
  687. "LLVMFunctionTypeKind",
  688. "LLVMStructTypeKind",
  689. "LLVMArrayTypeKind",
  690. "LLVMPointerTypeKind",
  691. "LLVMVectorTypeKind",
  692. "LLVMMetadataTypeKind",
  693. "LLVMX86_MMXTypeKind",
  694. "LLVMTokenTypeKind",
  695. "LLVMScalableVectorTypeKind",
  696. "LLVMBFloatTypeKind",
  697. };
  698. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  699. GB_ASSERT(is_type_pointer(s.type));
  700. Type *t = base_type(type_deref(s.type));
  701. Type *result_type = nullptr;
  702. if (is_type_relative_pointer(t)) {
  703. s = lb_addr_get_ptr(p, lb_addr(s));
  704. }
  705. if (is_type_struct(t)) {
  706. result_type = get_struct_field_type(t, index);
  707. } else if (is_type_union(t)) {
  708. GB_ASSERT(index == -1);
  709. return lb_emit_union_tag_ptr(p, s);
  710. } else if (is_type_tuple(t)) {
  711. GB_ASSERT(t->Tuple.variables.count > 0);
  712. result_type = t->Tuple.variables[index]->type;
  713. } else if (is_type_complex(t)) {
  714. Type *ft = base_complex_elem_type(t);
  715. switch (index) {
  716. case 0: result_type = ft; break;
  717. case 1: result_type = ft; break;
  718. }
  719. } else if (is_type_quaternion(t)) {
  720. Type *ft = base_complex_elem_type(t);
  721. switch (index) {
  722. case 0: result_type = ft; break;
  723. case 1: result_type = ft; break;
  724. case 2: result_type = ft; break;
  725. case 3: result_type = ft; break;
  726. }
  727. } else if (is_type_slice(t)) {
  728. switch (index) {
  729. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  730. case 1: result_type = t_int; break;
  731. }
  732. } else if (is_type_string(t)) {
  733. switch (index) {
  734. case 0: result_type = t_u8_ptr; break;
  735. case 1: result_type = t_int; break;
  736. }
  737. } else if (is_type_any(t)) {
  738. switch (index) {
  739. case 0: result_type = t_rawptr; break;
  740. case 1: result_type = t_typeid; break;
  741. }
  742. } else if (is_type_dynamic_array(t)) {
  743. switch (index) {
  744. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  745. case 1: result_type = t_int; break;
  746. case 2: result_type = t_int; break;
  747. case 3: result_type = t_allocator; break;
  748. }
  749. } else if (is_type_map(t)) {
  750. init_map_internal_types(t);
  751. Type *itp = alloc_type_pointer(t->Map.internal_type);
  752. s = lb_emit_transmute(p, s, itp);
  753. Type *gst = t->Map.internal_type;
  754. GB_ASSERT(gst->kind == Type_Struct);
  755. switch (index) {
  756. case 0: result_type = get_struct_field_type(gst, 0); break;
  757. case 1: result_type = get_struct_field_type(gst, 1); break;
  758. }
  759. } else if (is_type_array(t)) {
  760. return lb_emit_array_epi(p, s, index);
  761. } else if (is_type_relative_slice(t)) {
  762. switch (index) {
  763. case 0: result_type = t->RelativeSlice.base_integer; break;
  764. case 1: result_type = t->RelativeSlice.base_integer; break;
  765. }
  766. } else {
  767. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  768. }
  769. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  770. i32 original_index = index;
  771. index = lb_convert_struct_index(p->module, t, index);
  772. if (lb_is_const(s)) {
  773. lbModule *m = p->module;
  774. lbValue res = {};
  775. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  776. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  777. res.type = alloc_type_pointer(result_type);
  778. return res;
  779. } else {
  780. lbValue res = {};
  781. LLVMTypeRef st = LLVMGetElementType(LLVMTypeOf(s.value));
  782. // gb_printf_err("%s\n", type_to_string(s.type));
  783. // gb_printf_err("%s\n", LLVMPrintTypeToString(LLVMTypeOf(s.value)));
  784. // gb_printf_err("%d\n", index);
  785. GB_ASSERT_MSG(LLVMGetTypeKind(st) == LLVMStructTypeKind, "%s", llvm_type_kinds[LLVMGetTypeKind(st)]);
  786. unsigned count = LLVMCountStructElementTypes(st);
  787. GB_ASSERT_MSG(count >= cast(unsigned)index, "%u %d %d", count, index, original_index);
  788. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  789. res.type = alloc_type_pointer(result_type);
  790. return res;
  791. }
  792. }
  793. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  794. if (LLVMIsALoadInst(s.value)) {
  795. lbValue res = {};
  796. res.value = LLVMGetOperand(s.value, 0);
  797. res.type = alloc_type_pointer(s.type);
  798. lbValue ptr = lb_emit_struct_ep(p, res, index);
  799. return lb_emit_load(p, ptr);
  800. }
  801. Type *t = base_type(s.type);
  802. Type *result_type = nullptr;
  803. switch (t->kind) {
  804. case Type_Basic:
  805. switch (t->Basic.kind) {
  806. case Basic_string:
  807. switch (index) {
  808. case 0: result_type = t_u8_ptr; break;
  809. case 1: result_type = t_int; break;
  810. }
  811. break;
  812. case Basic_any:
  813. switch (index) {
  814. case 0: result_type = t_rawptr; break;
  815. case 1: result_type = t_typeid; break;
  816. }
  817. break;
  818. case Basic_complex32:
  819. case Basic_complex64:
  820. case Basic_complex128:
  821. {
  822. Type *ft = base_complex_elem_type(t);
  823. switch (index) {
  824. case 0: result_type = ft; break;
  825. case 1: result_type = ft; break;
  826. }
  827. break;
  828. }
  829. case Basic_quaternion64:
  830. case Basic_quaternion128:
  831. case Basic_quaternion256:
  832. {
  833. Type *ft = base_complex_elem_type(t);
  834. switch (index) {
  835. case 0: result_type = ft; break;
  836. case 1: result_type = ft; break;
  837. case 2: result_type = ft; break;
  838. case 3: result_type = ft; break;
  839. }
  840. break;
  841. }
  842. }
  843. break;
  844. case Type_Struct:
  845. result_type = get_struct_field_type(t, index);
  846. break;
  847. case Type_Union:
  848. GB_ASSERT(index == -1);
  849. // return lb_emit_union_tag_value(p, s);
  850. GB_PANIC("lb_emit_union_tag_value");
  851. case Type_Tuple:
  852. GB_ASSERT(t->Tuple.variables.count > 0);
  853. result_type = t->Tuple.variables[index]->type;
  854. if (t->Tuple.variables.count == 1) {
  855. return s;
  856. }
  857. break;
  858. case Type_Slice:
  859. switch (index) {
  860. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  861. case 1: result_type = t_int; break;
  862. }
  863. break;
  864. case Type_DynamicArray:
  865. switch (index) {
  866. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  867. case 1: result_type = t_int; break;
  868. case 2: result_type = t_int; break;
  869. case 3: result_type = t_allocator; break;
  870. }
  871. break;
  872. case Type_Map:
  873. {
  874. init_map_internal_types(t);
  875. Type *gst = t->Map.generated_struct_type;
  876. switch (index) {
  877. case 0: result_type = get_struct_field_type(gst, 0); break;
  878. case 1: result_type = get_struct_field_type(gst, 1); break;
  879. }
  880. }
  881. break;
  882. case Type_Array:
  883. result_type = t->Array.elem;
  884. break;
  885. default:
  886. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  887. break;
  888. }
  889. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  890. index = lb_convert_struct_index(p->module, t, index);
  891. lbValue res = {};
  892. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  893. res.type = result_type;
  894. return res;
  895. }
  896. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  897. GB_ASSERT(sel.index.count > 0);
  898. Type *type = type_deref(e.type);
  899. for_array(i, sel.index) {
  900. i32 index = cast(i32)sel.index[i];
  901. if (is_type_pointer(type)) {
  902. type = type_deref(type);
  903. e = lb_emit_load(p, e);
  904. }
  905. type = core_type(type);
  906. if (is_type_quaternion(type)) {
  907. e = lb_emit_struct_ep(p, e, index);
  908. } else if (is_type_raw_union(type)) {
  909. type = get_struct_field_type(type, index);
  910. GB_ASSERT(is_type_pointer(e.type));
  911. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  912. } else if (is_type_struct(type)) {
  913. type = get_struct_field_type(type, index);
  914. e = lb_emit_struct_ep(p, e, index);
  915. } else if (type->kind == Type_Union) {
  916. GB_ASSERT(index == -1);
  917. type = t_type_info_ptr;
  918. e = lb_emit_struct_ep(p, e, index);
  919. } else if (type->kind == Type_Tuple) {
  920. type = type->Tuple.variables[index]->type;
  921. e = lb_emit_struct_ep(p, e, index);
  922. } else if (type->kind == Type_Basic) {
  923. switch (type->Basic.kind) {
  924. case Basic_any: {
  925. if (index == 0) {
  926. type = t_rawptr;
  927. } else if (index == 1) {
  928. type = t_type_info_ptr;
  929. }
  930. e = lb_emit_struct_ep(p, e, index);
  931. break;
  932. }
  933. case Basic_string:
  934. e = lb_emit_struct_ep(p, e, index);
  935. break;
  936. default:
  937. GB_PANIC("un-gep-able type %s", type_to_string(type));
  938. break;
  939. }
  940. } else if (type->kind == Type_Slice) {
  941. e = lb_emit_struct_ep(p, e, index);
  942. } else if (type->kind == Type_DynamicArray) {
  943. e = lb_emit_struct_ep(p, e, index);
  944. } else if (type->kind == Type_Array) {
  945. e = lb_emit_array_epi(p, e, index);
  946. } else if (type->kind == Type_Map) {
  947. e = lb_emit_struct_ep(p, e, index);
  948. } else if (type->kind == Type_RelativePointer) {
  949. e = lb_emit_struct_ep(p, e, index);
  950. } else {
  951. GB_PANIC("un-gep-able type %s", type_to_string(type));
  952. }
  953. }
  954. return e;
  955. }
  956. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  957. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  958. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  959. return lb_emit_load(p, res);
  960. }
  961. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  962. Type *t = s.type;
  963. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  964. Type *st = base_type(type_deref(t));
  965. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  966. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  967. LLVMValueRef indices[2] = {};
  968. indices[0] = llvm_zero(p->module);
  969. indices[1] = lb_emit_conv(p, index, t_int).value;
  970. Type *ptr = base_array_type(st);
  971. lbValue res = {};
  972. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  973. res.type = alloc_type_pointer(ptr);
  974. return res;
  975. }
  976. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  977. Type *t = s.type;
  978. GB_ASSERT(is_type_pointer(t));
  979. Type *st = base_type(type_deref(t));
  980. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  981. GB_ASSERT(0 <= index);
  982. Type *ptr = base_array_type(st);
  983. LLVMValueRef indices[2] = {
  984. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  985. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  986. };
  987. lbValue res = {};
  988. if (lb_is_const(s)) {
  989. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  990. } else {
  991. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  992. }
  993. res.type = alloc_type_pointer(ptr);
  994. return res;
  995. }
  996. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  997. index = lb_emit_conv(p, index, t_int);
  998. LLVMValueRef indices[1] = {index.value};
  999. lbValue res = {};
  1000. res.type = ptr.type;
  1001. if (lb_is_const(ptr) && lb_is_const(index)) {
  1002. res.value = LLVMConstGEP(ptr.value, indices, 1);
  1003. } else {
  1004. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  1005. }
  1006. return res;
  1007. }
  1008. lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
  1009. Type *t = s.type;
  1010. GB_ASSERT(is_type_pointer(t));
  1011. Type *mt = base_type(type_deref(t));
  1012. Type *ptr = base_array_type(mt);
  1013. if (column == 0) {
  1014. GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt));
  1015. LLVMValueRef indices[2] = {
  1016. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1017. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)row, false),
  1018. };
  1019. lbValue res = {};
  1020. if (lb_is_const(s)) {
  1021. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1022. } else {
  1023. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1024. }
  1025. Type *ptr = base_array_type(mt);
  1026. res.type = alloc_type_pointer(ptr);
  1027. return res;
  1028. } else if (row == 0 && is_type_array_like(mt)) {
  1029. LLVMValueRef indices[2] = {
  1030. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1031. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)column, false),
  1032. };
  1033. lbValue res = {};
  1034. if (lb_is_const(s)) {
  1035. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1036. } else {
  1037. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1038. }
  1039. Type *ptr = base_array_type(mt);
  1040. res.type = alloc_type_pointer(ptr);
  1041. return res;
  1042. }
  1043. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1044. isize offset = matrix_indices_to_offset(mt, row, column);
  1045. LLVMValueRef indices[2] = {
  1046. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1047. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)offset, false),
  1048. };
  1049. lbValue res = {};
  1050. if (lb_is_const(s)) {
  1051. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1052. } else {
  1053. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1054. }
  1055. res.type = alloc_type_pointer(ptr);
  1056. return res;
  1057. }
  1058. lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) {
  1059. Type *t = s.type;
  1060. GB_ASSERT(is_type_pointer(t));
  1061. Type *mt = base_type(type_deref(t));
  1062. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1063. Type *ptr = base_array_type(mt);
  1064. LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value;
  1065. row = lb_emit_conv(p, row, t_int);
  1066. column = lb_emit_conv(p, column, t_int);
  1067. LLVMValueRef index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), "");
  1068. LLVMValueRef indices[2] = {
  1069. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1070. index,
  1071. };
  1072. lbValue res = {};
  1073. if (lb_is_const(s)) {
  1074. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  1075. } else {
  1076. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  1077. }
  1078. res.type = alloc_type_pointer(ptr);
  1079. return res;
  1080. }
  1081. lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) {
  1082. Type *st = base_type(s.type);
  1083. GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st));
  1084. lbValue value = lb_address_from_load_or_generate_local(p, s);
  1085. lbValue ptr = lb_emit_matrix_epi(p, value, row, column);
  1086. return lb_emit_load(p, ptr);
  1087. }
  1088. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  1089. Type *t = lb_addr_type(slice);
  1090. GB_ASSERT(is_type_slice(t));
  1091. lbValue ptr = lb_addr_get_ptr(p, slice);
  1092. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1093. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1094. }
  1095. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  1096. Type *t = lb_addr_type(string);
  1097. GB_ASSERT(is_type_string(t));
  1098. lbValue ptr = lb_addr_get_ptr(p, string);
  1099. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1100. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1101. }
  1102. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  1103. Type *t = base_type(string.type);
  1104. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  1105. return lb_emit_struct_ev(p, string, 0);
  1106. }
  1107. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  1108. Type *t = base_type(string.type);
  1109. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  1110. return lb_emit_struct_ev(p, string, 1);
  1111. }
  1112. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  1113. GB_ASSERT(is_type_cstring(value.type));
  1114. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1115. args[0] = lb_emit_conv(p, value, t_cstring);
  1116. return lb_emit_runtime_call(p, "cstring_len", args);
  1117. }
  1118. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  1119. Type *t = type_deref(array_ptr.type);
  1120. GB_ASSERT(is_type_array(t));
  1121. return lb_emit_struct_ep(p, array_ptr, 0);
  1122. }
  1123. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  1124. GB_ASSERT(is_type_slice(slice.type));
  1125. return lb_emit_struct_ev(p, slice, 0);
  1126. }
  1127. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  1128. GB_ASSERT(is_type_slice(slice.type));
  1129. return lb_emit_struct_ev(p, slice, 1);
  1130. }
  1131. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  1132. GB_ASSERT(is_type_dynamic_array(da.type));
  1133. return lb_emit_struct_ev(p, da, 0);
  1134. }
  1135. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  1136. GB_ASSERT(is_type_dynamic_array(da.type));
  1137. return lb_emit_struct_ev(p, da, 1);
  1138. }
  1139. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  1140. GB_ASSERT(is_type_dynamic_array(da.type));
  1141. return lb_emit_struct_ev(p, da, 2);
  1142. }
  1143. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  1144. GB_ASSERT(is_type_dynamic_array(da.type));
  1145. return lb_emit_struct_ev(p, da, 3);
  1146. }
  1147. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  1148. Type *t = base_type(value.type);
  1149. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1150. init_map_internal_types(t);
  1151. i32 index = 1;
  1152. lbValue entries = lb_emit_struct_ev(p, value, index);
  1153. return entries;
  1154. }
  1155. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  1156. Type *t = base_type(type_deref(value.type));
  1157. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1158. init_map_internal_types(t);
  1159. i32 index = 1;
  1160. lbValue entries = lb_emit_struct_ep(p, value, index);
  1161. return entries;
  1162. }
  1163. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  1164. lbValue entries = lb_map_entries(p, value);
  1165. return lb_dynamic_array_len(p, entries);
  1166. }
  1167. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  1168. lbValue entries = lb_map_entries(p, value);
  1169. return lb_dynamic_array_cap(p, entries);
  1170. }
  1171. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  1172. Type *t = base_type(value.type);
  1173. bool is_ptr = false;
  1174. if (is_type_pointer(t)) {
  1175. is_ptr = true;
  1176. t = base_type(type_deref(t));
  1177. }
  1178. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1179. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1180. }
  1181. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  1182. t->Struct.soa_kind == StructSoa_Dynamic);
  1183. isize n = 0;
  1184. Type *elem = base_type(t->Struct.soa_elem);
  1185. if (elem->kind == Type_Struct) {
  1186. n = cast(isize)elem->Struct.fields.count;
  1187. } else if (elem->kind == Type_Array) {
  1188. n = cast(isize)elem->Array.count;
  1189. } else {
  1190. GB_PANIC("Unreachable");
  1191. }
  1192. if (is_ptr) {
  1193. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1194. return lb_emit_load(p, v);
  1195. }
  1196. return lb_emit_struct_ev(p, value, cast(i32)n);
  1197. }
  1198. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  1199. Type *t = base_type(value.type);
  1200. bool is_ptr = false;
  1201. if (is_type_pointer(t)) {
  1202. is_ptr = true;
  1203. t = base_type(type_deref(t));
  1204. }
  1205. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1206. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1207. }
  1208. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  1209. isize n = 0;
  1210. Type *elem = base_type(t->Struct.soa_elem);
  1211. if (elem->kind == Type_Struct) {
  1212. n = cast(isize)elem->Struct.fields.count+1;
  1213. } else if (elem->kind == Type_Array) {
  1214. n = cast(isize)elem->Array.count+1;
  1215. } else {
  1216. GB_PANIC("Unreachable");
  1217. }
  1218. if (is_ptr) {
  1219. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1220. return lb_emit_load(p, v);
  1221. }
  1222. return lb_emit_struct_ev(p, value, cast(i32)n);
  1223. }
  1224. lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) {
  1225. lbModule *m = p->module;
  1226. a = lb_emit_conv(p, a, t);
  1227. b = lb_emit_conv(p, b, t);
  1228. c = lb_emit_conv(p, c, t);
  1229. bool is_possible = !is_type_different_to_arch_endianness(t) && is_type_float(t);
  1230. if (is_possible) {
  1231. switch (build_context.metrics.arch) {
  1232. case TargetArch_amd64:
  1233. if (type_size_of(t) == 2) {
  1234. is_possible = false;
  1235. }
  1236. break;
  1237. case TargetArch_arm64:
  1238. // possible
  1239. break;
  1240. case TargetArch_i386:
  1241. case TargetArch_wasm32:
  1242. case TargetArch_wasm64:
  1243. is_possible = false;
  1244. break;
  1245. }
  1246. }
  1247. if (is_possible) {
  1248. char const *name = "llvm.fma";
  1249. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1250. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1251. LLVMTypeRef types[1] = {};
  1252. types[0] = lb_type(m, t);
  1253. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types));
  1254. LLVMValueRef values[3] = {};
  1255. values[0] = a.value;
  1256. values[1] = b.value;
  1257. values[2] = c.value;
  1258. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), "");
  1259. return {call, t};
  1260. } else {
  1261. lbValue x = lb_emit_arith(p, Token_Mul, a, b, t);
  1262. lbValue y = lb_emit_arith(p, Token_Add, x, c, t);
  1263. return y;
  1264. }
  1265. }
  1266. LLVMValueRef llvm_mask_iota(lbModule *m, unsigned start, unsigned count) {
  1267. auto iota = slice_make<LLVMValueRef>(temporary_allocator(), count);
  1268. for (unsigned i = 0; i < count; i++) {
  1269. iota[i] = lb_const_int(m, t_u32, start+i).value;
  1270. }
  1271. return LLVMConstVector(iota.data, count);
  1272. }
  1273. LLVMValueRef llvm_mask_zero(lbModule *m, unsigned count) {
  1274. return LLVMConstNull(LLVMVectorType(lb_type(m, t_u32), count));
  1275. }
  1276. #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMGetUndef((type))
  1277. // #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMConstNull((type))
  1278. LLVMValueRef llvm_basic_shuffle(lbProcedure *p, LLVMValueRef vector, LLVMValueRef mask) {
  1279. return LLVMBuildShuffleVector(p->builder, vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask, "");
  1280. }
  1281. LLVMValueRef llvm_basic_const_shuffle(LLVMValueRef vector, LLVMValueRef mask) {
  1282. return LLVMConstShuffleVector(vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask);
  1283. }
  1284. LLVMValueRef llvm_vector_broadcast(lbProcedure *p, LLVMValueRef value, unsigned count) {
  1285. GB_ASSERT(count > 0);
  1286. if (LLVMIsConstant(value)) {
  1287. LLVMValueRef single = LLVMConstVector(&value, 1);
  1288. if (count == 1) {
  1289. return single;
  1290. }
  1291. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1292. return llvm_basic_const_shuffle(single, mask);
  1293. }
  1294. LLVMTypeRef single_type = LLVMVectorType(LLVMTypeOf(value), 1);
  1295. LLVMValueRef single = LLVMBuildBitCast(p->builder, value, single_type, "");
  1296. if (count == 1) {
  1297. return single;
  1298. }
  1299. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1300. return llvm_basic_shuffle(p, single, mask);
  1301. }
  1302. LLVMValueRef llvm_vector_shuffle_reduction(lbProcedure *p, LLVMValueRef value, LLVMOpcode op_code) {
  1303. LLVMTypeRef original_vector_type = LLVMTypeOf(value);
  1304. GB_ASSERT(LLVMGetTypeKind(original_vector_type) == LLVMVectorTypeKind);
  1305. unsigned len = LLVMGetVectorSize(original_vector_type);
  1306. LLVMValueRef v_zero32 = lb_const_int(p->module, t_u32, 0).value;
  1307. if (len == 1) {
  1308. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1309. }
  1310. GB_ASSERT((len & (len-1)) == 0);
  1311. for (unsigned i = len; i != 1; i >>= 1) {
  1312. unsigned mask_len = i/2;
  1313. LLVMValueRef lhs_mask = llvm_mask_iota(p->module, 0, mask_len);
  1314. LLVMValueRef rhs_mask = llvm_mask_iota(p->module, mask_len, mask_len);
  1315. GB_ASSERT(LLVMTypeOf(lhs_mask) == LLVMTypeOf(rhs_mask));
  1316. LLVMValueRef lhs = llvm_basic_shuffle(p, value, lhs_mask);
  1317. LLVMValueRef rhs = llvm_basic_shuffle(p, value, rhs_mask);
  1318. GB_ASSERT(LLVMTypeOf(lhs) == LLVMTypeOf(rhs));
  1319. value = LLVMBuildBinOp(p->builder, op_code, lhs, rhs, "");
  1320. }
  1321. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1322. }
  1323. LLVMValueRef llvm_vector_expand_to_power_of_two(lbProcedure *p, LLVMValueRef value) {
  1324. LLVMTypeRef vector_type = LLVMTypeOf(value);
  1325. unsigned len = LLVMGetVectorSize(vector_type);
  1326. if (len == 1) {
  1327. return value;
  1328. }
  1329. if ((len & (len-1)) == 0) {
  1330. return value;
  1331. }
  1332. unsigned expanded_len = cast(unsigned)next_pow2(cast(i64)len);
  1333. LLVMValueRef mask = llvm_mask_iota(p->module, 0, expanded_len);
  1334. return LLVMBuildShuffleVector(p->builder, value, LLVMConstNull(vector_type), mask, "");
  1335. }
  1336. LLVMValueRef llvm_vector_reduce_add(lbProcedure *p, LLVMValueRef value) {
  1337. LLVMTypeRef type = LLVMTypeOf(value);
  1338. GB_ASSERT(LLVMGetTypeKind(type) == LLVMVectorTypeKind);
  1339. LLVMTypeRef elem = LLVMGetElementType(type);
  1340. unsigned len = LLVMGetVectorSize(type);
  1341. if (len == 0) {
  1342. return LLVMConstNull(type);
  1343. }
  1344. char const *name = nullptr;
  1345. i32 value_offset = 0;
  1346. i32 value_count = 0;
  1347. switch (LLVMGetTypeKind(elem)) {
  1348. case LLVMHalfTypeKind:
  1349. case LLVMFloatTypeKind:
  1350. case LLVMDoubleTypeKind:
  1351. name = "llvm.vector.reduce.fadd";
  1352. value_offset = 0;
  1353. value_count = 2;
  1354. break;
  1355. case LLVMIntegerTypeKind:
  1356. name = "llvm.vector.reduce.add";
  1357. value_offset = 1;
  1358. value_count = 1;
  1359. break;
  1360. default:
  1361. GB_PANIC("invalid vector type %s", LLVMPrintTypeToString(type));
  1362. break;
  1363. }
  1364. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1365. if (id != 0 && false) {
  1366. LLVMTypeRef types[1] = {};
  1367. types[0] = type;
  1368. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1369. LLVMValueRef values[2] = {};
  1370. values[0] = LLVMConstNull(elem);
  1371. values[1] = value;
  1372. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values+value_offset, value_count, "");
  1373. return call;
  1374. }
  1375. // Manual reduce
  1376. #if 0
  1377. LLVMValueRef sum = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, 0).value, "");
  1378. for (unsigned i = 0; i < len; i++) {
  1379. LLVMValueRef val = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, i).value, "");
  1380. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1381. sum = LLVMBuildAdd(p->builder, sum, val, "");
  1382. } else {
  1383. sum = LLVMBuildFAdd(p->builder, sum, val, "");
  1384. }
  1385. }
  1386. return sum;
  1387. #else
  1388. LLVMOpcode op_code = LLVMFAdd;
  1389. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1390. op_code = LLVMAdd;
  1391. }
  1392. unsigned len_pow_2 = prev_pow2(len);
  1393. if (len_pow_2 == len) {
  1394. return llvm_vector_shuffle_reduction(p, value, op_code);
  1395. } else {
  1396. GB_ASSERT(len_pow_2 < len);
  1397. LLVMValueRef lower_mask = llvm_mask_iota(p->module, 0, len_pow_2);
  1398. LLVMValueRef upper_mask = llvm_mask_iota(p->module, len_pow_2, len-len_pow_2);
  1399. LLVMValueRef lower = llvm_basic_shuffle(p, value, lower_mask);
  1400. LLVMValueRef upper = llvm_basic_shuffle(p, value, upper_mask);
  1401. upper = llvm_vector_expand_to_power_of_two(p, upper);
  1402. LLVMValueRef lower_reduced = llvm_vector_shuffle_reduction(p, lower, op_code);
  1403. LLVMValueRef upper_reduced = llvm_vector_shuffle_reduction(p, upper, op_code);
  1404. GB_ASSERT(LLVMTypeOf(lower_reduced) == LLVMTypeOf(upper_reduced));
  1405. return LLVMBuildBinOp(p->builder, op_code, lower_reduced, upper_reduced, "");
  1406. }
  1407. #endif
  1408. }
  1409. LLVMValueRef llvm_vector_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1410. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1411. LLVMTypeRef elem = LLVMGetElementType(LLVMTypeOf(a));
  1412. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1413. return LLVMBuildAdd(p->builder, a, b, "");
  1414. }
  1415. return LLVMBuildFAdd(p->builder, a, b, "");
  1416. }
  1417. LLVMValueRef llvm_vector_mul(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1418. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1419. LLVMTypeRef elem = LLVMGetElementType(LLVMTypeOf(a));
  1420. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1421. return LLVMBuildMul(p->builder, a, b, "");
  1422. }
  1423. return LLVMBuildFMul(p->builder, a, b, "");
  1424. }
  1425. LLVMValueRef llvm_vector_dot(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1426. return llvm_vector_reduce_add(p, llvm_vector_mul(p, a, b));
  1427. }
  1428. LLVMValueRef llvm_vector_mul_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, LLVMValueRef c) {
  1429. lbModule *m = p->module;
  1430. LLVMTypeRef t = LLVMTypeOf(a);
  1431. GB_ASSERT(t == LLVMTypeOf(b));
  1432. GB_ASSERT(t == LLVMTypeOf(c));
  1433. GB_ASSERT(LLVMGetTypeKind(t) == LLVMVectorTypeKind);
  1434. LLVMTypeRef elem = LLVMGetElementType(t);
  1435. bool is_possible = false;
  1436. switch (LLVMGetTypeKind(elem)) {
  1437. case LLVMHalfTypeKind:
  1438. is_possible = true;
  1439. break;
  1440. case LLVMFloatTypeKind:
  1441. case LLVMDoubleTypeKind:
  1442. is_possible = true;
  1443. break;
  1444. }
  1445. if (is_possible) {
  1446. char const *name = "llvm.fmuladd";
  1447. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1448. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1449. LLVMTypeRef types[1] = {};
  1450. types[0] = t;
  1451. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types));
  1452. LLVMValueRef values[3] = {};
  1453. values[0] = a;
  1454. values[1] = b;
  1455. values[2] = c;
  1456. LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), "");
  1457. return call;
  1458. } else {
  1459. LLVMValueRef x = llvm_vector_mul(p, a, b);
  1460. LLVMValueRef y = llvm_vector_add(p, x, c);
  1461. return y;
  1462. }
  1463. }
  1464. 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) {
  1465. return LLVMGetInlineAsm(func_type,
  1466. cast(char *)str.text, cast(size_t)str.len,
  1467. cast(char *)clobbers.text, cast(size_t)clobbers.len,
  1468. /*HasSideEffects*/true, /*IsAlignStack*/false,
  1469. dialect
  1470. #if LLVM_VERSION_MAJOR >= 13
  1471. , /*CanThrow*/false
  1472. #endif
  1473. );
  1474. }
  1475. void lb_set_wasm_import_attributes(LLVMValueRef value, Entity *entity, String import_name) {
  1476. if (!is_arch_wasm()) {
  1477. return;
  1478. }
  1479. String module_name = str_lit("env");
  1480. if (entity->Procedure.foreign_library != nullptr) {
  1481. Entity *foreign_library = entity->Procedure.foreign_library;
  1482. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1483. GB_ASSERT(foreign_library->LibraryName.paths.count == 1);
  1484. module_name = foreign_library->LibraryName.paths[0];
  1485. if (string_starts_with(import_name, module_name)) {
  1486. import_name = substring(import_name, module_name.len+WASM_MODULE_NAME_SEPARATOR.len, import_name.len);
  1487. }
  1488. }
  1489. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-module", alloc_cstring(permanent_allocator(), module_name));
  1490. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-name", alloc_cstring(permanent_allocator(), import_name));
  1491. }
  1492. void lb_set_wasm_export_attributes(LLVMValueRef value, String export_name) {
  1493. if (!is_arch_wasm()) {
  1494. return;
  1495. }
  1496. LLVMSetLinkage(value, LLVMDLLExportLinkage);
  1497. LLVMSetDLLStorageClass(value, LLVMDLLExportStorageClass);
  1498. LLVMSetVisibility(value, LLVMDefaultVisibility);
  1499. LLVMAddTargetDependentFunctionAttr(value, "wasm-export-name", alloc_cstring(permanent_allocator(), export_name));
  1500. }
  1501. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name);
  1502. lbValue lb_handle_obj_id(lbProcedure *p, Ast *expr) {
  1503. TypeAndValue const &tav = type_and_value_of_expr(expr);
  1504. if (tav.mode == Addressing_Type) {
  1505. Type *type = tav.type;
  1506. GB_ASSERT_MSG(type->kind == Type_Named, "%s", type_to_string(type));
  1507. Entity *e = type->Named.type_name;
  1508. GB_ASSERT(e->kind == Entity_TypeName);
  1509. String name = e->TypeName.objc_class_name;
  1510. lbAddr *found = string_map_get(&p->module->objc_classes, name);
  1511. if (found) {
  1512. return lb_addr_load(p, *found);
  1513. } else {
  1514. lbModule *default_module = &p->module->gen->default_module;
  1515. Entity *e = nullptr;
  1516. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_Class, {}, &e);
  1517. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1518. lbAddr local_addr = lb_addr(ptr);
  1519. string_map_set(&default_module->objc_classes, name, default_addr);
  1520. if (default_module != p->module) {
  1521. string_map_set(&p->module->objc_classes, name, local_addr);
  1522. }
  1523. return lb_addr_load(p, local_addr);
  1524. }
  1525. }
  1526. return lb_build_expr(p, expr);
  1527. }
  1528. lbValue lb_handle_obj_selector(lbProcedure *p, String const &name) {
  1529. lbAddr *found = string_map_get(&p->module->objc_selectors, name);
  1530. if (found) {
  1531. return lb_addr_load(p, *found);
  1532. } else {
  1533. lbModule *default_module = &p->module->gen->default_module;
  1534. Entity *e = nullptr;
  1535. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_SEL, {}, &e);
  1536. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1537. lbAddr local_addr = lb_addr(ptr);
  1538. string_map_set(&default_module->objc_selectors, name, default_addr);
  1539. if (default_module != p->module) {
  1540. string_map_set(&p->module->objc_selectors, name, local_addr);
  1541. }
  1542. return lb_addr_load(p, local_addr);
  1543. }
  1544. }
  1545. lbValue lb_handle_obj_send(lbProcedure *p, Ast *expr) {
  1546. ast_node(ce, CallExpr, expr);
  1547. lbModule *m = p->module;
  1548. CheckerInfo *info = m->info;
  1549. ObjcMsgData data = map_must_get(&info->objc_msgSend_types, expr);
  1550. GB_ASSERT(data.proc_type != nullptr);
  1551. GB_ASSERT(ce->args.count >= 3);
  1552. auto args = array_make<lbValue>(permanent_allocator(), 0, ce->args.count-1);
  1553. lbValue id = lb_handle_obj_id(p, ce->args[1]);
  1554. Ast *sel_expr = ce->args[2];
  1555. GB_ASSERT(sel_expr->tav.value.kind == ExactValue_String);
  1556. lbValue sel = lb_handle_obj_selector(p, sel_expr->tav.value.value_string);
  1557. array_add(&args, id);
  1558. array_add(&args, sel);
  1559. for (isize i = 3; i < ce->args.count; i++) {
  1560. lbValue arg = lb_build_expr(p, ce->args[i]);
  1561. array_add(&args, arg);
  1562. }
  1563. lbValue the_proc = {};
  1564. switch (data.kind) {
  1565. default:
  1566. GB_PANIC("unhandled ObjcMsgKind %u", data.kind);
  1567. break;
  1568. case ObjcMsg_normal: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend")); break;
  1569. case ObjcMsg_fpret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fpret")); break;
  1570. case ObjcMsg_fp2ret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fp2ret")); break;
  1571. case ObjcMsg_stret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_stret")); break;
  1572. }
  1573. the_proc = lb_emit_conv(p, the_proc, data.proc_type);
  1574. return lb_emit_call(p, the_proc, args);
  1575. }