2 * mini-llvm.c: llvm "Backend" for the mono JIT
4 * Copyright 2009-2011 Novell Inc (http://www.novell.com)
5 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
9 #include <mono/metadata/debug-helpers.h>
10 #include <mono/metadata/debug-mono-symfile.h>
11 #include <mono/metadata/mempool-internals.h>
12 #include <mono/utils/mono-tls.h>
13 #include <mono/utils/mono-dl.h>
14 #include <mono/utils/mono-time.h>
15 #include <mono/utils/freebsd-dwarf.h>
17 #ifndef __STDC_LIMIT_MACROS
18 #define __STDC_LIMIT_MACROS
20 #ifndef __STDC_CONSTANT_MACROS
21 #define __STDC_CONSTANT_MACROS
24 #include "llvm-c/Core.h"
25 #include "llvm-c/ExecutionEngine.h"
26 #include "llvm-c/BitWriter.h"
27 #include "llvm-c/Analysis.h"
29 #include "mini-llvm-cpp.h"
34 extern void *memset(void *, int, size_t);
35 void bzero (void *to, size_t count) { memset (to, 0, count); }
40 * Information associated by mono with LLVM modules.
44 LLVMValueRef throw, rethrow, throw_corlib_exception;
45 GHashTable *llvm_types;
47 const char *got_symbol;
48 GHashTable *plt_entries;
49 GHashTable *plt_entries_ji;
50 GHashTable *method_to_lmethod;
55 GPtrArray *subprogram_mds;
57 LLVMExecutionEngineRef ee;
58 gboolean external_symbols;
64 * Information associated by the backend with mono basic blocks.
67 LLVMBasicBlockRef bblock, end_bblock;
68 LLVMValueRef finally_ind;
69 gboolean added, invoke_target;
71 * If this bblock is the start of a finally clause, this is a list of bblocks it
72 * needs to branch to in ENDFINALLY.
74 GSList *call_handler_return_bbs;
76 * If this bblock is the start of a finally clause, this is the bblock that
77 * CALL_HANDLER needs to branch to.
79 LLVMBasicBlockRef call_handler_target_bb;
80 /* The list of switch statements generated by ENDFINALLY instructions */
81 GSList *endfinally_switch_ins_list;
86 * Structure containing emit state
91 /* Maps method names to the corresponding LLVMValueRef */
92 GHashTable *emitted_method_decls;
96 MonoLLVMModule *lmodule;
99 int sindex, default_index, ex_index;
100 LLVMBuilderRef builder;
101 LLVMValueRef *values, *addresses;
102 MonoType **vreg_cli_types;
104 MonoMethodSignature *sig;
106 GHashTable *region_to_handler;
107 LLVMBuilderRef alloca_builder;
108 LLVMValueRef last_alloca;
109 LLVMValueRef rgctx_arg;
110 LLVMTypeRef *vreg_types;
112 gboolean *unreachable;
114 LLVMValueRef imt_rgctx_loc;
115 GHashTable *llvm_types;
117 MonoDebugMethodInfo *minfo;
124 MonoBasicBlock *in_bb;
129 * Instruction metadata
130 * This is the same as ins_info, but LREG != IREG.
138 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
139 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
146 /* keep in sync with the enum in mini.h */
149 #include "mini-ops.h"
154 #if SIZEOF_VOID_P == 4
155 #define GET_LONG_IMM(ins) (((guint64)(ins)->inst_ms_word << 32) | (guint64)(guint32)(ins)->inst_ls_word)
157 #define GET_LONG_IMM(ins) ((ins)->inst_imm)
160 #define LLVM_INS_INFO(opcode) (&llvm_ins_info [((opcode) - OP_START - 1) * 4])
163 #define TRACE_FAILURE(msg) do { printf ("%s\n", msg); } while (0)
165 #define TRACE_FAILURE(msg)
169 #define IS_TARGET_X86 1
171 #define IS_TARGET_X86 0
175 #define IS_TARGET_AMD64 1
177 #define IS_TARGET_AMD64 0
180 #define LLVM_FAILURE(ctx, reason) do { \
181 TRACE_FAILURE (reason); \
182 (ctx)->cfg->exception_message = g_strdup (reason); \
183 (ctx)->cfg->disable_llvm = TRUE; \
187 #define CHECK_FAILURE(ctx) do { \
188 if ((ctx)->cfg->disable_llvm) \
192 static LLVMIntPredicate cond_to_llvm_cond [] = {
205 static LLVMRealPredicate fpcond_to_llvm_cond [] = {
218 static MonoNativeTlsKey current_cfg_tls_id;
220 static MonoLLVMModule aot_module;
221 static int memset_param_count, memcpy_param_count;
222 static const char *memset_func_name;
223 static const char *memcpy_func_name;
225 static void init_jit_module (MonoDomain *domain);
227 static void emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code);
228 static LLVMValueRef emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name);
229 static void emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name);
234 * The LLVM type with width == sizeof (gpointer)
239 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
245 return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
251 return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
257 * Return the size of the LLVM representation of the vtype T.
260 get_vtype_size (MonoType *t)
264 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
266 while (size < 2 * sizeof (gpointer) && mono_is_power_of_two (size) == -1)
273 * simd_class_to_llvm_type:
275 * Return the LLVM type corresponding to the Mono.SIMD class KLASS
278 simd_class_to_llvm_type (EmitContext *ctx, MonoClass *klass)
280 if (!strcmp (klass->name, "Vector2d")) {
281 return LLVMVectorType (LLVMDoubleType (), 2);
282 } else if (!strcmp (klass->name, "Vector2l")) {
283 return LLVMVectorType (LLVMInt64Type (), 2);
284 } else if (!strcmp (klass->name, "Vector2ul")) {
285 return LLVMVectorType (LLVMInt64Type (), 2);
286 } else if (!strcmp (klass->name, "Vector4i")) {
287 return LLVMVectorType (LLVMInt32Type (), 4);
288 } else if (!strcmp (klass->name, "Vector4ui")) {
289 return LLVMVectorType (LLVMInt32Type (), 4);
290 } else if (!strcmp (klass->name, "Vector4f")) {
291 return LLVMVectorType (LLVMFloatType (), 4);
292 } else if (!strcmp (klass->name, "Vector8s")) {
293 return LLVMVectorType (LLVMInt16Type (), 8);
294 } else if (!strcmp (klass->name, "Vector8us")) {
295 return LLVMVectorType (LLVMInt16Type (), 8);
296 } else if (!strcmp (klass->name, "Vector16sb")) {
297 return LLVMVectorType (LLVMInt8Type (), 16);
298 } else if (!strcmp (klass->name, "Vector16b")) {
299 return LLVMVectorType (LLVMInt8Type (), 16);
301 printf ("%s\n", klass->name);
307 /* Return the 128 bit SIMD type corresponding to the mono type TYPE */
308 static inline G_GNUC_UNUSED LLVMTypeRef
309 type_to_simd_type (int type)
313 return LLVMVectorType (LLVMInt8Type (), 16);
315 return LLVMVectorType (LLVMInt16Type (), 8);
317 return LLVMVectorType (LLVMInt32Type (), 4);
319 return LLVMVectorType (LLVMInt64Type (), 2);
321 return LLVMVectorType (LLVMDoubleType (), 2);
323 return LLVMVectorType (LLVMFloatType (), 4);
325 g_assert_not_reached ();
333 * Return the LLVM type corresponding to T.
336 type_to_llvm_type (EmitContext *ctx, MonoType *t)
338 t = mini_replace_type (t);
341 return LLVMPointerType (LLVMInt8Type (), 0);
344 return LLVMVoidType ();
346 return LLVMInt8Type ();
348 return LLVMInt16Type ();
350 return LLVMInt32Type ();
352 return LLVMInt8Type ();
354 return LLVMInt16Type ();
356 return LLVMInt32Type ();
357 case MONO_TYPE_BOOLEAN:
358 return LLVMInt8Type ();
361 return LLVMInt64Type ();
363 return LLVMInt16Type ();
365 return LLVMFloatType ();
367 return LLVMDoubleType ();
370 return IntPtrType ();
371 case MONO_TYPE_OBJECT:
372 case MONO_TYPE_CLASS:
373 case MONO_TYPE_ARRAY:
374 case MONO_TYPE_SZARRAY:
375 case MONO_TYPE_STRING:
377 return ObjRefType ();
380 /* Because of generic sharing */
381 return ObjRefType ();
382 case MONO_TYPE_GENERICINST:
383 if (!mono_type_generic_inst_is_valuetype (t))
384 return ObjRefType ();
386 case MONO_TYPE_VALUETYPE:
387 case MONO_TYPE_TYPEDBYREF: {
391 klass = mono_class_from_mono_type (t);
393 if (MONO_CLASS_IS_SIMD (ctx->cfg, klass))
394 return simd_class_to_llvm_type (ctx, klass);
397 return type_to_llvm_type (ctx, mono_class_enum_basetype (klass));
399 ltype = g_hash_table_lookup (ctx->lmodule->llvm_types, klass);
402 LLVMTypeRef *eltypes;
405 size = get_vtype_size (t);
407 eltypes = g_new (LLVMTypeRef, size);
408 for (i = 0; i < size; ++i)
409 eltypes [i] = LLVMInt8Type ();
411 name = mono_type_full_name (&klass->byval_arg);
412 ltype = LLVMStructCreateNamed (LLVMGetGlobalContext (), name);
413 LLVMStructSetBody (ltype, eltypes, size, FALSE);
414 g_hash_table_insert (ctx->lmodule->llvm_types, klass, ltype);
422 printf ("X: %d\n", t->type);
423 ctx->cfg->exception_message = g_strdup_printf ("type %s", mono_type_full_name (t));
424 ctx->cfg->disable_llvm = TRUE;
432 * Return whenever T is an unsigned int type.
435 type_is_unsigned (EmitContext *ctx, MonoType *t)
452 * type_to_llvm_arg_type:
454 * Same as type_to_llvm_type, but treat i8/i16 as i32.
457 type_to_llvm_arg_type (EmitContext *ctx, MonoType *t)
459 LLVMTypeRef ptype = type_to_llvm_type (ctx, t);
462 * This works on all abis except arm64/ios which passes multiple
463 * arguments in one stack slot.
466 if (ptype == LLVMInt8Type () || ptype == LLVMInt16Type ()) {
468 * LLVM generates code which only sets the lower bits, while JITted
469 * code expects all the bits to be set.
471 ptype = LLVMInt32Type ();
479 * llvm_type_to_stack_type:
481 * Return the LLVM type which needs to be used when a value of type TYPE is pushed
484 static G_GNUC_UNUSED LLVMTypeRef
485 llvm_type_to_stack_type (LLVMTypeRef type)
489 if (type == LLVMInt8Type ())
490 return LLVMInt32Type ();
491 else if (type == LLVMInt16Type ())
492 return LLVMInt32Type ();
493 else if (type == LLVMFloatType ())
494 return LLVMDoubleType ();
500 * regtype_to_llvm_type:
502 * Return the LLVM type corresponding to the regtype C used in instruction
506 regtype_to_llvm_type (char c)
510 return LLVMInt32Type ();
512 return LLVMInt64Type ();
514 return LLVMDoubleType ();
523 * Return the LLVM type corresponding to the unary/binary opcode OPCODE.
526 op_to_llvm_type (int opcode)
531 return LLVMInt8Type ();
534 return LLVMInt8Type ();
537 return LLVMInt16Type ();
540 return LLVMInt16Type ();
543 return LLVMInt32Type ();
546 return LLVMInt32Type ();
548 return LLVMInt64Type ();
550 return LLVMFloatType ();
552 return LLVMDoubleType ();
554 return LLVMInt64Type ();
556 return LLVMInt32Type ();
558 return LLVMInt64Type ();
561 return LLVMInt8Type ();
564 return LLVMInt16Type ();
567 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
574 return LLVMInt32Type ();
581 return LLVMInt64Type ();
583 printf ("%s\n", mono_inst_name (opcode));
584 g_assert_not_reached ();
590 * load_store_to_llvm_type:
592 * Return the size/sign/zero extension corresponding to the load/store opcode
596 load_store_to_llvm_type (int opcode, int *size, gboolean *sext, gboolean *zext)
602 case OP_LOADI1_MEMBASE:
603 case OP_STOREI1_MEMBASE_REG:
604 case OP_STOREI1_MEMBASE_IMM:
605 case OP_ATOMIC_LOAD_I1:
606 case OP_ATOMIC_STORE_I1:
609 return LLVMInt8Type ();
610 case OP_LOADU1_MEMBASE:
612 case OP_ATOMIC_LOAD_U1:
613 case OP_ATOMIC_STORE_U1:
616 return LLVMInt8Type ();
617 case OP_LOADI2_MEMBASE:
618 case OP_STOREI2_MEMBASE_REG:
619 case OP_STOREI2_MEMBASE_IMM:
620 case OP_ATOMIC_LOAD_I2:
621 case OP_ATOMIC_STORE_I2:
624 return LLVMInt16Type ();
625 case OP_LOADU2_MEMBASE:
627 case OP_ATOMIC_LOAD_U2:
628 case OP_ATOMIC_STORE_U2:
631 return LLVMInt16Type ();
632 case OP_LOADI4_MEMBASE:
633 case OP_LOADU4_MEMBASE:
636 case OP_STOREI4_MEMBASE_REG:
637 case OP_STOREI4_MEMBASE_IMM:
638 case OP_ATOMIC_LOAD_I4:
639 case OP_ATOMIC_STORE_I4:
640 case OP_ATOMIC_LOAD_U4:
641 case OP_ATOMIC_STORE_U4:
643 return LLVMInt32Type ();
644 case OP_LOADI8_MEMBASE:
646 case OP_STOREI8_MEMBASE_REG:
647 case OP_STOREI8_MEMBASE_IMM:
648 case OP_ATOMIC_LOAD_I8:
649 case OP_ATOMIC_STORE_I8:
650 case OP_ATOMIC_LOAD_U8:
651 case OP_ATOMIC_STORE_U8:
653 return LLVMInt64Type ();
654 case OP_LOADR4_MEMBASE:
655 case OP_STORER4_MEMBASE_REG:
656 case OP_ATOMIC_LOAD_R4:
657 case OP_ATOMIC_STORE_R4:
659 return LLVMFloatType ();
660 case OP_LOADR8_MEMBASE:
661 case OP_STORER8_MEMBASE_REG:
662 case OP_ATOMIC_LOAD_R8:
663 case OP_ATOMIC_STORE_R8:
665 return LLVMDoubleType ();
666 case OP_LOAD_MEMBASE:
668 case OP_STORE_MEMBASE_REG:
669 case OP_STORE_MEMBASE_IMM:
670 *size = sizeof (gpointer);
671 return IntPtrType ();
673 g_assert_not_reached ();
681 * Return the LLVM intrinsics corresponding to the overflow opcode OPCODE.
684 ovf_op_to_intrins (int opcode)
688 return "llvm.sadd.with.overflow.i32";
690 return "llvm.uadd.with.overflow.i32";
692 return "llvm.ssub.with.overflow.i32";
694 return "llvm.usub.with.overflow.i32";
696 return "llvm.smul.with.overflow.i32";
698 return "llvm.umul.with.overflow.i32";
700 return "llvm.sadd.with.overflow.i64";
702 return "llvm.uadd.with.overflow.i64";
704 return "llvm.ssub.with.overflow.i64";
706 return "llvm.usub.with.overflow.i64";
708 return "llvm.smul.with.overflow.i64";
710 return "llvm.umul.with.overflow.i64";
712 g_assert_not_reached ();
718 simd_op_to_intrins (int opcode)
721 #if defined(TARGET_X86) || defined(TARGET_AMD64)
723 return "llvm.x86.sse2.min.pd";
725 return "llvm.x86.sse.min.ps";
727 return "llvm.x86.sse41.pminud";
729 return "llvm.x86.sse41.pminuw";
731 return "llvm.x86.sse2.pminu.b";
733 return "llvm.x86.sse2.pmins.w";
735 return "llvm.x86.sse2.max.pd";
737 return "llvm.x86.sse.max.ps";
739 return "llvm.x86.sse3.hadd.pd";
741 return "llvm.x86.sse3.hadd.ps";
743 return "llvm.x86.sse3.hsub.pd";
745 return "llvm.x86.sse3.hsub.ps";
747 return "llvm.x86.sse41.pmaxud";
749 return "llvm.x86.sse41.pmaxuw";
751 return "llvm.x86.sse2.pmaxu.b";
753 return "llvm.x86.sse3.addsub.ps";
755 return "llvm.x86.sse3.addsub.pd";
756 case OP_EXTRACT_MASK:
757 return "llvm.x86.sse2.pmovmskb.128";
760 return "llvm.x86.sse2.psrli.w";
763 return "llvm.x86.sse2.psrli.d";
766 return "llvm.x86.sse2.psrli.q";
769 return "llvm.x86.sse2.pslli.w";
772 return "llvm.x86.sse2.pslli.d";
775 return "llvm.x86.sse2.pslli.q";
778 return "llvm.x86.sse2.psrai.w";
781 return "llvm.x86.sse2.psrai.d";
783 return "llvm.x86.sse2.padds.b";
785 return "llvm.x86.sse2.padds.w";
787 return "llvm.x86.sse2.psubs.b";
789 return "llvm.x86.sse2.psubs.w";
790 case OP_PADDB_SAT_UN:
791 return "llvm.x86.sse2.paddus.b";
792 case OP_PADDW_SAT_UN:
793 return "llvm.x86.sse2.paddus.w";
794 case OP_PSUBB_SAT_UN:
795 return "llvm.x86.sse2.psubus.b";
796 case OP_PSUBW_SAT_UN:
797 return "llvm.x86.sse2.psubus.w";
799 return "llvm.x86.sse2.pavg.b";
801 return "llvm.x86.sse2.pavg.w";
803 return "llvm.x86.sse.sqrt.ps";
805 return "llvm.x86.sse2.sqrt.pd";
807 return "llvm.x86.sse.rsqrt.ps";
809 return "llvm.x86.sse.rcp.ps";
811 return "llvm.x86.sse2.cvtdq2pd";
813 return "llvm.x86.sse2.cvtdq2ps";
815 return "llvm.x86.sse2.cvtpd2dq";
817 return "llvm.x86.sse2.cvtps2dq";
819 return "llvm.x86.sse2.cvtpd2ps";
821 return "llvm.x86.sse2.cvtps2pd";
823 return "llvm.x86.sse2.cvttpd2dq";
825 return "llvm.x86.sse2.cvttps2dq";
827 return "llvm.x86.sse.cmp.ps";
829 return "llvm.x86.sse2.cmp.pd";
831 return "llvm.x86.sse2.packsswb.128";
833 return "llvm.x86.sse2.packssdw.128";
835 return "llvm.x86.sse2.packuswb.128";
837 return "llvm.x86.sse41.packusdw";
839 return "llvm.x86.sse2.pmulh.w";
840 case OP_PMULW_HIGH_UN:
841 return "llvm.x86.sse2.pmulhu.w";
844 g_assert_not_reached ();
850 simd_op_to_llvm_type (int opcode)
852 #if defined(TARGET_X86) || defined(TARGET_AMD64)
856 return type_to_simd_type (MONO_TYPE_R8);
859 return type_to_simd_type (MONO_TYPE_I8);
862 return type_to_simd_type (MONO_TYPE_I4);
867 return type_to_simd_type (MONO_TYPE_I2);
871 return type_to_simd_type (MONO_TYPE_I1);
873 return type_to_simd_type (MONO_TYPE_R4);
876 return type_to_simd_type (MONO_TYPE_I4);
880 return type_to_simd_type (MONO_TYPE_R8);
884 return type_to_simd_type (MONO_TYPE_R4);
885 case OP_EXTRACT_MASK:
886 return type_to_simd_type (MONO_TYPE_I1);
892 return type_to_simd_type (MONO_TYPE_R4);
895 return type_to_simd_type (MONO_TYPE_R8);
897 g_assert_not_reached ();
908 * Return the LLVM basic block corresponding to BB.
910 static LLVMBasicBlockRef
911 get_bb (EmitContext *ctx, MonoBasicBlock *bb)
913 char bb_name_buf [128];
916 if (ctx->bblocks [bb->block_num].bblock == NULL) {
917 if (bb->flags & BB_EXCEPTION_HANDLER) {
918 int clause_index = (mono_get_block_region_notry (ctx->cfg, bb->region) >> 8) - 1;
919 sprintf (bb_name_buf, "EH_CLAUSE%d_BB%d", clause_index, bb->block_num);
920 bb_name = bb_name_buf;
921 } else if (bb->block_num < 256) {
922 if (!ctx->lmodule->bb_names) {
923 ctx->lmodule->bb_names_len = 256;
924 ctx->lmodule->bb_names = g_new0 (char*, ctx->lmodule->bb_names_len);
926 if (!ctx->lmodule->bb_names [bb->block_num]) {
929 n = g_strdup_printf ("BB%d", bb->block_num);
930 mono_memory_barrier ();
931 ctx->lmodule->bb_names [bb->block_num] = n;
933 bb_name = ctx->lmodule->bb_names [bb->block_num];
935 sprintf (bb_name_buf, "BB%d", bb->block_num);
936 bb_name = bb_name_buf;
939 ctx->bblocks [bb->block_num].bblock = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
940 ctx->bblocks [bb->block_num].end_bblock = ctx->bblocks [bb->block_num].bblock;
943 return ctx->bblocks [bb->block_num].bblock;
949 * Return the last LLVM bblock corresponding to BB.
950 * This might not be equal to the bb returned by get_bb () since we need to generate
951 * multiple LLVM bblocks for a mono bblock to handle throwing exceptions.
953 static LLVMBasicBlockRef
954 get_end_bb (EmitContext *ctx, MonoBasicBlock *bb)
957 return ctx->bblocks [bb->block_num].end_bblock;
960 static LLVMBasicBlockRef
961 gen_bb (EmitContext *ctx, const char *prefix)
965 sprintf (bb_name, "%s%d", prefix, ++ ctx->ex_index);
966 return LLVMAppendBasicBlock (ctx->lmethod, bb_name);
972 * Return the target of the patch identified by TYPE and TARGET.
975 resolve_patch (MonoCompile *cfg, MonoJumpInfoType type, gconstpointer target)
979 memset (&ji, 0, sizeof (ji));
981 ji.data.target = target;
983 return mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
989 * Emit code to convert the LLVM value V to DTYPE.
992 convert_full (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype, gboolean is_unsigned)
994 LLVMTypeRef stype = LLVMTypeOf (v);
996 if (stype != dtype) {
997 gboolean ext = FALSE;
1000 if (dtype == LLVMInt64Type () && (stype == LLVMInt32Type () || stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
1002 else if (dtype == LLVMInt32Type () && (stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
1004 else if (dtype == LLVMInt16Type () && (stype == LLVMInt8Type ()))
1008 return is_unsigned ? LLVMBuildZExt (ctx->builder, v, dtype, "") : LLVMBuildSExt (ctx->builder, v, dtype, "");
1010 if (dtype == LLVMDoubleType () && stype == LLVMFloatType ())
1011 return LLVMBuildFPExt (ctx->builder, v, dtype, "");
1014 if (stype == LLVMInt64Type () && (dtype == LLVMInt32Type () || dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
1015 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1016 if (stype == LLVMInt32Type () && (dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
1017 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1018 if (stype == LLVMInt16Type () && dtype == LLVMInt8Type ())
1019 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1020 if (stype == LLVMDoubleType () && dtype == LLVMFloatType ())
1021 return LLVMBuildFPTrunc (ctx->builder, v, dtype, "");
1023 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind && LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
1024 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1025 if (LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
1026 return LLVMBuildIntToPtr (ctx->builder, v, dtype, "");
1027 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind)
1028 return LLVMBuildPtrToInt (ctx->builder, v, dtype, "");
1030 if (mono_arch_is_soft_float ()) {
1031 if (stype == LLVMInt32Type () && dtype == LLVMFloatType ())
1032 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1033 if (stype == LLVMInt32Type () && dtype == LLVMDoubleType ())
1034 return LLVMBuildBitCast (ctx->builder, LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), ""), dtype, "");
1037 if (LLVMGetTypeKind (stype) == LLVMVectorTypeKind && LLVMGetTypeKind (dtype) == LLVMVectorTypeKind)
1038 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1041 LLVMDumpValue (LLVMConstNull (dtype));
1042 g_assert_not_reached ();
1050 convert (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype)
1052 return convert_full (ctx, v, dtype, FALSE);
1056 * emit_volatile_load:
1058 * If vreg is volatile, emit a load from its address.
1061 emit_volatile_load (EmitContext *ctx, int vreg)
1065 LLVMValueRef v = LLVMBuildLoad (ctx->builder, ctx->addresses [vreg], "");
1066 t = ctx->vreg_cli_types [vreg];
1067 if (t && !t->byref) {
1069 * Might have to zero extend since llvm doesn't have
1072 if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_U2 || t->type == MONO_TYPE_CHAR || t->type == MONO_TYPE_BOOLEAN)
1073 v = LLVMBuildZExt (ctx->builder, v, LLVMInt32Type (), "");
1074 else if (t->type == MONO_TYPE_U8)
1075 v = LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), "");
1082 * emit_volatile_store:
1084 * If VREG is volatile, emit a store from its value to its address.
1087 emit_volatile_store (EmitContext *ctx, int vreg)
1089 MonoInst *var = get_vreg_to_inst (ctx->cfg, vreg);
1091 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
1092 g_assert (ctx->addresses [vreg]);
1093 LLVMBuildStore (ctx->builder, convert (ctx, ctx->values [vreg], type_to_llvm_type (ctx, var->inst_vtype)), ctx->addresses [vreg]);
1099 * Maps parameter indexes in the original signature to parameter indexes
1100 * in the LLVM signature.
1103 /* The indexes of various special arguments in the LLVM signature */
1104 int vret_arg_pindex, this_arg_pindex, rgctx_arg_pindex, imt_arg_pindex;
1108 * sig_to_llvm_sig_full:
1110 * Return the LLVM signature corresponding to the mono signature SIG using the
1111 * calling convention information in CINFO. Return parameter mapping information in SINFO.
1114 sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *cinfo,
1117 LLVMTypeRef ret_type;
1118 LLVMTypeRef *param_types = NULL;
1120 int i, j, pindex, vret_arg_pindex = 0;
1122 gboolean vretaddr = FALSE;
1126 memset (sinfo, 0, sizeof (LLVMSigInfo));
1128 rtype = mini_replace_type (sig->ret);
1129 ret_type = type_to_llvm_type (ctx, rtype);
1130 CHECK_FAILURE (ctx);
1132 if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
1133 /* LLVM models this by returning an aggregate value */
1134 if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgNone) {
1135 LLVMTypeRef members [2];
1137 members [0] = IntPtrType ();
1138 ret_type = LLVMStructType (members, 1, FALSE);
1140 g_assert_not_reached ();
1142 } else if (cinfo && cinfo->ret.storage == LLVMArgVtypeByVal) {
1143 /* Vtype returned normally by val */
1144 } else if (cinfo && mini_type_is_vtype (ctx->cfg, rtype)) {
1145 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1147 ret_type = LLVMVoidType ();
1150 pindexes = g_new0 (int, sig->param_count);
1151 param_types = g_new0 (LLVMTypeRef, (sig->param_count * 8) + 3);
1153 if (cinfo && cinfo->rgctx_arg) {
1155 sinfo->rgctx_arg_pindex = pindex;
1156 param_types [pindex] = ctx->lmodule->ptr_type;
1159 if (cinfo && cinfo->imt_arg) {
1161 sinfo->imt_arg_pindex = pindex;
1162 param_types [pindex] = ctx->lmodule->ptr_type;
1166 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1167 vret_arg_pindex = pindex;
1168 if (cinfo->vret_arg_index == 1) {
1169 /* Add the slots consumed by the first argument */
1170 LLVMArgInfo *ainfo = &cinfo->args [0];
1171 switch (ainfo->storage) {
1172 case LLVMArgVtypeInReg:
1173 for (j = 0; j < 2; ++j) {
1174 if (ainfo->pair_storage [j] == LLVMArgInIReg)
1184 sinfo->vret_arg_pindex = vret_arg_pindex;
1187 if (vretaddr && vret_arg_pindex == pindex)
1188 param_types [pindex ++] = IntPtrType ();
1191 sinfo->this_arg_pindex = pindex;
1192 param_types [pindex ++] = ThisType ();
1194 if (vretaddr && vret_arg_pindex == pindex)
1195 param_types [pindex ++] = IntPtrType ();
1196 for (i = 0; i < sig->param_count; ++i) {
1197 LLVMArgInfo *ainfo = cinfo ? &cinfo->args [i + sig->hasthis] : NULL;
1199 if (vretaddr && vret_arg_pindex == pindex)
1200 param_types [pindex ++] = IntPtrType ();
1201 pindexes [i] = pindex;
1202 if (ainfo && ainfo->storage == LLVMArgVtypeInReg) {
1203 for (j = 0; j < 2; ++j) {
1204 switch (ainfo->pair_storage [j]) {
1206 param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1211 g_assert_not_reached ();
1214 } else if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
1215 param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1216 CHECK_FAILURE (ctx);
1217 param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1219 } else if (ainfo && ainfo->storage == LLVMArgAsIArgs) {
1220 param_types [pindex] = LLVMArrayType (IntPtrType (), ainfo->nslots);
1222 } else if (ainfo && ainfo->storage == LLVMArgAsFpArgs) {
1225 for (j = 0; j < ainfo->nslots; ++j)
1226 param_types [pindex + j] = ainfo->esize == 8 ? LLVMDoubleType () : LLVMFloatType ();
1227 pindex += ainfo->nslots;
1229 param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1232 if (vretaddr && vret_arg_pindex == pindex)
1233 param_types [pindex ++] = IntPtrType ();
1235 CHECK_FAILURE (ctx);
1237 res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1238 g_free (param_types);
1241 sinfo->pindexes = pindexes;
1249 g_free (param_types);
1255 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1257 return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1261 * LLVMFunctionType1:
1263 * Create an LLVM function type from the arguments.
1265 static G_GNUC_UNUSED LLVMTypeRef
1266 LLVMFunctionType1(LLVMTypeRef ReturnType,
1267 LLVMTypeRef ParamType1,
1270 LLVMTypeRef param_types [1];
1272 param_types [0] = ParamType1;
1274 return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1278 * LLVMFunctionType2:
1280 * Create an LLVM function type from the arguments.
1282 static G_GNUC_UNUSED LLVMTypeRef
1283 LLVMFunctionType2(LLVMTypeRef ReturnType,
1284 LLVMTypeRef ParamType1,
1285 LLVMTypeRef ParamType2,
1288 LLVMTypeRef param_types [2];
1290 param_types [0] = ParamType1;
1291 param_types [1] = ParamType2;
1293 return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1297 * LLVMFunctionType3:
1299 * Create an LLVM function type from the arguments.
1301 static G_GNUC_UNUSED LLVMTypeRef
1302 LLVMFunctionType3(LLVMTypeRef ReturnType,
1303 LLVMTypeRef ParamType1,
1304 LLVMTypeRef ParamType2,
1305 LLVMTypeRef ParamType3,
1308 LLVMTypeRef param_types [3];
1310 param_types [0] = ParamType1;
1311 param_types [1] = ParamType2;
1312 param_types [2] = ParamType3;
1314 return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1320 * Create an LLVM builder and remember it so it can be freed later.
1322 static LLVMBuilderRef
1323 create_builder (EmitContext *ctx)
1325 LLVMBuilderRef builder = LLVMCreateBuilder ();
1327 ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1333 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1335 char *callee_name = mono_aot_get_plt_symbol (type, data);
1336 LLVMValueRef callee;
1337 MonoJumpInfo *ji = NULL;
1342 if (ctx->cfg->compile_aot)
1343 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1344 mono_add_patch_info (ctx->cfg, 0, type, data);
1347 callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1349 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1351 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1353 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1356 if (ctx->cfg->compile_aot) {
1357 ji = g_new0 (MonoJumpInfo, 1);
1359 ji->data.target = data;
1361 g_hash_table_insert (ctx->lmodule->plt_entries_ji, ji, callee);
1368 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1370 MonoMethodHeader *header = cfg->header;
1371 MonoExceptionClause *clause;
1375 if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1376 return (bb->region >> 8) - 1;
1379 for (i = 0; i < header->num_clauses; ++i) {
1380 clause = &header->clauses [i];
1382 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1390 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1392 LLVMValueRef md_arg;
1395 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1396 md_arg = LLVMMDString ("mono", 4);
1397 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1401 set_invariant_load_flag (LLVMValueRef v)
1403 LLVMValueRef md_arg;
1405 const char *flag_name;
1407 // FIXME: Cache this
1408 flag_name = "invariant.load";
1409 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1410 md_arg = LLVMMDString ("<index>", strlen ("<index>"));
1411 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1417 * Emit an LLVM call or invoke instruction depending on whenever the call is inside
1421 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1423 MonoCompile *cfg = ctx->cfg;
1425 LLVMBuilderRef builder = *builder_ref;
1428 clause_index = get_handler_clause (cfg, bb);
1430 if (clause_index != -1) {
1431 MonoMethodHeader *header = cfg->header;
1432 MonoExceptionClause *ec = &header->clauses [clause_index];
1433 MonoBasicBlock *tblock;
1434 LLVMBasicBlockRef ex_bb, noex_bb;
1437 * Have to use an invoke instead of a call, branching to the
1438 * handler bblock of the clause containing this bblock.
1441 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1443 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1446 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1448 ex_bb = get_bb (ctx, tblock);
1450 noex_bb = gen_bb (ctx, "NOEX_BB");
1453 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1455 builder = ctx->builder = create_builder (ctx);
1456 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1458 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1460 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1461 ctx->builder = builder;
1464 *builder_ref = ctx->builder;
1469 #if LLVM_API_VERSION >= 4
1470 #define EXTRA_MONO_LOAD_STORE_ARGS 1
1472 #define EXTRA_MONO_LOAD_STORE_ARGS 0
1476 emit_load_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting, BarrierKind barrier)
1478 const char *intrins_name;
1479 LLVMValueRef args [16], res;
1480 LLVMTypeRef addr_type;
1482 if (is_faulting && bb->region != -1) {
1483 #if LLVM_API_VERSION >= 4
1484 LLVMAtomicOrdering ordering;
1487 case LLVM_BARRIER_NONE:
1488 ordering = LLVMAtomicOrderingNotAtomic;
1490 case LLVM_BARRIER_ACQ:
1491 ordering = LLVMAtomicOrderingAcquire;
1493 case LLVM_BARRIER_SEQ:
1494 ordering = LLVMAtomicOrderingSequentiallyConsistent;
1497 g_assert_not_reached ();
1503 * We handle loads which can fault by calling a mono specific intrinsic
1504 * using an invoke, so they are handled properly inside try blocks.
1505 * We can't use this outside clauses, since LLVM optimizes intrinsics which
1506 * are marked with IntrReadArgMem.
1510 intrins_name = "llvm.mono.load.i8.p0i8";
1513 intrins_name = "llvm.mono.load.i16.p0i16";
1516 intrins_name = "llvm.mono.load.i32.p0i32";
1519 intrins_name = "llvm.mono.load.i64.p0i64";
1522 g_assert_not_reached ();
1525 addr_type = LLVMTypeOf (addr);
1526 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1527 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1530 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1531 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1532 #if LLVM_API_VERSION >= 4
1533 args [3] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1535 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 3 + EXTRA_MONO_LOAD_STORE_ARGS);
1537 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1538 res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1539 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1540 res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1547 * We emit volatile loads for loads which can fault, because otherwise
1548 * LLVM will generate invalid code when encountering a load from a
1551 res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting, barrier);
1553 /* Mark it with a custom metadata */
1556 set_metadata_flag (res, "mono.faulting.load");
1564 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1566 return emit_load_general (ctx, bb, builder_ref, size, addr, name, is_faulting, LLVM_BARRIER_NONE);
1570 emit_store_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting, BarrierKind barrier)
1572 const char *intrins_name;
1573 LLVMValueRef args [16];
1575 if (is_faulting && bb->region != -1) {
1576 #if LLVM_API_VERSION >= 4
1577 LLVMAtomicOrdering ordering;
1580 case LLVM_BARRIER_NONE:
1581 ordering = LLVMAtomicOrderingNotAtomic;
1583 case LLVM_BARRIER_REL:
1584 ordering = LLVMAtomicOrderingRelease;
1586 case LLVM_BARRIER_SEQ:
1587 ordering = LLVMAtomicOrderingSequentiallyConsistent;
1590 g_assert_not_reached ();
1597 intrins_name = "llvm.mono.store.i8.p0i8";
1600 intrins_name = "llvm.mono.store.i16.p0i16";
1603 intrins_name = "llvm.mono.store.i32.p0i32";
1606 intrins_name = "llvm.mono.store.i64.p0i64";
1609 g_assert_not_reached ();
1612 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1613 value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1614 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1619 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1620 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1621 #if LLVM_API_VERSION >= 4
1622 args [4] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1624 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4 + EXTRA_MONO_LOAD_STORE_ARGS);
1626 mono_llvm_build_store (*builder_ref, value, addr, is_faulting, barrier);
1631 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1633 emit_store_general (ctx, bb, builder_ref, size, value, addr, is_faulting, LLVM_BARRIER_NONE);
1637 * emit_cond_system_exception:
1639 * Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1640 * Might set the ctx exception.
1643 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1645 LLVMBasicBlockRef ex_bb, noex_bb;
1646 LLVMBuilderRef builder;
1647 MonoClass *exc_class;
1648 LLVMValueRef args [2];
1650 ex_bb = gen_bb (ctx, "EX_BB");
1651 noex_bb = gen_bb (ctx, "NOEX_BB");
1653 LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1655 exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1656 g_assert (exc_class);
1658 /* Emit exception throwing code */
1659 builder = create_builder (ctx);
1660 LLVMPositionBuilderAtEnd (builder, ex_bb);
1662 if (!ctx->lmodule->throw_corlib_exception) {
1663 LLVMValueRef callee;
1665 const char *icall_name;
1667 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1668 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1669 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1670 icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1671 /* This will become i8* */
1672 throw_sig->params [1] = &mono_get_byte_class ()->this_arg;
1673 sig = sig_to_llvm_sig (ctx, throw_sig);
1675 if (ctx->cfg->compile_aot) {
1676 callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1678 callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1681 * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1682 * - On x86, LLVM generated code doesn't push the arguments
1683 * - The trampoline takes the throw address as an arguments, not a pc offset.
1685 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1688 mono_memory_barrier ();
1689 ctx->lmodule->throw_corlib_exception = callee;
1692 if (IS_TARGET_X86 || IS_TARGET_AMD64)
1693 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1695 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1698 * The LLVM mono branch contains changes so a block address can be passed as an
1699 * argument to a call.
1701 args [1] = LLVMBlockAddress (ctx->lmethod, ex_bb);
1702 emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1704 LLVMBuildUnreachable (builder);
1706 ctx->builder = create_builder (ctx);
1707 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1709 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1716 * emit_args_to_vtype:
1718 * Emit code to store the vtype in the arguments args to the address ADDRESS.
1721 emit_args_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *args)
1723 int j, size, nslots;
1725 size = get_vtype_size (t);
1727 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1728 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1731 if (ainfo->storage == LLVMArgAsFpArgs)
1732 nslots = ainfo->nslots;
1736 for (j = 0; j < nslots; ++j) {
1737 LLVMValueRef index [2], addr;
1738 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1739 LLVMTypeRef part_type;
1741 if (ainfo->pair_storage [j] == LLVMArgNone)
1744 switch (ainfo->pair_storage [j]) {
1745 case LLVMArgInIReg: {
1746 part_type = LLVMIntType (part_size * 8);
1747 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1748 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1749 addr = LLVMBuildGEP (builder, address, index, 1, "");
1751 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1752 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1753 addr = LLVMBuildGEP (builder, address, index, 2, "");
1755 LLVMBuildStore (builder, convert (ctx, args [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1758 case LLVMArgInFPReg: {
1760 LLVMTypeRef arg_type;
1762 if (ainfo->esize == 8)
1763 arg_type = LLVMDoubleType ();
1765 arg_type = LLVMFloatType ();
1767 index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1768 daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (arg_type, 0), "");
1769 addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1770 LLVMBuildStore (builder, args [j], addr);
1776 g_assert_not_reached ();
1779 size -= sizeof (gpointer);
1784 * emit_vtype_to_args:
1786 * Emit code to load a vtype at address ADDRESS into scalar arguments. Store the arguments
1787 * into ARGS, and the number of arguments into NARGS.
1790 emit_vtype_to_args (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *args, guint32 *nargs)
1793 int j, size, nslots;
1794 LLVMTypeRef arg_type;
1796 size = get_vtype_size (t);
1798 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t)))
1799 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1801 if (ainfo->storage == LLVMArgAsFpArgs)
1802 nslots = ainfo->nslots;
1805 for (j = 0; j < nslots; ++j) {
1806 LLVMValueRef index [2], addr, daddr;
1807 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1809 if (ainfo->pair_storage [j] == LLVMArgNone)
1812 switch (ainfo->pair_storage [j]) {
1814 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1815 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1816 addr = LLVMBuildGEP (builder, address, index, 1, "");
1818 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1819 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1820 addr = LLVMBuildGEP (builder, address, index, 2, "");
1822 args [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1824 case LLVMArgInFPReg:
1825 if (ainfo->esize == 8)
1826 arg_type = LLVMDoubleType ();
1828 arg_type = LLVMFloatType ();
1829 daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (arg_type, 0), "");
1830 index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1831 addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1832 args [pindex ++] = LLVMBuildLoad (builder, addr, "");
1837 g_assert_not_reached ();
1839 size -= sizeof (gpointer);
1846 build_alloca_llvm_type (EmitContext *ctx, LLVMTypeRef t, int align)
1849 * Have to place all alloca's at the end of the entry bb, since otherwise they would
1850 * get executed every time control reaches them.
1852 LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1854 ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, t, NULL, align, "");
1855 return ctx->last_alloca;
1859 build_alloca (EmitContext *ctx, MonoType *t)
1861 MonoClass *k = mono_class_from_mono_type (t);
1864 if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1867 align = mono_class_min_align (k);
1869 /* Sometimes align is not a power of 2 */
1870 while (mono_is_power_of_two (align) == -1)
1873 return build_alloca_llvm_type (ctx, type_to_llvm_type (ctx, t), align);
1877 * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1880 mark_as_used (MonoLLVMModule *lmodule, LLVMValueRef global)
1883 lmodule->used = g_ptr_array_sized_new (16);
1884 g_ptr_array_add (lmodule->used, global);
1888 emit_llvm_used (MonoLLVMModule *lmodule)
1890 LLVMModuleRef module = lmodule->module;
1891 LLVMTypeRef used_type;
1892 LLVMValueRef used, *used_elem;
1898 used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), lmodule->used->len);
1899 used = LLVMAddGlobal (module, used_type, "llvm.used");
1900 used_elem = g_new0 (LLVMValueRef, lmodule->used->len);
1901 for (i = 0; i < lmodule->used->len; ++i)
1902 used_elem [i] = LLVMConstBitCast (g_ptr_array_index (lmodule->used, i), LLVMPointerType (LLVMInt8Type (), 0));
1903 LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), used_elem, lmodule->used->len));
1904 LLVMSetLinkage (used, LLVMAppendingLinkage);
1905 LLVMSetSection (used, "llvm.metadata");
1911 * Emit code to load/convert arguments.
1914 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
1917 MonoCompile *cfg = ctx->cfg;
1918 MonoMethodSignature *sig = ctx->sig;
1919 LLVMCallInfo *linfo = ctx->linfo;
1922 ctx->alloca_builder = create_builder (ctx);
1925 * Handle indirect/volatile variables by allocating memory for them
1926 * using 'alloca', and storing their address in a temporary.
1928 for (i = 0; i < cfg->num_varinfo; ++i) {
1929 MonoInst *var = cfg->varinfo [i];
1932 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || mini_type_is_vtype (cfg, var->inst_vtype)) {
1933 vtype = type_to_llvm_type (ctx, var->inst_vtype);
1934 CHECK_FAILURE (ctx);
1935 /* Could be already created by an OP_VPHI */
1936 if (!ctx->addresses [var->dreg])
1937 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
1938 ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
1942 for (i = 0; i < sig->param_count; ++i) {
1943 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
1944 int reg = cfg->args [i + sig->hasthis]->dreg;
1946 if (ainfo->storage == LLVMArgVtypeInReg || ainfo->storage == LLVMArgAsFpArgs) {
1947 LLVMValueRef args [8];
1950 /* The argument is received as a set of int/fp arguments, store them into the real argument */
1951 memset (args, 0, sizeof (args));
1952 pindex = ctx->pindexes [i];
1953 if (ainfo->storage == LLVMArgVtypeInReg) {
1954 args [0] = LLVMGetParam (ctx->lmethod, pindex);
1955 if (ainfo->pair_storage [1] != LLVMArgNone)
1956 args [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
1958 g_assert (ainfo->nslots <= 8);
1959 for (j = 0; j < ainfo->nslots; ++j)
1960 args [j] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i] + j);
1962 ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1964 emit_args_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, args);
1966 if (ainfo->storage == LLVMArgVtypeInReg && MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1967 /* Treat these as normal values */
1968 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1970 } else if (ainfo->storage == LLVMArgVtypeByVal) {
1971 ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1973 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1974 /* Treat these as normal values */
1975 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1977 } else if (ainfo->storage == LLVMArgAsIArgs) {
1978 LLVMValueRef arg = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1980 ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1982 /* The argument is received as an array of ints, store it into the real argument */
1983 LLVMBuildStore (ctx->builder, arg, convert (ctx, ctx->addresses [reg], LLVMPointerType (LLVMTypeOf (arg), 0)));
1985 ctx->values [reg] = convert_full (ctx, ctx->values [reg], llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->params [i])), type_is_unsigned (ctx, sig->params [i]));
1990 emit_volatile_store (ctx, cfg->vret_addr->dreg);
1992 emit_volatile_store (ctx, cfg->args [0]->dreg);
1993 for (i = 0; i < sig->param_count; ++i)
1994 if (!mini_type_is_vtype (cfg, sig->params [i]))
1995 emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
1997 if (sig->hasthis && !cfg->rgctx_var && cfg->generic_sharing_context) {
1998 LLVMValueRef this_alloc;
2001 * The exception handling code needs the location where the this argument was
2002 * stored for gshared methods. We create a separate alloca to hold it, and mark it
2003 * with the "mono.this" custom metadata to tell llvm that it needs to save its
2004 * location into the LSDA.
2006 this_alloc = mono_llvm_build_alloca (builder, ThisType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
2007 /* This volatile store will keep the alloca alive */
2008 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE, LLVM_BARRIER_NONE);
2010 set_metadata_flag (this_alloc, "mono.this");
2013 if (cfg->rgctx_var) {
2014 LLVMValueRef rgctx_alloc, store;
2017 * We handle the rgctx arg similarly to the this pointer.
2019 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
2020 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
2021 /* This volatile store will keep the alloca alive */
2022 store = mono_llvm_build_store (builder, convert (ctx, ctx->rgctx_arg, IntPtrType ()), rgctx_alloc, TRUE, LLVM_BARRIER_NONE);
2024 set_metadata_flag (rgctx_alloc, "mono.this");
2028 * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
2029 * it needs to continue normally, or return back to the exception handling system.
2031 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2032 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER))
2033 g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
2034 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER) && bb->in_scount == 0) {
2038 sprintf (name, "finally_ind_bb%d", bb->block_num);
2039 val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
2040 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
2042 ctx->bblocks [bb->block_num].finally_ind = val;
2045 * Create a new bblock which CALL_HANDLER can branch to, because branching to the
2046 * LLVM bblock containing the call to llvm.eh.selector causes problems for the
2047 * LLVM optimizer passes.
2049 sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
2050 ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
2058 /* Have to export this for AOT */
2060 mono_personality (void);
2063 mono_personality (void)
2066 g_assert_not_reached ();
2070 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
2072 MonoCompile *cfg = ctx->cfg;
2073 LLVMModuleRef module = ctx->module;
2074 LLVMValueRef *values = ctx->values;
2075 LLVMValueRef *addresses = ctx->addresses;
2076 MonoCallInst *call = (MonoCallInst*)ins;
2077 MonoMethodSignature *sig = call->signature;
2078 LLVMValueRef callee = NULL, lcall;
2080 LLVMCallInfo *cinfo;
2084 LLVMTypeRef llvm_sig;
2086 gboolean virtual, calli;
2087 LLVMBuilderRef builder = *builder_ref;
2090 if (call->signature->call_convention != MONO_CALL_DEFAULT)
2091 LLVM_FAILURE (ctx, "non-default callconv");
2093 cinfo = call->cinfo;
2094 if (call->rgctx_arg_reg)
2095 cinfo->rgctx_arg = TRUE;
2096 if (call->imt_arg_reg)
2097 cinfo->imt_arg = TRUE;
2099 vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
2101 llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
2102 CHECK_FAILURE (ctx);
2104 virtual = (ins->opcode == OP_VOIDCALL_MEMBASE || ins->opcode == OP_CALL_MEMBASE || ins->opcode == OP_VCALL_MEMBASE || ins->opcode == OP_LCALL_MEMBASE || ins->opcode == OP_FCALL_MEMBASE);
2105 calli = (ins->opcode == OP_VOIDCALL_REG || ins->opcode == OP_CALL_REG || ins->opcode == OP_VCALL_REG || ins->opcode == OP_LCALL_REG || ins->opcode == OP_FCALL_REG);
2107 /* FIXME: Avoid creating duplicate methods */
2109 if (ins->flags & MONO_INST_HAS_METHOD) {
2113 if (cfg->compile_aot) {
2114 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
2116 LLVM_FAILURE (ctx, "can't encode patch");
2118 callee = LLVMAddFunction (module, "", llvm_sig);
2121 mono_create_jit_trampoline_in_domain (mono_domain_get (),
2123 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2127 if (call->method && strstr (call->method->klass->name, "AsyncVoidMethodBuilder"))
2128 /* LLVM miscompiles async methods */
2129 LLVM_FAILURE (ctx, "#13734");
2132 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
2138 memset (&ji, 0, sizeof (ji));
2139 ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
2140 ji.data.target = info->name;
2142 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
2144 if (cfg->compile_aot) {
2145 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
2147 LLVM_FAILURE (ctx, "can't encode patch");
2149 callee = LLVMAddFunction (module, "", llvm_sig);
2150 target = (gpointer)mono_icall_get_wrapper (info);
2151 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2154 if (cfg->compile_aot) {
2156 if (cfg->abs_patches) {
2157 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2159 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
2161 LLVM_FAILURE (ctx, "can't encode patch");
2165 LLVM_FAILURE (ctx, "aot");
2167 callee = LLVMAddFunction (module, "", llvm_sig);
2169 if (cfg->abs_patches) {
2170 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2173 * FIXME: Some trampolines might have
2174 * their own calling convention on some platforms.
2176 #ifndef TARGET_AMD64
2177 if (abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER || abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER_V4 ||
2178 abs_ji->type == MONO_PATCH_INFO_MONITOR_EXIT || abs_ji->type == MONO_PATCH_INFO_GENERIC_CLASS_INIT)
2179 LLVM_FAILURE (ctx, "trampoline with own cconv");
2181 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
2182 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2186 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, (gpointer)call->fptr);
2192 int size = sizeof (gpointer);
2195 g_assert (ins->inst_offset % size == 0);
2196 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
2198 callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
2200 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
2202 if (ins->flags & MONO_INST_HAS_METHOD) {
2207 * Collect and convert arguments
2209 nargs = (sig->param_count * 2) + sig->hasthis + vretaddr + call->rgctx_reg + call->imt_arg_reg;
2210 len = sizeof (LLVMValueRef) * nargs;
2211 args = alloca (len);
2212 memset (args, 0, len);
2213 l = call->out_ireg_args;
2215 if (call->rgctx_arg_reg) {
2216 g_assert (values [call->rgctx_arg_reg]);
2217 g_assert (sinfo.rgctx_arg_pindex < nargs);
2219 * On ARM, the imt/rgctx argument is passed in a caller save register, but some of our trampolines etc. clobber it, leading to
2220 * problems is LLVM moves the arg assignment earlier. To work around this, save the argument into a stack slot and load
2221 * it using a volatile load.
2224 if (!ctx->imt_rgctx_loc)
2225 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2226 LLVMBuildStore (builder, convert (ctx, ctx->values [call->rgctx_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2227 args [sinfo.rgctx_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2229 args [sinfo.rgctx_arg_pindex] = convert (ctx, values [call->rgctx_arg_reg], ctx->lmodule->ptr_type);
2232 if (call->imt_arg_reg) {
2233 g_assert (values [call->imt_arg_reg]);
2234 g_assert (sinfo.imt_arg_pindex < nargs);
2236 if (!ctx->imt_rgctx_loc)
2237 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2238 LLVMBuildStore (builder, convert (ctx, ctx->values [call->imt_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2239 args [sinfo.imt_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2241 args [sinfo.imt_arg_pindex] = convert (ctx, values [call->imt_arg_reg], ctx->lmodule->ptr_type);
2246 if (!addresses [call->inst.dreg])
2247 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2248 g_assert (sinfo.vret_arg_pindex < nargs);
2249 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2252 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2255 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
2259 pindex = sinfo.this_arg_pindex;
2261 pindex = sinfo.pindexes [i - 1];
2263 pindex = sinfo.pindexes [i];
2266 regpair = (guint32)(gssize)(l->data);
2267 reg = regpair & 0xffffff;
2268 args [pindex] = values [reg];
2269 if (ainfo->storage == LLVMArgVtypeInReg || ainfo->storage == LLVMArgAsFpArgs) {
2272 g_assert (addresses [reg]);
2273 emit_vtype_to_args (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, args + pindex, &nargs);
2277 // FIXME: Get rid of the VMOVE
2278 } else if (ainfo->storage == LLVMArgVtypeByVal) {
2279 g_assert (addresses [reg]);
2280 args [pindex] = addresses [reg];
2281 } else if (ainfo->storage == LLVMArgAsIArgs) {
2282 g_assert (addresses [reg]);
2283 args [pindex] = LLVMBuildLoad (ctx->builder, convert (ctx, addresses [reg], LLVMPointerType (LLVMArrayType (IntPtrType (), ainfo->nslots), 0)), "");
2285 g_assert (args [pindex]);
2286 if (i == 0 && sig->hasthis)
2287 args [pindex] = convert (ctx, args [pindex], ThisType ());
2289 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2295 // FIXME: Align call sites
2301 lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2304 * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2306 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2307 g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2309 /* The two can't be used together, so use only one LLVM calling conv to pass them */
2310 g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2312 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2314 if (call->rgctx_arg_reg)
2315 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2316 if (call->imt_arg_reg)
2317 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2319 /* Add byval attributes if needed */
2320 for (i = 0; i < sig->param_count; ++i) {
2321 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2323 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2324 LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2329 * Convert the result
2331 if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
2332 LLVMValueRef regs [2];
2334 if (!addresses [ins->dreg])
2335 addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2337 regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2338 if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2339 regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2341 emit_args_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2342 } else if (cinfo && cinfo->ret.storage == LLVMArgVtypeByVal) {
2343 if (!addresses [call->inst.dreg])
2344 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2345 LLVMBuildStore (builder, lcall, addresses [call->inst.dreg]);
2346 } else if (sig->ret->type != MONO_TYPE_VOID && !vretaddr) {
2347 /* If the method returns an unsigned value, need to zext it */
2349 values [ins->dreg] = convert_full (ctx, lcall, llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->ret)), type_is_unsigned (ctx, sig->ret));
2353 if (!addresses [call->inst.dreg])
2354 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2355 g_assert (sinfo.vret_arg_pindex < nargs);
2356 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2359 *builder_ref = ctx->builder;
2361 g_free (sinfo.pindexes);
2369 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2371 MonoCompile *cfg = ctx->cfg;
2372 MonoMethodSignature *sig = ctx->sig;
2373 LLVMValueRef method = ctx->lmethod;
2374 LLVMValueRef *values = ctx->values;
2375 LLVMValueRef *addresses = ctx->addresses;
2376 LLVMCallInfo *linfo = ctx->linfo;
2377 LLVMModuleRef module = ctx->module;
2378 BBInfo *bblocks = ctx->bblocks;
2380 LLVMBasicBlockRef cbb;
2381 LLVMBuilderRef builder, starting_builder;
2382 gboolean has_terminator;
2384 LLVMValueRef lhs, rhs;
2387 cbb = get_bb (ctx, bb);
2388 builder = create_builder (ctx);
2389 ctx->builder = builder;
2390 LLVMPositionBuilderAtEnd (builder, cbb);
2392 if (bb == cfg->bb_entry)
2393 emit_entry_bb (ctx, builder);
2394 CHECK_FAILURE (ctx);
2396 if (bb->flags & BB_EXCEPTION_HANDLER) {
2398 LLVMValueRef personality;
2399 LLVMBasicBlockRef target_bb;
2401 static gint32 mapping_inited;
2402 static int ti_generator;
2405 LLVMValueRef type_info;
2408 if (!bblocks [bb->block_num].invoke_target) {
2410 * LLVM asserts if llvm.eh.selector is called from a bblock which
2411 * doesn't have an invoke pointing at it.
2412 * Update: LLVM no longer asserts, but some tests in exceptions.exe now fail.
2414 LLVM_FAILURE (ctx, "handler without invokes");
2417 // <resultval> = landingpad <somety> personality <type> <pers_fn> <clause>+
2419 if (cfg->compile_aot) {
2420 /* Use a dummy personality function */
2421 personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2422 g_assert (personality);
2424 personality = LLVMGetNamedFunction (module, "mono_personality");
2425 if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2426 LLVMAddGlobalMapping (ctx->lmodule->ee, personality, mono_personality);
2429 i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2431 clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2434 * Create the type info
2436 sprintf (ti_name, "type_info_%d", ti_generator);
2439 if (cfg->compile_aot) {
2440 /* decode_eh_frame () in aot-runtime.c will decode this */
2441 type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2442 LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2445 * These symbols are not really used, the clause_index is embedded into the EH tables generated by DwarfMonoException in LLVM.
2447 LLVMSetLinkage (type_info, LLVMInternalLinkage);
2450 * Enabling this causes llc to crash:
2451 * http://llvm.org/bugs/show_bug.cgi?id=6102
2453 //LLVM_FAILURE (ctx, "aot+clauses");
2455 // test_0_invalid_unbox_arrays () fails
2456 LLVM_FAILURE (ctx, "aot+clauses");
2460 * After the cfg mempool is freed, the type info will point to stale memory,
2461 * but this is not a problem, since we decode it once in exception_cb during
2464 ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2465 *(gint32*)ti = clause_index;
2467 type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2469 LLVMAddGlobalMapping (ctx->lmodule->ee, type_info, ti);
2473 LLVMTypeRef members [2], ret_type;
2474 LLVMValueRef landing_pad;
2476 members [0] = i8ptr;
2477 members [1] = LLVMInt32Type ();
2478 ret_type = LLVMStructType (members, 2, FALSE);
2480 landing_pad = LLVMBuildLandingPad (builder, ret_type, personality, 1, "");
2481 LLVMAddClause (landing_pad, type_info);
2483 /* Store the exception into the exvar */
2484 if (bb->in_scount == 1) {
2485 g_assert (bb->in_scount == 1);
2486 exvar = bb->in_stack [0];
2488 // FIXME: This is shared with filter clauses ?
2489 g_assert (!values [exvar->dreg]);
2491 values [exvar->dreg] = LLVMBuildExtractValue (builder, landing_pad, 0, "ex_obj");
2492 emit_volatile_store (ctx, exvar->dreg);
2496 /* Start a new bblock which CALL_HANDLER can branch to */
2497 target_bb = bblocks [bb->block_num].call_handler_target_bb;
2499 LLVMBuildBr (builder, target_bb);
2501 ctx->builder = builder = create_builder (ctx);
2502 LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2504 ctx->bblocks [bb->block_num].end_bblock = target_bb;
2508 has_terminator = FALSE;
2509 starting_builder = builder;
2510 for (ins = bb->code; ins; ins = ins->next) {
2511 const char *spec = LLVM_INS_INFO (ins->opcode);
2513 char dname_buf [128];
2515 emit_dbg_loc (ctx, builder, ins->cil_code);
2518 if (nins > 5000 && builder == starting_builder) {
2519 /* some steps in llc are non-linear in the size of basic blocks, see #5714 */
2520 LLVM_FAILURE (ctx, "basic block too long");
2524 /* There could be instructions after a terminator, skip them */
2527 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2528 sprintf (dname_buf, "t%d", ins->dreg);
2532 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2533 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2535 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2536 lhs = emit_volatile_load (ctx, ins->sreg1);
2538 /* It is ok for SETRET to have an uninitialized argument */
2539 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2540 LLVM_FAILURE (ctx, "sreg1");
2541 lhs = values [ins->sreg1];
2547 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2548 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2549 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2550 rhs = emit_volatile_load (ctx, ins->sreg2);
2552 if (!values [ins->sreg2])
2553 LLVM_FAILURE (ctx, "sreg2");
2554 rhs = values [ins->sreg2];
2560 //mono_print_ins (ins);
2561 switch (ins->opcode) {
2564 case OP_LIVERANGE_START:
2565 case OP_LIVERANGE_END:
2568 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2571 #if SIZEOF_VOID_P == 4
2572 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2574 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2578 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2581 values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2583 case OP_DUMMY_ICONST:
2584 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
2586 case OP_DUMMY_I8CONST:
2587 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
2589 case OP_DUMMY_R8CONST:
2590 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), 0.0f);
2593 LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2594 has_terminator = TRUE;
2600 LLVMBasicBlockRef new_bb;
2601 LLVMBuilderRef new_builder;
2603 // The default branch is already handled
2604 // FIXME: Handle it here
2606 /* Start new bblock */
2607 sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2608 new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2610 lhs = convert (ctx, lhs, LLVMInt32Type ());
2611 v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2612 for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2613 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2615 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2618 new_builder = create_builder (ctx);
2619 LLVMPositionBuilderAtEnd (new_builder, new_bb);
2620 LLVMBuildUnreachable (new_builder);
2622 has_terminator = TRUE;
2623 g_assert (!ins->next);
2629 if (linfo->ret.storage == LLVMArgVtypeInReg) {
2630 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2631 LLVMValueRef part1, retval;
2634 size = get_vtype_size (sig->ret);
2636 g_assert (addresses [ins->sreg1]);
2638 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2639 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2641 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2643 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2645 LLVMBuildRet (builder, retval);
2649 if (linfo->ret.storage == LLVMArgVtypeByVal) {
2650 LLVMValueRef retval;
2652 g_assert (addresses [ins->sreg1]);
2653 retval = LLVMBuildLoad (builder, addresses [ins->sreg1], "");
2654 LLVMBuildRet (builder, retval);
2658 if (linfo->ret.storage == LLVMArgVtypeRetAddr) {
2659 LLVMBuildRetVoid (builder);
2663 if (!lhs || ctx->is_dead [ins->sreg1]) {
2665 * The method did not set its return value, probably because it
2666 * ends with a throw.
2669 LLVMBuildRetVoid (builder);
2671 LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2673 LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2675 has_terminator = TRUE;
2681 case OP_ICOMPARE_IMM:
2682 case OP_LCOMPARE_IMM:
2683 case OP_COMPARE_IMM: {
2687 if (ins->next->opcode == OP_NOP)
2690 if (ins->next->opcode == OP_BR)
2691 /* The comparison result is not needed */
2694 rel = mono_opcode_to_cond (ins->next->opcode);
2696 if (ins->opcode == OP_ICOMPARE_IMM) {
2697 lhs = convert (ctx, lhs, LLVMInt32Type ());
2698 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2700 if (ins->opcode == OP_LCOMPARE_IMM) {
2701 lhs = convert (ctx, lhs, LLVMInt64Type ());
2702 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2704 if (ins->opcode == OP_LCOMPARE) {
2705 lhs = convert (ctx, lhs, LLVMInt64Type ());
2706 rhs = convert (ctx, rhs, LLVMInt64Type ());
2708 if (ins->opcode == OP_ICOMPARE) {
2709 lhs = convert (ctx, lhs, LLVMInt32Type ());
2710 rhs = convert (ctx, rhs, LLVMInt32Type ());
2714 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2715 rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
2716 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
2717 lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
2720 /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
2721 if (ins->opcode == OP_FCOMPARE)
2722 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2723 else if (ins->opcode == OP_COMPARE_IMM) {
2724 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && ins->inst_imm == 0)
2725 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, LLVMConstNull (LLVMTypeOf (lhs)), "");
2727 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
2728 } else if (ins->opcode == OP_LCOMPARE_IMM) {
2729 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg)) {
2730 /* The immediate is encoded in two fields */
2731 guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
2732 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
2734 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
2737 else if (ins->opcode == OP_COMPARE) {
2738 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && LLVMTypeOf (lhs) == LLVMTypeOf (rhs))
2739 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2741 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
2743 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2745 if (MONO_IS_COND_BRANCH_OP (ins->next)) {
2746 if (ins->next->inst_true_bb == ins->next->inst_false_bb) {
2748 * If the target bb contains PHI instructions, LLVM requires
2749 * two PHI entries for this bblock, while we only generate one.
2750 * So convert this to an unconditional bblock. (bxc #171).
2752 LLVMBuildBr (builder, get_bb (ctx, ins->next->inst_true_bb));
2754 LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
2756 has_terminator = TRUE;
2757 } else if (MONO_IS_SETCC (ins->next)) {
2758 sprintf (dname_buf, "t%d", ins->next->dreg);
2760 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2762 /* Add stores for volatile variables */
2763 emit_volatile_store (ctx, ins->next->dreg);
2764 } else if (MONO_IS_COND_EXC (ins->next)) {
2765 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
2766 CHECK_FAILURE (ctx);
2767 builder = ctx->builder;
2769 LLVM_FAILURE (ctx, "next");
2783 rel = mono_opcode_to_cond (ins->opcode);
2785 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2786 values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2794 gboolean empty = TRUE;
2796 /* Check that all input bblocks really branch to us */
2797 for (i = 0; i < bb->in_count; ++i) {
2798 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
2799 ins->inst_phi_args [i + 1] = -1;
2805 /* LLVM doesn't like phi instructions with zero operands */
2806 ctx->is_dead [ins->dreg] = TRUE;
2810 /* Created earlier, insert it now */
2811 LLVMInsertIntoBuilder (builder, values [ins->dreg]);
2813 for (i = 0; i < ins->inst_phi_args [0]; i++) {
2814 int sreg1 = ins->inst_phi_args [i + 1];
2818 * Count the number of times the incoming bblock branches to us,
2819 * since llvm requires a separate entry for each.
2821 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
2822 MonoInst *switch_ins = bb->in_bb [i]->last_ins;
2825 for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
2826 if (switch_ins->inst_many_bb [j] == bb)
2833 /* Remember for later */
2834 for (j = 0; j < count; ++j) {
2835 PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
2838 node->in_bb = bb->in_bb [i];
2840 bblocks [bb->in_bb [i]->block_num].phi_nodes = g_slist_prepend_mempool (ctx->mempool, bblocks [bb->in_bb [i]->block_num].phi_nodes, node);
2850 values [ins->dreg] = lhs;
2853 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
2856 values [ins->dreg] = lhs;
2858 if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
2860 * This is added by the spilling pass in case of the JIT,
2861 * but we have to do it ourselves.
2863 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
2867 case OP_MOVE_F_TO_I4: {
2868 values [ins->dreg] = LLVMBuildBitCast (builder, LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), ""), LLVMInt32Type (), "");
2871 case OP_MOVE_I4_TO_F: {
2872 values [ins->dreg] = LLVMBuildFPExt (builder, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType (), "");
2875 case OP_MOVE_F_TO_I8: {
2876 values [ins->dreg] = LLVMBuildBitCast (builder, lhs, LLVMInt64Type (), "");
2879 case OP_MOVE_I8_TO_F: {
2880 values [ins->dreg] = LLVMBuildBitCast (builder, lhs, LLVMDoubleType (), "");
2913 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2914 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2916 switch (ins->opcode) {
2919 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
2923 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
2927 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
2931 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
2935 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
2939 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
2943 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
2946 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
2950 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
2954 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
2958 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
2962 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
2966 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
2970 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
2974 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
2977 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
2980 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
2984 g_assert_not_reached ();
2991 case OP_IREM_UN_IMM:
2993 case OP_IDIV_UN_IMM:
2999 case OP_ISHR_UN_IMM:
3008 case OP_LSHR_UN_IMM:
3014 case OP_SHR_UN_IMM: {
3017 if (spec [MONO_INST_SRC1] == 'l') {
3018 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
3020 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3023 #if SIZEOF_VOID_P == 4
3024 if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
3025 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3028 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
3029 lhs = convert (ctx, lhs, IntPtrType ());
3030 imm = convert (ctx, imm, LLVMTypeOf (lhs));
3031 switch (ins->opcode) {
3035 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
3039 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
3043 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
3047 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
3049 case OP_IDIV_UN_IMM:
3050 case OP_LDIV_UN_IMM:
3051 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
3055 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
3057 case OP_IREM_UN_IMM:
3058 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
3063 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
3067 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
3071 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
3076 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
3081 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
3083 case OP_ISHR_UN_IMM:
3084 /* This is used to implement conv.u4, so the lhs could be an i8 */
3085 lhs = convert (ctx, lhs, LLVMInt32Type ());
3086 imm = convert (ctx, imm, LLVMInt32Type ());
3087 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3089 case OP_LSHR_UN_IMM:
3091 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3094 g_assert_not_reached ();
3099 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3102 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
3105 lhs = convert (ctx, lhs, LLVMDoubleType ());
3106 values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
3109 guint32 v = 0xffffffff;
3110 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3114 guint64 v = 0xffffffffffffffffLL;
3115 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
3118 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3120 LLVMValueRef v1, v2;
3122 v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
3123 v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
3124 values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
3129 case OP_ICONV_TO_I1:
3130 case OP_ICONV_TO_I2:
3131 case OP_ICONV_TO_I4:
3132 case OP_ICONV_TO_U1:
3133 case OP_ICONV_TO_U2:
3134 case OP_ICONV_TO_U4:
3135 case OP_LCONV_TO_I1:
3136 case OP_LCONV_TO_I2:
3137 case OP_LCONV_TO_U1:
3138 case OP_LCONV_TO_U2:
3139 case OP_LCONV_TO_U4: {
3142 sign = (ins->opcode == OP_ICONV_TO_I1) || (ins->opcode == OP_ICONV_TO_I2) || (ins->opcode == OP_ICONV_TO_I4) || (ins->opcode == OP_LCONV_TO_I1) || (ins->opcode == OP_LCONV_TO_I2);
3144 /* Have to do two casts since our vregs have type int */
3145 v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
3147 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
3149 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
3152 case OP_ICONV_TO_I8:
3153 values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
3155 case OP_ICONV_TO_U8:
3156 values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
3158 case OP_FCONV_TO_I4:
3159 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
3161 case OP_FCONV_TO_I1:
3162 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3164 case OP_FCONV_TO_U1:
3165 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3167 case OP_FCONV_TO_I2:
3168 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3170 case OP_FCONV_TO_U2:
3171 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3173 case OP_FCONV_TO_I8:
3174 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
3177 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
3179 case OP_ICONV_TO_R8:
3180 case OP_LCONV_TO_R8:
3181 values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
3183 case OP_LCONV_TO_R_UN:
3184 values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
3186 #if SIZEOF_VOID_P == 4
3189 case OP_LCONV_TO_I4:
3190 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3192 case OP_ICONV_TO_R4:
3193 case OP_LCONV_TO_R4:
3194 v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
3195 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3197 case OP_FCONV_TO_R4:
3198 v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
3199 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3202 values [ins->dreg] = LLVMBuildSExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3205 values [ins->dreg] = LLVMBuildZExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3208 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3210 case OP_LOCALLOC_IMM: {
3213 guint32 size = ins->inst_imm;
3214 size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3216 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
3218 if (ins->flags & MONO_INST_INIT) {
3219 LLVMValueRef args [5];
3222 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3223 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
3224 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3225 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3226 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3229 values [ins->dreg] = v;
3233 LLVMValueRef v, size;
3235 size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
3237 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
3239 if (ins->flags & MONO_INST_INIT) {
3240 LLVMValueRef args [5];
3243 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3245 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3246 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3247 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3249 values [ins->dreg] = v;
3253 case OP_LOADI1_MEMBASE:
3254 case OP_LOADU1_MEMBASE:
3255 case OP_LOADI2_MEMBASE:
3256 case OP_LOADU2_MEMBASE:
3257 case OP_LOADI4_MEMBASE:
3258 case OP_LOADU4_MEMBASE:
3259 case OP_LOADI8_MEMBASE:
3260 case OP_LOADR4_MEMBASE:
3261 case OP_LOADR8_MEMBASE:
3262 case OP_LOAD_MEMBASE:
3270 LLVMValueRef base, index, addr;
3272 gboolean sext = FALSE, zext = FALSE;
3273 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3275 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3280 if ((ins->opcode == OP_LOADI8_MEM) || (ins->opcode == OP_LOAD_MEM) || (ins->opcode == OP_LOADI4_MEM) || (ins->opcode == OP_LOADU4_MEM) || (ins->opcode == OP_LOADU1_MEM) || (ins->opcode == OP_LOADU2_MEM)) {
3281 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
3286 if (ins->inst_offset == 0) {
3288 } else if (ins->inst_offset % size != 0) {
3289 /* Unaligned load */
3290 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3291 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3293 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3294 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (t, 0)), &index, 1, "");
3298 addr = convert (ctx, addr, LLVMPointerType (t, 0));
3300 values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
3302 if (!is_volatile && (ins->flags & MONO_INST_INVARIANT_LOAD)) {
3304 * These will signal LLVM that these loads do not alias any stores, and
3305 * they can't fail, allowing them to be hoisted out of loops.
3307 set_invariant_load_flag (values [ins->dreg]);
3308 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
3312 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3314 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3315 else if (ins->opcode == OP_LOADR4_MEMBASE)
3316 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
3320 case OP_STOREI1_MEMBASE_REG:
3321 case OP_STOREI2_MEMBASE_REG:
3322 case OP_STOREI4_MEMBASE_REG:
3323 case OP_STOREI8_MEMBASE_REG:
3324 case OP_STORER4_MEMBASE_REG:
3325 case OP_STORER8_MEMBASE_REG:
3326 case OP_STORE_MEMBASE_REG: {
3328 LLVMValueRef index, addr;
3330 gboolean sext = FALSE, zext = FALSE;
3331 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3333 if (!values [ins->inst_destbasereg])
3334 LLVM_FAILURE (ctx, "inst_destbasereg");
3336 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3338 if (ins->inst_offset % size != 0) {
3339 /* Unaligned store */
3340 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3341 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3343 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3344 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3346 emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3350 case OP_STOREI1_MEMBASE_IMM:
3351 case OP_STOREI2_MEMBASE_IMM:
3352 case OP_STOREI4_MEMBASE_IMM:
3353 case OP_STOREI8_MEMBASE_IMM:
3354 case OP_STORE_MEMBASE_IMM: {
3356 LLVMValueRef index, addr;
3358 gboolean sext = FALSE, zext = FALSE;
3359 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3361 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3363 if (ins->inst_offset % size != 0) {
3364 /* Unaligned store */
3365 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3366 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3368 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3369 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3371 emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3376 emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, lhs, LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3378 case OP_OUTARG_VTRETADDR:
3385 case OP_VOIDCALL_MEMBASE:
3386 case OP_CALL_MEMBASE:
3387 case OP_LCALL_MEMBASE:
3388 case OP_FCALL_MEMBASE:
3389 case OP_VCALL_MEMBASE:
3390 case OP_VOIDCALL_REG:
3394 case OP_VCALL_REG: {
3395 process_call (ctx, bb, &builder, ins);
3396 CHECK_FAILURE (ctx);
3401 LLVMValueRef indexes [2];
3403 LLVMValueRef got_entry_addr;
3406 * FIXME: Can't allocate from the cfg mempool since that is freed if
3407 * the LLVM compile fails.
3409 ji = g_new0 (MonoJumpInfo, 1);
3410 ji->type = (MonoJumpInfoType)ins->inst_i1;
3411 ji->data.target = ins->inst_p0;
3413 ji = mono_aot_patch_info_dup (ji);
3415 ji->next = cfg->patch_info;
3416 cfg->patch_info = ji;
3418 //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3419 got_offset = mono_aot_get_got_offset (cfg->patch_info);
3420 ctx->lmodule->max_got_offset = MAX (ctx->lmodule->max_got_offset, got_offset);
3422 indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3423 indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3424 got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3426 values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3427 set_invariant_load_flag (values [ins->dreg]);
3430 case OP_NOT_REACHED:
3431 LLVMBuildUnreachable (builder);
3432 has_terminator = TRUE;
3433 g_assert (bb->block_num < cfg->max_block_num);
3434 ctx->unreachable [bb->block_num] = TRUE;
3435 /* Might have instructions after this */
3437 MonoInst *next = ins->next;
3439 * FIXME: If later code uses the regs defined by these instructions,
3440 * compilation will fail.
3442 MONO_DELETE_INS (bb, next);
3446 MonoInst *var = ins->inst_p0;
3448 values [ins->dreg] = addresses [var->dreg];
3452 LLVMValueRef args [1];
3454 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3455 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3459 LLVMValueRef args [1];
3461 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3462 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3466 LLVMValueRef args [1];
3469 /* This no longer seems to happen */
3471 * LLVM optimizes sqrt(nan) into undefined in
3472 * lib/Analysis/ConstantFolding.cpp
3473 * Also, sqrt(NegativeInfinity) is optimized into 0.
3475 LLVM_FAILURE (ctx, "sqrt");
3477 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3478 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3482 LLVMValueRef args [1];
3484 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3485 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3499 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3500 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3502 switch (ins->opcode) {
3505 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3509 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3513 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3517 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3520 g_assert_not_reached ();
3523 values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3526 case OP_ATOMIC_EXCHANGE_I4:
3527 case OP_ATOMIC_EXCHANGE_I8: {
3528 LLVMValueRef args [2];
3531 if (ins->opcode == OP_ATOMIC_EXCHANGE_I4)
3532 t = LLVMInt32Type ();
3534 t = LLVMInt64Type ();
3536 g_assert (ins->inst_offset == 0);
3538 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3539 args [1] = convert (ctx, rhs, t);
3541 values [ins->dreg] = mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_XCHG, args [0], args [1]);
3544 case OP_ATOMIC_ADD_I4:
3545 case OP_ATOMIC_ADD_I8: {
3546 LLVMValueRef args [2];
3549 if (ins->opcode == OP_ATOMIC_ADD_I4)
3550 t = LLVMInt32Type ();
3552 t = LLVMInt64Type ();
3554 g_assert (ins->inst_offset == 0);
3556 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3557 args [1] = convert (ctx, rhs, t);
3558 values [ins->dreg] = LLVMBuildAdd (builder, mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_ADD, args [0], args [1]), args [1], dname);
3561 case OP_ATOMIC_CAS_I4:
3562 case OP_ATOMIC_CAS_I8: {
3563 LLVMValueRef args [3], val;
3566 if (ins->opcode == OP_ATOMIC_CAS_I4)
3567 t = LLVMInt32Type ();
3569 t = LLVMInt64Type ();
3571 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3573 args [1] = convert (ctx, values [ins->sreg3], t);
3575 args [2] = convert (ctx, values [ins->sreg2], t);
3576 val = mono_llvm_build_cmpxchg (builder, args [0], args [1], args [2]);
3577 #if LLVM_API_VERSION >= 1
3578 /* cmpxchg returns a pair */
3579 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, "");
3581 values [ins->dreg] = val;
3585 case OP_MEMORY_BARRIER: {
3586 mono_llvm_build_fence (builder, (BarrierKind) ins->backend.memory_barrier_kind);
3589 case OP_ATOMIC_LOAD_I1:
3590 case OP_ATOMIC_LOAD_I2:
3591 case OP_ATOMIC_LOAD_I4:
3592 case OP_ATOMIC_LOAD_I8:
3593 case OP_ATOMIC_LOAD_U1:
3594 case OP_ATOMIC_LOAD_U2:
3595 case OP_ATOMIC_LOAD_U4:
3596 case OP_ATOMIC_LOAD_U8:
3597 case OP_ATOMIC_LOAD_R4:
3598 case OP_ATOMIC_LOAD_R8: {
3599 #if LLVM_API_VERSION >= 4
3601 gboolean sext, zext;
3603 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3604 BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
3605 LLVMValueRef index, addr;
3607 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3612 if (ins->inst_offset != 0) {
3613 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3614 addr = LLVMBuildGEP (builder, convert (ctx, lhs, LLVMPointerType (t, 0)), &index, 1, "");
3619 addr = convert (ctx, addr, LLVMPointerType (t, 0));
3621 values [ins->dreg] = emit_load_general (ctx, bb, &builder, size, addr, dname, is_volatile, barrier);
3624 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3626 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3628 LLVM_FAILURE (ctx, "atomic mono.load intrinsic");
3632 case OP_ATOMIC_STORE_I1:
3633 case OP_ATOMIC_STORE_I2:
3634 case OP_ATOMIC_STORE_I4:
3635 case OP_ATOMIC_STORE_I8:
3636 case OP_ATOMIC_STORE_U1:
3637 case OP_ATOMIC_STORE_U2:
3638 case OP_ATOMIC_STORE_U4:
3639 case OP_ATOMIC_STORE_U8:
3640 case OP_ATOMIC_STORE_R4:
3641 case OP_ATOMIC_STORE_R8: {
3642 #if LLVM_API_VERSION >= 4
3644 gboolean sext, zext;
3646 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3647 BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
3648 LLVMValueRef index, addr, value;
3650 if (!values [ins->inst_destbasereg])
3651 LLVM_FAILURE (ctx, "inst_destbasereg");
3653 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3655 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3656 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3657 value = convert (ctx, values [ins->sreg1], t);
3659 emit_store_general (ctx, bb, &builder, size, value, addr, is_volatile, barrier);
3662 LLVM_FAILURE (ctx, "atomic mono.store intrinsic");
3666 case OP_RELAXED_NOP: {
3667 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3668 emit_call (ctx, bb, &builder, LLVMGetNamedFunction (ctx->module, "llvm.x86.sse2.pause"), NULL, 0);
3675 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(__linux__)
3677 // 257 == FS segment register
3678 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
3680 // 256 == GS segment register
3681 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3684 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
3685 #elif defined(TARGET_AMD64) && defined(TARGET_OSX)
3686 /* See mono_amd64_emit_tls_get () */
3687 int offset = mono_amd64_get_tls_gs_offset () + (ins->inst_offset * 8);
3689 // 256 == GS segment register
3690 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3691 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), offset, TRUE), ptrtype, ""), "");
3693 LLVM_FAILURE (ctx, "opcode tls-get");
3698 case OP_TLS_GET_REG: {
3699 #if defined(TARGET_AMD64) && defined(TARGET_OSX)
3700 /* See emit_tls_get_reg () */
3701 // 256 == GS segment register
3702 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3703 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, convert (ctx, lhs, LLVMInt32Type ()), ptrtype, ""), "");
3705 LLVM_FAILURE (ctx, "opcode tls-get");
3714 case OP_IADD_OVF_UN:
3716 case OP_ISUB_OVF_UN:
3718 case OP_IMUL_OVF_UN:
3719 #if SIZEOF_VOID_P == 8
3721 case OP_LADD_OVF_UN:
3723 case OP_LSUB_OVF_UN:
3725 case OP_LMUL_OVF_UN:
3728 LLVMValueRef args [2], val, ovf, func;
3730 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
3731 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
3732 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
3734 val = LLVMBuildCall (builder, func, args, 2, "");
3735 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
3736 ovf = LLVMBuildExtractValue (builder, val, 1, "");
3737 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
3738 CHECK_FAILURE (ctx);
3739 builder = ctx->builder;
3745 * We currently model them using arrays. Promotion to local vregs is
3746 * disabled for them in mono_handle_global_vregs () in the LLVM case,
3747 * so we always have an entry in cfg->varinfo for them.
3748 * FIXME: Is this needed ?
3751 MonoClass *klass = ins->klass;
3752 LLVMValueRef args [5];
3756 LLVM_FAILURE (ctx, "!klass");
3760 if (!addresses [ins->dreg])
3761 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3762 args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3763 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3764 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3766 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3767 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3768 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3771 case OP_DUMMY_VZERO:
3774 case OP_STOREV_MEMBASE:
3775 case OP_LOADV_MEMBASE:
3777 MonoClass *klass = ins->klass;
3778 LLVMValueRef src = NULL, dst, args [5];
3779 gboolean done = FALSE;
3783 LLVM_FAILURE (ctx, "!klass");
3787 if (mini_is_gsharedvt_klass (cfg, klass)) {
3789 LLVM_FAILURE (ctx, "gsharedvt");
3793 switch (ins->opcode) {
3794 case OP_STOREV_MEMBASE:
3795 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg &&
3796 LLVMGetInstructionOpcode (values [ins->inst_destbasereg]) != LLVMAlloca) {
3797 /* Decomposed earlier */
3798 g_assert_not_reached ();
3801 if (!addresses [ins->sreg1]) {
3803 g_assert (values [ins->sreg1]);
3804 dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (type_to_llvm_type (ctx, &klass->byval_arg), 0));
3805 LLVMBuildStore (builder, values [ins->sreg1], dst);
3808 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3809 dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3812 case OP_LOADV_MEMBASE:
3813 if (!addresses [ins->dreg])
3814 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3815 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3816 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3819 if (!addresses [ins->sreg1])
3820 addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
3821 if (!addresses [ins->dreg])
3822 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3823 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3824 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3827 g_assert_not_reached ();
3829 CHECK_FAILURE (ctx);
3836 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3837 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3839 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3840 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3841 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
3844 case OP_LLVM_OUTARG_VT:
3845 if (!addresses [ins->sreg1]) {
3846 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
3847 g_assert (values [ins->sreg1]);
3848 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
3850 addresses [ins->dreg] = addresses [ins->sreg1];
3856 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3858 values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
3861 case OP_LOADX_MEMBASE: {
3862 LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
3865 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3866 values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
3869 case OP_STOREX_MEMBASE: {
3870 LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
3873 dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3874 mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
3881 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
3885 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
3891 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
3895 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
3899 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
3903 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
3906 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
3909 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
3912 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
3916 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, "");
3927 LLVMValueRef v = NULL;
3929 switch (ins->opcode) {
3934 t = LLVMVectorType (LLVMInt32Type (), 4);
3935 rt = LLVMVectorType (LLVMFloatType (), 4);
3941 t = LLVMVectorType (LLVMInt64Type (), 2);
3942 rt = LLVMVectorType (LLVMDoubleType (), 2);
3945 t = LLVMInt32Type ();
3946 rt = LLVMInt32Type ();
3947 g_assert_not_reached ();
3950 lhs = LLVMBuildBitCast (builder, lhs, t, "");
3951 rhs = LLVMBuildBitCast (builder, rhs, t, "");
3952 switch (ins->opcode) {
3955 v = LLVMBuildAnd (builder, lhs, rhs, "");
3959 v = LLVMBuildOr (builder, lhs, rhs, "");
3963 v = LLVMBuildXor (builder, lhs, rhs, "");
3967 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
3970 values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
3994 case OP_PADDB_SAT_UN:
3995 case OP_PADDW_SAT_UN:
3996 case OP_PSUBB_SAT_UN:
3997 case OP_PSUBW_SAT_UN:
4005 case OP_PMULW_HIGH_UN: {
4006 LLVMValueRef args [2];
4011 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4018 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntEQ, lhs, rhs, ""), LLVMTypeOf (lhs), "");
4022 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntSGT, lhs, rhs, ""), LLVMTypeOf (lhs), "");
4030 case OP_EXTRACTX_U2:
4032 case OP_EXTRACT_U1: {
4034 gboolean zext = FALSE;
4036 t = simd_op_to_llvm_type (ins->opcode);
4038 switch (ins->opcode) {
4046 case OP_EXTRACTX_U2:
4051 t = LLVMInt32Type ();
4052 g_assert_not_reached ();
4055 lhs = LLVMBuildBitCast (builder, lhs, t, "");
4056 values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
4058 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
4067 case OP_EXPAND_R8: {
4068 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4069 LLVMValueRef mask [16], v;
4072 for (i = 0; i < 16; ++i)
4073 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4075 v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
4077 values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4078 values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
4083 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt8Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4086 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt16Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4089 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4092 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt64Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4095 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMFloatType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4098 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMDoubleType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4109 case OP_EXTRACT_MASK:
4116 v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
4118 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
4122 case OP_ICONV_TO_R8_RAW:
4123 /* Same as OP_ICONV_TO_R8 */
4124 values [ins->dreg] = convert (ctx, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType ());
4129 LLVMValueRef args [3];
4133 args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
4135 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
4140 /* This is only used for implementing shifts by non-immediate */
4141 values [ins->dreg] = lhs;
4152 LLVMValueRef args [3];
4155 args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
4157 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4168 case OP_PSHLQ_REG: {
4169 LLVMValueRef args [3];
4172 args [1] = values [ins->sreg2];
4174 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4181 case OP_PSHUFLEW_LOW:
4182 case OP_PSHUFLEW_HIGH: {
4184 LLVMValueRef v1 = NULL, v2 = NULL, mask_values [16];
4185 int i, mask_size = 0;
4186 int imask = ins->inst_c0;
4188 /* Convert the x86 shuffle mask to LLVM's */
4189 switch (ins->opcode) {
4192 mask [0] = ((imask >> 0) & 3);
4193 mask [1] = ((imask >> 2) & 3);
4194 mask [2] = ((imask >> 4) & 3) + 4;
4195 mask [3] = ((imask >> 6) & 3) + 4;
4196 v1 = values [ins->sreg1];
4197 v2 = values [ins->sreg2];
4201 mask [0] = ((imask >> 0) & 1);
4202 mask [1] = ((imask >> 1) & 1) + 2;
4203 v1 = values [ins->sreg1];
4204 v2 = values [ins->sreg2];
4206 case OP_PSHUFLEW_LOW:
4208 mask [0] = ((imask >> 0) & 3);
4209 mask [1] = ((imask >> 2) & 3);
4210 mask [2] = ((imask >> 4) & 3);
4211 mask [3] = ((imask >> 6) & 3);
4216 v1 = values [ins->sreg1];
4217 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4219 case OP_PSHUFLEW_HIGH:
4225 mask [4] = 4 + ((imask >> 0) & 3);
4226 mask [5] = 4 + ((imask >> 2) & 3);
4227 mask [6] = 4 + ((imask >> 4) & 3);
4228 mask [7] = 4 + ((imask >> 6) & 3);
4229 v1 = values [ins->sreg1];
4230 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4234 mask [0] = ((imask >> 0) & 3);
4235 mask [1] = ((imask >> 2) & 3);
4236 mask [2] = ((imask >> 4) & 3);
4237 mask [3] = ((imask >> 6) & 3);
4238 v1 = values [ins->sreg1];
4239 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4242 g_assert_not_reached ();
4244 for (i = 0; i < mask_size; ++i)
4245 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4247 values [ins->dreg] =
4248 LLVMBuildShuffleVector (builder, v1, v2,
4249 LLVMConstVector (mask_values, mask_size), dname);
4253 case OP_UNPACK_LOWB:
4254 case OP_UNPACK_LOWW:
4255 case OP_UNPACK_LOWD:
4256 case OP_UNPACK_LOWQ:
4257 case OP_UNPACK_LOWPS:
4258 case OP_UNPACK_LOWPD:
4259 case OP_UNPACK_HIGHB:
4260 case OP_UNPACK_HIGHW:
4261 case OP_UNPACK_HIGHD:
4262 case OP_UNPACK_HIGHQ:
4263 case OP_UNPACK_HIGHPS:
4264 case OP_UNPACK_HIGHPD: {
4266 LLVMValueRef mask_values [16];
4267 int i, mask_size = 0;
4268 gboolean low = FALSE;
4270 switch (ins->opcode) {
4271 case OP_UNPACK_LOWB:
4275 case OP_UNPACK_LOWW:
4279 case OP_UNPACK_LOWD:
4280 case OP_UNPACK_LOWPS:
4284 case OP_UNPACK_LOWQ:
4285 case OP_UNPACK_LOWPD:
4289 case OP_UNPACK_HIGHB:
4292 case OP_UNPACK_HIGHW:
4295 case OP_UNPACK_HIGHD:
4296 case OP_UNPACK_HIGHPS:
4299 case OP_UNPACK_HIGHQ:
4300 case OP_UNPACK_HIGHPD:
4304 g_assert_not_reached ();
4308 for (i = 0; i < (mask_size / 2); ++i) {
4310 mask [(i * 2) + 1] = mask_size + i;
4313 for (i = 0; i < (mask_size / 2); ++i) {
4314 mask [(i * 2)] = (mask_size / 2) + i;
4315 mask [(i * 2) + 1] = mask_size + (mask_size / 2) + i;
4319 for (i = 0; i < mask_size; ++i)
4320 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4322 values [ins->dreg] =
4323 LLVMBuildShuffleVector (builder, values [ins->sreg1], values [ins->sreg2],
4324 LLVMConstVector (mask_values, mask_size), dname);
4329 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4330 LLVMValueRef v, val;
4332 v = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4333 val = LLVMConstNull (t);
4334 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4335 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 1, FALSE), dname);
4337 values [ins->dreg] = val;
4341 case OP_DUPPS_HIGH: {
4342 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4343 LLVMValueRef v1, v2, val;
4346 if (ins->opcode == OP_DUPPS_LOW) {
4347 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4348 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4350 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4351 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4353 val = LLVMConstNull (t);
4354 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4355 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4356 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4357 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4359 values [ins->dreg] = val;
4369 * EXCEPTION HANDLING
4371 case OP_IMPLICIT_EXCEPTION:
4372 /* This marks a place where an implicit exception can happen */
4373 if (bb->region != -1)
4374 LLVM_FAILURE (ctx, "implicit-exception");
4378 MonoMethodSignature *throw_sig;
4379 LLVMValueRef callee, arg;
4380 gboolean rethrow = (ins->opcode == OP_RETHROW);
4381 const char *icall_name;
4383 callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
4384 icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
4387 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
4388 throw_sig->ret = &mono_get_void_class ()->byval_arg;
4389 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
4390 if (cfg->compile_aot) {
4391 callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
4393 callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
4397 * LLVM doesn't push the exception argument, so we need a different
4400 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
4402 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
4406 mono_memory_barrier ();
4408 ctx->lmodule->rethrow = callee;
4410 ctx->lmodule->throw = callee;
4412 arg = convert (ctx, lhs, type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
4413 emit_call (ctx, bb, &builder, callee, &arg, 1);
4416 case OP_CALL_HANDLER: {
4418 * We don't 'call' handlers, but instead simply branch to them.
4419 * The code generated by ENDFINALLY will branch back to us.
4421 LLVMBasicBlockRef noex_bb;
4423 BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
4425 bb_list = info->call_handler_return_bbs;
4428 * Set the indicator variable for the finally clause.
4430 lhs = info->finally_ind;
4432 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
4434 /* Branch to the finally clause */
4435 LLVMBuildBr (builder, info->call_handler_target_bb);
4437 noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
4438 info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
4440 builder = ctx->builder = create_builder (ctx);
4441 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
4443 bblocks [bb->block_num].end_bblock = noex_bb;
4446 case OP_START_HANDLER: {
4449 case OP_ENDFINALLY: {
4450 LLVMBasicBlockRef resume_bb;
4451 MonoBasicBlock *handler_bb;
4452 LLVMValueRef val, switch_ins, callee;
4456 handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
4457 g_assert (handler_bb);
4458 info = &bblocks [handler_bb->block_num];
4459 lhs = info->finally_ind;
4462 bb_list = info->call_handler_return_bbs;
4464 resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
4466 /* Load the finally variable */
4467 val = LLVMBuildLoad (builder, lhs, "");
4469 /* Reset the variable */
4470 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
4472 /* Branch to either resume_bb, or to the bblocks in bb_list */
4473 switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
4475 * The other targets are added at the end to handle OP_CALL_HANDLER
4476 * opcodes processed later.
4478 info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
4480 builder = ctx->builder = create_builder (ctx);
4481 LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
4483 if (ctx->cfg->compile_aot) {
4484 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
4486 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
4488 LLVMBuildCall (builder, callee, NULL, 0, "");
4490 LLVMBuildUnreachable (builder);
4491 has_terminator = TRUE;
4497 sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
4498 LLVM_FAILURE (ctx, reason);
4503 /* Convert the value to the type required by phi nodes */
4504 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
4505 if (!values [ins->dreg])
4507 values [ins->dreg] = addresses [ins->dreg];
4509 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
4512 /* Add stores for volatile variables */
4513 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
4514 emit_volatile_store (ctx, ins->dreg);
4517 if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
4518 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
4520 if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID) {
4521 emit_dbg_loc (ctx, builder, cfg->header->code + cfg->header->code_size - 1);
4522 LLVMBuildRetVoid (builder);
4525 if (bb == cfg->bb_entry)
4526 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
4535 * mono_llvm_check_method_supported:
4537 * Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
4538 * compiling a method twice.
4541 mono_llvm_check_method_supported (MonoCompile *cfg)
4543 MonoMethodHeader *header = cfg->header;
4544 MonoExceptionClause *clause;
4547 if (cfg->method->save_lmf) {
4548 cfg->exception_message = g_strdup ("lmf");
4549 cfg->disable_llvm = TRUE;
4551 if (cfg->disable_llvm)
4555 for (i = 0; i < header->num_clauses; ++i) {
4556 clause = &header->clauses [i];
4558 if (i > 0 && clause->try_offset <= header->clauses [i - 1].handler_offset + header->clauses [i - 1].handler_len) {
4560 * FIXME: Some tests still fail with nested clauses.
4562 cfg->exception_message = g_strdup ("nested clauses");
4563 cfg->disable_llvm = TRUE;
4567 if (cfg->disable_llvm)
4572 if (cfg->method->dynamic) {
4573 cfg->exception_message = g_strdup ("dynamic.");
4574 cfg->disable_llvm = TRUE;
4576 if (cfg->disable_llvm)
4581 * mono_llvm_emit_method:
4583 * Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
4586 mono_llvm_emit_method (MonoCompile *cfg)
4589 MonoMethodSignature *sig;
4591 LLVMTypeRef method_type;
4592 LLVMValueRef method = NULL;
4594 LLVMValueRef *values;
4595 int i, max_block_num, bb_index;
4596 gboolean last = FALSE;
4597 GPtrArray *phi_values;
4598 LLVMCallInfo *linfo;
4600 LLVMModuleRef module;
4602 GPtrArray *bblock_list;
4603 MonoMethodHeader *header;
4604 MonoExceptionClause *clause;
4608 /* The code below might acquire the loader lock, so use it for global locking */
4609 mono_loader_lock ();
4611 /* Used to communicate with the callbacks */
4612 mono_native_tls_set_value (current_cfg_tls_id, cfg);
4614 ctx = g_new0 (EmitContext, 1);
4616 ctx->mempool = cfg->mempool;
4619 * This maps vregs to the LLVM instruction defining them
4621 values = g_new0 (LLVMValueRef, cfg->next_vreg);
4623 * This maps vregs for volatile variables to the LLVM instruction defining their
4626 ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
4627 ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
4628 ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
4629 phi_values = g_ptr_array_sized_new (256);
4631 * This signals whenever the vreg was defined by a phi node with no input vars
4632 * (i.e. all its input bblocks end with NOT_REACHABLE).
4634 ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
4635 /* Whenever the bblock is unreachable */
4636 ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
4638 bblock_list = g_ptr_array_sized_new (256);
4640 ctx->values = values;
4641 ctx->region_to_handler = g_hash_table_new (NULL, NULL);
4643 if (cfg->compile_aot) {
4644 ctx->lmodule = &aot_module;
4645 method_name = mono_aot_get_method_name (cfg);
4646 cfg->llvm_method_name = g_strdup (method_name);
4648 init_jit_module (cfg->domain);
4649 ctx->lmodule = domain_jit_info (cfg->domain)->llvm_module;
4650 method_name = mono_method_full_name (cfg->method, TRUE);
4653 module = ctx->module = ctx->lmodule->module;
4656 LLVM_FAILURE (ctx, "gsharedvt");
4660 static int count = 0;
4663 if (g_getenv ("LLVM_COUNT")) {
4664 if (count == atoi (g_getenv ("LLVM_COUNT"))) {
4665 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4669 if (count > atoi (g_getenv ("LLVM_COUNT")))
4670 LLVM_FAILURE (ctx, "");
4675 sig = mono_method_signature (cfg->method);
4678 linfo = mono_arch_get_llvm_call_info (cfg, sig);
4680 CHECK_FAILURE (ctx);
4683 linfo->rgctx_arg = TRUE;
4684 method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
4685 CHECK_FAILURE (ctx);
4688 * This maps parameter indexes in the original signature to the indexes in
4689 * the LLVM signature.
4691 ctx->pindexes = sinfo.pindexes;
4693 method = LLVMAddFunction (module, method_name, method_type);
4694 ctx->lmethod = method;
4696 LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
4697 LLVMSetLinkage (method, LLVMPrivateLinkage);
4699 LLVMAddFunctionAttr (method, LLVMUWTable);
4701 if (cfg->compile_aot) {
4702 LLVMSetLinkage (method, LLVMInternalLinkage);
4703 #if LLVM_API_VERSION == 0
4704 /* This causes an assertion in later LLVM versions */
4705 LLVMSetVisibility (method, LLVMHiddenVisibility);
4707 if (ctx->lmodule->external_symbols) {
4708 LLVMSetLinkage (method, LLVMExternalLinkage);
4709 LLVMSetVisibility (method, LLVMHiddenVisibility);
4712 LLVMSetLinkage (method, LLVMPrivateLinkage);
4715 if (cfg->method->save_lmf)
4716 LLVM_FAILURE (ctx, "lmf");
4718 if (sig->pinvoke && cfg->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
4719 LLVM_FAILURE (ctx, "pinvoke signature");
4721 header = cfg->header;
4722 for (i = 0; i < header->num_clauses; ++i) {
4723 clause = &header->clauses [i];
4724 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
4725 LLVM_FAILURE (ctx, "non-finally/catch clause.");
4728 if (linfo->rgctx_arg) {
4729 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
4731 * We mark the rgctx parameter with the inreg attribute, which is mapped to
4732 * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
4733 * CC_X86_64_Mono in X86CallingConv.td.
4735 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
4736 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
4738 if (cfg->vret_addr) {
4739 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
4740 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
4743 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
4744 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
4747 names = g_new (char *, sig->param_count);
4748 mono_method_get_param_names (cfg->method, (const char **) names);
4750 for (i = 0; i < sig->param_count; ++i) {
4753 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
4754 if (names [i] && names [i][0] != '\0')
4755 name = g_strdup_printf ("arg_%s", names [i]);
4757 name = g_strdup_printf ("arg_%d", i);
4758 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
4760 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
4761 LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
4765 if (ctx->lmodule->emit_dwarf && cfg->compile_aot && mono_debug_enabled ()) {
4766 ctx->minfo = mono_debug_lookup_method (cfg->method);
4767 ctx->dbg_md = emit_dbg_subprogram (ctx, cfg, method, method_name);
4771 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4772 max_block_num = MAX (max_block_num, bb->block_num);
4773 ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
4775 /* Add branches between non-consecutive bblocks */
4776 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4777 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4778 bb->next_bb != bb->last_ins->inst_false_bb) {
4780 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4781 inst->opcode = OP_BR;
4782 inst->inst_target_bb = bb->last_ins->inst_false_bb;
4783 mono_bblock_add_inst (bb, inst);
4788 * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
4789 * was later optimized away, so clear these flags, and add them back for the still
4790 * present OP_LDADDR instructions.
4792 for (i = 0; i < cfg->next_vreg; ++i) {
4795 ins = get_vreg_to_inst (cfg, i);
4796 if (ins && ins != cfg->rgctx_var)
4797 ins->flags &= ~MONO_INST_INDIRECT;
4801 * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
4803 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4805 LLVMBuilderRef builder;
4807 char dname_buf[128];
4809 builder = create_builder (ctx);
4811 for (ins = bb->code; ins; ins = ins->next) {
4812 switch (ins->opcode) {
4817 LLVMTypeRef phi_type = llvm_type_to_stack_type (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4819 CHECK_FAILURE (ctx);
4821 if (ins->opcode == OP_VPHI) {
4822 /* Treat valuetype PHI nodes as operating on the address itself */
4823 g_assert (ins->klass);
4824 phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
4828 * Have to precreate these, as they can be referenced by
4829 * earlier instructions.
4831 sprintf (dname_buf, "t%d", ins->dreg);
4833 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
4835 if (ins->opcode == OP_VPHI)
4836 ctx->addresses [ins->dreg] = values [ins->dreg];
4838 g_ptr_array_add (phi_values, values [ins->dreg]);
4841 * Set the expected type of the incoming arguments since these have
4842 * to have the same type.
4844 for (i = 0; i < ins->inst_phi_args [0]; i++) {
4845 int sreg1 = ins->inst_phi_args [i + 1];
4848 ctx->vreg_types [sreg1] = phi_type;
4853 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
4862 * Create an ordering for bblocks, use the depth first order first, then
4863 * put the exception handling bblocks last.
4865 for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
4866 bb = cfg->bblocks [bb_index];
4867 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
4868 g_ptr_array_add (bblock_list, bb);
4869 bblocks [bb->block_num].added = TRUE;
4873 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4874 if (!bblocks [bb->block_num].added)
4875 g_ptr_array_add (bblock_list, bb);
4879 * Second pass: generate code.
4881 for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
4882 bb = g_ptr_array_index (bblock_list, bb_index);
4884 if (!(bb == cfg->bb_entry || bb->in_count > 0))
4887 process_bb (ctx, bb);
4888 CHECK_FAILURE (ctx);
4891 /* Add incoming phi values */
4892 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4893 GSList *l, *ins_list;
4895 ins_list = bblocks [bb->block_num].phi_nodes;
4897 for (l = ins_list; l; l = l->next) {
4898 PhiNode *node = l->data;
4899 MonoInst *phi = node->phi;
4900 int sreg1 = node->sreg;
4901 LLVMBasicBlockRef in_bb;
4906 in_bb = get_end_bb (ctx, node->in_bb);
4908 if (ctx->unreachable [node->in_bb->block_num])
4911 if (!values [sreg1])
4912 /* Can happen with values in EH clauses */
4913 LLVM_FAILURE (ctx, "incoming phi sreg1");
4915 if (phi->opcode == OP_VPHI) {
4916 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4917 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
4919 if (LLVMTypeOf (values [sreg1]) != LLVMTypeOf (values [phi->dreg]))
4921 LLVM_FAILURE (ctx, "incoming phi arg type mismatch");
4922 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4923 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
4928 /* Create the SWITCH statements for ENDFINALLY instructions */
4929 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4930 BBInfo *info = &bblocks [bb->block_num];
4932 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
4933 LLVMValueRef switch_ins = l->data;
4934 GSList *bb_list = info->call_handler_return_bbs;
4936 for (i = 0; i < g_slist_length (bb_list); ++i)
4937 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
4941 if (cfg->verbose_level > 1)
4942 mono_llvm_dump_value (method);
4944 if (cfg->compile_aot)
4945 mark_as_used (ctx->lmodule, method);
4947 if (cfg->compile_aot) {
4948 LLVMValueRef md_args [16];
4949 LLVMValueRef md_node;
4952 method_index = mono_aot_get_method_index (cfg->orig_method);
4953 md_args [0] = LLVMMDString (method_name, strlen (method_name));
4954 md_args [1] = LLVMConstInt (LLVMInt32Type (), method_index, FALSE);
4955 md_node = LLVMMDNode (md_args, 2);
4956 LLVMAddNamedMetadataOperand (module, "mono.function_indexes", md_node);
4957 //LLVMSetMetadata (method, md_kind, LLVMMDNode (&md_arg, 1));
4960 if (cfg->compile_aot) {
4961 /* Don't generate native code, keep the LLVM IR */
4962 if (cfg->compile_aot && cfg->verbose_level)
4963 printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
4965 //LLVMVerifyFunction(method, 0);
4967 mono_llvm_optimize_method (ctx->lmodule->mono_ee, method);
4969 if (cfg->verbose_level > 1)
4970 mono_llvm_dump_value (method);
4972 cfg->native_code = LLVMGetPointerToGlobal (ctx->lmodule->ee, method);
4974 /* Set by emit_cb */
4975 g_assert (cfg->code_len);
4977 /* FIXME: Free the LLVM IL for the function */
4980 if (ctx->lmodule->method_to_lmethod)
4981 g_hash_table_insert (ctx->lmodule->method_to_lmethod, cfg->method, method);
4988 /* Need to add unused phi nodes as they can be referenced by other values */
4989 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
4990 LLVMBuilderRef builder;
4992 builder = create_builder (ctx);
4993 LLVMPositionBuilderAtEnd (builder, phi_bb);
4995 for (i = 0; i < phi_values->len; ++i) {
4996 LLVMValueRef v = g_ptr_array_index (phi_values, i);
4997 if (LLVMGetInstructionParent (v) == NULL)
4998 LLVMInsertIntoBuilder (builder, v);
5001 LLVMDeleteFunction (method);
5006 g_free (ctx->addresses);
5007 g_free (ctx->vreg_types);
5008 g_free (ctx->vreg_cli_types);
5009 g_free (ctx->pindexes);
5010 g_free (ctx->is_dead);
5011 g_free (ctx->unreachable);
5012 g_ptr_array_free (phi_values, TRUE);
5013 g_free (ctx->bblocks);
5014 g_hash_table_destroy (ctx->region_to_handler);
5015 g_free (method_name);
5016 g_ptr_array_free (bblock_list, TRUE);
5018 for (l = ctx->builders; l; l = l->next) {
5019 LLVMBuilderRef builder = l->data;
5020 LLVMDisposeBuilder (builder);
5025 mono_native_tls_set_value (current_cfg_tls_id, NULL);
5027 mono_loader_unlock ();
5031 * mono_llvm_emit_call:
5033 * Same as mono_arch_emit_call () for LLVM.
5036 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
5039 MonoMethodSignature *sig;
5040 int i, n, stack_size;
5045 sig = call->signature;
5046 n = sig->param_count + sig->hasthis;
5048 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
5050 if (cfg->disable_llvm)
5053 if (sig->call_convention == MONO_CALL_VARARG) {
5054 cfg->exception_message = g_strdup ("varargs");
5055 cfg->disable_llvm = TRUE;
5058 for (i = 0; i < n; ++i) {
5061 ainfo = call->cinfo->args + i;
5063 in = call->args [i];
5065 /* Simply remember the arguments */
5066 switch (ainfo->storage) {
5068 case LLVMArgInFPReg: {
5069 MonoType *t = (sig->hasthis && i == 0) ? &mono_get_intptr_class ()->byval_arg : sig->params [i - sig->hasthis];
5072 opcode = mono_type_to_regmove (cfg, t);
5073 if (opcode == OP_FMOVE) {
5074 MONO_INST_NEW (cfg, ins, OP_FMOVE);
5075 ins->dreg = mono_alloc_freg (cfg);
5076 } else if (opcode == OP_LMOVE) {
5077 MONO_INST_NEW (cfg, ins, OP_LMOVE);
5078 ins->dreg = mono_alloc_lreg (cfg);
5080 MONO_INST_NEW (cfg, ins, OP_MOVE);
5081 ins->dreg = mono_alloc_ireg (cfg);
5083 ins->sreg1 = in->dreg;
5086 case LLVMArgVtypeByVal:
5087 case LLVMArgVtypeInReg:
5088 case LLVMArgAsIArgs:
5089 case LLVMArgAsFpArgs:
5090 MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
5091 ins->dreg = mono_alloc_ireg (cfg);
5092 ins->sreg1 = in->dreg;
5093 ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
5096 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
5097 cfg->exception_message = g_strdup ("ainfo->storage");
5098 cfg->disable_llvm = TRUE;
5102 if (!cfg->disable_llvm) {
5103 MONO_ADD_INS (cfg->cbb, ins);
5104 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
5109 static unsigned char*
5110 alloc_cb (LLVMValueRef function, int size)
5114 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5118 return mono_domain_code_reserve (cfg->domain, size);
5120 return mono_domain_code_reserve (mono_domain_get (), size);
5125 emitted_cb (LLVMValueRef function, void *start, void *end)
5129 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5131 cfg->code_len = (guint8*)end - (guint8*)start;
5135 exception_cb (void *data)
5138 MonoJitExceptionInfo *ei;
5139 guint32 ei_len, i, j, nested_len, nindex;
5140 gpointer *type_info;
5141 int this_reg, this_offset;
5143 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5147 * data points to a DWARF FDE structure, convert it to our unwind format and
5149 * An alternative would be to save it directly, and modify our unwinder to work
5152 cfg->encoded_unwind_ops = mono_unwind_decode_fde ((guint8*)data, &cfg->encoded_unwind_ops_len, NULL, &ei, &ei_len, &type_info, &this_reg, &this_offset);
5153 if (cfg->verbose_level > 1)
5154 mono_print_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
5156 /* Count nested clauses */
5158 for (i = 0; i < ei_len; ++i) {
5159 for (j = 0; j < ei_len; ++j) {
5160 gint32 cindex1 = *(gint32*)type_info [i];
5161 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5162 gint32 cindex2 = *(gint32*)type_info [j];
5163 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5165 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5171 cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
5172 cfg->llvm_ex_info_len = ei_len + nested_len;
5173 memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
5174 /* Fill the rest of the information from the type info */
5175 for (i = 0; i < ei_len; ++i) {
5176 gint32 clause_index = *(gint32*)type_info [i];
5177 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
5179 cfg->llvm_ex_info [i].flags = clause->flags;
5180 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
5184 * For nested clauses, the LLVM produced exception info associates the try interval with
5185 * the innermost handler, while mono expects it to be associated with all nesting clauses.
5187 /* FIXME: These should be order with the normal clauses */
5189 for (i = 0; i < ei_len; ++i) {
5190 for (j = 0; j < ei_len; ++j) {
5191 gint32 cindex1 = *(gint32*)type_info [i];
5192 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5193 gint32 cindex2 = *(gint32*)type_info [j];
5194 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5196 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5198 * The try interval comes from the nested clause, everything else from the
5201 memcpy (&cfg->llvm_ex_info [nindex], &cfg->llvm_ex_info [j], sizeof (MonoJitExceptionInfo));
5202 cfg->llvm_ex_info [nindex].try_start = cfg->llvm_ex_info [i].try_start;
5203 cfg->llvm_ex_info [nindex].try_end = cfg->llvm_ex_info [i].try_end;
5208 g_assert (nindex == ei_len + nested_len);
5209 cfg->llvm_this_reg = this_reg;
5210 cfg->llvm_this_offset = this_offset;
5212 /* type_info [i] is cfg mempool allocated, no need to free it */
5219 dlsym_cb (const char *name, void **symbol)
5225 if (!strcmp (name, "__bzero")) {
5226 *symbol = (void*)bzero;
5228 current = mono_dl_open (NULL, 0, NULL);
5231 err = mono_dl_symbol (current, name, symbol);
5233 mono_dl_close (current);
5235 #ifdef MONO_ARCH_HAVE_CREATE_LLVM_NATIVE_THUNK
5236 *symbol = (char*)mono_arch_create_llvm_native_thunk (mono_domain_get (), (guint8*)(*symbol));
5242 AddFunc (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef *param_types, int nparams)
5244 LLVMAddFunction (module, name, LLVMFunctionType (ret_type, param_types, nparams, FALSE));
5248 AddFunc2 (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef param_type1, LLVMTypeRef param_type2)
5250 LLVMTypeRef param_types [4];
5252 param_types [0] = param_type1;
5253 param_types [1] = param_type2;
5255 AddFunc (module, name, ret_type, param_types, 2);
5259 add_intrinsics (LLVMModuleRef module)
5261 /* Emit declarations of instrinsics */
5263 * It would be nicer to emit only the intrinsics actually used, but LLVM's Module
5264 * type doesn't seem to do any locking.
5267 LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5269 memset_param_count = 5;
5270 memset_func_name = "llvm.memset.p0i8.i32";
5272 LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
5276 LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5278 memcpy_param_count = 5;
5279 memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
5281 LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
5285 LLVMTypeRef params [] = { LLVMDoubleType () };
5287 LLVMAddFunction (module, "llvm.sin.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5288 LLVMAddFunction (module, "llvm.cos.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5289 LLVMAddFunction (module, "llvm.sqrt.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5291 /* This isn't an intrinsic, instead llvm seems to special case it by name */
5292 LLVMAddFunction (module, "fabs", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5296 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
5297 LLVMTypeRef ovf_params_i32 [] = { LLVMInt32Type (), LLVMInt32Type () };
5299 LLVMAddFunction (module, "llvm.sadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5300 LLVMAddFunction (module, "llvm.uadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5301 LLVMAddFunction (module, "llvm.ssub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5302 LLVMAddFunction (module, "llvm.usub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5303 LLVMAddFunction (module, "llvm.smul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5304 LLVMAddFunction (module, "llvm.umul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5308 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
5309 LLVMTypeRef ovf_params_i64 [] = { LLVMInt64Type (), LLVMInt64Type () };
5311 LLVMAddFunction (module, "llvm.sadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5312 LLVMAddFunction (module, "llvm.uadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5313 LLVMAddFunction (module, "llvm.ssub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5314 LLVMAddFunction (module, "llvm.usub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5315 LLVMAddFunction (module, "llvm.smul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5316 LLVMAddFunction (module, "llvm.umul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5321 LLVMTypeRef arg_types [2];
5322 LLVMTypeRef ret_type;
5324 arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
5325 arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
5326 ret_type = LLVMInt32Type ();
5328 LLVMAddFunction (module, "mono_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5330 LLVMAddFunction (module, "llvm_resume_unwind_trampoline", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5333 /* SSE intrinsics */
5334 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5336 LLVMTypeRef ret_type, arg_types [16];
5339 ret_type = type_to_simd_type (MONO_TYPE_I4);
5340 arg_types [0] = ret_type;
5341 arg_types [1] = ret_type;
5342 AddFunc (module, "llvm.x86.sse41.pminud", ret_type, arg_types, 2);
5343 AddFunc (module, "llvm.x86.sse41.pmaxud", ret_type, arg_types, 2);
5345 ret_type = type_to_simd_type (MONO_TYPE_I2);
5346 arg_types [0] = ret_type;
5347 arg_types [1] = ret_type;
5348 AddFunc (module, "llvm.x86.sse41.pminuw", ret_type, arg_types, 2);
5349 AddFunc (module, "llvm.x86.sse2.pmins.w", ret_type, arg_types, 2);
5350 AddFunc (module, "llvm.x86.sse41.pmaxuw", ret_type, arg_types, 2);
5351 AddFunc (module, "llvm.x86.sse2.padds.w", ret_type, arg_types, 2);
5352 AddFunc (module, "llvm.x86.sse2.psubs.w", ret_type, arg_types, 2);
5353 AddFunc (module, "llvm.x86.sse2.paddus.w", ret_type, arg_types, 2);
5354 AddFunc (module, "llvm.x86.sse2.psubus.w", ret_type, arg_types, 2);
5355 AddFunc (module, "llvm.x86.sse2.pavg.w", ret_type, arg_types, 2);
5356 AddFunc (module, "llvm.x86.sse2.pmulh.w", ret_type, arg_types, 2);
5357 AddFunc (module, "llvm.x86.sse2.pmulhu.w", ret_type, arg_types, 2);
5359 ret_type = type_to_simd_type (MONO_TYPE_I1);
5360 arg_types [0] = ret_type;
5361 arg_types [1] = ret_type;
5362 AddFunc (module, "llvm.x86.sse2.pminu.b", ret_type, arg_types, 2);
5363 AddFunc (module, "llvm.x86.sse2.pmaxu.b", ret_type, arg_types, 2);
5364 AddFunc (module, "llvm.x86.sse2.padds.b", ret_type, arg_types, 2);
5365 AddFunc (module, "llvm.x86.sse2.psubs.b", ret_type, arg_types, 2);
5366 AddFunc (module, "llvm.x86.sse2.paddus.b", ret_type, arg_types, 2);
5367 AddFunc (module, "llvm.x86.sse2.psubus.b", ret_type, arg_types, 2);
5368 AddFunc (module, "llvm.x86.sse2.pavg.b", ret_type, arg_types, 2);
5370 ret_type = type_to_simd_type (MONO_TYPE_R8);
5371 arg_types [0] = ret_type;
5372 arg_types [1] = ret_type;
5373 AddFunc (module, "llvm.x86.sse2.min.pd", ret_type, arg_types, 2);
5374 AddFunc (module, "llvm.x86.sse2.max.pd", ret_type, arg_types, 2);
5375 AddFunc (module, "llvm.x86.sse3.hadd.pd", ret_type, arg_types, 2);
5376 AddFunc (module, "llvm.x86.sse3.hsub.pd", ret_type, arg_types, 2);
5377 AddFunc (module, "llvm.x86.sse3.addsub.pd", ret_type, arg_types, 2);
5379 ret_type = type_to_simd_type (MONO_TYPE_R4);
5380 arg_types [0] = ret_type;
5381 arg_types [1] = ret_type;
5382 AddFunc (module, "llvm.x86.sse.min.ps", ret_type, arg_types, 2);
5383 AddFunc (module, "llvm.x86.sse.max.ps", ret_type, arg_types, 2);
5384 AddFunc (module, "llvm.x86.sse3.hadd.ps", ret_type, arg_types, 2);
5385 AddFunc (module, "llvm.x86.sse3.hsub.ps", ret_type, arg_types, 2);
5386 AddFunc (module, "llvm.x86.sse3.addsub.ps", ret_type, arg_types, 2);
5389 ret_type = type_to_simd_type (MONO_TYPE_I1);
5390 arg_types [0] = type_to_simd_type (MONO_TYPE_I2);
5391 arg_types [1] = type_to_simd_type (MONO_TYPE_I2);
5392 AddFunc (module, "llvm.x86.sse2.packsswb.128", ret_type, arg_types, 2);
5393 AddFunc (module, "llvm.x86.sse2.packuswb.128", ret_type, arg_types, 2);
5394 ret_type = type_to_simd_type (MONO_TYPE_I2);
5395 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5396 arg_types [1] = type_to_simd_type (MONO_TYPE_I4);
5397 AddFunc (module, "llvm.x86.sse2.packssdw.128", ret_type, arg_types, 2);
5398 AddFunc (module, "llvm.x86.sse41.packusdw", ret_type, arg_types, 2);
5401 ret_type = type_to_simd_type (MONO_TYPE_R8);
5402 arg_types [0] = ret_type;
5403 arg_types [1] = ret_type;
5404 arg_types [2] = LLVMInt8Type ();
5405 AddFunc (module, "llvm.x86.sse2.cmp.pd", ret_type, arg_types, 3);
5406 ret_type = type_to_simd_type (MONO_TYPE_R4);
5407 arg_types [0] = ret_type;
5408 arg_types [1] = ret_type;
5409 arg_types [2] = LLVMInt8Type ();
5410 AddFunc (module, "llvm.x86.sse.cmp.ps", ret_type, arg_types, 3);
5412 /* Conversion ops */
5413 ret_type = type_to_simd_type (MONO_TYPE_R8);
5414 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5415 AddFunc (module, "llvm.x86.sse2.cvtdq2pd", ret_type, arg_types, 1);
5416 ret_type = type_to_simd_type (MONO_TYPE_R4);
5417 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5418 AddFunc (module, "llvm.x86.sse2.cvtdq2ps", ret_type, arg_types, 1);
5419 ret_type = type_to_simd_type (MONO_TYPE_I4);
5420 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5421 AddFunc (module, "llvm.x86.sse2.cvtpd2dq", ret_type, arg_types, 1);
5422 ret_type = type_to_simd_type (MONO_TYPE_I4);
5423 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5424 AddFunc (module, "llvm.x86.sse2.cvtps2dq", ret_type, arg_types, 1);
5425 ret_type = type_to_simd_type (MONO_TYPE_R4);
5426 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5427 AddFunc (module, "llvm.x86.sse2.cvtpd2ps", ret_type, arg_types, 1);
5428 ret_type = type_to_simd_type (MONO_TYPE_R8);
5429 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5430 AddFunc (module, "llvm.x86.sse2.cvtps2pd", ret_type, arg_types, 1);
5432 ret_type = type_to_simd_type (MONO_TYPE_I4);
5433 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5434 AddFunc (module, "llvm.x86.sse2.cvttpd2dq", ret_type, arg_types, 1);
5435 ret_type = type_to_simd_type (MONO_TYPE_I4);
5436 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5437 AddFunc (module, "llvm.x86.sse2.cvttps2dq", ret_type, arg_types, 1);
5440 ret_type = type_to_simd_type (MONO_TYPE_R8);
5441 arg_types [0] = ret_type;
5442 AddFunc (module, "llvm.x86.sse2.sqrt.pd", ret_type, arg_types, 1);
5443 ret_type = type_to_simd_type (MONO_TYPE_R4);
5444 arg_types [0] = ret_type;
5445 AddFunc (module, "llvm.x86.sse.sqrt.ps", ret_type, arg_types, 1);
5446 ret_type = type_to_simd_type (MONO_TYPE_R4);
5447 arg_types [0] = ret_type;
5448 AddFunc (module, "llvm.x86.sse.rsqrt.ps", ret_type, arg_types, 1);
5449 ret_type = type_to_simd_type (MONO_TYPE_R4);
5450 arg_types [0] = ret_type;
5451 AddFunc (module, "llvm.x86.sse.rcp.ps", ret_type, arg_types, 1);
5454 ret_type = type_to_simd_type (MONO_TYPE_I2);
5455 arg_types [0] = ret_type;
5456 arg_types [1] = LLVMInt32Type ();
5457 AddFunc (module, "llvm.x86.sse2.psrli.w", ret_type, arg_types, 2);
5458 AddFunc (module, "llvm.x86.sse2.psrai.w", ret_type, arg_types, 2);
5459 AddFunc (module, "llvm.x86.sse2.pslli.w", ret_type, arg_types, 2);
5460 ret_type = type_to_simd_type (MONO_TYPE_I4);
5461 arg_types [0] = ret_type;
5462 arg_types [1] = LLVMInt32Type ();
5463 AddFunc (module, "llvm.x86.sse2.psrli.d", ret_type, arg_types, 2);
5464 AddFunc (module, "llvm.x86.sse2.psrai.d", ret_type, arg_types, 2);
5465 AddFunc (module, "llvm.x86.sse2.pslli.d", ret_type, arg_types, 2);
5466 ret_type = type_to_simd_type (MONO_TYPE_I8);
5467 arg_types [0] = ret_type;
5468 arg_types [1] = LLVMInt32Type ();
5469 AddFunc (module, "llvm.x86.sse2.psrli.q", ret_type, arg_types, 2);
5470 AddFunc (module, "llvm.x86.sse2.pslli.q", ret_type, arg_types, 2);
5473 ret_type = LLVMInt32Type ();
5474 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
5475 AddFunc (module, "llvm.x86.sse2.pmovmskb.128", ret_type, arg_types, 1);
5478 AddFunc (module, "llvm.x86.sse2.pause", LLVMVoidType (), NULL, 0);
5481 /* Load/Store intrinsics */
5483 LLVMTypeRef arg_types [5];
5487 for (i = 1; i <= 8; i *= 2) {
5488 arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
5489 arg_types [1] = LLVMInt32Type ();
5490 arg_types [2] = LLVMInt1Type ();
5491 #if LLVM_API_VERSION >= 4
5492 arg_types [3] = LLVMInt32Type ();
5494 sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
5495 LLVMAddFunction (module, name, LLVMFunctionType (LLVMIntType (i * 8), arg_types, 3 + EXTRA_MONO_LOAD_STORE_ARGS, FALSE));
5497 arg_types [0] = LLVMIntType (i * 8);
5498 arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
5499 arg_types [2] = LLVMInt32Type ();
5500 arg_types [3] = LLVMInt1Type ();
5501 #if LLVM_API_VERSION >= 4
5502 arg_types [4] = LLVMInt32Type ();
5504 sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
5505 LLVMAddFunction (module, name, LLVMFunctionType (LLVMVoidType (), arg_types, 4 + EXTRA_MONO_LOAD_STORE_ARGS, FALSE));
5511 add_types (MonoLLVMModule *lmodule)
5513 lmodule->ptr_type = LLVMPointerType (sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type (), 0);
5517 mono_llvm_init (void)
5519 mono_native_tls_alloc (¤t_cfg_tls_id, NULL);
5523 init_jit_module (MonoDomain *domain)
5525 MonoJitICallInfo *info;
5526 MonoJitDomainInfo *dinfo;
5527 MonoLLVMModule *module;
5530 dinfo = domain_jit_info (domain);
5531 if (dinfo->llvm_module)
5534 mono_loader_lock ();
5536 if (dinfo->llvm_module) {
5537 mono_loader_unlock ();
5541 module = g_new0 (MonoLLVMModule, 1);
5543 name = g_strdup_printf ("mono-%s", domain->friendly_name);
5544 module->module = LLVMModuleCreateWithName (name);
5546 module->mono_ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (module->module), alloc_cb, emitted_cb, exception_cb, dlsym_cb, &module->ee);
5548 add_intrinsics (module->module);
5551 module->llvm_types = g_hash_table_new (NULL, NULL);
5553 info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
5555 LLVMAddGlobalMapping (module->ee, LLVMGetNamedFunction (module->module, "llvm_resume_unwind_trampoline"), (void*)info->func);
5557 mono_memory_barrier ();
5559 dinfo->llvm_module = module;
5561 mono_loader_unlock ();
5565 mono_llvm_cleanup (void)
5567 if (aot_module.module)
5568 LLVMDisposeModule (aot_module.module);
5570 LLVMContextDispose (LLVMGetGlobalContext ());
5574 mono_llvm_free_domain_info (MonoDomain *domain)
5576 MonoJitDomainInfo *info = domain_jit_info (domain);
5577 MonoLLVMModule *module = info->llvm_module;
5583 if (module->llvm_types)
5584 g_hash_table_destroy (module->llvm_types);
5586 mono_llvm_dispose_ee (module->mono_ee);
5588 if (module->bb_names) {
5589 for (i = 0; i < module->bb_names_len; ++i)
5590 g_free (module->bb_names [i]);
5591 g_free (module->bb_names);
5593 //LLVMDisposeModule (module->module);
5597 info->llvm_module = NULL;
5601 mono_llvm_create_aot_module (const char *got_symbol, gboolean external_symbols, gboolean emit_dwarf)
5603 /* Delete previous module */
5604 if (aot_module.plt_entries)
5605 g_hash_table_destroy (aot_module.plt_entries);
5606 if (aot_module.module)
5607 LLVMDisposeModule (aot_module.module);
5609 memset (&aot_module, 0, sizeof (aot_module));
5611 aot_module.module = LLVMModuleCreateWithName ("aot");
5612 aot_module.got_symbol = got_symbol;
5613 aot_module.external_symbols = external_symbols;
5614 aot_module.emit_dwarf = emit_dwarf;
5615 /* The first few entries are reserved */
5616 aot_module.max_got_offset = 16;
5618 add_intrinsics (aot_module.module);
5619 add_types (&aot_module);
5623 * We couldn't compute the type of the LLVM global representing the got because
5624 * its size is only known after all the methods have been emitted. So create
5625 * a dummy variable, and replace all uses it with the real got variable when
5626 * its size is known in mono_llvm_emit_aot_module ().
5629 LLVMTypeRef got_type = LLVMArrayType (aot_module.ptr_type, 0);
5631 aot_module.got_var = LLVMAddGlobal (aot_module.module, got_type, "mono_dummy_got");
5632 LLVMSetInitializer (aot_module.got_var, LLVMConstNull (got_type));
5635 /* Add a dummy personality function */
5637 LLVMBasicBlockRef lbb;
5638 LLVMBuilderRef lbuilder;
5639 LLVMValueRef personality;
5641 personality = LLVMAddFunction (aot_module.module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5642 LLVMSetLinkage (personality, LLVMInternalLinkage);
5643 lbb = LLVMAppendBasicBlock (personality, "BB0");
5644 lbuilder = LLVMCreateBuilder ();
5645 LLVMPositionBuilderAtEnd (lbuilder, lbb);
5646 LLVMBuildRetVoid (lbuilder);
5649 aot_module.llvm_types = g_hash_table_new (NULL, NULL);
5650 aot_module.plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
5651 aot_module.plt_entries_ji = g_hash_table_new (NULL, NULL);
5652 aot_module.method_to_lmethod = g_hash_table_new (NULL, NULL);
5656 * Emit the aot module into the LLVM bitcode file FILENAME.
5659 mono_llvm_emit_aot_module (const char *filename, const char *cu_name)
5661 LLVMTypeRef got_type;
5662 LLVMValueRef real_got;
5663 MonoLLVMModule *module = &aot_module;
5666 * Create the real got variable and replace all uses of the dummy variable with
5669 got_type = LLVMArrayType (aot_module.ptr_type, module->max_got_offset + 1);
5670 real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
5671 LLVMSetInitializer (real_got, LLVMConstNull (got_type));
5672 if (module->external_symbols) {
5673 LLVMSetLinkage (real_got, LLVMExternalLinkage);
5674 LLVMSetVisibility (real_got, LLVMHiddenVisibility);
5676 LLVMSetLinkage (real_got, LLVMInternalLinkage);
5678 mono_llvm_replace_uses_of (aot_module.got_var, real_got);
5680 mark_as_used (&aot_module, real_got);
5682 /* Delete the dummy got so it doesn't become a global */
5683 LLVMDeleteGlobal (aot_module.got_var);
5685 emit_llvm_used (&aot_module);
5686 emit_dbg_info (&aot_module, filename, cu_name);
5688 /* Replace PLT entries for directly callable methods with the methods themselves */
5690 GHashTableIter iter;
5692 LLVMValueRef callee;
5694 g_hash_table_iter_init (&iter, aot_module.plt_entries_ji);
5695 while (g_hash_table_iter_next (&iter, (void**)&ji, (void**)&callee)) {
5696 if (mono_aot_is_direct_callable (ji)) {
5697 LLVMValueRef lmethod;
5699 lmethod = g_hash_table_lookup (module->method_to_lmethod, ji->data.method);
5700 /* The types might not match because the caller might pass an rgctx */
5701 if (lmethod && LLVMTypeOf (callee) == LLVMTypeOf (lmethod)) {
5702 mono_llvm_replace_uses_of (callee, lmethod);
5703 mono_aot_mark_unused_llvm_plt_entry (ji);
5713 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
5714 g_assert_not_reached ();
5719 LLVMWriteBitcodeToFile (aot_module.module, filename);
5724 md_string (const char *s)
5726 return LLVMMDString (s, strlen (s));
5729 /* Debugging support */
5732 emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name)
5734 LLVMModuleRef module = lmodule->module;
5735 LLVMValueRef args [16], cu_args [16], cu, ver;
5737 char *build_info, *s, *dir;
5740 * This can only be enabled when LLVM code is emitted into a separate object
5741 * file, since the AOT compiler also emits dwarf info,
5742 * and the abbrev indexes will not be correct since llvm has added its own
5745 if (!lmodule->emit_dwarf)
5749 * Emit dwarf info in the form of LLVM metadata. There is some
5750 * out-of-date documentation at:
5751 * http://llvm.org/docs/SourceLevelDebugging.html
5752 * but most of this was gathered from the llvm and
5757 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_TAG_compile_unit, FALSE);
5758 /* CU name/compilation dir */
5759 dir = g_path_get_dirname (filename);
5760 args [0] = LLVMMDString (cu_name, strlen (cu_name));
5761 args [1] = LLVMMDString (dir, strlen (dir));
5762 cu_args [n_cuargs ++] = LLVMMDNode (args, 2);
5765 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_LANG_C99, FALSE);
5767 build_info = mono_get_runtime_build_info ();
5768 s = g_strdup_printf ("Mono AOT Compiler %s (LLVM)", build_info);
5769 cu_args [n_cuargs ++] = LLVMMDString (s, strlen (s));
5770 g_free (build_info);
5772 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5774 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5775 /* Runtime version */
5776 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5778 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5779 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5781 if (lmodule->subprogram_mds) {
5785 mds = g_new0 (LLVMValueRef, lmodule->subprogram_mds->len);
5786 for (i = 0; i < lmodule->subprogram_mds->len; ++i)
5787 mds [i] = g_ptr_array_index (lmodule->subprogram_mds, i);
5788 cu_args [n_cuargs ++] = LLVMMDNode (mds, lmodule->subprogram_mds->len);
5790 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5793 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5794 /* Imported modules */
5795 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5797 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5798 /* DebugEmissionKind = FullDebug */
5799 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5800 cu = LLVMMDNode (cu_args, n_cuargs);
5801 LLVMAddNamedMetadataOperand (module, "llvm.dbg.cu", cu);
5803 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5804 args [1] = LLVMMDString ("Dwarf Version", strlen ("Dwarf Version"));
5805 args [2] = LLVMConstInt (LLVMInt32Type (), 2, FALSE);
5806 ver = LLVMMDNode (args, 3);
5807 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5809 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5810 args [1] = LLVMMDString ("Debug Info Version", strlen ("Debug Info Version"));
5811 args [2] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5812 ver = LLVMMDNode (args, 3);
5813 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5817 emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name)
5819 MonoLLVMModule *module = ctx->lmodule;
5820 MonoDebugMethodInfo *minfo = ctx->minfo;
5821 char *source_file, *dir, *filename;
5822 LLVMValueRef md, args [16], ctx_args [16], md_args [64], type_args [16], ctx_md, type_md;
5830 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, NULL, &n_il_offsets, &il_offsets, &line_numbers, NULL, NULL, NULL, NULL);
5832 source_file = g_strdup ("<unknown>");
5833 dir = g_path_get_dirname (source_file);
5834 filename = g_path_get_basename (source_file);
5836 ctx_args [0] = LLVMConstInt (LLVMInt32Type (), 0x29, FALSE);
5837 args [0] = md_string (filename);
5838 args [1] = md_string (dir);
5839 ctx_args [1] = LLVMMDNode (args, 2);
5840 ctx_md = LLVMMDNode (ctx_args, 2);
5842 type_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subroutine_type, FALSE);
5843 type_args [1] = NULL;
5844 type_args [2] = NULL;
5845 type_args [3] = LLVMMDString ("", 0);
5846 type_args [4] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5847 type_args [5] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5848 type_args [6] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5849 type_args [7] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5850 type_args [8] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5851 type_args [9] = NULL;
5852 type_args [10] = NULL;
5853 type_args [11] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5854 type_args [12] = NULL;
5855 type_args [13] = NULL;
5856 type_args [14] = NULL;
5857 type_md = LLVMMDNode (type_args, 14);
5859 /* http://llvm.org/docs/SourceLevelDebugging.html#subprogram-descriptors */
5860 md_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subprogram, FALSE);
5861 /* Source directory + file pair */
5862 args [0] = md_string (filename);
5863 args [1] = md_string (dir);
5864 md_args [1] = LLVMMDNode (args ,2);
5865 md_args [2] = ctx_md;
5866 md_args [3] = md_string (cfg->method->name);
5867 md_args [4] = md_string (name);
5868 md_args [5] = md_string (name);
5871 md_args [6] = LLVMConstInt (LLVMInt32Type (), line_numbers [0], FALSE);
5873 md_args [6] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5875 md_args [7] = type_md;
5877 md_args [8] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5879 md_args [9] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5881 md_args [10] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5882 /* Index into a virtual function */
5883 md_args [11] = NULL;
5884 md_args [12] = NULL;
5886 md_args [13] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5888 md_args [14] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5889 /* Pointer to LLVM function */
5890 md_args [15] = method;
5891 /* Function template parameter */
5892 md_args [16] = NULL;
5893 /* Function declaration descriptor */
5894 md_args [17] = NULL;
5895 /* List of function variables */
5896 md_args [18] = LLVMMDNode (args, 0);
5898 md_args [19] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5899 md = LLVMMDNode (md_args, 20);
5901 if (!module->subprogram_mds)
5902 module->subprogram_mds = g_ptr_array_new ();
5903 g_ptr_array_add (module->subprogram_mds, md);
5907 g_free (source_file);
5908 g_free (il_offsets);
5909 g_free (line_numbers);
5915 emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code)
5917 MonoCompile *cfg = ctx->cfg;
5919 if (ctx->minfo && cil_code && cil_code >= cfg->header->code && cil_code < cfg->header->code + cfg->header->code_size) {
5920 MonoDebugSourceLocation *loc;
5921 LLVMValueRef loc_md, md_args [16];
5924 loc = mono_debug_symfile_lookup_location (ctx->minfo, cil_code - cfg->header->code);
5928 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->row, FALSE);
5929 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->column, FALSE);
5930 md_args [nmd_args ++] = ctx->dbg_md;
5931 md_args [nmd_args ++] = NULL;
5932 loc_md = LLVMMDNode (md_args, nmd_args);
5933 LLVMSetCurrentDebugLocation (builder, loc_md);
5934 mono_debug_symfile_free_location (loc);
5941 - Emit LLVM IR from the mono IR using the LLVM C API.
5942 - The original arch specific code remains, so we can fall back to it if we run
5943 into something we can't handle.
5947 A partial list of issues:
5948 - Handling of opcodes which can throw exceptions.
5950 In the mono JIT, these are implemented using code like this:
5957 push throw_pos - method
5958 call <exception trampoline>
5960 The problematic part is push throw_pos - method, which cannot be represented
5961 in the LLVM IR, since it does not support label values.
5962 -> this can be implemented in AOT mode using inline asm + labels, but cannot
5963 be implemented in JIT mode ?
5964 -> a possible but slower implementation would use the normal exception
5965 throwing code but it would need to control the placement of the throw code
5966 (it needs to be exactly after the compare+branch).
5967 -> perhaps add a PC offset intrinsics ?
5969 - efficient implementation of .ovf opcodes.
5971 These are currently implemented as:
5972 <ins which sets the condition codes>
5975 Some overflow opcodes are now supported by LLVM SVN.
5977 - exception handling, unwinding.
5978 - SSA is disabled for methods with exception handlers
5979 - How to obtain unwind info for LLVM compiled methods ?
5980 -> this is now solved by converting the unwind info generated by LLVM
5982 - LLVM uses the c++ exception handling framework, while we use our home grown
5983 code, and couldn't use the c++ one:
5984 - its not supported under VC++, other exotic platforms.
5985 - it might be impossible to support filter clauses with it.
5989 The trampolines need a predictable call sequence, since they need to disasm
5990 the calling code to obtain register numbers / offsets.
5992 LLVM currently generates this code in non-JIT mode:
5993 mov -0x98(%rax),%eax
5995 Here, the vtable pointer is lost.
5996 -> solution: use one vtable trampoline per class.
5998 - passing/receiving the IMT pointer/RGCTX.
5999 -> solution: pass them as normal arguments ?
6003 LLVM does not allow the specification of argument registers etc. This means
6004 that all calls are made according to the platform ABI.
6006 - passing/receiving vtypes.
6008 Vtypes passed/received in registers are handled by the front end by using
6009 a signature with scalar arguments, and loading the parts of the vtype into those
6012 Vtypes passed on the stack are handled using the 'byval' attribute.
6016 Supported though alloca, we need to emit the load/store code.
6020 The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
6021 typed registers, so we have to keep track of the precise LLVM type of each vreg.
6022 This is made easier because the IR is already in SSA form.
6023 An additional problem is that our IR is not consistent with types, i.e. i32/ia64
6024 types are frequently used incorrectly.
6029 Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then
6030 append the AOT data structures to that file. For methods which cannot be
6031 handled by LLVM, the normal JIT compiled versions are used.
6034 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
6035 * - each bblock should end with a branch
6036 * - setting the return value, making cfg->ret non-volatile
6037 * - avoid some transformations in the JIT which make it harder for us to generate
6039 * - use pointer types to help optimizations.