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 && mini_type_is_vtype (ctx->cfg, rtype)) {
1143 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1145 ret_type = LLVMVoidType ();
1148 pindexes = g_new0 (int, sig->param_count);
1149 param_types = g_new0 (LLVMTypeRef, (sig->param_count * 2) + 3);
1151 if (cinfo && cinfo->rgctx_arg) {
1153 sinfo->rgctx_arg_pindex = pindex;
1154 param_types [pindex] = ctx->lmodule->ptr_type;
1157 if (cinfo && cinfo->imt_arg) {
1159 sinfo->imt_arg_pindex = pindex;
1160 param_types [pindex] = ctx->lmodule->ptr_type;
1164 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1165 vret_arg_pindex = pindex;
1166 if (cinfo->vret_arg_index == 1) {
1167 /* Add the slots consumed by the first argument */
1168 LLVMArgInfo *ainfo = &cinfo->args [0];
1169 switch (ainfo->storage) {
1170 case LLVMArgVtypeInReg:
1171 for (j = 0; j < 2; ++j) {
1172 if (ainfo->pair_storage [j] == LLVMArgInIReg)
1182 sinfo->vret_arg_pindex = vret_arg_pindex;
1185 if (vretaddr && vret_arg_pindex == pindex)
1186 param_types [pindex ++] = IntPtrType ();
1189 sinfo->this_arg_pindex = pindex;
1190 param_types [pindex ++] = ThisType ();
1192 if (vretaddr && vret_arg_pindex == pindex)
1193 param_types [pindex ++] = IntPtrType ();
1194 for (i = 0; i < sig->param_count; ++i) {
1195 LLVMArgInfo *ainfo = cinfo ? &cinfo->args [i + sig->hasthis] : NULL;
1197 if (vretaddr && vret_arg_pindex == pindex)
1198 param_types [pindex ++] = IntPtrType ();
1199 pindexes [i] = pindex;
1200 if (ainfo && ainfo->storage == LLVMArgVtypeInReg) {
1201 for (j = 0; j < 2; ++j) {
1202 switch (ainfo->pair_storage [j]) {
1204 param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1209 g_assert_not_reached ();
1212 } else if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
1213 param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1214 CHECK_FAILURE (ctx);
1215 param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1217 } else if (ainfo && ainfo->storage == LLVMArgAsIArgs) {
1218 param_types [pindex] = LLVMArrayType (IntPtrType (), ainfo->nslots);
1221 param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1224 if (vretaddr && vret_arg_pindex == pindex)
1225 param_types [pindex ++] = IntPtrType ();
1227 CHECK_FAILURE (ctx);
1229 res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1230 g_free (param_types);
1233 sinfo->pindexes = pindexes;
1241 g_free (param_types);
1247 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1249 return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1253 * LLVMFunctionType1:
1255 * Create an LLVM function type from the arguments.
1257 static G_GNUC_UNUSED LLVMTypeRef
1258 LLVMFunctionType1(LLVMTypeRef ReturnType,
1259 LLVMTypeRef ParamType1,
1262 LLVMTypeRef param_types [1];
1264 param_types [0] = ParamType1;
1266 return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1270 * LLVMFunctionType2:
1272 * Create an LLVM function type from the arguments.
1274 static G_GNUC_UNUSED LLVMTypeRef
1275 LLVMFunctionType2(LLVMTypeRef ReturnType,
1276 LLVMTypeRef ParamType1,
1277 LLVMTypeRef ParamType2,
1280 LLVMTypeRef param_types [2];
1282 param_types [0] = ParamType1;
1283 param_types [1] = ParamType2;
1285 return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1289 * LLVMFunctionType3:
1291 * Create an LLVM function type from the arguments.
1293 static G_GNUC_UNUSED LLVMTypeRef
1294 LLVMFunctionType3(LLVMTypeRef ReturnType,
1295 LLVMTypeRef ParamType1,
1296 LLVMTypeRef ParamType2,
1297 LLVMTypeRef ParamType3,
1300 LLVMTypeRef param_types [3];
1302 param_types [0] = ParamType1;
1303 param_types [1] = ParamType2;
1304 param_types [2] = ParamType3;
1306 return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1312 * Create an LLVM builder and remember it so it can be freed later.
1314 static LLVMBuilderRef
1315 create_builder (EmitContext *ctx)
1317 LLVMBuilderRef builder = LLVMCreateBuilder ();
1319 ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1325 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1327 char *callee_name = mono_aot_get_plt_symbol (type, data);
1328 LLVMValueRef callee;
1329 MonoJumpInfo *ji = NULL;
1334 if (ctx->cfg->compile_aot)
1335 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1336 mono_add_patch_info (ctx->cfg, 0, type, data);
1339 callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1341 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1343 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1345 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1348 if (ctx->cfg->compile_aot) {
1349 ji = g_new0 (MonoJumpInfo, 1);
1351 ji->data.target = data;
1353 g_hash_table_insert (ctx->lmodule->plt_entries_ji, ji, callee);
1360 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1362 MonoMethodHeader *header = cfg->header;
1363 MonoExceptionClause *clause;
1367 if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1368 return (bb->region >> 8) - 1;
1371 for (i = 0; i < header->num_clauses; ++i) {
1372 clause = &header->clauses [i];
1374 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1382 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1384 LLVMValueRef md_arg;
1387 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1388 md_arg = LLVMMDString ("mono", 4);
1389 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1393 set_invariant_load_flag (LLVMValueRef v)
1395 LLVMValueRef md_arg;
1397 const char *flag_name;
1399 // FIXME: Cache this
1400 flag_name = "invariant.load";
1401 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1402 md_arg = LLVMMDString ("<index>", strlen ("<index>"));
1403 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1409 * Emit an LLVM call or invoke instruction depending on whenever the call is inside
1413 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1415 MonoCompile *cfg = ctx->cfg;
1417 LLVMBuilderRef builder = *builder_ref;
1420 clause_index = get_handler_clause (cfg, bb);
1422 if (clause_index != -1) {
1423 MonoMethodHeader *header = cfg->header;
1424 MonoExceptionClause *ec = &header->clauses [clause_index];
1425 MonoBasicBlock *tblock;
1426 LLVMBasicBlockRef ex_bb, noex_bb;
1429 * Have to use an invoke instead of a call, branching to the
1430 * handler bblock of the clause containing this bblock.
1433 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1435 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1438 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1440 ex_bb = get_bb (ctx, tblock);
1442 noex_bb = gen_bb (ctx, "NOEX_BB");
1445 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1447 builder = ctx->builder = create_builder (ctx);
1448 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1450 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1452 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1453 ctx->builder = builder;
1456 *builder_ref = ctx->builder;
1461 #if LLVM_API_VERSION >= 4
1462 #define EXTRA_MONO_LOAD_STORE_ARGS 1
1464 #define EXTRA_MONO_LOAD_STORE_ARGS 0
1468 emit_load_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting, BarrierKind barrier)
1470 const char *intrins_name;
1471 LLVMValueRef args [16], res;
1472 LLVMTypeRef addr_type;
1474 if (is_faulting && bb->region != -1) {
1475 #if LLVM_API_VERSION >= 4
1476 LLVMAtomicOrdering ordering;
1479 case LLVM_BARRIER_NONE:
1480 ordering = LLVMAtomicOrderingNotAtomic;
1482 case LLVM_BARRIER_ACQ:
1483 ordering = LLVMAtomicOrderingAcquire;
1485 case LLVM_BARRIER_SEQ:
1486 ordering = LLVMAtomicOrderingSequentiallyConsistent;
1489 g_assert_not_reached ();
1495 * We handle loads which can fault by calling a mono specific intrinsic
1496 * using an invoke, so they are handled properly inside try blocks.
1497 * We can't use this outside clauses, since LLVM optimizes intrinsics which
1498 * are marked with IntrReadArgMem.
1502 intrins_name = "llvm.mono.load.i8.p0i8";
1505 intrins_name = "llvm.mono.load.i16.p0i16";
1508 intrins_name = "llvm.mono.load.i32.p0i32";
1511 intrins_name = "llvm.mono.load.i64.p0i64";
1514 g_assert_not_reached ();
1517 addr_type = LLVMTypeOf (addr);
1518 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1519 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1522 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1523 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1524 #if LLVM_API_VERSION >= 4
1525 args [3] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1527 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 3 + EXTRA_MONO_LOAD_STORE_ARGS);
1529 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1530 res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1531 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1532 res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1539 * We emit volatile loads for loads which can fault, because otherwise
1540 * LLVM will generate invalid code when encountering a load from a
1543 res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting, barrier);
1545 /* Mark it with a custom metadata */
1548 set_metadata_flag (res, "mono.faulting.load");
1556 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1558 return emit_load_general (ctx, bb, builder_ref, size, addr, name, is_faulting, LLVM_BARRIER_NONE);
1562 emit_store_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting, BarrierKind barrier)
1564 const char *intrins_name;
1565 LLVMValueRef args [16];
1567 if (is_faulting && bb->region != -1) {
1568 #if LLVM_API_VERSION >= 4
1569 LLVMAtomicOrdering ordering;
1572 case LLVM_BARRIER_NONE:
1573 ordering = LLVMAtomicOrderingNotAtomic;
1575 case LLVM_BARRIER_REL:
1576 ordering = LLVMAtomicOrderingRelease;
1578 case LLVM_BARRIER_SEQ:
1579 ordering = LLVMAtomicOrderingSequentiallyConsistent;
1582 g_assert_not_reached ();
1589 intrins_name = "llvm.mono.store.i8.p0i8";
1592 intrins_name = "llvm.mono.store.i16.p0i16";
1595 intrins_name = "llvm.mono.store.i32.p0i32";
1598 intrins_name = "llvm.mono.store.i64.p0i64";
1601 g_assert_not_reached ();
1604 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1605 value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1606 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1611 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1612 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1613 #if LLVM_API_VERSION >= 4
1614 args [4] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1616 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4 + EXTRA_MONO_LOAD_STORE_ARGS);
1618 mono_llvm_build_store (*builder_ref, value, addr, is_faulting, barrier);
1623 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1625 emit_store_general (ctx, bb, builder_ref, size, value, addr, is_faulting, LLVM_BARRIER_NONE);
1629 * emit_cond_system_exception:
1631 * Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1632 * Might set the ctx exception.
1635 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1637 LLVMBasicBlockRef ex_bb, noex_bb;
1638 LLVMBuilderRef builder;
1639 MonoClass *exc_class;
1640 LLVMValueRef args [2];
1642 ex_bb = gen_bb (ctx, "EX_BB");
1643 noex_bb = gen_bb (ctx, "NOEX_BB");
1645 LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1647 exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1648 g_assert (exc_class);
1650 /* Emit exception throwing code */
1651 builder = create_builder (ctx);
1652 LLVMPositionBuilderAtEnd (builder, ex_bb);
1654 if (!ctx->lmodule->throw_corlib_exception) {
1655 LLVMValueRef callee;
1657 const char *icall_name;
1659 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1660 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1661 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1662 icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1663 /* This will become i8* */
1664 throw_sig->params [1] = &mono_get_byte_class ()->this_arg;
1665 sig = sig_to_llvm_sig (ctx, throw_sig);
1667 if (ctx->cfg->compile_aot) {
1668 callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1670 callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1673 * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1674 * - On x86, LLVM generated code doesn't push the arguments
1675 * - The trampoline takes the throw address as an arguments, not a pc offset.
1677 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1680 mono_memory_barrier ();
1681 ctx->lmodule->throw_corlib_exception = callee;
1684 if (IS_TARGET_X86 || IS_TARGET_AMD64)
1685 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1687 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1690 * The LLVM mono branch contains changes so a block address can be passed as an
1691 * argument to a call.
1693 args [1] = LLVMBlockAddress (ctx->lmethod, ex_bb);
1694 emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1696 LLVMBuildUnreachable (builder);
1698 ctx->builder = create_builder (ctx);
1699 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1701 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1708 * emit_reg_to_vtype:
1710 * Emit code to store the vtype in the registers REGS to the address ADDRESS.
1713 emit_reg_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs)
1717 size = get_vtype_size (t);
1719 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1720 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1723 for (j = 0; j < 2; ++j) {
1724 LLVMValueRef index [2], addr;
1725 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1726 LLVMTypeRef part_type;
1728 if (ainfo->pair_storage [j] == LLVMArgNone)
1731 part_type = LLVMIntType (part_size * 8);
1732 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1733 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1734 addr = LLVMBuildGEP (builder, address, index, 1, "");
1736 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1737 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1738 addr = LLVMBuildGEP (builder, address, index, 2, "");
1740 switch (ainfo->pair_storage [j]) {
1742 LLVMBuildStore (builder, convert (ctx, regs [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1747 g_assert_not_reached ();
1750 size -= sizeof (gpointer);
1755 * emit_vtype_to_reg:
1757 * Emit code to load a vtype at address ADDRESS into registers. Store the registers
1758 * into REGS, and the number of registers into NREGS.
1761 emit_vtype_to_reg (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs, guint32 *nregs)
1766 size = get_vtype_size (t);
1768 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1769 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1772 for (j = 0; j < 2; ++j) {
1773 LLVMValueRef index [2], addr;
1774 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1776 if (ainfo->pair_storage [j] == LLVMArgNone)
1779 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1780 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1781 addr = LLVMBuildGEP (builder, address, index, 1, "");
1783 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1784 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1785 addr = LLVMBuildGEP (builder, address, index, 2, "");
1787 switch (ainfo->pair_storage [j]) {
1789 regs [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1794 g_assert_not_reached ();
1796 size -= sizeof (gpointer);
1803 build_alloca_llvm_type (EmitContext *ctx, LLVMTypeRef t, int align)
1806 * Have to place all alloca's at the end of the entry bb, since otherwise they would
1807 * get executed every time control reaches them.
1809 LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1811 ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, t, NULL, align, "");
1812 return ctx->last_alloca;
1816 build_alloca (EmitContext *ctx, MonoType *t)
1818 MonoClass *k = mono_class_from_mono_type (t);
1821 if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1824 align = mono_class_min_align (k);
1826 /* Sometimes align is not a power of 2 */
1827 while (mono_is_power_of_two (align) == -1)
1830 return build_alloca_llvm_type (ctx, type_to_llvm_type (ctx, t), align);
1834 * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1837 mark_as_used (MonoLLVMModule *lmodule, LLVMValueRef global)
1840 lmodule->used = g_ptr_array_sized_new (16);
1841 g_ptr_array_add (lmodule->used, global);
1845 emit_llvm_used (MonoLLVMModule *lmodule)
1847 LLVMModuleRef module = lmodule->module;
1848 LLVMTypeRef used_type;
1849 LLVMValueRef used, *used_elem;
1855 used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), lmodule->used->len);
1856 used = LLVMAddGlobal (module, used_type, "llvm.used");
1857 used_elem = g_new0 (LLVMValueRef, lmodule->used->len);
1858 for (i = 0; i < lmodule->used->len; ++i)
1859 used_elem [i] = LLVMConstBitCast (g_ptr_array_index (lmodule->used, i), LLVMPointerType (LLVMInt8Type (), 0));
1860 LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), used_elem, lmodule->used->len));
1861 LLVMSetLinkage (used, LLVMAppendingLinkage);
1862 LLVMSetSection (used, "llvm.metadata");
1868 * Emit code to load/convert arguments.
1871 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
1874 MonoCompile *cfg = ctx->cfg;
1875 MonoMethodSignature *sig = ctx->sig;
1876 LLVMCallInfo *linfo = ctx->linfo;
1879 ctx->alloca_builder = create_builder (ctx);
1882 * Handle indirect/volatile variables by allocating memory for them
1883 * using 'alloca', and storing their address in a temporary.
1885 for (i = 0; i < cfg->num_varinfo; ++i) {
1886 MonoInst *var = cfg->varinfo [i];
1889 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || mini_type_is_vtype (cfg, var->inst_vtype)) {
1890 vtype = type_to_llvm_type (ctx, var->inst_vtype);
1891 CHECK_FAILURE (ctx);
1892 /* Could be already created by an OP_VPHI */
1893 if (!ctx->addresses [var->dreg])
1894 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
1895 ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
1899 for (i = 0; i < sig->param_count; ++i) {
1900 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
1901 int reg = cfg->args [i + sig->hasthis]->dreg;
1903 if (ainfo->storage == LLVMArgVtypeInReg) {
1904 LLVMValueRef regs [2];
1907 * Emit code to save the argument from the registers to
1908 * the real argument.
1910 pindex = ctx->pindexes [i];
1911 regs [0] = LLVMGetParam (ctx->lmethod, pindex);
1912 if (ainfo->pair_storage [1] != LLVMArgNone)
1913 regs [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
1917 ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1919 emit_reg_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, regs);
1921 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1922 /* Treat these as normal values */
1923 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1925 } else if (ainfo->storage == LLVMArgVtypeByVal) {
1926 ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1928 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1929 /* Treat these as normal values */
1930 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1932 } else if (ainfo->storage == LLVMArgAsIArgs) {
1933 LLVMValueRef arg = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1935 ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1937 /* The argument is received as an array of ints, store it into the real argument */
1938 LLVMBuildStore (ctx->builder, arg, convert (ctx, ctx->addresses [reg], LLVMPointerType (LLVMTypeOf (arg), 0)));
1940 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]));
1945 emit_volatile_store (ctx, cfg->vret_addr->dreg);
1947 emit_volatile_store (ctx, cfg->args [0]->dreg);
1948 for (i = 0; i < sig->param_count; ++i)
1949 if (!mini_type_is_vtype (cfg, sig->params [i]))
1950 emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
1952 if (sig->hasthis && !cfg->rgctx_var && cfg->generic_sharing_context) {
1953 LLVMValueRef this_alloc;
1956 * The exception handling code needs the location where the this argument was
1957 * stored for gshared methods. We create a separate alloca to hold it, and mark it
1958 * with the "mono.this" custom metadata to tell llvm that it needs to save its
1959 * location into the LSDA.
1961 this_alloc = mono_llvm_build_alloca (builder, ThisType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
1962 /* This volatile store will keep the alloca alive */
1963 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE, LLVM_BARRIER_NONE);
1965 set_metadata_flag (this_alloc, "mono.this");
1968 if (cfg->rgctx_var) {
1969 LLVMValueRef rgctx_alloc, store;
1972 * We handle the rgctx arg similarly to the this pointer.
1974 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
1975 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
1976 /* This volatile store will keep the alloca alive */
1977 store = mono_llvm_build_store (builder, convert (ctx, ctx->rgctx_arg, IntPtrType ()), rgctx_alloc, TRUE, LLVM_BARRIER_NONE);
1979 set_metadata_flag (rgctx_alloc, "mono.this");
1983 * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
1984 * it needs to continue normally, or return back to the exception handling system.
1986 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1987 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER))
1988 g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
1989 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER) && bb->in_scount == 0) {
1993 sprintf (name, "finally_ind_bb%d", bb->block_num);
1994 val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
1995 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
1997 ctx->bblocks [bb->block_num].finally_ind = val;
2000 * Create a new bblock which CALL_HANDLER can branch to, because branching to the
2001 * LLVM bblock containing the call to llvm.eh.selector causes problems for the
2002 * LLVM optimizer passes.
2004 sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
2005 ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
2013 /* Have to export this for AOT */
2015 mono_personality (void);
2018 mono_personality (void)
2021 g_assert_not_reached ();
2025 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
2027 MonoCompile *cfg = ctx->cfg;
2028 LLVMModuleRef module = ctx->module;
2029 LLVMValueRef *values = ctx->values;
2030 LLVMValueRef *addresses = ctx->addresses;
2031 MonoCallInst *call = (MonoCallInst*)ins;
2032 MonoMethodSignature *sig = call->signature;
2033 LLVMValueRef callee = NULL, lcall;
2035 LLVMCallInfo *cinfo;
2039 LLVMTypeRef llvm_sig;
2041 gboolean virtual, calli;
2042 LLVMBuilderRef builder = *builder_ref;
2045 if (call->signature->call_convention != MONO_CALL_DEFAULT)
2046 LLVM_FAILURE (ctx, "non-default callconv");
2048 cinfo = call->cinfo;
2049 if (call->rgctx_arg_reg)
2050 cinfo->rgctx_arg = TRUE;
2051 if (call->imt_arg_reg)
2052 cinfo->imt_arg = TRUE;
2054 vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
2056 llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
2057 CHECK_FAILURE (ctx);
2059 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);
2060 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);
2062 /* FIXME: Avoid creating duplicate methods */
2064 if (ins->flags & MONO_INST_HAS_METHOD) {
2068 if (cfg->compile_aot) {
2069 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
2071 LLVM_FAILURE (ctx, "can't encode patch");
2073 callee = LLVMAddFunction (module, "", llvm_sig);
2076 mono_create_jit_trampoline_in_domain (mono_domain_get (),
2078 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2082 if (call->method && strstr (call->method->klass->name, "AsyncVoidMethodBuilder"))
2083 /* LLVM miscompiles async methods */
2084 LLVM_FAILURE (ctx, "#13734");
2087 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
2093 memset (&ji, 0, sizeof (ji));
2094 ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
2095 ji.data.target = info->name;
2097 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
2099 if (cfg->compile_aot) {
2100 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
2102 LLVM_FAILURE (ctx, "can't encode patch");
2104 callee = LLVMAddFunction (module, "", llvm_sig);
2105 target = (gpointer)mono_icall_get_wrapper (info);
2106 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2109 if (cfg->compile_aot) {
2111 if (cfg->abs_patches) {
2112 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2114 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
2116 LLVM_FAILURE (ctx, "can't encode patch");
2120 LLVM_FAILURE (ctx, "aot");
2122 callee = LLVMAddFunction (module, "", llvm_sig);
2124 if (cfg->abs_patches) {
2125 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2128 * FIXME: Some trampolines might have
2129 * their own calling convention on some platforms.
2131 #ifndef TARGET_AMD64
2132 if (abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER || abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER_V4 ||
2133 abs_ji->type == MONO_PATCH_INFO_MONITOR_EXIT || abs_ji->type == MONO_PATCH_INFO_GENERIC_CLASS_INIT)
2134 LLVM_FAILURE (ctx, "trampoline with own cconv");
2136 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
2137 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2141 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, (gpointer)call->fptr);
2147 int size = sizeof (gpointer);
2150 g_assert (ins->inst_offset % size == 0);
2151 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
2153 callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
2155 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
2157 if (ins->flags & MONO_INST_HAS_METHOD) {
2162 * Collect and convert arguments
2164 nargs = (sig->param_count * 2) + sig->hasthis + vretaddr + call->rgctx_reg + call->imt_arg_reg;
2165 len = sizeof (LLVMValueRef) * nargs;
2166 args = alloca (len);
2167 memset (args, 0, len);
2168 l = call->out_ireg_args;
2170 if (call->rgctx_arg_reg) {
2171 g_assert (values [call->rgctx_arg_reg]);
2172 g_assert (sinfo.rgctx_arg_pindex < nargs);
2174 * On ARM, the imt/rgctx argument is passed in a caller save register, but some of our trampolines etc. clobber it, leading to
2175 * problems is LLVM moves the arg assignment earlier. To work around this, save the argument into a stack slot and load
2176 * it using a volatile load.
2179 if (!ctx->imt_rgctx_loc)
2180 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2181 LLVMBuildStore (builder, convert (ctx, ctx->values [call->rgctx_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2182 args [sinfo.rgctx_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2184 args [sinfo.rgctx_arg_pindex] = convert (ctx, values [call->rgctx_arg_reg], ctx->lmodule->ptr_type);
2187 if (call->imt_arg_reg) {
2188 g_assert (values [call->imt_arg_reg]);
2189 g_assert (sinfo.imt_arg_pindex < nargs);
2191 if (!ctx->imt_rgctx_loc)
2192 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2193 LLVMBuildStore (builder, convert (ctx, ctx->values [call->imt_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2194 args [sinfo.imt_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2196 args [sinfo.imt_arg_pindex] = convert (ctx, values [call->imt_arg_reg], ctx->lmodule->ptr_type);
2201 if (!addresses [call->inst.dreg])
2202 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2203 g_assert (sinfo.vret_arg_pindex < nargs);
2204 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2207 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2210 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
2214 pindex = sinfo.this_arg_pindex;
2216 pindex = sinfo.pindexes [i - 1];
2218 pindex = sinfo.pindexes [i];
2221 regpair = (guint32)(gssize)(l->data);
2222 reg = regpair & 0xffffff;
2223 args [pindex] = values [reg];
2224 if (ainfo->storage == LLVMArgVtypeInReg) {
2226 LLVMValueRef regs [2];
2231 g_assert (addresses [reg]);
2233 emit_vtype_to_reg (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, regs, &nregs);
2234 for (j = 0; j < nregs; ++j)
2235 args [pindex ++] = regs [j];
2238 // FIXME: Get rid of the VMOVE
2239 } else if (ainfo->storage == LLVMArgVtypeByVal) {
2240 g_assert (addresses [reg]);
2241 args [pindex] = addresses [reg];
2242 } else if (ainfo->storage == LLVMArgAsIArgs) {
2243 g_assert (addresses [reg]);
2244 args [pindex] = LLVMBuildLoad (ctx->builder, convert (ctx, addresses [reg], LLVMPointerType (LLVMArrayType (IntPtrType (), ainfo->nslots), 0)), "");
2246 g_assert (args [pindex]);
2247 if (i == 0 && sig->hasthis)
2248 args [pindex] = convert (ctx, args [pindex], ThisType ());
2250 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2256 // FIXME: Align call sites
2262 lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2265 * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2267 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2268 g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2270 /* The two can't be used together, so use only one LLVM calling conv to pass them */
2271 g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2273 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2275 if (call->rgctx_arg_reg)
2276 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2277 if (call->imt_arg_reg)
2278 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2280 /* Add byval attributes if needed */
2281 for (i = 0; i < sig->param_count; ++i) {
2282 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2284 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2285 LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2290 * Convert the result
2292 if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
2293 LLVMValueRef regs [2];
2295 if (!addresses [ins->dreg])
2296 addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2298 regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2299 if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2300 regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2302 emit_reg_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2303 } else if (sig->ret->type != MONO_TYPE_VOID && !vretaddr) {
2304 /* If the method returns an unsigned value, need to zext it */
2306 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));
2309 *builder_ref = ctx->builder;
2311 g_free (sinfo.pindexes);
2319 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2321 MonoCompile *cfg = ctx->cfg;
2322 MonoMethodSignature *sig = ctx->sig;
2323 LLVMValueRef method = ctx->lmethod;
2324 LLVMValueRef *values = ctx->values;
2325 LLVMValueRef *addresses = ctx->addresses;
2327 LLVMCallInfo *linfo = ctx->linfo;
2328 LLVMModuleRef module = ctx->module;
2329 BBInfo *bblocks = ctx->bblocks;
2331 LLVMBasicBlockRef cbb;
2332 LLVMBuilderRef builder, starting_builder;
2333 gboolean has_terminator;
2335 LLVMValueRef lhs, rhs;
2338 cbb = get_bb (ctx, bb);
2339 builder = create_builder (ctx);
2340 ctx->builder = builder;
2341 LLVMPositionBuilderAtEnd (builder, cbb);
2343 if (bb == cfg->bb_entry)
2344 emit_entry_bb (ctx, builder);
2345 CHECK_FAILURE (ctx);
2347 if (bb->flags & BB_EXCEPTION_HANDLER) {
2349 LLVMValueRef personality;
2350 LLVMBasicBlockRef target_bb;
2352 static gint32 mapping_inited;
2353 static int ti_generator;
2356 LLVMValueRef type_info;
2359 if (!bblocks [bb->block_num].invoke_target) {
2361 * LLVM asserts if llvm.eh.selector is called from a bblock which
2362 * doesn't have an invoke pointing at it.
2363 * Update: LLVM no longer asserts, but some tests in exceptions.exe now fail.
2365 LLVM_FAILURE (ctx, "handler without invokes");
2368 // <resultval> = landingpad <somety> personality <type> <pers_fn> <clause>+
2370 if (cfg->compile_aot) {
2371 /* Use a dummy personality function */
2372 personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2373 g_assert (personality);
2375 personality = LLVMGetNamedFunction (module, "mono_personality");
2376 if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2377 LLVMAddGlobalMapping (ctx->lmodule->ee, personality, mono_personality);
2380 i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2382 clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2385 * Create the type info
2387 sprintf (ti_name, "type_info_%d", ti_generator);
2390 if (cfg->compile_aot) {
2391 /* decode_eh_frame () in aot-runtime.c will decode this */
2392 type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2393 LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2396 * These symbols are not really used, the clause_index is embedded into the EH tables generated by DwarfMonoException in LLVM.
2398 LLVMSetLinkage (type_info, LLVMInternalLinkage);
2401 * Enabling this causes llc to crash:
2402 * http://llvm.org/bugs/show_bug.cgi?id=6102
2404 //LLVM_FAILURE (ctx, "aot+clauses");
2406 // test_0_invalid_unbox_arrays () fails
2407 LLVM_FAILURE (ctx, "aot+clauses");
2411 * After the cfg mempool is freed, the type info will point to stale memory,
2412 * but this is not a problem, since we decode it once in exception_cb during
2415 ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2416 *(gint32*)ti = clause_index;
2418 type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2420 LLVMAddGlobalMapping (ctx->lmodule->ee, type_info, ti);
2424 LLVMTypeRef members [2], ret_type;
2425 LLVMValueRef landing_pad;
2427 members [0] = i8ptr;
2428 members [1] = LLVMInt32Type ();
2429 ret_type = LLVMStructType (members, 2, FALSE);
2431 landing_pad = LLVMBuildLandingPad (builder, ret_type, personality, 1, "");
2432 LLVMAddClause (landing_pad, type_info);
2434 /* Store the exception into the exvar */
2435 if (bb->in_scount == 1) {
2436 g_assert (bb->in_scount == 1);
2437 exvar = bb->in_stack [0];
2439 // FIXME: This is shared with filter clauses ?
2440 g_assert (!values [exvar->dreg]);
2442 values [exvar->dreg] = LLVMBuildExtractValue (builder, landing_pad, 0, "ex_obj");
2443 emit_volatile_store (ctx, exvar->dreg);
2447 /* Start a new bblock which CALL_HANDLER can branch to */
2448 target_bb = bblocks [bb->block_num].call_handler_target_bb;
2450 LLVMBuildBr (builder, target_bb);
2452 ctx->builder = builder = create_builder (ctx);
2453 LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2455 ctx->bblocks [bb->block_num].end_bblock = target_bb;
2459 has_terminator = FALSE;
2460 starting_builder = builder;
2461 for (ins = bb->code; ins; ins = ins->next) {
2462 const char *spec = LLVM_INS_INFO (ins->opcode);
2464 char dname_buf [128];
2466 emit_dbg_loc (ctx, builder, ins->cil_code);
2469 if (nins > 5000 && builder == starting_builder) {
2470 /* some steps in llc are non-linear in the size of basic blocks, see #5714 */
2471 LLVM_FAILURE (ctx, "basic block too long");
2475 /* There could be instructions after a terminator, skip them */
2478 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2479 sprintf (dname_buf, "t%d", ins->dreg);
2483 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2484 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2486 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2487 lhs = emit_volatile_load (ctx, ins->sreg1);
2489 /* It is ok for SETRET to have an uninitialized argument */
2490 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2491 LLVM_FAILURE (ctx, "sreg1");
2492 lhs = values [ins->sreg1];
2498 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2499 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2500 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2501 rhs = emit_volatile_load (ctx, ins->sreg2);
2503 if (!values [ins->sreg2])
2504 LLVM_FAILURE (ctx, "sreg2");
2505 rhs = values [ins->sreg2];
2511 //mono_print_ins (ins);
2512 switch (ins->opcode) {
2515 case OP_LIVERANGE_START:
2516 case OP_LIVERANGE_END:
2519 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2522 #if SIZEOF_VOID_P == 4
2523 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2525 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2529 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2532 values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2534 case OP_DUMMY_ICONST:
2535 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
2537 case OP_DUMMY_I8CONST:
2538 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
2540 case OP_DUMMY_R8CONST:
2541 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), 0.0f);
2544 LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2545 has_terminator = TRUE;
2551 LLVMBasicBlockRef new_bb;
2552 LLVMBuilderRef new_builder;
2554 // The default branch is already handled
2555 // FIXME: Handle it here
2557 /* Start new bblock */
2558 sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2559 new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2561 lhs = convert (ctx, lhs, LLVMInt32Type ());
2562 v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2563 for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2564 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2566 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2569 new_builder = create_builder (ctx);
2570 LLVMPositionBuilderAtEnd (new_builder, new_bb);
2571 LLVMBuildUnreachable (new_builder);
2573 has_terminator = TRUE;
2574 g_assert (!ins->next);
2580 if (linfo->ret.storage == LLVMArgVtypeInReg) {
2581 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2582 LLVMValueRef part1, retval;
2585 size = get_vtype_size (sig->ret);
2587 g_assert (addresses [ins->sreg1]);
2589 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2590 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2592 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2594 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2596 LLVMBuildRet (builder, retval);
2600 if (linfo->ret.storage == LLVMArgVtypeRetAddr) {
2601 LLVMBuildRetVoid (builder);
2605 if (!lhs || ctx->is_dead [ins->sreg1]) {
2607 * The method did not set its return value, probably because it
2608 * ends with a throw.
2611 LLVMBuildRetVoid (builder);
2613 LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2615 LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2617 has_terminator = TRUE;
2623 case OP_ICOMPARE_IMM:
2624 case OP_LCOMPARE_IMM:
2625 case OP_COMPARE_IMM: {
2629 if (ins->next->opcode == OP_NOP)
2632 if (ins->next->opcode == OP_BR)
2633 /* The comparison result is not needed */
2636 rel = mono_opcode_to_cond (ins->next->opcode);
2638 if (ins->opcode == OP_ICOMPARE_IMM) {
2639 lhs = convert (ctx, lhs, LLVMInt32Type ());
2640 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2642 if (ins->opcode == OP_LCOMPARE_IMM) {
2643 lhs = convert (ctx, lhs, LLVMInt64Type ());
2644 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2646 if (ins->opcode == OP_LCOMPARE) {
2647 lhs = convert (ctx, lhs, LLVMInt64Type ());
2648 rhs = convert (ctx, rhs, LLVMInt64Type ());
2650 if (ins->opcode == OP_ICOMPARE) {
2651 lhs = convert (ctx, lhs, LLVMInt32Type ());
2652 rhs = convert (ctx, rhs, LLVMInt32Type ());
2656 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2657 rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
2658 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
2659 lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
2662 /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
2663 if (ins->opcode == OP_FCOMPARE)
2664 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2665 else if (ins->opcode == OP_COMPARE_IMM) {
2666 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && ins->inst_imm == 0)
2667 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, LLVMConstNull (LLVMTypeOf (lhs)), "");
2669 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
2670 } else if (ins->opcode == OP_LCOMPARE_IMM) {
2671 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg)) {
2672 /* The immediate is encoded in two fields */
2673 guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
2674 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
2676 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
2679 else if (ins->opcode == OP_COMPARE) {
2680 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && LLVMTypeOf (lhs) == LLVMTypeOf (rhs))
2681 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2683 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
2685 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2687 if (MONO_IS_COND_BRANCH_OP (ins->next)) {
2688 if (ins->next->inst_true_bb == ins->next->inst_false_bb) {
2690 * If the target bb contains PHI instructions, LLVM requires
2691 * two PHI entries for this bblock, while we only generate one.
2692 * So convert this to an unconditional bblock. (bxc #171).
2694 LLVMBuildBr (builder, get_bb (ctx, ins->next->inst_true_bb));
2696 LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
2698 has_terminator = TRUE;
2699 } else if (MONO_IS_SETCC (ins->next)) {
2700 sprintf (dname_buf, "t%d", ins->next->dreg);
2702 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2704 /* Add stores for volatile variables */
2705 emit_volatile_store (ctx, ins->next->dreg);
2706 } else if (MONO_IS_COND_EXC (ins->next)) {
2707 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
2708 CHECK_FAILURE (ctx);
2709 builder = ctx->builder;
2711 LLVM_FAILURE (ctx, "next");
2725 rel = mono_opcode_to_cond (ins->opcode);
2727 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2728 values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2736 gboolean empty = TRUE;
2738 /* Check that all input bblocks really branch to us */
2739 for (i = 0; i < bb->in_count; ++i) {
2740 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
2741 ins->inst_phi_args [i + 1] = -1;
2747 /* LLVM doesn't like phi instructions with zero operands */
2748 ctx->is_dead [ins->dreg] = TRUE;
2752 /* Created earlier, insert it now */
2753 LLVMInsertIntoBuilder (builder, values [ins->dreg]);
2755 for (i = 0; i < ins->inst_phi_args [0]; i++) {
2756 int sreg1 = ins->inst_phi_args [i + 1];
2760 * Count the number of times the incoming bblock branches to us,
2761 * since llvm requires a separate entry for each.
2763 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
2764 MonoInst *switch_ins = bb->in_bb [i]->last_ins;
2767 for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
2768 if (switch_ins->inst_many_bb [j] == bb)
2775 /* Remember for later */
2776 for (j = 0; j < count; ++j) {
2777 PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
2780 node->in_bb = bb->in_bb [i];
2782 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);
2792 values [ins->dreg] = lhs;
2795 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
2798 values [ins->dreg] = lhs;
2800 if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
2802 * This is added by the spilling pass in case of the JIT,
2803 * but we have to do it ourselves.
2805 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
2839 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2840 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2842 switch (ins->opcode) {
2845 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
2849 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
2853 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
2857 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
2861 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
2865 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
2869 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
2872 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
2876 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
2880 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
2884 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
2888 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
2892 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
2896 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
2900 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
2903 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
2906 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
2910 g_assert_not_reached ();
2917 case OP_IREM_UN_IMM:
2919 case OP_IDIV_UN_IMM:
2925 case OP_ISHR_UN_IMM:
2934 case OP_LSHR_UN_IMM:
2940 case OP_SHR_UN_IMM: {
2943 if (spec [MONO_INST_SRC1] == 'l') {
2944 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2946 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2949 #if SIZEOF_VOID_P == 4
2950 if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
2951 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2954 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2955 lhs = convert (ctx, lhs, IntPtrType ());
2956 imm = convert (ctx, imm, LLVMTypeOf (lhs));
2957 switch (ins->opcode) {
2961 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
2965 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
2969 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
2973 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
2975 case OP_IDIV_UN_IMM:
2976 case OP_LDIV_UN_IMM:
2977 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
2981 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
2983 case OP_IREM_UN_IMM:
2984 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
2989 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
2993 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
2997 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
3002 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
3007 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
3009 case OP_ISHR_UN_IMM:
3010 /* This is used to implement conv.u4, so the lhs could be an i8 */
3011 lhs = convert (ctx, lhs, LLVMInt32Type ());
3012 imm = convert (ctx, imm, LLVMInt32Type ());
3013 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3015 case OP_LSHR_UN_IMM:
3017 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3020 g_assert_not_reached ();
3025 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3028 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
3031 lhs = convert (ctx, lhs, LLVMDoubleType ());
3032 values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
3035 guint32 v = 0xffffffff;
3036 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3040 guint64 v = 0xffffffffffffffffLL;
3041 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
3044 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3046 LLVMValueRef v1, v2;
3048 v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
3049 v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
3050 values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
3055 case OP_ICONV_TO_I1:
3056 case OP_ICONV_TO_I2:
3057 case OP_ICONV_TO_I4:
3058 case OP_ICONV_TO_U1:
3059 case OP_ICONV_TO_U2:
3060 case OP_ICONV_TO_U4:
3061 case OP_LCONV_TO_I1:
3062 case OP_LCONV_TO_I2:
3063 case OP_LCONV_TO_U1:
3064 case OP_LCONV_TO_U2:
3065 case OP_LCONV_TO_U4: {
3068 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);
3070 /* Have to do two casts since our vregs have type int */
3071 v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
3073 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
3075 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
3078 case OP_ICONV_TO_I8:
3079 values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
3081 case OP_ICONV_TO_U8:
3082 values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
3084 case OP_FCONV_TO_I4:
3085 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
3087 case OP_FCONV_TO_I1:
3088 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3090 case OP_FCONV_TO_U1:
3091 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3093 case OP_FCONV_TO_I2:
3094 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3096 case OP_FCONV_TO_U2:
3097 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3099 case OP_FCONV_TO_I8:
3100 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
3103 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
3105 case OP_ICONV_TO_R8:
3106 case OP_LCONV_TO_R8:
3107 values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
3109 case OP_LCONV_TO_R_UN:
3110 values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
3112 #if SIZEOF_VOID_P == 4
3115 case OP_LCONV_TO_I4:
3116 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3118 case OP_ICONV_TO_R4:
3119 case OP_LCONV_TO_R4:
3120 v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
3121 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3123 case OP_FCONV_TO_R4:
3124 v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
3125 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3128 values [ins->dreg] = LLVMBuildSExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3131 values [ins->dreg] = LLVMBuildZExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3134 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3136 case OP_LOCALLOC_IMM: {
3139 guint32 size = ins->inst_imm;
3140 size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3142 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
3144 if (ins->flags & MONO_INST_INIT) {
3145 LLVMValueRef args [5];
3148 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3149 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
3150 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3151 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3152 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3155 values [ins->dreg] = v;
3159 LLVMValueRef v, size;
3161 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), "");
3163 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
3165 if (ins->flags & MONO_INST_INIT) {
3166 LLVMValueRef args [5];
3169 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3171 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3172 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3173 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3175 values [ins->dreg] = v;
3179 case OP_LOADI1_MEMBASE:
3180 case OP_LOADU1_MEMBASE:
3181 case OP_LOADI2_MEMBASE:
3182 case OP_LOADU2_MEMBASE:
3183 case OP_LOADI4_MEMBASE:
3184 case OP_LOADU4_MEMBASE:
3185 case OP_LOADI8_MEMBASE:
3186 case OP_LOADR4_MEMBASE:
3187 case OP_LOADR8_MEMBASE:
3188 case OP_LOAD_MEMBASE:
3196 LLVMValueRef base, index, addr;
3198 gboolean sext = FALSE, zext = FALSE;
3199 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3201 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3206 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)) {
3207 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
3212 if (ins->inst_offset == 0) {
3214 } else if (ins->inst_offset % size != 0) {
3215 /* Unaligned load */
3216 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3217 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3219 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3220 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (t, 0)), &index, 1, "");
3224 addr = convert (ctx, addr, LLVMPointerType (t, 0));
3226 values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
3228 if (!is_volatile && (ins->flags & MONO_INST_INVARIANT_LOAD)) {
3230 * These will signal LLVM that these loads do not alias any stores, and
3231 * they can't fail, allowing them to be hoisted out of loops.
3233 set_invariant_load_flag (values [ins->dreg]);
3234 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
3238 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3240 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3241 else if (ins->opcode == OP_LOADR4_MEMBASE)
3242 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
3246 case OP_STOREI1_MEMBASE_REG:
3247 case OP_STOREI2_MEMBASE_REG:
3248 case OP_STOREI4_MEMBASE_REG:
3249 case OP_STOREI8_MEMBASE_REG:
3250 case OP_STORER4_MEMBASE_REG:
3251 case OP_STORER8_MEMBASE_REG:
3252 case OP_STORE_MEMBASE_REG: {
3254 LLVMValueRef index, addr;
3256 gboolean sext = FALSE, zext = FALSE;
3257 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3259 if (!values [ins->inst_destbasereg])
3260 LLVM_FAILURE (ctx, "inst_destbasereg");
3262 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3264 if (ins->inst_offset % size != 0) {
3265 /* Unaligned store */
3266 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3267 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3269 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3270 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3272 emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3276 case OP_STOREI1_MEMBASE_IMM:
3277 case OP_STOREI2_MEMBASE_IMM:
3278 case OP_STOREI4_MEMBASE_IMM:
3279 case OP_STOREI8_MEMBASE_IMM:
3280 case OP_STORE_MEMBASE_IMM: {
3282 LLVMValueRef index, addr;
3284 gboolean sext = FALSE, zext = FALSE;
3285 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3287 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3289 if (ins->inst_offset % size != 0) {
3290 /* Unaligned store */
3291 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3292 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3294 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3295 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3297 emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3302 emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, lhs, LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3304 case OP_OUTARG_VTRETADDR:
3311 case OP_VOIDCALL_MEMBASE:
3312 case OP_CALL_MEMBASE:
3313 case OP_LCALL_MEMBASE:
3314 case OP_FCALL_MEMBASE:
3315 case OP_VCALL_MEMBASE:
3316 case OP_VOIDCALL_REG:
3320 case OP_VCALL_REG: {
3321 process_call (ctx, bb, &builder, ins);
3322 CHECK_FAILURE (ctx);
3327 LLVMValueRef indexes [2];
3329 LLVMValueRef got_entry_addr;
3332 * FIXME: Can't allocate from the cfg mempool since that is freed if
3333 * the LLVM compile fails.
3335 ji = g_new0 (MonoJumpInfo, 1);
3336 ji->type = (MonoJumpInfoType)ins->inst_i1;
3337 ji->data.target = ins->inst_p0;
3339 ji = mono_aot_patch_info_dup (ji);
3341 ji->next = cfg->patch_info;
3342 cfg->patch_info = ji;
3344 //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3345 got_offset = mono_aot_get_got_offset (cfg->patch_info);
3346 ctx->lmodule->max_got_offset = MAX (ctx->lmodule->max_got_offset, got_offset);
3348 indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3349 indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3350 got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3352 values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3353 set_invariant_load_flag (values [ins->dreg]);
3356 case OP_NOT_REACHED:
3357 LLVMBuildUnreachable (builder);
3358 has_terminator = TRUE;
3359 g_assert (bb->block_num < cfg->max_block_num);
3360 ctx->unreachable [bb->block_num] = TRUE;
3361 /* Might have instructions after this */
3363 MonoInst *next = ins->next;
3365 * FIXME: If later code uses the regs defined by these instructions,
3366 * compilation will fail.
3368 MONO_DELETE_INS (bb, next);
3372 MonoInst *var = ins->inst_p0;
3374 values [ins->dreg] = addresses [var->dreg];
3378 LLVMValueRef args [1];
3380 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3381 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3385 LLVMValueRef args [1];
3387 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3388 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3392 LLVMValueRef args [1];
3395 /* This no longer seems to happen */
3397 * LLVM optimizes sqrt(nan) into undefined in
3398 * lib/Analysis/ConstantFolding.cpp
3399 * Also, sqrt(NegativeInfinity) is optimized into 0.
3401 LLVM_FAILURE (ctx, "sqrt");
3403 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3404 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3408 LLVMValueRef args [1];
3410 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3411 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3425 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3426 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3428 switch (ins->opcode) {
3431 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3435 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3439 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3443 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3446 g_assert_not_reached ();
3449 values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3452 case OP_ATOMIC_EXCHANGE_I4:
3453 case OP_ATOMIC_EXCHANGE_I8: {
3454 LLVMValueRef args [2];
3457 if (ins->opcode == OP_ATOMIC_EXCHANGE_I4)
3458 t = LLVMInt32Type ();
3460 t = LLVMInt64Type ();
3462 g_assert (ins->inst_offset == 0);
3464 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3465 args [1] = convert (ctx, rhs, t);
3467 values [ins->dreg] = mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_XCHG, args [0], args [1]);
3470 case OP_ATOMIC_ADD_I4:
3471 case OP_ATOMIC_ADD_I8: {
3472 LLVMValueRef args [2];
3475 if (ins->opcode == OP_ATOMIC_ADD_I4)
3476 t = LLVMInt32Type ();
3478 t = LLVMInt64Type ();
3480 g_assert (ins->inst_offset == 0);
3482 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3483 args [1] = convert (ctx, rhs, t);
3484 values [ins->dreg] = LLVMBuildAdd (builder, mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_ADD, args [0], args [1]), args [1], dname);
3487 case OP_ATOMIC_CAS_I4:
3488 case OP_ATOMIC_CAS_I8: {
3489 LLVMValueRef args [3], val;
3492 if (ins->opcode == OP_ATOMIC_CAS_I4)
3493 t = LLVMInt32Type ();
3495 t = LLVMInt64Type ();
3497 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3499 args [1] = convert (ctx, values [ins->sreg3], t);
3501 args [2] = convert (ctx, values [ins->sreg2], t);
3502 val = mono_llvm_build_cmpxchg (builder, args [0], args [1], args [2]);
3503 #if LLVM_API_VERSION >= 1
3504 /* cmpxchg returns a pair */
3505 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, "");
3507 values [ins->dreg] = val;
3511 case OP_MEMORY_BARRIER: {
3512 mono_llvm_build_fence (builder, (BarrierKind) ins->backend.memory_barrier_kind);
3515 case OP_ATOMIC_LOAD_I1:
3516 case OP_ATOMIC_LOAD_I2:
3517 case OP_ATOMIC_LOAD_I4:
3518 case OP_ATOMIC_LOAD_I8:
3519 case OP_ATOMIC_LOAD_U1:
3520 case OP_ATOMIC_LOAD_U2:
3521 case OP_ATOMIC_LOAD_U4:
3522 case OP_ATOMIC_LOAD_U8:
3523 case OP_ATOMIC_LOAD_R4:
3524 case OP_ATOMIC_LOAD_R8: {
3525 #if LLVM_API_VERSION >= 4
3527 gboolean sext, zext;
3529 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3530 BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
3531 LLVMValueRef index, addr;
3533 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3538 if (ins->inst_offset != 0) {
3539 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3540 addr = LLVMBuildGEP (builder, convert (ctx, lhs, LLVMPointerType (t, 0)), &index, 1, "");
3545 addr = convert (ctx, addr, LLVMPointerType (t, 0));
3547 values [ins->dreg] = emit_load_general (ctx, bb, &builder, size, addr, dname, is_volatile, barrier);
3550 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3552 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3554 LLVM_FAILURE (ctx, "atomic mono.load intrinsic");
3558 case OP_ATOMIC_STORE_I1:
3559 case OP_ATOMIC_STORE_I2:
3560 case OP_ATOMIC_STORE_I4:
3561 case OP_ATOMIC_STORE_I8:
3562 case OP_ATOMIC_STORE_U1:
3563 case OP_ATOMIC_STORE_U2:
3564 case OP_ATOMIC_STORE_U4:
3565 case OP_ATOMIC_STORE_U8:
3566 case OP_ATOMIC_STORE_R4:
3567 case OP_ATOMIC_STORE_R8: {
3568 #if LLVM_API_VERSION >= 4
3570 gboolean sext, zext;
3572 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3573 BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
3574 LLVMValueRef index, addr, value;
3576 if (!values [ins->inst_destbasereg])
3577 LLVM_FAILURE (ctx, "inst_destbasereg");
3579 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3581 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3582 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3583 value = convert (ctx, values [ins->sreg1], t);
3585 emit_store_general (ctx, bb, &builder, size, value, addr, is_volatile, barrier);
3588 LLVM_FAILURE (ctx, "atomic mono.store intrinsic");
3592 case OP_RELAXED_NOP: {
3593 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3594 emit_call (ctx, bb, &builder, LLVMGetNamedFunction (ctx->module, "llvm.x86.sse2.pause"), NULL, 0);
3601 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(__linux__)
3603 // 257 == FS segment register
3604 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
3606 // 256 == GS segment register
3607 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3610 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
3611 #elif defined(TARGET_AMD64) && defined(TARGET_OSX)
3612 /* See mono_amd64_emit_tls_get () */
3613 int offset = mono_amd64_get_tls_gs_offset () + (ins->inst_offset * 8);
3615 // 256 == GS segment register
3616 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3617 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), offset, TRUE), ptrtype, ""), "");
3619 LLVM_FAILURE (ctx, "opcode tls-get");
3624 case OP_TLS_GET_REG: {
3625 #if defined(TARGET_AMD64) && defined(TARGET_OSX)
3626 /* See emit_tls_get_reg () */
3627 // 256 == GS segment register
3628 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3629 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, convert (ctx, lhs, LLVMInt32Type ()), ptrtype, ""), "");
3631 LLVM_FAILURE (ctx, "opcode tls-get");
3640 case OP_IADD_OVF_UN:
3642 case OP_ISUB_OVF_UN:
3644 case OP_IMUL_OVF_UN:
3645 #if SIZEOF_VOID_P == 8
3647 case OP_LADD_OVF_UN:
3649 case OP_LSUB_OVF_UN:
3651 case OP_LMUL_OVF_UN:
3654 LLVMValueRef args [2], val, ovf, func;
3656 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
3657 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
3658 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
3660 val = LLVMBuildCall (builder, func, args, 2, "");
3661 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
3662 ovf = LLVMBuildExtractValue (builder, val, 1, "");
3663 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
3664 CHECK_FAILURE (ctx);
3665 builder = ctx->builder;
3671 * We currently model them using arrays. Promotion to local vregs is
3672 * disabled for them in mono_handle_global_vregs () in the LLVM case,
3673 * so we always have an entry in cfg->varinfo for them.
3674 * FIXME: Is this needed ?
3677 MonoClass *klass = ins->klass;
3678 LLVMValueRef args [5];
3682 LLVM_FAILURE (ctx, "!klass");
3686 if (!addresses [ins->dreg])
3687 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3688 args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3689 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3690 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3692 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3693 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3694 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3697 case OP_DUMMY_VZERO:
3700 case OP_STOREV_MEMBASE:
3701 case OP_LOADV_MEMBASE:
3703 MonoClass *klass = ins->klass;
3704 LLVMValueRef src = NULL, dst, args [5];
3705 gboolean done = FALSE;
3709 LLVM_FAILURE (ctx, "!klass");
3713 if (mini_is_gsharedvt_klass (cfg, klass)) {
3715 LLVM_FAILURE (ctx, "gsharedvt");
3719 switch (ins->opcode) {
3720 case OP_STOREV_MEMBASE:
3721 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg &&
3722 LLVMGetInstructionOpcode (values [ins->inst_destbasereg]) != LLVMAlloca) {
3723 /* Decomposed earlier */
3724 g_assert_not_reached ();
3727 if (!addresses [ins->sreg1]) {
3729 g_assert (values [ins->sreg1]);
3730 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));
3731 LLVMBuildStore (builder, values [ins->sreg1], dst);
3734 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3735 dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3738 case OP_LOADV_MEMBASE:
3739 if (!addresses [ins->dreg])
3740 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3741 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3742 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3745 if (!addresses [ins->sreg1])
3746 addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
3747 if (!addresses [ins->dreg])
3748 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3749 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3750 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3753 g_assert_not_reached ();
3755 CHECK_FAILURE (ctx);
3762 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3763 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3765 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3766 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3767 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
3770 case OP_LLVM_OUTARG_VT:
3771 if (!addresses [ins->sreg1]) {
3772 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
3773 g_assert (values [ins->sreg1]);
3774 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
3776 addresses [ins->dreg] = addresses [ins->sreg1];
3782 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3784 values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
3787 case OP_LOADX_MEMBASE: {
3788 LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
3791 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3792 values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
3795 case OP_STOREX_MEMBASE: {
3796 LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
3799 dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3800 mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
3807 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
3811 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
3817 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
3821 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
3825 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
3829 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
3832 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
3835 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
3838 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
3842 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, "");
3853 LLVMValueRef v = NULL;
3855 switch (ins->opcode) {
3860 t = LLVMVectorType (LLVMInt32Type (), 4);
3861 rt = LLVMVectorType (LLVMFloatType (), 4);
3867 t = LLVMVectorType (LLVMInt64Type (), 2);
3868 rt = LLVMVectorType (LLVMDoubleType (), 2);
3871 t = LLVMInt32Type ();
3872 rt = LLVMInt32Type ();
3873 g_assert_not_reached ();
3876 lhs = LLVMBuildBitCast (builder, lhs, t, "");
3877 rhs = LLVMBuildBitCast (builder, rhs, t, "");
3878 switch (ins->opcode) {
3881 v = LLVMBuildAnd (builder, lhs, rhs, "");
3885 v = LLVMBuildOr (builder, lhs, rhs, "");
3889 v = LLVMBuildXor (builder, lhs, rhs, "");
3893 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
3896 values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
3920 case OP_PADDB_SAT_UN:
3921 case OP_PADDW_SAT_UN:
3922 case OP_PSUBB_SAT_UN:
3923 case OP_PSUBW_SAT_UN:
3931 case OP_PMULW_HIGH_UN: {
3932 LLVMValueRef args [2];
3937 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3944 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntEQ, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3948 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntSGT, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3956 case OP_EXTRACTX_U2:
3958 case OP_EXTRACT_U1: {
3960 gboolean zext = FALSE;
3962 t = simd_op_to_llvm_type (ins->opcode);
3964 switch (ins->opcode) {
3972 case OP_EXTRACTX_U2:
3977 t = LLVMInt32Type ();
3978 g_assert_not_reached ();
3981 lhs = LLVMBuildBitCast (builder, lhs, t, "");
3982 values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
3984 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
3993 case OP_EXPAND_R8: {
3994 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
3995 LLVMValueRef mask [16], v;
3997 for (i = 0; i < 16; ++i)
3998 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4000 v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
4002 values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4003 values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
4008 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt8Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4011 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt16Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4014 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4017 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt64Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4020 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMFloatType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4023 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMDoubleType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4034 case OP_EXTRACT_MASK:
4041 v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
4043 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
4047 case OP_ICONV_TO_R8_RAW:
4048 /* Same as OP_ICONV_TO_R8 */
4049 values [ins->dreg] = convert (ctx, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType ());
4054 LLVMValueRef args [3];
4058 args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
4060 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
4065 /* This is only used for implementing shifts by non-immediate */
4066 values [ins->dreg] = lhs;
4077 LLVMValueRef args [3];
4080 args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
4082 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4093 case OP_PSHLQ_REG: {
4094 LLVMValueRef args [3];
4097 args [1] = values [ins->sreg2];
4099 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4106 case OP_PSHUFLEW_LOW:
4107 case OP_PSHUFLEW_HIGH: {
4109 LLVMValueRef v1 = NULL, v2 = NULL, mask_values [16];
4110 int i, mask_size = 0;
4111 int imask = ins->inst_c0;
4113 /* Convert the x86 shuffle mask to LLVM's */
4114 switch (ins->opcode) {
4117 mask [0] = ((imask >> 0) & 3);
4118 mask [1] = ((imask >> 2) & 3);
4119 mask [2] = ((imask >> 4) & 3) + 4;
4120 mask [3] = ((imask >> 6) & 3) + 4;
4121 v1 = values [ins->sreg1];
4122 v2 = values [ins->sreg2];
4126 mask [0] = ((imask >> 0) & 1);
4127 mask [1] = ((imask >> 1) & 1) + 2;
4128 v1 = values [ins->sreg1];
4129 v2 = values [ins->sreg2];
4131 case OP_PSHUFLEW_LOW:
4133 mask [0] = ((imask >> 0) & 3);
4134 mask [1] = ((imask >> 2) & 3);
4135 mask [2] = ((imask >> 4) & 3);
4136 mask [3] = ((imask >> 6) & 3);
4141 v1 = values [ins->sreg1];
4142 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4144 case OP_PSHUFLEW_HIGH:
4150 mask [4] = 4 + ((imask >> 0) & 3);
4151 mask [5] = 4 + ((imask >> 2) & 3);
4152 mask [6] = 4 + ((imask >> 4) & 3);
4153 mask [7] = 4 + ((imask >> 6) & 3);
4154 v1 = values [ins->sreg1];
4155 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4159 mask [0] = ((imask >> 0) & 3);
4160 mask [1] = ((imask >> 2) & 3);
4161 mask [2] = ((imask >> 4) & 3);
4162 mask [3] = ((imask >> 6) & 3);
4163 v1 = values [ins->sreg1];
4164 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4167 g_assert_not_reached ();
4169 for (i = 0; i < mask_size; ++i)
4170 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4172 values [ins->dreg] =
4173 LLVMBuildShuffleVector (builder, v1, v2,
4174 LLVMConstVector (mask_values, mask_size), dname);
4178 case OP_UNPACK_LOWB:
4179 case OP_UNPACK_LOWW:
4180 case OP_UNPACK_LOWD:
4181 case OP_UNPACK_LOWQ:
4182 case OP_UNPACK_LOWPS:
4183 case OP_UNPACK_LOWPD:
4184 case OP_UNPACK_HIGHB:
4185 case OP_UNPACK_HIGHW:
4186 case OP_UNPACK_HIGHD:
4187 case OP_UNPACK_HIGHQ:
4188 case OP_UNPACK_HIGHPS:
4189 case OP_UNPACK_HIGHPD: {
4191 LLVMValueRef mask_values [16];
4192 int i, mask_size = 0;
4193 gboolean low = FALSE;
4195 switch (ins->opcode) {
4196 case OP_UNPACK_LOWB:
4200 case OP_UNPACK_LOWW:
4204 case OP_UNPACK_LOWD:
4205 case OP_UNPACK_LOWPS:
4209 case OP_UNPACK_LOWQ:
4210 case OP_UNPACK_LOWPD:
4214 case OP_UNPACK_HIGHB:
4217 case OP_UNPACK_HIGHW:
4220 case OP_UNPACK_HIGHD:
4221 case OP_UNPACK_HIGHPS:
4224 case OP_UNPACK_HIGHQ:
4225 case OP_UNPACK_HIGHPD:
4229 g_assert_not_reached ();
4233 for (i = 0; i < (mask_size / 2); ++i) {
4235 mask [(i * 2) + 1] = mask_size + i;
4238 for (i = 0; i < (mask_size / 2); ++i) {
4239 mask [(i * 2)] = (mask_size / 2) + i;
4240 mask [(i * 2) + 1] = mask_size + (mask_size / 2) + i;
4244 for (i = 0; i < mask_size; ++i)
4245 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4247 values [ins->dreg] =
4248 LLVMBuildShuffleVector (builder, values [ins->sreg1], values [ins->sreg2],
4249 LLVMConstVector (mask_values, mask_size), dname);
4254 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4255 LLVMValueRef v, val;
4257 v = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4258 val = LLVMConstNull (t);
4259 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4260 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 1, FALSE), dname);
4262 values [ins->dreg] = val;
4266 case OP_DUPPS_HIGH: {
4267 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4268 LLVMValueRef v1, v2, val;
4271 if (ins->opcode == OP_DUPPS_LOW) {
4272 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4273 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4275 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4276 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4278 val = LLVMConstNull (t);
4279 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4280 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4281 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4282 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4284 values [ins->dreg] = val;
4294 * EXCEPTION HANDLING
4296 case OP_IMPLICIT_EXCEPTION:
4297 /* This marks a place where an implicit exception can happen */
4298 if (bb->region != -1)
4299 LLVM_FAILURE (ctx, "implicit-exception");
4303 MonoMethodSignature *throw_sig;
4304 LLVMValueRef callee, arg;
4305 gboolean rethrow = (ins->opcode == OP_RETHROW);
4306 const char *icall_name;
4308 callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
4309 icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
4312 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
4313 throw_sig->ret = &mono_get_void_class ()->byval_arg;
4314 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
4315 if (cfg->compile_aot) {
4316 callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
4318 callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
4322 * LLVM doesn't push the exception argument, so we need a different
4325 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
4327 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
4331 mono_memory_barrier ();
4333 ctx->lmodule->rethrow = callee;
4335 ctx->lmodule->throw = callee;
4337 arg = convert (ctx, lhs, type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
4338 emit_call (ctx, bb, &builder, callee, &arg, 1);
4341 case OP_CALL_HANDLER: {
4343 * We don't 'call' handlers, but instead simply branch to them.
4344 * The code generated by ENDFINALLY will branch back to us.
4346 LLVMBasicBlockRef noex_bb;
4348 BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
4350 bb_list = info->call_handler_return_bbs;
4353 * Set the indicator variable for the finally clause.
4355 lhs = info->finally_ind;
4357 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
4359 /* Branch to the finally clause */
4360 LLVMBuildBr (builder, info->call_handler_target_bb);
4362 noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
4363 info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
4365 builder = ctx->builder = create_builder (ctx);
4366 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
4368 bblocks [bb->block_num].end_bblock = noex_bb;
4371 case OP_START_HANDLER: {
4374 case OP_ENDFINALLY: {
4375 LLVMBasicBlockRef resume_bb;
4376 MonoBasicBlock *handler_bb;
4377 LLVMValueRef val, switch_ins, callee;
4381 handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
4382 g_assert (handler_bb);
4383 info = &bblocks [handler_bb->block_num];
4384 lhs = info->finally_ind;
4387 bb_list = info->call_handler_return_bbs;
4389 resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
4391 /* Load the finally variable */
4392 val = LLVMBuildLoad (builder, lhs, "");
4394 /* Reset the variable */
4395 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
4397 /* Branch to either resume_bb, or to the bblocks in bb_list */
4398 switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
4400 * The other targets are added at the end to handle OP_CALL_HANDLER
4401 * opcodes processed later.
4403 info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
4405 builder = ctx->builder = create_builder (ctx);
4406 LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
4408 if (ctx->cfg->compile_aot) {
4409 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
4411 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
4413 LLVMBuildCall (builder, callee, NULL, 0, "");
4415 LLVMBuildUnreachable (builder);
4416 has_terminator = TRUE;
4422 sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
4423 LLVM_FAILURE (ctx, reason);
4428 /* Convert the value to the type required by phi nodes */
4429 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
4430 if (!values [ins->dreg])
4432 values [ins->dreg] = addresses [ins->dreg];
4434 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
4437 /* Add stores for volatile variables */
4438 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
4439 emit_volatile_store (ctx, ins->dreg);
4442 if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
4443 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
4445 if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID) {
4446 emit_dbg_loc (ctx, builder, cfg->header->code + cfg->header->code_size - 1);
4447 LLVMBuildRetVoid (builder);
4450 if (bb == cfg->bb_entry)
4451 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
4460 * mono_llvm_check_method_supported:
4462 * Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
4463 * compiling a method twice.
4466 mono_llvm_check_method_supported (MonoCompile *cfg)
4468 MonoMethodHeader *header = cfg->header;
4469 MonoExceptionClause *clause;
4472 if (cfg->method->save_lmf) {
4473 cfg->exception_message = g_strdup ("lmf");
4474 cfg->disable_llvm = TRUE;
4476 if (cfg->disable_llvm)
4480 for (i = 0; i < header->num_clauses; ++i) {
4481 clause = &header->clauses [i];
4483 if (i > 0 && clause->try_offset <= header->clauses [i - 1].handler_offset + header->clauses [i - 1].handler_len) {
4485 * FIXME: Some tests still fail with nested clauses.
4487 cfg->exception_message = g_strdup ("nested clauses");
4488 cfg->disable_llvm = TRUE;
4492 if (cfg->disable_llvm)
4497 if (cfg->method->dynamic) {
4498 cfg->exception_message = g_strdup ("dynamic.");
4499 cfg->disable_llvm = TRUE;
4501 if (cfg->disable_llvm)
4506 * mono_llvm_emit_method:
4508 * Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
4511 mono_llvm_emit_method (MonoCompile *cfg)
4514 MonoMethodSignature *sig;
4516 LLVMTypeRef method_type;
4517 LLVMValueRef method = NULL;
4519 LLVMValueRef *values;
4520 int i, max_block_num, bb_index;
4521 gboolean last = FALSE;
4522 GPtrArray *phi_values;
4523 LLVMCallInfo *linfo;
4525 LLVMModuleRef module;
4527 GPtrArray *bblock_list;
4528 MonoMethodHeader *header;
4529 MonoExceptionClause *clause;
4533 /* The code below might acquire the loader lock, so use it for global locking */
4534 mono_loader_lock ();
4536 /* Used to communicate with the callbacks */
4537 mono_native_tls_set_value (current_cfg_tls_id, cfg);
4539 ctx = g_new0 (EmitContext, 1);
4541 ctx->mempool = cfg->mempool;
4544 * This maps vregs to the LLVM instruction defining them
4546 values = g_new0 (LLVMValueRef, cfg->next_vreg);
4548 * This maps vregs for volatile variables to the LLVM instruction defining their
4551 ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
4552 ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
4553 ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
4554 phi_values = g_ptr_array_sized_new (256);
4556 * This signals whenever the vreg was defined by a phi node with no input vars
4557 * (i.e. all its input bblocks end with NOT_REACHABLE).
4559 ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
4560 /* Whenever the bblock is unreachable */
4561 ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
4563 bblock_list = g_ptr_array_sized_new (256);
4565 ctx->values = values;
4566 ctx->region_to_handler = g_hash_table_new (NULL, NULL);
4568 if (cfg->compile_aot) {
4569 ctx->lmodule = &aot_module;
4570 method_name = mono_aot_get_method_name (cfg);
4571 cfg->llvm_method_name = g_strdup (method_name);
4573 init_jit_module (cfg->domain);
4574 ctx->lmodule = domain_jit_info (cfg->domain)->llvm_module;
4575 method_name = mono_method_full_name (cfg->method, TRUE);
4578 module = ctx->module = ctx->lmodule->module;
4581 LLVM_FAILURE (ctx, "gsharedvt");
4585 static int count = 0;
4588 if (g_getenv ("LLVM_COUNT")) {
4589 if (count == atoi (g_getenv ("LLVM_COUNT"))) {
4590 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4594 if (count > atoi (g_getenv ("LLVM_COUNT")))
4595 LLVM_FAILURE (ctx, "");
4600 sig = mono_method_signature (cfg->method);
4603 linfo = mono_arch_get_llvm_call_info (cfg, sig);
4605 CHECK_FAILURE (ctx);
4608 linfo->rgctx_arg = TRUE;
4609 method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
4610 CHECK_FAILURE (ctx);
4613 * This maps parameter indexes in the original signature to the indexes in
4614 * the LLVM signature.
4616 ctx->pindexes = sinfo.pindexes;
4618 method = LLVMAddFunction (module, method_name, method_type);
4619 ctx->lmethod = method;
4621 LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
4622 LLVMSetLinkage (method, LLVMPrivateLinkage);
4624 LLVMAddFunctionAttr (method, LLVMUWTable);
4626 if (cfg->compile_aot) {
4627 LLVMSetLinkage (method, LLVMInternalLinkage);
4628 #if LLVM_API_VERSION == 0
4629 /* This causes an assertion in later LLVM versions */
4630 LLVMSetVisibility (method, LLVMHiddenVisibility);
4632 if (ctx->lmodule->external_symbols) {
4633 LLVMSetLinkage (method, LLVMExternalLinkage);
4634 LLVMSetVisibility (method, LLVMHiddenVisibility);
4637 LLVMSetLinkage (method, LLVMPrivateLinkage);
4640 if (cfg->method->save_lmf)
4641 LLVM_FAILURE (ctx, "lmf");
4643 if (sig->pinvoke && cfg->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
4644 LLVM_FAILURE (ctx, "pinvoke signature");
4646 header = cfg->header;
4647 for (i = 0; i < header->num_clauses; ++i) {
4648 clause = &header->clauses [i];
4649 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
4650 LLVM_FAILURE (ctx, "non-finally/catch clause.");
4653 if (linfo->rgctx_arg) {
4654 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
4656 * We mark the rgctx parameter with the inreg attribute, which is mapped to
4657 * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
4658 * CC_X86_64_Mono in X86CallingConv.td.
4660 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
4661 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
4663 if (cfg->vret_addr) {
4664 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
4665 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
4668 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
4669 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
4672 names = g_new (char *, sig->param_count);
4673 mono_method_get_param_names (cfg->method, (const char **) names);
4675 for (i = 0; i < sig->param_count; ++i) {
4678 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
4679 if (names [i] && names [i][0] != '\0')
4680 name = g_strdup_printf ("arg_%s", names [i]);
4682 name = g_strdup_printf ("arg_%d", i);
4683 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
4685 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
4686 LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
4690 if (ctx->lmodule->emit_dwarf && cfg->compile_aot && mono_debug_enabled ()) {
4691 ctx->minfo = mono_debug_lookup_method (cfg->method);
4692 ctx->dbg_md = emit_dbg_subprogram (ctx, cfg, method, method_name);
4696 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4697 max_block_num = MAX (max_block_num, bb->block_num);
4698 ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
4700 /* Add branches between non-consecutive bblocks */
4701 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4702 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4703 bb->next_bb != bb->last_ins->inst_false_bb) {
4705 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4706 inst->opcode = OP_BR;
4707 inst->inst_target_bb = bb->last_ins->inst_false_bb;
4708 mono_bblock_add_inst (bb, inst);
4713 * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
4714 * was later optimized away, so clear these flags, and add them back for the still
4715 * present OP_LDADDR instructions.
4717 for (i = 0; i < cfg->next_vreg; ++i) {
4720 ins = get_vreg_to_inst (cfg, i);
4721 if (ins && ins != cfg->rgctx_var)
4722 ins->flags &= ~MONO_INST_INDIRECT;
4726 * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
4728 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4730 LLVMBuilderRef builder;
4732 char dname_buf[128];
4734 builder = create_builder (ctx);
4736 for (ins = bb->code; ins; ins = ins->next) {
4737 switch (ins->opcode) {
4742 LLVMTypeRef phi_type = llvm_type_to_stack_type (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4744 CHECK_FAILURE (ctx);
4746 if (ins->opcode == OP_VPHI) {
4747 /* Treat valuetype PHI nodes as operating on the address itself */
4748 g_assert (ins->klass);
4749 phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
4753 * Have to precreate these, as they can be referenced by
4754 * earlier instructions.
4756 sprintf (dname_buf, "t%d", ins->dreg);
4758 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
4760 if (ins->opcode == OP_VPHI)
4761 ctx->addresses [ins->dreg] = values [ins->dreg];
4763 g_ptr_array_add (phi_values, values [ins->dreg]);
4766 * Set the expected type of the incoming arguments since these have
4767 * to have the same type.
4769 for (i = 0; i < ins->inst_phi_args [0]; i++) {
4770 int sreg1 = ins->inst_phi_args [i + 1];
4773 ctx->vreg_types [sreg1] = phi_type;
4778 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
4787 * Create an ordering for bblocks, use the depth first order first, then
4788 * put the exception handling bblocks last.
4790 for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
4791 bb = cfg->bblocks [bb_index];
4792 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
4793 g_ptr_array_add (bblock_list, bb);
4794 bblocks [bb->block_num].added = TRUE;
4798 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4799 if (!bblocks [bb->block_num].added)
4800 g_ptr_array_add (bblock_list, bb);
4804 * Second pass: generate code.
4806 for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
4807 bb = g_ptr_array_index (bblock_list, bb_index);
4809 if (!(bb == cfg->bb_entry || bb->in_count > 0))
4812 process_bb (ctx, bb);
4813 CHECK_FAILURE (ctx);
4816 /* Add incoming phi values */
4817 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4818 GSList *l, *ins_list;
4820 ins_list = bblocks [bb->block_num].phi_nodes;
4822 for (l = ins_list; l; l = l->next) {
4823 PhiNode *node = l->data;
4824 MonoInst *phi = node->phi;
4825 int sreg1 = node->sreg;
4826 LLVMBasicBlockRef in_bb;
4831 in_bb = get_end_bb (ctx, node->in_bb);
4833 if (ctx->unreachable [node->in_bb->block_num])
4836 if (!values [sreg1])
4837 /* Can happen with values in EH clauses */
4838 LLVM_FAILURE (ctx, "incoming phi sreg1");
4840 if (phi->opcode == OP_VPHI) {
4841 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4842 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
4844 if (LLVMTypeOf (values [sreg1]) != LLVMTypeOf (values [phi->dreg]))
4846 LLVM_FAILURE (ctx, "incoming phi arg type mismatch");
4847 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4848 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
4853 /* Create the SWITCH statements for ENDFINALLY instructions */
4854 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4855 BBInfo *info = &bblocks [bb->block_num];
4857 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
4858 LLVMValueRef switch_ins = l->data;
4859 GSList *bb_list = info->call_handler_return_bbs;
4861 for (i = 0; i < g_slist_length (bb_list); ++i)
4862 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
4866 if (cfg->verbose_level > 1)
4867 mono_llvm_dump_value (method);
4869 if (cfg->compile_aot)
4870 mark_as_used (ctx->lmodule, method);
4872 if (cfg->compile_aot) {
4873 LLVMValueRef md_args [16];
4874 LLVMValueRef md_node;
4877 method_index = mono_aot_get_method_index (cfg->orig_method);
4878 md_args [0] = LLVMMDString (method_name, strlen (method_name));
4879 md_args [1] = LLVMConstInt (LLVMInt32Type (), method_index, FALSE);
4880 md_node = LLVMMDNode (md_args, 2);
4881 LLVMAddNamedMetadataOperand (module, "mono.function_indexes", md_node);
4882 //LLVMSetMetadata (method, md_kind, LLVMMDNode (&md_arg, 1));
4885 if (cfg->compile_aot) {
4886 /* Don't generate native code, keep the LLVM IR */
4887 if (cfg->compile_aot && cfg->verbose_level)
4888 printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
4890 //LLVMVerifyFunction(method, 0);
4892 mono_llvm_optimize_method (ctx->lmodule->mono_ee, method);
4894 if (cfg->verbose_level > 1)
4895 mono_llvm_dump_value (method);
4897 cfg->native_code = LLVMGetPointerToGlobal (ctx->lmodule->ee, method);
4899 /* Set by emit_cb */
4900 g_assert (cfg->code_len);
4902 /* FIXME: Free the LLVM IL for the function */
4905 if (ctx->lmodule->method_to_lmethod)
4906 g_hash_table_insert (ctx->lmodule->method_to_lmethod, cfg->method, method);
4913 /* Need to add unused phi nodes as they can be referenced by other values */
4914 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
4915 LLVMBuilderRef builder;
4917 builder = create_builder (ctx);
4918 LLVMPositionBuilderAtEnd (builder, phi_bb);
4920 for (i = 0; i < phi_values->len; ++i) {
4921 LLVMValueRef v = g_ptr_array_index (phi_values, i);
4922 if (LLVMGetInstructionParent (v) == NULL)
4923 LLVMInsertIntoBuilder (builder, v);
4926 LLVMDeleteFunction (method);
4931 g_free (ctx->addresses);
4932 g_free (ctx->vreg_types);
4933 g_free (ctx->vreg_cli_types);
4934 g_free (ctx->pindexes);
4935 g_free (ctx->is_dead);
4936 g_free (ctx->unreachable);
4937 g_ptr_array_free (phi_values, TRUE);
4938 g_free (ctx->bblocks);
4939 g_hash_table_destroy (ctx->region_to_handler);
4940 g_free (method_name);
4941 g_ptr_array_free (bblock_list, TRUE);
4943 for (l = ctx->builders; l; l = l->next) {
4944 LLVMBuilderRef builder = l->data;
4945 LLVMDisposeBuilder (builder);
4950 mono_native_tls_set_value (current_cfg_tls_id, NULL);
4952 mono_loader_unlock ();
4956 * mono_llvm_emit_call:
4958 * Same as mono_arch_emit_call () for LLVM.
4961 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
4964 MonoMethodSignature *sig;
4965 int i, n, stack_size;
4970 sig = call->signature;
4971 n = sig->param_count + sig->hasthis;
4973 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4975 if (cfg->disable_llvm)
4978 if (sig->call_convention == MONO_CALL_VARARG) {
4979 cfg->exception_message = g_strdup ("varargs");
4980 cfg->disable_llvm = TRUE;
4983 for (i = 0; i < n; ++i) {
4986 ainfo = call->cinfo->args + i;
4988 in = call->args [i];
4990 /* Simply remember the arguments */
4991 switch (ainfo->storage) {
4993 case LLVMArgInFPReg: {
4994 MonoType *t = (sig->hasthis && i == 0) ? &mono_get_intptr_class ()->byval_arg : sig->params [i - sig->hasthis];
4997 opcode = mono_type_to_regmove (cfg, t);
4998 if (opcode == OP_FMOVE) {
4999 MONO_INST_NEW (cfg, ins, OP_FMOVE);
5000 ins->dreg = mono_alloc_freg (cfg);
5001 } else if (opcode == OP_LMOVE) {
5002 MONO_INST_NEW (cfg, ins, OP_LMOVE);
5003 ins->dreg = mono_alloc_lreg (cfg);
5005 MONO_INST_NEW (cfg, ins, OP_MOVE);
5006 ins->dreg = mono_alloc_ireg (cfg);
5008 ins->sreg1 = in->dreg;
5011 case LLVMArgVtypeByVal:
5012 case LLVMArgVtypeInReg:
5013 case LLVMArgAsIArgs:
5014 MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
5015 ins->dreg = mono_alloc_ireg (cfg);
5016 ins->sreg1 = in->dreg;
5017 ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
5020 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
5021 cfg->exception_message = g_strdup ("ainfo->storage");
5022 cfg->disable_llvm = TRUE;
5026 if (!cfg->disable_llvm) {
5027 MONO_ADD_INS (cfg->cbb, ins);
5028 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
5033 static unsigned char*
5034 alloc_cb (LLVMValueRef function, int size)
5038 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5042 return mono_domain_code_reserve (cfg->domain, size);
5044 return mono_domain_code_reserve (mono_domain_get (), size);
5049 emitted_cb (LLVMValueRef function, void *start, void *end)
5053 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5055 cfg->code_len = (guint8*)end - (guint8*)start;
5059 exception_cb (void *data)
5062 MonoJitExceptionInfo *ei;
5063 guint32 ei_len, i, j, nested_len, nindex;
5064 gpointer *type_info;
5065 int this_reg, this_offset;
5067 cfg = mono_native_tls_get_value (current_cfg_tls_id);
5071 * data points to a DWARF FDE structure, convert it to our unwind format and
5073 * An alternative would be to save it directly, and modify our unwinder to work
5076 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);
5077 if (cfg->verbose_level > 1)
5078 mono_print_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
5080 /* Count nested clauses */
5082 for (i = 0; i < ei_len; ++i) {
5083 for (j = 0; j < ei_len; ++j) {
5084 gint32 cindex1 = *(gint32*)type_info [i];
5085 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5086 gint32 cindex2 = *(gint32*)type_info [j];
5087 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5089 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5095 cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
5096 cfg->llvm_ex_info_len = ei_len + nested_len;
5097 memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
5098 /* Fill the rest of the information from the type info */
5099 for (i = 0; i < ei_len; ++i) {
5100 gint32 clause_index = *(gint32*)type_info [i];
5101 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
5103 cfg->llvm_ex_info [i].flags = clause->flags;
5104 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
5108 * For nested clauses, the LLVM produced exception info associates the try interval with
5109 * the innermost handler, while mono expects it to be associated with all nesting clauses.
5111 /* FIXME: These should be order with the normal clauses */
5113 for (i = 0; i < ei_len; ++i) {
5114 for (j = 0; j < ei_len; ++j) {
5115 gint32 cindex1 = *(gint32*)type_info [i];
5116 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5117 gint32 cindex2 = *(gint32*)type_info [j];
5118 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5120 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5122 * The try interval comes from the nested clause, everything else from the
5125 memcpy (&cfg->llvm_ex_info [nindex], &cfg->llvm_ex_info [j], sizeof (MonoJitExceptionInfo));
5126 cfg->llvm_ex_info [nindex].try_start = cfg->llvm_ex_info [i].try_start;
5127 cfg->llvm_ex_info [nindex].try_end = cfg->llvm_ex_info [i].try_end;
5132 g_assert (nindex == ei_len + nested_len);
5133 cfg->llvm_this_reg = this_reg;
5134 cfg->llvm_this_offset = this_offset;
5136 /* type_info [i] is cfg mempool allocated, no need to free it */
5143 dlsym_cb (const char *name, void **symbol)
5149 if (!strcmp (name, "__bzero")) {
5150 *symbol = (void*)bzero;
5152 current = mono_dl_open (NULL, 0, NULL);
5155 err = mono_dl_symbol (current, name, symbol);
5157 mono_dl_close (current);
5159 #ifdef MONO_ARCH_HAVE_CREATE_LLVM_NATIVE_THUNK
5160 *symbol = (char*)mono_arch_create_llvm_native_thunk (mono_domain_get (), (guint8*)(*symbol));
5166 AddFunc (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef *param_types, int nparams)
5168 LLVMAddFunction (module, name, LLVMFunctionType (ret_type, param_types, nparams, FALSE));
5172 AddFunc2 (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef param_type1, LLVMTypeRef param_type2)
5174 LLVMTypeRef param_types [4];
5176 param_types [0] = param_type1;
5177 param_types [1] = param_type2;
5179 AddFunc (module, name, ret_type, param_types, 2);
5183 add_intrinsics (LLVMModuleRef module)
5185 /* Emit declarations of instrinsics */
5187 * It would be nicer to emit only the intrinsics actually used, but LLVM's Module
5188 * type doesn't seem to do any locking.
5191 LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5193 memset_param_count = 5;
5194 memset_func_name = "llvm.memset.p0i8.i32";
5196 LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
5200 LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5202 memcpy_param_count = 5;
5203 memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
5205 LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
5209 LLVMTypeRef params [] = { LLVMDoubleType () };
5211 LLVMAddFunction (module, "llvm.sin.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5212 LLVMAddFunction (module, "llvm.cos.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5213 LLVMAddFunction (module, "llvm.sqrt.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5215 /* This isn't an intrinsic, instead llvm seems to special case it by name */
5216 LLVMAddFunction (module, "fabs", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5220 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
5221 LLVMTypeRef ovf_params_i32 [] = { LLVMInt32Type (), LLVMInt32Type () };
5223 LLVMAddFunction (module, "llvm.sadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5224 LLVMAddFunction (module, "llvm.uadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5225 LLVMAddFunction (module, "llvm.ssub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5226 LLVMAddFunction (module, "llvm.usub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5227 LLVMAddFunction (module, "llvm.smul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5228 LLVMAddFunction (module, "llvm.umul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5232 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
5233 LLVMTypeRef ovf_params_i64 [] = { LLVMInt64Type (), LLVMInt64Type () };
5235 LLVMAddFunction (module, "llvm.sadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5236 LLVMAddFunction (module, "llvm.uadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5237 LLVMAddFunction (module, "llvm.ssub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5238 LLVMAddFunction (module, "llvm.usub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5239 LLVMAddFunction (module, "llvm.smul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5240 LLVMAddFunction (module, "llvm.umul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5245 LLVMTypeRef arg_types [2];
5246 LLVMTypeRef ret_type;
5248 arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
5249 arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
5250 ret_type = LLVMInt32Type ();
5252 LLVMAddFunction (module, "mono_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5254 LLVMAddFunction (module, "llvm_resume_unwind_trampoline", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5257 /* SSE intrinsics */
5258 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5260 LLVMTypeRef ret_type, arg_types [16];
5263 ret_type = type_to_simd_type (MONO_TYPE_I4);
5264 arg_types [0] = ret_type;
5265 arg_types [1] = ret_type;
5266 AddFunc (module, "llvm.x86.sse41.pminud", ret_type, arg_types, 2);
5267 AddFunc (module, "llvm.x86.sse41.pmaxud", ret_type, arg_types, 2);
5269 ret_type = type_to_simd_type (MONO_TYPE_I2);
5270 arg_types [0] = ret_type;
5271 arg_types [1] = ret_type;
5272 AddFunc (module, "llvm.x86.sse41.pminuw", ret_type, arg_types, 2);
5273 AddFunc (module, "llvm.x86.sse2.pmins.w", ret_type, arg_types, 2);
5274 AddFunc (module, "llvm.x86.sse41.pmaxuw", ret_type, arg_types, 2);
5275 AddFunc (module, "llvm.x86.sse2.padds.w", ret_type, arg_types, 2);
5276 AddFunc (module, "llvm.x86.sse2.psubs.w", ret_type, arg_types, 2);
5277 AddFunc (module, "llvm.x86.sse2.paddus.w", ret_type, arg_types, 2);
5278 AddFunc (module, "llvm.x86.sse2.psubus.w", ret_type, arg_types, 2);
5279 AddFunc (module, "llvm.x86.sse2.pavg.w", ret_type, arg_types, 2);
5280 AddFunc (module, "llvm.x86.sse2.pmulh.w", ret_type, arg_types, 2);
5281 AddFunc (module, "llvm.x86.sse2.pmulhu.w", ret_type, arg_types, 2);
5283 ret_type = type_to_simd_type (MONO_TYPE_I1);
5284 arg_types [0] = ret_type;
5285 arg_types [1] = ret_type;
5286 AddFunc (module, "llvm.x86.sse2.pminu.b", ret_type, arg_types, 2);
5287 AddFunc (module, "llvm.x86.sse2.pmaxu.b", ret_type, arg_types, 2);
5288 AddFunc (module, "llvm.x86.sse2.padds.b", ret_type, arg_types, 2);
5289 AddFunc (module, "llvm.x86.sse2.psubs.b", ret_type, arg_types, 2);
5290 AddFunc (module, "llvm.x86.sse2.paddus.b", ret_type, arg_types, 2);
5291 AddFunc (module, "llvm.x86.sse2.psubus.b", ret_type, arg_types, 2);
5292 AddFunc (module, "llvm.x86.sse2.pavg.b", ret_type, arg_types, 2);
5294 ret_type = type_to_simd_type (MONO_TYPE_R8);
5295 arg_types [0] = ret_type;
5296 arg_types [1] = ret_type;
5297 AddFunc (module, "llvm.x86.sse2.min.pd", ret_type, arg_types, 2);
5298 AddFunc (module, "llvm.x86.sse2.max.pd", ret_type, arg_types, 2);
5299 AddFunc (module, "llvm.x86.sse3.hadd.pd", ret_type, arg_types, 2);
5300 AddFunc (module, "llvm.x86.sse3.hsub.pd", ret_type, arg_types, 2);
5301 AddFunc (module, "llvm.x86.sse3.addsub.pd", ret_type, arg_types, 2);
5303 ret_type = type_to_simd_type (MONO_TYPE_R4);
5304 arg_types [0] = ret_type;
5305 arg_types [1] = ret_type;
5306 AddFunc (module, "llvm.x86.sse.min.ps", ret_type, arg_types, 2);
5307 AddFunc (module, "llvm.x86.sse.max.ps", ret_type, arg_types, 2);
5308 AddFunc (module, "llvm.x86.sse3.hadd.ps", ret_type, arg_types, 2);
5309 AddFunc (module, "llvm.x86.sse3.hsub.ps", ret_type, arg_types, 2);
5310 AddFunc (module, "llvm.x86.sse3.addsub.ps", ret_type, arg_types, 2);
5313 ret_type = type_to_simd_type (MONO_TYPE_I1);
5314 arg_types [0] = type_to_simd_type (MONO_TYPE_I2);
5315 arg_types [1] = type_to_simd_type (MONO_TYPE_I2);
5316 AddFunc (module, "llvm.x86.sse2.packsswb.128", ret_type, arg_types, 2);
5317 AddFunc (module, "llvm.x86.sse2.packuswb.128", ret_type, arg_types, 2);
5318 ret_type = type_to_simd_type (MONO_TYPE_I2);
5319 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5320 arg_types [1] = type_to_simd_type (MONO_TYPE_I4);
5321 AddFunc (module, "llvm.x86.sse2.packssdw.128", ret_type, arg_types, 2);
5322 AddFunc (module, "llvm.x86.sse41.packusdw", ret_type, arg_types, 2);
5325 ret_type = type_to_simd_type (MONO_TYPE_R8);
5326 arg_types [0] = ret_type;
5327 arg_types [1] = ret_type;
5328 arg_types [2] = LLVMInt8Type ();
5329 AddFunc (module, "llvm.x86.sse2.cmp.pd", ret_type, arg_types, 3);
5330 ret_type = type_to_simd_type (MONO_TYPE_R4);
5331 arg_types [0] = ret_type;
5332 arg_types [1] = ret_type;
5333 arg_types [2] = LLVMInt8Type ();
5334 AddFunc (module, "llvm.x86.sse.cmp.ps", ret_type, arg_types, 3);
5336 /* Conversion ops */
5337 ret_type = type_to_simd_type (MONO_TYPE_R8);
5338 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5339 AddFunc (module, "llvm.x86.sse2.cvtdq2pd", ret_type, arg_types, 1);
5340 ret_type = type_to_simd_type (MONO_TYPE_R4);
5341 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5342 AddFunc (module, "llvm.x86.sse2.cvtdq2ps", ret_type, arg_types, 1);
5343 ret_type = type_to_simd_type (MONO_TYPE_I4);
5344 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5345 AddFunc (module, "llvm.x86.sse2.cvtpd2dq", ret_type, arg_types, 1);
5346 ret_type = type_to_simd_type (MONO_TYPE_I4);
5347 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5348 AddFunc (module, "llvm.x86.sse2.cvtps2dq", ret_type, arg_types, 1);
5349 ret_type = type_to_simd_type (MONO_TYPE_R4);
5350 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5351 AddFunc (module, "llvm.x86.sse2.cvtpd2ps", ret_type, arg_types, 1);
5352 ret_type = type_to_simd_type (MONO_TYPE_R8);
5353 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5354 AddFunc (module, "llvm.x86.sse2.cvtps2pd", ret_type, arg_types, 1);
5356 ret_type = type_to_simd_type (MONO_TYPE_I4);
5357 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5358 AddFunc (module, "llvm.x86.sse2.cvttpd2dq", ret_type, arg_types, 1);
5359 ret_type = type_to_simd_type (MONO_TYPE_I4);
5360 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5361 AddFunc (module, "llvm.x86.sse2.cvttps2dq", ret_type, arg_types, 1);
5364 ret_type = type_to_simd_type (MONO_TYPE_R8);
5365 arg_types [0] = ret_type;
5366 AddFunc (module, "llvm.x86.sse2.sqrt.pd", ret_type, arg_types, 1);
5367 ret_type = type_to_simd_type (MONO_TYPE_R4);
5368 arg_types [0] = ret_type;
5369 AddFunc (module, "llvm.x86.sse.sqrt.ps", ret_type, arg_types, 1);
5370 ret_type = type_to_simd_type (MONO_TYPE_R4);
5371 arg_types [0] = ret_type;
5372 AddFunc (module, "llvm.x86.sse.rsqrt.ps", ret_type, arg_types, 1);
5373 ret_type = type_to_simd_type (MONO_TYPE_R4);
5374 arg_types [0] = ret_type;
5375 AddFunc (module, "llvm.x86.sse.rcp.ps", ret_type, arg_types, 1);
5378 ret_type = type_to_simd_type (MONO_TYPE_I2);
5379 arg_types [0] = ret_type;
5380 arg_types [1] = LLVMInt32Type ();
5381 AddFunc (module, "llvm.x86.sse2.psrli.w", ret_type, arg_types, 2);
5382 AddFunc (module, "llvm.x86.sse2.psrai.w", ret_type, arg_types, 2);
5383 AddFunc (module, "llvm.x86.sse2.pslli.w", ret_type, arg_types, 2);
5384 ret_type = type_to_simd_type (MONO_TYPE_I4);
5385 arg_types [0] = ret_type;
5386 arg_types [1] = LLVMInt32Type ();
5387 AddFunc (module, "llvm.x86.sse2.psrli.d", ret_type, arg_types, 2);
5388 AddFunc (module, "llvm.x86.sse2.psrai.d", ret_type, arg_types, 2);
5389 AddFunc (module, "llvm.x86.sse2.pslli.d", ret_type, arg_types, 2);
5390 ret_type = type_to_simd_type (MONO_TYPE_I8);
5391 arg_types [0] = ret_type;
5392 arg_types [1] = LLVMInt32Type ();
5393 AddFunc (module, "llvm.x86.sse2.psrli.q", ret_type, arg_types, 2);
5394 AddFunc (module, "llvm.x86.sse2.pslli.q", ret_type, arg_types, 2);
5397 ret_type = LLVMInt32Type ();
5398 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
5399 AddFunc (module, "llvm.x86.sse2.pmovmskb.128", ret_type, arg_types, 1);
5402 AddFunc (module, "llvm.x86.sse2.pause", LLVMVoidType (), NULL, 0);
5405 /* Load/Store intrinsics */
5407 LLVMTypeRef arg_types [5];
5411 for (i = 1; i <= 8; i *= 2) {
5412 arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
5413 arg_types [1] = LLVMInt32Type ();
5414 arg_types [2] = LLVMInt1Type ();
5415 #if LLVM_API_VERSION >= 4
5416 arg_types [3] = LLVMInt32Type ();
5418 sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
5419 LLVMAddFunction (module, name, LLVMFunctionType (LLVMIntType (i * 8), arg_types, 3 + EXTRA_MONO_LOAD_STORE_ARGS, FALSE));
5421 arg_types [0] = LLVMIntType (i * 8);
5422 arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
5423 arg_types [2] = LLVMInt32Type ();
5424 arg_types [3] = LLVMInt1Type ();
5425 #if LLVM_API_VERSION >= 4
5426 arg_types [4] = LLVMInt32Type ();
5428 sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
5429 LLVMAddFunction (module, name, LLVMFunctionType (LLVMVoidType (), arg_types, 4 + EXTRA_MONO_LOAD_STORE_ARGS, FALSE));
5435 add_types (MonoLLVMModule *lmodule)
5437 lmodule->ptr_type = LLVMPointerType (sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type (), 0);
5441 mono_llvm_init (void)
5443 mono_native_tls_alloc (¤t_cfg_tls_id, NULL);
5447 init_jit_module (MonoDomain *domain)
5449 MonoJitICallInfo *info;
5450 MonoJitDomainInfo *dinfo;
5451 MonoLLVMModule *module;
5454 dinfo = domain_jit_info (domain);
5455 if (dinfo->llvm_module)
5458 mono_loader_lock ();
5460 if (dinfo->llvm_module) {
5461 mono_loader_unlock ();
5465 module = g_new0 (MonoLLVMModule, 1);
5467 name = g_strdup_printf ("mono-%s", domain->friendly_name);
5468 module->module = LLVMModuleCreateWithName (name);
5470 module->mono_ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (module->module), alloc_cb, emitted_cb, exception_cb, dlsym_cb, &module->ee);
5472 add_intrinsics (module->module);
5475 module->llvm_types = g_hash_table_new (NULL, NULL);
5477 info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
5479 LLVMAddGlobalMapping (module->ee, LLVMGetNamedFunction (module->module, "llvm_resume_unwind_trampoline"), (void*)info->func);
5481 mono_memory_barrier ();
5483 dinfo->llvm_module = module;
5485 mono_loader_unlock ();
5489 mono_llvm_cleanup (void)
5491 if (aot_module.module)
5492 LLVMDisposeModule (aot_module.module);
5494 LLVMContextDispose (LLVMGetGlobalContext ());
5498 mono_llvm_free_domain_info (MonoDomain *domain)
5500 MonoJitDomainInfo *info = domain_jit_info (domain);
5501 MonoLLVMModule *module = info->llvm_module;
5507 if (module->llvm_types)
5508 g_hash_table_destroy (module->llvm_types);
5510 mono_llvm_dispose_ee (module->mono_ee);
5512 if (module->bb_names) {
5513 for (i = 0; i < module->bb_names_len; ++i)
5514 g_free (module->bb_names [i]);
5515 g_free (module->bb_names);
5517 //LLVMDisposeModule (module->module);
5521 info->llvm_module = NULL;
5525 mono_llvm_create_aot_module (const char *got_symbol, gboolean external_symbols, gboolean emit_dwarf)
5527 /* Delete previous module */
5528 if (aot_module.plt_entries)
5529 g_hash_table_destroy (aot_module.plt_entries);
5530 if (aot_module.module)
5531 LLVMDisposeModule (aot_module.module);
5533 memset (&aot_module, 0, sizeof (aot_module));
5535 aot_module.module = LLVMModuleCreateWithName ("aot");
5536 aot_module.got_symbol = got_symbol;
5537 aot_module.external_symbols = external_symbols;
5538 aot_module.emit_dwarf = emit_dwarf;
5539 /* The first few entries are reserved */
5540 aot_module.max_got_offset = 16;
5542 add_intrinsics (aot_module.module);
5543 add_types (&aot_module);
5547 * We couldn't compute the type of the LLVM global representing the got because
5548 * its size is only known after all the methods have been emitted. So create
5549 * a dummy variable, and replace all uses it with the real got variable when
5550 * its size is known in mono_llvm_emit_aot_module ().
5553 LLVMTypeRef got_type = LLVMArrayType (aot_module.ptr_type, 0);
5555 aot_module.got_var = LLVMAddGlobal (aot_module.module, got_type, "mono_dummy_got");
5556 LLVMSetInitializer (aot_module.got_var, LLVMConstNull (got_type));
5559 /* Add a dummy personality function */
5561 LLVMBasicBlockRef lbb;
5562 LLVMBuilderRef lbuilder;
5563 LLVMValueRef personality;
5565 personality = LLVMAddFunction (aot_module.module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5566 LLVMSetLinkage (personality, LLVMInternalLinkage);
5567 lbb = LLVMAppendBasicBlock (personality, "BB0");
5568 lbuilder = LLVMCreateBuilder ();
5569 LLVMPositionBuilderAtEnd (lbuilder, lbb);
5570 LLVMBuildRetVoid (lbuilder);
5573 aot_module.llvm_types = g_hash_table_new (NULL, NULL);
5574 aot_module.plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
5575 aot_module.plt_entries_ji = g_hash_table_new (NULL, NULL);
5576 aot_module.method_to_lmethod = g_hash_table_new (NULL, NULL);
5580 * Emit the aot module into the LLVM bitcode file FILENAME.
5583 mono_llvm_emit_aot_module (const char *filename, const char *cu_name)
5585 LLVMTypeRef got_type;
5586 LLVMValueRef real_got;
5587 MonoLLVMModule *module = &aot_module;
5590 * Create the real got variable and replace all uses of the dummy variable with
5593 got_type = LLVMArrayType (aot_module.ptr_type, module->max_got_offset + 1);
5594 real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
5595 LLVMSetInitializer (real_got, LLVMConstNull (got_type));
5596 if (module->external_symbols) {
5597 LLVMSetLinkage (real_got, LLVMExternalLinkage);
5598 LLVMSetVisibility (real_got, LLVMHiddenVisibility);
5600 LLVMSetLinkage (real_got, LLVMInternalLinkage);
5602 mono_llvm_replace_uses_of (aot_module.got_var, real_got);
5604 mark_as_used (&aot_module, real_got);
5606 /* Delete the dummy got so it doesn't become a global */
5607 LLVMDeleteGlobal (aot_module.got_var);
5609 emit_llvm_used (&aot_module);
5610 emit_dbg_info (&aot_module, filename, cu_name);
5612 /* Replace PLT entries for directly callable methods with the methods themselves */
5614 GHashTableIter iter;
5616 LLVMValueRef callee;
5618 g_hash_table_iter_init (&iter, aot_module.plt_entries_ji);
5619 while (g_hash_table_iter_next (&iter, (void**)&ji, (void**)&callee)) {
5620 if (mono_aot_is_direct_callable (ji)) {
5621 LLVMValueRef lmethod;
5623 lmethod = g_hash_table_lookup (module->method_to_lmethod, ji->data.method);
5624 /* The types might not match because the caller might pass an rgctx */
5625 if (lmethod && LLVMTypeOf (callee) == LLVMTypeOf (lmethod)) {
5626 mono_llvm_replace_uses_of (callee, lmethod);
5627 mono_aot_mark_unused_llvm_plt_entry (ji);
5637 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
5638 g_assert_not_reached ();
5643 LLVMWriteBitcodeToFile (aot_module.module, filename);
5648 md_string (const char *s)
5650 return LLVMMDString (s, strlen (s));
5653 /* Debugging support */
5656 emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name)
5658 LLVMModuleRef module = lmodule->module;
5659 LLVMValueRef args [16], cu_args [16], cu, ver;
5661 char *build_info, *s, *dir;
5664 * This can only be enabled when LLVM code is emitted into a separate object
5665 * file, since the AOT compiler also emits dwarf info,
5666 * and the abbrev indexes will not be correct since llvm has added its own
5669 if (!lmodule->emit_dwarf)
5673 * Emit dwarf info in the form of LLVM metadata. There is some
5674 * out-of-date documentation at:
5675 * http://llvm.org/docs/SourceLevelDebugging.html
5676 * but most of this was gathered from the llvm and
5681 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_TAG_compile_unit, FALSE);
5682 /* CU name/compilation dir */
5683 dir = g_path_get_dirname (filename);
5684 args [0] = LLVMMDString (cu_name, strlen (cu_name));
5685 args [1] = LLVMMDString (dir, strlen (dir));
5686 cu_args [n_cuargs ++] = LLVMMDNode (args, 2);
5689 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_LANG_C99, FALSE);
5691 build_info = mono_get_runtime_build_info ();
5692 s = g_strdup_printf ("Mono AOT Compiler %s (LLVM)", build_info);
5693 cu_args [n_cuargs ++] = LLVMMDString (s, strlen (s));
5694 g_free (build_info);
5696 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5698 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5699 /* Runtime version */
5700 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5702 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5703 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5705 if (lmodule->subprogram_mds) {
5709 mds = g_new0 (LLVMValueRef, lmodule->subprogram_mds->len);
5710 for (i = 0; i < lmodule->subprogram_mds->len; ++i)
5711 mds [i] = g_ptr_array_index (lmodule->subprogram_mds, i);
5712 cu_args [n_cuargs ++] = LLVMMDNode (mds, lmodule->subprogram_mds->len);
5714 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5717 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5718 /* Imported modules */
5719 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5721 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5722 /* DebugEmissionKind = FullDebug */
5723 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5724 cu = LLVMMDNode (cu_args, n_cuargs);
5725 LLVMAddNamedMetadataOperand (module, "llvm.dbg.cu", cu);
5727 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5728 args [1] = LLVMMDString ("Dwarf Version", strlen ("Dwarf Version"));
5729 args [2] = LLVMConstInt (LLVMInt32Type (), 2, FALSE);
5730 ver = LLVMMDNode (args, 3);
5731 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5733 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5734 args [1] = LLVMMDString ("Debug Info Version", strlen ("Debug Info Version"));
5735 args [2] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5736 ver = LLVMMDNode (args, 3);
5737 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5741 emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name)
5743 MonoLLVMModule *module = ctx->lmodule;
5744 MonoDebugMethodInfo *minfo = ctx->minfo;
5745 char *source_file, *dir, *filename;
5746 LLVMValueRef md, args [16], ctx_args [16], md_args [64], type_args [16], ctx_md, type_md;
5754 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, NULL, &n_il_offsets, &il_offsets, &line_numbers, NULL, NULL, NULL, NULL);
5756 source_file = g_strdup ("<unknown>");
5757 dir = g_path_get_dirname (source_file);
5758 filename = g_path_get_basename (source_file);
5760 ctx_args [0] = LLVMConstInt (LLVMInt32Type (), 0x29, FALSE);
5761 args [0] = md_string (filename);
5762 args [1] = md_string (dir);
5763 ctx_args [1] = LLVMMDNode (args, 2);
5764 ctx_md = LLVMMDNode (ctx_args, 2);
5766 type_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subroutine_type, FALSE);
5767 type_args [1] = NULL;
5768 type_args [2] = NULL;
5769 type_args [3] = LLVMMDString ("", 0);
5770 type_args [4] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5771 type_args [5] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5772 type_args [6] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5773 type_args [7] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5774 type_args [8] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5775 type_args [9] = NULL;
5776 type_args [10] = NULL;
5777 type_args [11] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5778 type_args [12] = NULL;
5779 type_args [13] = NULL;
5780 type_args [14] = NULL;
5781 type_md = LLVMMDNode (type_args, 14);
5783 /* http://llvm.org/docs/SourceLevelDebugging.html#subprogram-descriptors */
5784 md_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subprogram, FALSE);
5785 /* Source directory + file pair */
5786 args [0] = md_string (filename);
5787 args [1] = md_string (dir);
5788 md_args [1] = LLVMMDNode (args ,2);
5789 md_args [2] = ctx_md;
5790 md_args [3] = md_string (cfg->method->name);
5791 md_args [4] = md_string (name);
5792 md_args [5] = md_string (name);
5795 md_args [6] = LLVMConstInt (LLVMInt32Type (), line_numbers [0], FALSE);
5797 md_args [6] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5799 md_args [7] = type_md;
5801 md_args [8] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5803 md_args [9] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5805 md_args [10] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5806 /* Index into a virtual function */
5807 md_args [11] = NULL;
5808 md_args [12] = NULL;
5810 md_args [13] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5812 md_args [14] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5813 /* Pointer to LLVM function */
5814 md_args [15] = method;
5815 /* Function template parameter */
5816 md_args [16] = NULL;
5817 /* Function declaration descriptor */
5818 md_args [17] = NULL;
5819 /* List of function variables */
5820 md_args [18] = LLVMMDNode (args, 0);
5822 md_args [19] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5823 md = LLVMMDNode (md_args, 20);
5825 if (!module->subprogram_mds)
5826 module->subprogram_mds = g_ptr_array_new ();
5827 g_ptr_array_add (module->subprogram_mds, md);
5831 g_free (source_file);
5832 g_free (il_offsets);
5833 g_free (line_numbers);
5839 emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code)
5841 MonoCompile *cfg = ctx->cfg;
5843 if (ctx->minfo && cil_code && cil_code >= cfg->header->code && cil_code < cfg->header->code + cfg->header->code_size) {
5844 MonoDebugSourceLocation *loc;
5845 LLVMValueRef loc_md, md_args [16];
5848 loc = mono_debug_symfile_lookup_location (ctx->minfo, cil_code - cfg->header->code);
5852 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->row, FALSE);
5853 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->column, FALSE);
5854 md_args [nmd_args ++] = ctx->dbg_md;
5855 md_args [nmd_args ++] = NULL;
5856 loc_md = LLVMMDNode (md_args, nmd_args);
5857 LLVMSetCurrentDebugLocation (builder, loc_md);
5858 mono_debug_symfile_free_location (loc);
5865 - Emit LLVM IR from the mono IR using the LLVM C API.
5866 - The original arch specific code remains, so we can fall back to it if we run
5867 into something we can't handle.
5871 A partial list of issues:
5872 - Handling of opcodes which can throw exceptions.
5874 In the mono JIT, these are implemented using code like this:
5881 push throw_pos - method
5882 call <exception trampoline>
5884 The problematic part is push throw_pos - method, which cannot be represented
5885 in the LLVM IR, since it does not support label values.
5886 -> this can be implemented in AOT mode using inline asm + labels, but cannot
5887 be implemented in JIT mode ?
5888 -> a possible but slower implementation would use the normal exception
5889 throwing code but it would need to control the placement of the throw code
5890 (it needs to be exactly after the compare+branch).
5891 -> perhaps add a PC offset intrinsics ?
5893 - efficient implementation of .ovf opcodes.
5895 These are currently implemented as:
5896 <ins which sets the condition codes>
5899 Some overflow opcodes are now supported by LLVM SVN.
5901 - exception handling, unwinding.
5902 - SSA is disabled for methods with exception handlers
5903 - How to obtain unwind info for LLVM compiled methods ?
5904 -> this is now solved by converting the unwind info generated by LLVM
5906 - LLVM uses the c++ exception handling framework, while we use our home grown
5907 code, and couldn't use the c++ one:
5908 - its not supported under VC++, other exotic platforms.
5909 - it might be impossible to support filter clauses with it.
5913 The trampolines need a predictable call sequence, since they need to disasm
5914 the calling code to obtain register numbers / offsets.
5916 LLVM currently generates this code in non-JIT mode:
5917 mov -0x98(%rax),%eax
5919 Here, the vtable pointer is lost.
5920 -> solution: use one vtable trampoline per class.
5922 - passing/receiving the IMT pointer/RGCTX.
5923 -> solution: pass them as normal arguments ?
5927 LLVM does not allow the specification of argument registers etc. This means
5928 that all calls are made according to the platform ABI.
5930 - passing/receiving vtypes.
5932 Vtypes passed/received in registers are handled by the front end by using
5933 a signature with scalar arguments, and loading the parts of the vtype into those
5936 Vtypes passed on the stack are handled using the 'byval' attribute.
5940 Supported though alloca, we need to emit the load/store code.
5944 The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
5945 typed registers, so we have to keep track of the precise LLVM type of each vreg.
5946 This is made easier because the IR is already in SSA form.
5947 An additional problem is that our IR is not consistent with types, i.e. i32/ia64
5948 types are frequently used incorrectly.
5953 Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then
5954 append the AOT data structures to that file. For methods which cannot be
5955 handled by LLVM, the normal JIT compiled versions are used.
5958 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
5959 * - each bblock should end with a branch
5960 * - setting the return value, making cfg->ret non-volatile
5961 * - avoid some transformations in the JIT which make it harder for us to generate
5963 * - use pointer types to help optimizations.