Merge pull request #4928 from kumpera/ptr_to_struct_intrinsic
[mono.git] / mono / mini / method-to-ir.c
1 /**
2  * \file
3  * Convert CIL to the JIT internal representation
4  *
5  * Author:
6  *   Paolo Molaro (lupus@ximian.com)
7  *   Dietmar Maurer (dietmar@ximian.com)
8  *
9  * (C) 2002 Ximian, Inc.
10  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
11  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14
15 #include <config.h>
16 #include <mono/utils/mono-compiler.h>
17 #include "mini.h"
18
19 #ifndef DISABLE_JIT
20
21 #include <signal.h>
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include <math.h>
28 #include <string.h>
29 #include <ctype.h>
30
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34
35 #ifdef HAVE_ALLOCA_H
36 #include <alloca.h>
37 #endif
38
39 #include <mono/utils/memcheck.h>
40 #include <mono/metadata/abi-details.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/attrdefs.h>
43 #include <mono/metadata/loader.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/class.h>
46 #include <mono/metadata/object.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/opcodes.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/marshal.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/debug-internals.h>
55 #include <mono/metadata/gc-internals.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/security-core-clr.h>
59 #include <mono/metadata/profiler-private.h>
60 #include <mono/metadata/profiler.h>
61 #include <mono/metadata/monitor.h>
62 #include <mono/utils/mono-memory-model.h>
63 #include <mono/utils/mono-error-internals.h>
64 #include <mono/metadata/mono-basic-block.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/utils/mono-threads-coop.h>
67
68 #include "trace.h"
69
70 #include "ir-emit.h"
71
72 #include "jit-icalls.h"
73 #include "jit.h"
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "aot-compiler.h"
77 #include "mini-llvm.h"
78
79 #define BRANCH_COST 10
80 #define INLINE_LENGTH_LIMIT 20
81
82 /* These have 'cfg' as an implicit argument */
83 #define INLINE_FAILURE(msg) do {                                                                        \
84         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
85                 inline_failure (cfg, msg);                                                                              \
86                 goto exception_exit;                                                                                    \
87         } \
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
91                         goto exception_exit;                                            \
92         } while (0)
93 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
94                 field_access_failure ((cfg), (method), (field));                        \
95                 goto exception_exit;    \
96         } while (0)
97 #define GENERIC_SHARING_FAILURE(opcode) do {            \
98                 if (cfg->gshared) {                                                                     \
99                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
100                         goto exception_exit;    \
101                 }                       \
102         } while (0)
103 #define GSHAREDVT_FAILURE(opcode) do {          \
104         if (cfg->gsharedvt) {                                                                                           \
105                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
106                 goto exception_exit;                                                                                    \
107         }                                                                                                                                       \
108         } while (0)
109 #define OUT_OF_MEMORY_FAILURE do {      \
110                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
111                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
112                 goto exception_exit;    \
113         } while (0)
114 #define DISABLE_AOT(cfg) do { \
115                 if ((cfg)->verbose_level >= 2)                                            \
116                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
117                 (cfg)->disable_aot = TRUE;                                                        \
118         } while (0)
119 #define LOAD_ERROR do { \
120                 break_on_unverified ();                                                         \
121                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
122                 goto exception_exit;                                                                    \
123         } while (0)
124
125 #define TYPE_LOAD_ERROR(klass) do { \
126                 cfg->exception_ptr = klass; \
127                 LOAD_ERROR;                                     \
128         } while (0)
129
130 #define CHECK_CFG_ERROR do {\
131                 if (!mono_error_ok (&cfg->error)) { \
132                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
133                         goto mono_error_exit; \
134                 } \
135         } while (0)
136
137 /* Determine whenever 'ins' represents a load of the 'this' argument */
138 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
139
140 static int ldind_to_load_membase (int opcode);
141 static int stind_to_store_membase (int opcode);
142
143 int mono_op_to_op_imm (int opcode);
144 int mono_op_to_op_imm_noemul (int opcode);
145
146 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
147                                                   guchar *ip, guint real_offset, gboolean inline_always);
148 static MonoInst*
149 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
150
151 /* helper methods signatures */
152 static MonoMethodSignature *helper_sig_domain_get;
153 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
154 static MonoMethodSignature *helper_sig_llvmonly_imt_trampoline;
155 static MonoMethodSignature *helper_sig_jit_thread_attach;
156 static MonoMethodSignature *helper_sig_get_tls_tramp;
157 static MonoMethodSignature *helper_sig_set_tls_tramp;
158
159 /* type loading helpers */
160 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
161 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
162
163 /*
164  * Instruction metadata
165  */
166 #ifdef MINI_OP
167 #undef MINI_OP
168 #endif
169 #ifdef MINI_OP3
170 #undef MINI_OP3
171 #endif
172 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
173 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
174 #define NONE ' '
175 #define IREG 'i'
176 #define FREG 'f'
177 #define VREG 'v'
178 #define XREG 'x'
179 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
180 #define LREG IREG
181 #else
182 #define LREG 'l'
183 #endif
184 /* keep in sync with the enum in mini.h */
185 const char
186 ins_info[] = {
187 #include "mini-ops.h"
188 };
189 #undef MINI_OP
190 #undef MINI_OP3
191
192 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
193 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
194 /* 
195  * This should contain the index of the last sreg + 1. This is not the same
196  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
197  */
198 const gint8 ins_sreg_counts[] = {
199 #include "mini-ops.h"
200 };
201 #undef MINI_OP
202 #undef MINI_OP3
203
204 guint32
205 mono_alloc_ireg (MonoCompile *cfg)
206 {
207         return alloc_ireg (cfg);
208 }
209
210 guint32
211 mono_alloc_lreg (MonoCompile *cfg)
212 {
213         return alloc_lreg (cfg);
214 }
215
216 guint32
217 mono_alloc_freg (MonoCompile *cfg)
218 {
219         return alloc_freg (cfg);
220 }
221
222 guint32
223 mono_alloc_preg (MonoCompile *cfg)
224 {
225         return alloc_preg (cfg);
226 }
227
228 guint32
229 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
230 {
231         return alloc_dreg (cfg, stack_type);
232 }
233
234 /*
235  * mono_alloc_ireg_ref:
236  *
237  *   Allocate an IREG, and mark it as holding a GC ref.
238  */
239 guint32
240 mono_alloc_ireg_ref (MonoCompile *cfg)
241 {
242         return alloc_ireg_ref (cfg);
243 }
244
245 /*
246  * mono_alloc_ireg_mp:
247  *
248  *   Allocate an IREG, and mark it as holding a managed pointer.
249  */
250 guint32
251 mono_alloc_ireg_mp (MonoCompile *cfg)
252 {
253         return alloc_ireg_mp (cfg);
254 }
255
256 /*
257  * mono_alloc_ireg_copy:
258  *
259  *   Allocate an IREG with the same GC type as VREG.
260  */
261 guint32
262 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
263 {
264         if (vreg_is_ref (cfg, vreg))
265                 return alloc_ireg_ref (cfg);
266         else if (vreg_is_mp (cfg, vreg))
267                 return alloc_ireg_mp (cfg);
268         else
269                 return alloc_ireg (cfg);
270 }
271
272 guint
273 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
274 {
275         if (type->byref)
276                 return OP_MOVE;
277
278         type = mini_get_underlying_type (type);
279 handle_enum:
280         switch (type->type) {
281         case MONO_TYPE_I1:
282         case MONO_TYPE_U1:
283                 return OP_MOVE;
284         case MONO_TYPE_I2:
285         case MONO_TYPE_U2:
286                 return OP_MOVE;
287         case MONO_TYPE_I4:
288         case MONO_TYPE_U4:
289                 return OP_MOVE;
290         case MONO_TYPE_I:
291         case MONO_TYPE_U:
292         case MONO_TYPE_PTR:
293         case MONO_TYPE_FNPTR:
294                 return OP_MOVE;
295         case MONO_TYPE_CLASS:
296         case MONO_TYPE_STRING:
297         case MONO_TYPE_OBJECT:
298         case MONO_TYPE_SZARRAY:
299         case MONO_TYPE_ARRAY:    
300                 return OP_MOVE;
301         case MONO_TYPE_I8:
302         case MONO_TYPE_U8:
303 #if SIZEOF_REGISTER == 8
304                 return OP_MOVE;
305 #else
306                 return OP_LMOVE;
307 #endif
308         case MONO_TYPE_R4:
309                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
310         case MONO_TYPE_R8:
311                 return OP_FMOVE;
312         case MONO_TYPE_VALUETYPE:
313                 if (type->data.klass->enumtype) {
314                         type = mono_class_enum_basetype (type->data.klass);
315                         goto handle_enum;
316                 }
317                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
318                         return OP_XMOVE;
319                 return OP_VMOVE;
320         case MONO_TYPE_TYPEDBYREF:
321                 return OP_VMOVE;
322         case MONO_TYPE_GENERICINST:
323                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
324                         return OP_XMOVE;
325                 type = &type->data.generic_class->container_class->byval_arg;
326                 goto handle_enum;
327         case MONO_TYPE_VAR:
328         case MONO_TYPE_MVAR:
329                 g_assert (cfg->gshared);
330                 if (mini_type_var_is_vt (type))
331                         return OP_VMOVE;
332                 else
333                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
334         default:
335                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
336         }
337         return -1;
338 }
339
340 void
341 mono_print_bb (MonoBasicBlock *bb, const char *msg)
342 {
343         int i;
344         MonoInst *tree;
345         GString *str = g_string_new ("");
346
347         g_string_append_printf (str, "%s %d: [IN: ", msg, bb->block_num);
348         for (i = 0; i < bb->in_count; ++i)
349                 g_string_append_printf (str, " BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
350         g_string_append_printf (str, ", OUT: ");
351         for (i = 0; i < bb->out_count; ++i)
352                 g_string_append_printf (str, " BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
353         g_string_append_printf (str, " ]\n");
354
355         g_print ("%s", str->str);
356         g_string_free (str, TRUE);
357
358         for (tree = bb->code; tree; tree = tree->next)
359                 mono_print_ins_index (-1, tree);
360 }
361
362 void
363 mono_create_helper_signatures (void)
364 {
365         helper_sig_domain_get = mono_create_icall_signature ("ptr");
366         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
367         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
368         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
369         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
370         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
371 }
372
373 static MONO_NEVER_INLINE void
374 break_on_unverified (void)
375 {
376         if (mini_get_debug_options ()->break_on_unverified)
377                 G_BREAKPOINT ();
378 }
379
380 static MONO_NEVER_INLINE void
381 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
382 {
383         char *method_fname = mono_method_full_name (method, TRUE);
384         char *field_fname = mono_field_full_name (field);
385         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
386         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
387         g_free (method_fname);
388         g_free (field_fname);
389 }
390
391 static MONO_NEVER_INLINE void
392 inline_failure (MonoCompile *cfg, const char *msg)
393 {
394         if (cfg->verbose_level >= 2)
395                 printf ("inline failed: %s\n", msg);
396         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
397 }
398
399 static MONO_NEVER_INLINE void
400 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
401 {
402         if (cfg->verbose_level > 2)                                                                                     \
403                 printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), line);
404         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
405 }
406
407 static MONO_NEVER_INLINE void
408 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
409 {
410         cfg->exception_message = g_strdup_printf ("gsharedvt failed for method %s.%s.%s/%d opcode %s %s:%d", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), file, line);
411         if (cfg->verbose_level >= 2)
412                 printf ("%s\n", cfg->exception_message);
413         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
414 }
415
416 /*
417  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
418  * foo<T> (int i) { ldarg.0; box T; }
419  */
420 #define UNVERIFIED do { \
421         if (cfg->gsharedvt) { \
422                 if (cfg->verbose_level > 2)                                                                     \
423                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
424                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
425                 goto exception_exit;                                                                                    \
426         }                                                                                                                                       \
427         break_on_unverified ();                                                                                         \
428         goto unverified;                                                                                                        \
429 } while (0)
430
431 #define GET_BBLOCK(cfg,tblock,ip) do {  \
432                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
433                 if (!(tblock)) {        \
434                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
435             NEW_BBLOCK (cfg, (tblock)); \
436                         (tblock)->cil_code = (ip);      \
437                         ADD_BBLOCK (cfg, (tblock));     \
438                 } \
439         } while (0)
440
441 #if defined(TARGET_X86) || defined(TARGET_AMD64)
442 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
443                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
444                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
445                 (dest)->sreg1 = (sr1); \
446                 (dest)->sreg2 = (sr2); \
447                 (dest)->inst_imm = (imm); \
448                 (dest)->backend.shift_amount = (shift); \
449                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
450         } while (0)
451 #endif
452
453 /* Emit conversions so both operands of a binary opcode are of the same type */
454 static void
455 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
456 {
457         MonoInst *arg1 = *arg1_ref;
458         MonoInst *arg2 = *arg2_ref;
459
460         if (cfg->r4fp &&
461                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
462                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
463                 MonoInst *conv;
464
465                 /* Mixing r4/r8 is allowed by the spec */
466                 if (arg1->type == STACK_R4) {
467                         int dreg = alloc_freg (cfg);
468
469                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
470                         conv->type = STACK_R8;
471                         ins->sreg1 = dreg;
472                         *arg1_ref = conv;
473                 }
474                 if (arg2->type == STACK_R4) {
475                         int dreg = alloc_freg (cfg);
476
477                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
478                         conv->type = STACK_R8;
479                         ins->sreg2 = dreg;
480                         *arg2_ref = conv;
481                 }
482         }
483
484 #if SIZEOF_REGISTER == 8
485         /* FIXME: Need to add many more cases */
486         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
487                 MonoInst *widen;
488
489                 int dr = alloc_preg (cfg);
490                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
491                 (ins)->sreg2 = widen->dreg;
492         }
493 #endif
494 }
495
496 #define ADD_BINOP(op) do {      \
497                 MONO_INST_NEW (cfg, ins, (op)); \
498                 sp -= 2;        \
499                 ins->sreg1 = sp [0]->dreg;      \
500                 ins->sreg2 = sp [1]->dreg;      \
501                 type_from_op (cfg, ins, sp [0], sp [1]);        \
502                 CHECK_TYPE (ins);       \
503                 /* Have to insert a widening op */               \
504         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
505         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
506         MONO_ADD_INS ((cfg)->cbb, (ins)); \
507         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
508         } while (0)
509
510 #define ADD_UNOP(op) do {       \
511                 MONO_INST_NEW (cfg, ins, (op)); \
512                 sp--;   \
513                 ins->sreg1 = sp [0]->dreg;      \
514                 type_from_op (cfg, ins, sp [0], NULL);  \
515                 CHECK_TYPE (ins);       \
516         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
517         MONO_ADD_INS ((cfg)->cbb, (ins)); \
518                 *sp++ = mono_decompose_opcode (cfg, ins);       \
519         } while (0)
520
521 #define ADD_BINCOND(next_block) do {    \
522                 MonoInst *cmp;  \
523                 sp -= 2; \
524                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
525                 cmp->sreg1 = sp [0]->dreg;      \
526                 cmp->sreg2 = sp [1]->dreg;      \
527                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
528                 CHECK_TYPE (cmp);       \
529                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
530                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
531                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
532                 GET_BBLOCK (cfg, tblock, target);               \
533                 link_bblock (cfg, cfg->cbb, tblock);    \
534                 ins->inst_true_bb = tblock;     \
535                 if ((next_block)) {     \
536                         link_bblock (cfg, cfg->cbb, (next_block));      \
537                         ins->inst_false_bb = (next_block);      \
538                         start_new_bblock = 1;   \
539                 } else {        \
540                         GET_BBLOCK (cfg, tblock, ip);           \
541                         link_bblock (cfg, cfg->cbb, tblock);    \
542                         ins->inst_false_bb = tblock;    \
543                         start_new_bblock = 2;   \
544                 }       \
545                 if (sp != stack_start) {                                                                        \
546                     handle_stack_args (cfg, stack_start, sp - stack_start); \
547                         CHECK_UNVERIFIABLE (cfg); \
548                 } \
549         MONO_ADD_INS (cfg->cbb, cmp); \
550                 MONO_ADD_INS (cfg->cbb, ins);   \
551         } while (0)
552
553 /* *
554  * link_bblock: Links two basic blocks
555  *
556  * links two basic blocks in the control flow graph, the 'from'
557  * argument is the starting block and the 'to' argument is the block
558  * the control flow ends to after 'from'.
559  */
560 static void
561 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
562 {
563         MonoBasicBlock **newa;
564         int i, found;
565
566 #if 0
567         if (from->cil_code) {
568                 if (to->cil_code)
569                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
570                 else
571                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
572         } else {
573                 if (to->cil_code)
574                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
575                 else
576                         printf ("edge from entry to exit\n");
577         }
578 #endif
579
580         found = FALSE;
581         for (i = 0; i < from->out_count; ++i) {
582                 if (to == from->out_bb [i]) {
583                         found = TRUE;
584                         break;
585                 }
586         }
587         if (!found) {
588                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
589                 for (i = 0; i < from->out_count; ++i) {
590                         newa [i] = from->out_bb [i];
591                 }
592                 newa [i] = to;
593                 from->out_count++;
594                 from->out_bb = newa;
595         }
596
597         found = FALSE;
598         for (i = 0; i < to->in_count; ++i) {
599                 if (from == to->in_bb [i]) {
600                         found = TRUE;
601                         break;
602                 }
603         }
604         if (!found) {
605                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
606                 for (i = 0; i < to->in_count; ++i) {
607                         newa [i] = to->in_bb [i];
608                 }
609                 newa [i] = from;
610                 to->in_count++;
611                 to->in_bb = newa;
612         }
613 }
614
615 void
616 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
617 {
618         link_bblock (cfg, from, to);
619 }
620
621 /**
622  * mono_find_block_region:
623  *
624  *   We mark each basic block with a region ID. We use that to avoid BB
625  *   optimizations when blocks are in different regions.
626  *
627  * Returns:
628  *   A region token that encodes where this region is, and information
629  *   about the clause owner for this block.
630  *
631  *   The region encodes the try/catch/filter clause that owns this block
632  *   as well as the type.  -1 is a special value that represents a block
633  *   that is in none of try/catch/filter.
634  */
635 static int
636 mono_find_block_region (MonoCompile *cfg, int offset)
637 {
638         MonoMethodHeader *header = cfg->header;
639         MonoExceptionClause *clause;
640         int i;
641
642         for (i = 0; i < header->num_clauses; ++i) {
643                 clause = &header->clauses [i];
644                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
645                     (offset < (clause->handler_offset)))
646                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
647                            
648                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
649                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
650                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
651                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
652                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
653                         else
654                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
655                 }
656         }
657         for (i = 0; i < header->num_clauses; ++i) {
658                 clause = &header->clauses [i];
659
660                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
661                         return ((i + 1) << 8) | clause->flags;
662         }
663
664         return -1;
665 }
666
667 static gboolean
668 ip_in_finally_clause (MonoCompile *cfg, int offset)
669 {
670         MonoMethodHeader *header = cfg->header;
671         MonoExceptionClause *clause;
672         int i;
673
674         for (i = 0; i < header->num_clauses; ++i) {
675                 clause = &header->clauses [i];
676                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
677                         continue;
678
679                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
680                         return TRUE;
681         }
682         return FALSE;
683 }
684
685 static GList*
686 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
687 {
688         MonoMethodHeader *header = cfg->header;
689         MonoExceptionClause *clause;
690         int i;
691         GList *res = NULL;
692
693         for (i = 0; i < header->num_clauses; ++i) {
694                 clause = &header->clauses [i];
695                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
696                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
697                         if (clause->flags == type)
698                                 res = g_list_append (res, clause);
699                 }
700         }
701         return res;
702 }
703
704 static void
705 mono_create_spvar_for_region (MonoCompile *cfg, int region)
706 {
707         MonoInst *var;
708
709         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
710         if (var)
711                 return;
712
713         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
714         /* prevent it from being register allocated */
715         var->flags |= MONO_INST_VOLATILE;
716
717         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
718 }
719
720 MonoInst *
721 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
722 {
723         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
724 }
725
726 static MonoInst*
727 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
728 {
729         MonoInst *var;
730
731         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
732         if (var)
733                 return var;
734
735         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
736         /* prevent it from being register allocated */
737         var->flags |= MONO_INST_VOLATILE;
738
739         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
740
741         return var;
742 }
743
744 /*
745  * Returns the type used in the eval stack when @type is loaded.
746  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
747  */
748 void
749 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
750 {
751         MonoClass *klass;
752
753         type = mini_get_underlying_type (type);
754         inst->klass = klass = mono_class_from_mono_type (type);
755         if (type->byref) {
756                 inst->type = STACK_MP;
757                 return;
758         }
759
760 handle_enum:
761         switch (type->type) {
762         case MONO_TYPE_VOID:
763                 inst->type = STACK_INV;
764                 return;
765         case MONO_TYPE_I1:
766         case MONO_TYPE_U1:
767         case MONO_TYPE_I2:
768         case MONO_TYPE_U2:
769         case MONO_TYPE_I4:
770         case MONO_TYPE_U4:
771                 inst->type = STACK_I4;
772                 return;
773         case MONO_TYPE_I:
774         case MONO_TYPE_U:
775         case MONO_TYPE_PTR:
776         case MONO_TYPE_FNPTR:
777                 inst->type = STACK_PTR;
778                 return;
779         case MONO_TYPE_CLASS:
780         case MONO_TYPE_STRING:
781         case MONO_TYPE_OBJECT:
782         case MONO_TYPE_SZARRAY:
783         case MONO_TYPE_ARRAY:    
784                 inst->type = STACK_OBJ;
785                 return;
786         case MONO_TYPE_I8:
787         case MONO_TYPE_U8:
788                 inst->type = STACK_I8;
789                 return;
790         case MONO_TYPE_R4:
791                 inst->type = cfg->r4_stack_type;
792                 break;
793         case MONO_TYPE_R8:
794                 inst->type = STACK_R8;
795                 return;
796         case MONO_TYPE_VALUETYPE:
797                 if (type->data.klass->enumtype) {
798                         type = mono_class_enum_basetype (type->data.klass);
799                         goto handle_enum;
800                 } else {
801                         inst->klass = klass;
802                         inst->type = STACK_VTYPE;
803                         return;
804                 }
805         case MONO_TYPE_TYPEDBYREF:
806                 inst->klass = mono_defaults.typed_reference_class;
807                 inst->type = STACK_VTYPE;
808                 return;
809         case MONO_TYPE_GENERICINST:
810                 type = &type->data.generic_class->container_class->byval_arg;
811                 goto handle_enum;
812         case MONO_TYPE_VAR:
813         case MONO_TYPE_MVAR:
814                 g_assert (cfg->gshared);
815                 if (mini_is_gsharedvt_type (type)) {
816                         g_assert (cfg->gsharedvt);
817                         inst->type = STACK_VTYPE;
818                 } else {
819                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
820                 }
821                 return;
822         default:
823                 g_error ("unknown type 0x%02x in eval stack type", type->type);
824         }
825 }
826
827 /*
828  * The following tables are used to quickly validate the IL code in type_from_op ().
829  */
830 static const char
831 bin_num_table [STACK_MAX] [STACK_MAX] = {
832         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
834         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
835         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
836         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
837         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
838         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
839         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
840         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
841 };
842
843 static const char 
844 neg_table [] = {
845         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
846 };
847
848 /* reduce the size of this table */
849 static const char
850 bin_int_table [STACK_MAX] [STACK_MAX] = {
851         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
852         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
853         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
854         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
856         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
857         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
859 };
860
861 static const char
862 bin_comp_table [STACK_MAX] [STACK_MAX] = {
863 /*      Inv i  L  p  F  &  O  vt r4 */
864         {0},
865         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
866         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
867         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
868         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
869         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
870         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
871         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
872         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
873 };
874
875 /* reduce the size of this table */
876 static const char
877 shift_table [STACK_MAX] [STACK_MAX] = {
878         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
879         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
880         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
881         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
883         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
884         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
885         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
886 };
887
888 /*
889  * Tables to map from the non-specific opcode to the matching
890  * type-specific opcode.
891  */
892 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
893 static const guint16
894 binops_op_map [STACK_MAX] = {
895         0, OP_IADD-CEE_ADD, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD, 0, 0, OP_RADD-CEE_ADD
896 };
897
898 /* handles from CEE_NEG to CEE_CONV_U8 */
899 static const guint16
900 unops_op_map [STACK_MAX] = {
901         0, OP_INEG-CEE_NEG, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG, 0, 0, OP_RNEG-CEE_NEG
902 };
903
904 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
905 static const guint16
906 ovfops_op_map [STACK_MAX] = {
907         0, OP_ICONV_TO_U2-CEE_CONV_U2, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, 0, OP_RCONV_TO_U2-CEE_CONV_U2
908 };
909
910 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
911 static const guint16
912 ovf2ops_op_map [STACK_MAX] = {
913         0, OP_ICONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0, 0, OP_RCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
914 };
915
916 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
917 static const guint16
918 ovf3ops_op_map [STACK_MAX] = {
919         0, OP_ICONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0, 0, OP_RCONV_TO_OVF_I1-CEE_CONV_OVF_I1
920 };
921
922 /* handles from CEE_BEQ to CEE_BLT_UN */
923 static const guint16
924 beqops_op_map [STACK_MAX] = {
925         0, OP_IBEQ-CEE_BEQ, OP_LBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_FBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, 0, OP_FBEQ-CEE_BEQ
926 };
927
928 /* handles from CEE_CEQ to CEE_CLT_UN */
929 static const guint16
930 ceqops_op_map [STACK_MAX] = {
931         0, OP_ICEQ-OP_CEQ, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, 0, OP_RCEQ-OP_CEQ
932 };
933
934 /*
935  * Sets ins->type (the type on the eval stack) according to the
936  * type of the opcode and the arguments to it.
937  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
938  *
939  * FIXME: this function sets ins->type unconditionally in some cases, but
940  * it should set it to invalid for some types (a conv.x on an object)
941  */
942 static void
943 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
944 {
945         switch (ins->opcode) {
946         /* binops */
947         case CEE_ADD:
948         case CEE_SUB:
949         case CEE_MUL:
950         case CEE_DIV:
951         case CEE_REM:
952                 /* FIXME: check unverifiable args for STACK_MP */
953                 ins->type = bin_num_table [src1->type] [src2->type];
954                 ins->opcode += binops_op_map [ins->type];
955                 break;
956         case CEE_DIV_UN:
957         case CEE_REM_UN:
958         case CEE_AND:
959         case CEE_OR:
960         case CEE_XOR:
961                 ins->type = bin_int_table [src1->type] [src2->type];
962                 ins->opcode += binops_op_map [ins->type];
963                 break;
964         case CEE_SHL:
965         case CEE_SHR:
966         case CEE_SHR_UN:
967                 ins->type = shift_table [src1->type] [src2->type];
968                 ins->opcode += binops_op_map [ins->type];
969                 break;
970         case OP_COMPARE:
971         case OP_LCOMPARE:
972         case OP_ICOMPARE:
973                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
974                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
975                         ins->opcode = OP_LCOMPARE;
976                 else if (src1->type == STACK_R4)
977                         ins->opcode = OP_RCOMPARE;
978                 else if (src1->type == STACK_R8)
979                         ins->opcode = OP_FCOMPARE;
980                 else
981                         ins->opcode = OP_ICOMPARE;
982                 break;
983         case OP_ICOMPARE_IMM:
984                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
985                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
986                         ins->opcode = OP_LCOMPARE_IMM;          
987                 break;
988         case CEE_BEQ:
989         case CEE_BGE:
990         case CEE_BGT:
991         case CEE_BLE:
992         case CEE_BLT:
993         case CEE_BNE_UN:
994         case CEE_BGE_UN:
995         case CEE_BGT_UN:
996         case CEE_BLE_UN:
997         case CEE_BLT_UN:
998                 ins->opcode += beqops_op_map [src1->type];
999                 break;
1000         case OP_CEQ:
1001                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1002                 ins->opcode += ceqops_op_map [src1->type];
1003                 break;
1004         case OP_CGT:
1005         case OP_CGT_UN:
1006         case OP_CLT:
1007         case OP_CLT_UN:
1008                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1009                 ins->opcode += ceqops_op_map [src1->type];
1010                 break;
1011         /* unops */
1012         case CEE_NEG:
1013                 ins->type = neg_table [src1->type];
1014                 ins->opcode += unops_op_map [ins->type];
1015                 break;
1016         case CEE_NOT:
1017                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1018                         ins->type = src1->type;
1019                 else
1020                         ins->type = STACK_INV;
1021                 ins->opcode += unops_op_map [ins->type];
1022                 break;
1023         case CEE_CONV_I1:
1024         case CEE_CONV_I2:
1025         case CEE_CONV_I4:
1026         case CEE_CONV_U4:
1027                 ins->type = STACK_I4;
1028                 ins->opcode += unops_op_map [src1->type];
1029                 break;
1030         case CEE_CONV_R_UN:
1031                 ins->type = STACK_R8;
1032                 switch (src1->type) {
1033                 case STACK_I4:
1034                 case STACK_PTR:
1035                         ins->opcode = OP_ICONV_TO_R_UN;
1036                         break;
1037                 case STACK_I8:
1038                         ins->opcode = OP_LCONV_TO_R_UN; 
1039                         break;
1040                 }
1041                 break;
1042         case CEE_CONV_OVF_I1:
1043         case CEE_CONV_OVF_U1:
1044         case CEE_CONV_OVF_I2:
1045         case CEE_CONV_OVF_U2:
1046         case CEE_CONV_OVF_I4:
1047         case CEE_CONV_OVF_U4:
1048                 ins->type = STACK_I4;
1049                 ins->opcode += ovf3ops_op_map [src1->type];
1050                 break;
1051         case CEE_CONV_OVF_I_UN:
1052         case CEE_CONV_OVF_U_UN:
1053                 ins->type = STACK_PTR;
1054                 ins->opcode += ovf2ops_op_map [src1->type];
1055                 break;
1056         case CEE_CONV_OVF_I1_UN:
1057         case CEE_CONV_OVF_I2_UN:
1058         case CEE_CONV_OVF_I4_UN:
1059         case CEE_CONV_OVF_U1_UN:
1060         case CEE_CONV_OVF_U2_UN:
1061         case CEE_CONV_OVF_U4_UN:
1062                 ins->type = STACK_I4;
1063                 ins->opcode += ovf2ops_op_map [src1->type];
1064                 break;
1065         case CEE_CONV_U:
1066                 ins->type = STACK_PTR;
1067                 switch (src1->type) {
1068                 case STACK_I4:
1069                         ins->opcode = OP_ICONV_TO_U;
1070                         break;
1071                 case STACK_PTR:
1072                 case STACK_MP:
1073 #if SIZEOF_VOID_P == 8
1074                         ins->opcode = OP_LCONV_TO_U;
1075 #else
1076                         ins->opcode = OP_MOVE;
1077 #endif
1078                         break;
1079                 case STACK_I8:
1080                         ins->opcode = OP_LCONV_TO_U;
1081                         break;
1082                 case STACK_R8:
1083                         ins->opcode = OP_FCONV_TO_U;
1084                         break;
1085                 }
1086                 break;
1087         case CEE_CONV_I8:
1088         case CEE_CONV_U8:
1089                 ins->type = STACK_I8;
1090                 ins->opcode += unops_op_map [src1->type];
1091                 break;
1092         case CEE_CONV_OVF_I8:
1093         case CEE_CONV_OVF_U8:
1094                 ins->type = STACK_I8;
1095                 ins->opcode += ovf3ops_op_map [src1->type];
1096                 break;
1097         case CEE_CONV_OVF_U8_UN:
1098         case CEE_CONV_OVF_I8_UN:
1099                 ins->type = STACK_I8;
1100                 ins->opcode += ovf2ops_op_map [src1->type];
1101                 break;
1102         case CEE_CONV_R4:
1103                 ins->type = cfg->r4_stack_type;
1104                 ins->opcode += unops_op_map [src1->type];
1105                 break;
1106         case CEE_CONV_R8:
1107                 ins->type = STACK_R8;
1108                 ins->opcode += unops_op_map [src1->type];
1109                 break;
1110         case OP_CKFINITE:
1111                 ins->type = STACK_R8;           
1112                 break;
1113         case CEE_CONV_U2:
1114         case CEE_CONV_U1:
1115                 ins->type = STACK_I4;
1116                 ins->opcode += ovfops_op_map [src1->type];
1117                 break;
1118         case CEE_CONV_I:
1119         case CEE_CONV_OVF_I:
1120         case CEE_CONV_OVF_U:
1121                 ins->type = STACK_PTR;
1122                 ins->opcode += ovfops_op_map [src1->type];
1123                 break;
1124         case CEE_ADD_OVF:
1125         case CEE_ADD_OVF_UN:
1126         case CEE_MUL_OVF:
1127         case CEE_MUL_OVF_UN:
1128         case CEE_SUB_OVF:
1129         case CEE_SUB_OVF_UN:
1130                 ins->type = bin_num_table [src1->type] [src2->type];
1131                 ins->opcode += ovfops_op_map [src1->type];
1132                 if (ins->type == STACK_R8)
1133                         ins->type = STACK_INV;
1134                 break;
1135         case OP_LOAD_MEMBASE:
1136                 ins->type = STACK_PTR;
1137                 break;
1138         case OP_LOADI1_MEMBASE:
1139         case OP_LOADU1_MEMBASE:
1140         case OP_LOADI2_MEMBASE:
1141         case OP_LOADU2_MEMBASE:
1142         case OP_LOADI4_MEMBASE:
1143         case OP_LOADU4_MEMBASE:
1144                 ins->type = STACK_PTR;
1145                 break;
1146         case OP_LOADI8_MEMBASE:
1147                 ins->type = STACK_I8;
1148                 break;
1149         case OP_LOADR4_MEMBASE:
1150                 ins->type = cfg->r4_stack_type;
1151                 break;
1152         case OP_LOADR8_MEMBASE:
1153                 ins->type = STACK_R8;
1154                 break;
1155         default:
1156                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1157                 break;
1158         }
1159
1160         if (ins->type == STACK_MP)
1161                 ins->klass = mono_defaults.object_class;
1162 }
1163
1164 static MonoClass*
1165 ldind_to_type (int op)
1166 {
1167         switch (op) {
1168         case CEE_LDIND_I1: return mono_defaults.sbyte_class;
1169         case CEE_LDIND_U1: return mono_defaults.byte_class;
1170         case CEE_LDIND_I2: return mono_defaults.int16_class;
1171         case CEE_LDIND_U2: return mono_defaults.uint16_class;
1172         case CEE_LDIND_I4: return mono_defaults.int32_class;
1173         case CEE_LDIND_U4: return mono_defaults.uint32_class;
1174         case CEE_LDIND_I8: return mono_defaults.int64_class;
1175         case CEE_LDIND_I: return mono_defaults.int_class;
1176         case CEE_LDIND_R4: return mono_defaults.single_class;
1177         case CEE_LDIND_R8: return mono_defaults.double_class;
1178         case CEE_LDIND_REF:return mono_defaults.object_class; //FIXME we should try to return a more specific type
1179         default: g_error ("Unknown ldind type %d", op);
1180         }
1181 }
1182
1183 #if 0
1184
1185 static const char
1186 param_table [STACK_MAX] [STACK_MAX] = {
1187         {0},
1188 };
1189
1190 static int
1191 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1192 {
1193         int i;
1194
1195         if (sig->hasthis) {
1196                 switch (args->type) {
1197                 case STACK_I4:
1198                 case STACK_I8:
1199                 case STACK_R8:
1200                 case STACK_VTYPE:
1201                 case STACK_INV:
1202                         return 0;
1203                 }
1204                 args++;
1205         }
1206         for (i = 0; i < sig->param_count; ++i) {
1207                 switch (args [i].type) {
1208                 case STACK_INV:
1209                         return 0;
1210                 case STACK_MP:
1211                         if (!sig->params [i]->byref)
1212                                 return 0;
1213                         continue;
1214                 case STACK_OBJ:
1215                         if (sig->params [i]->byref)
1216                                 return 0;
1217                         switch (sig->params [i]->type) {
1218                         case MONO_TYPE_CLASS:
1219                         case MONO_TYPE_STRING:
1220                         case MONO_TYPE_OBJECT:
1221                         case MONO_TYPE_SZARRAY:
1222                         case MONO_TYPE_ARRAY:
1223                                 break;
1224                         default:
1225                                 return 0;
1226                         }
1227                         continue;
1228                 case STACK_R8:
1229                         if (sig->params [i]->byref)
1230                                 return 0;
1231                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1232                                 return 0;
1233                         continue;
1234                 case STACK_PTR:
1235                 case STACK_I4:
1236                 case STACK_I8:
1237                 case STACK_VTYPE:
1238                         break;
1239                 }
1240                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1241                         return 0;*/
1242         }
1243         return 1;
1244 }
1245 #endif
1246
1247 /*
1248  * When we need a pointer to the current domain many times in a method, we
1249  * call mono_domain_get() once and we store the result in a local variable.
1250  * This function returns the variable that represents the MonoDomain*.
1251  */
1252 inline static MonoInst *
1253 mono_get_domainvar (MonoCompile *cfg)
1254 {
1255         if (!cfg->domainvar)
1256                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1257         return cfg->domainvar;
1258 }
1259
1260 /*
1261  * The got_var contains the address of the Global Offset Table when AOT 
1262  * compiling.
1263  */
1264 MonoInst *
1265 mono_get_got_var (MonoCompile *cfg)
1266 {
1267         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1268                 return NULL;
1269         if (!cfg->got_var) {
1270                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1271         }
1272         return cfg->got_var;
1273 }
1274
1275 static void
1276 mono_create_rgctx_var (MonoCompile *cfg)
1277 {
1278         if (!cfg->rgctx_var) {
1279                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1280                 /* force the var to be stack allocated */
1281                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1282         }
1283 }
1284
1285 static MonoInst *
1286 mono_get_vtable_var (MonoCompile *cfg)
1287 {
1288         g_assert (cfg->gshared);
1289
1290         mono_create_rgctx_var (cfg);
1291
1292         return cfg->rgctx_var;
1293 }
1294
1295 static MonoType*
1296 type_from_stack_type (MonoInst *ins) {
1297         switch (ins->type) {
1298         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1299         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1300         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1301         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1302         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1303         case STACK_MP:
1304                 return &ins->klass->this_arg;
1305         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1306         case STACK_VTYPE: return &ins->klass->byval_arg;
1307         default:
1308                 g_error ("stack type %d to monotype not handled\n", ins->type);
1309         }
1310         return NULL;
1311 }
1312
1313 static G_GNUC_UNUSED int
1314 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1315 {
1316         t = mono_type_get_underlying_type (t);
1317         switch (t->type) {
1318         case MONO_TYPE_I1:
1319         case MONO_TYPE_U1:
1320         case MONO_TYPE_I2:
1321         case MONO_TYPE_U2:
1322         case MONO_TYPE_I4:
1323         case MONO_TYPE_U4:
1324                 return STACK_I4;
1325         case MONO_TYPE_I:
1326         case MONO_TYPE_U:
1327         case MONO_TYPE_PTR:
1328         case MONO_TYPE_FNPTR:
1329                 return STACK_PTR;
1330         case MONO_TYPE_CLASS:
1331         case MONO_TYPE_STRING:
1332         case MONO_TYPE_OBJECT:
1333         case MONO_TYPE_SZARRAY:
1334         case MONO_TYPE_ARRAY:    
1335                 return STACK_OBJ;
1336         case MONO_TYPE_I8:
1337         case MONO_TYPE_U8:
1338                 return STACK_I8;
1339         case MONO_TYPE_R4:
1340                 return cfg->r4_stack_type;
1341         case MONO_TYPE_R8:
1342                 return STACK_R8;
1343         case MONO_TYPE_VALUETYPE:
1344         case MONO_TYPE_TYPEDBYREF:
1345                 return STACK_VTYPE;
1346         case MONO_TYPE_GENERICINST:
1347                 if (mono_type_generic_inst_is_valuetype (t))
1348                         return STACK_VTYPE;
1349                 else
1350                         return STACK_OBJ;
1351                 break;
1352         default:
1353                 g_assert_not_reached ();
1354         }
1355
1356         return -1;
1357 }
1358
1359 static MonoClass*
1360 array_access_to_klass (int opcode)
1361 {
1362         switch (opcode) {
1363         case CEE_LDELEM_U1:
1364                 return mono_defaults.byte_class;
1365         case CEE_LDELEM_U2:
1366                 return mono_defaults.uint16_class;
1367         case CEE_LDELEM_I:
1368         case CEE_STELEM_I:
1369                 return mono_defaults.int_class;
1370         case CEE_LDELEM_I1:
1371         case CEE_STELEM_I1:
1372                 return mono_defaults.sbyte_class;
1373         case CEE_LDELEM_I2:
1374         case CEE_STELEM_I2:
1375                 return mono_defaults.int16_class;
1376         case CEE_LDELEM_I4:
1377         case CEE_STELEM_I4:
1378                 return mono_defaults.int32_class;
1379         case CEE_LDELEM_U4:
1380                 return mono_defaults.uint32_class;
1381         case CEE_LDELEM_I8:
1382         case CEE_STELEM_I8:
1383                 return mono_defaults.int64_class;
1384         case CEE_LDELEM_R4:
1385         case CEE_STELEM_R4:
1386                 return mono_defaults.single_class;
1387         case CEE_LDELEM_R8:
1388         case CEE_STELEM_R8:
1389                 return mono_defaults.double_class;
1390         case CEE_LDELEM_REF:
1391         case CEE_STELEM_REF:
1392                 return mono_defaults.object_class;
1393         default:
1394                 g_assert_not_reached ();
1395         }
1396         return NULL;
1397 }
1398
1399 /*
1400  * We try to share variables when possible
1401  */
1402 static MonoInst *
1403 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1404 {
1405         MonoInst *res;
1406         int pos, vnum;
1407
1408         /* inlining can result in deeper stacks */ 
1409         if (slot >= cfg->header->max_stack)
1410                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1411
1412         pos = ins->type - 1 + slot * STACK_MAX;
1413
1414         switch (ins->type) {
1415         case STACK_I4:
1416         case STACK_I8:
1417         case STACK_R8:
1418         case STACK_PTR:
1419         case STACK_MP:
1420         case STACK_OBJ:
1421                 if ((vnum = cfg->intvars [pos]))
1422                         return cfg->varinfo [vnum];
1423                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1424                 cfg->intvars [pos] = res->inst_c0;
1425                 break;
1426         default:
1427                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1428         }
1429         return res;
1430 }
1431
1432 static void
1433 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1434 {
1435         /* 
1436          * Don't use this if a generic_context is set, since that means AOT can't
1437          * look up the method using just the image+token.
1438          * table == 0 means this is a reference made from a wrapper.
1439          */
1440         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1441                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1442                 jump_info_token->image = image;
1443                 jump_info_token->token = token;
1444                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1445         }
1446 }
1447
1448 /*
1449  * This function is called to handle items that are left on the evaluation stack
1450  * at basic block boundaries. What happens is that we save the values to local variables
1451  * and we reload them later when first entering the target basic block (with the
1452  * handle_loaded_temps () function).
1453  * A single joint point will use the same variables (stored in the array bb->out_stack or
1454  * bb->in_stack, if the basic block is before or after the joint point).
1455  *
1456  * This function needs to be called _before_ emitting the last instruction of
1457  * the bb (i.e. before emitting a branch).
1458  * If the stack merge fails at a join point, cfg->unverifiable is set.
1459  */
1460 static void
1461 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1462 {
1463         int i, bindex;
1464         MonoBasicBlock *bb = cfg->cbb;
1465         MonoBasicBlock *outb;
1466         MonoInst *inst, **locals;
1467         gboolean found;
1468
1469         if (!count)
1470                 return;
1471         if (cfg->verbose_level > 3)
1472                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1473         if (!bb->out_scount) {
1474                 bb->out_scount = count;
1475                 //printf ("bblock %d has out:", bb->block_num);
1476                 found = FALSE;
1477                 for (i = 0; i < bb->out_count; ++i) {
1478                         outb = bb->out_bb [i];
1479                         /* exception handlers are linked, but they should not be considered for stack args */
1480                         if (outb->flags & BB_EXCEPTION_HANDLER)
1481                                 continue;
1482                         //printf (" %d", outb->block_num);
1483                         if (outb->in_stack) {
1484                                 found = TRUE;
1485                                 bb->out_stack = outb->in_stack;
1486                                 break;
1487                         }
1488                 }
1489                 //printf ("\n");
1490                 if (!found) {
1491                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1492                         for (i = 0; i < count; ++i) {
1493                                 /* 
1494                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1495                                  * stack slot and if they are of the same type.
1496                                  * This won't cause conflicts since if 'local' is used to 
1497                                  * store one of the values in the in_stack of a bblock, then
1498                                  * the same variable will be used for the same outgoing stack 
1499                                  * slot as well. 
1500                                  * This doesn't work when inlining methods, since the bblocks
1501                                  * in the inlined methods do not inherit their in_stack from
1502                                  * the bblock they are inlined to. See bug #58863 for an
1503                                  * example.
1504                                  */
1505                                 if (cfg->inlined_method)
1506                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1507                                 else
1508                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1509                         }
1510                 }
1511         }
1512
1513         for (i = 0; i < bb->out_count; ++i) {
1514                 outb = bb->out_bb [i];
1515                 /* exception handlers are linked, but they should not be considered for stack args */
1516                 if (outb->flags & BB_EXCEPTION_HANDLER)
1517                         continue;
1518                 if (outb->in_scount) {
1519                         if (outb->in_scount != bb->out_scount) {
1520                                 cfg->unverifiable = TRUE;
1521                                 return;
1522                         }
1523                         continue; /* check they are the same locals */
1524                 }
1525                 outb->in_scount = count;
1526                 outb->in_stack = bb->out_stack;
1527         }
1528
1529         locals = bb->out_stack;
1530         cfg->cbb = bb;
1531         for (i = 0; i < count; ++i) {
1532                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1533                 inst->cil_code = sp [i]->cil_code;
1534                 sp [i] = locals [i];
1535                 if (cfg->verbose_level > 3)
1536                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1537         }
1538
1539         /*
1540          * It is possible that the out bblocks already have in_stack assigned, and
1541          * the in_stacks differ. In this case, we will store to all the different 
1542          * in_stacks.
1543          */
1544
1545         found = TRUE;
1546         bindex = 0;
1547         while (found) {
1548                 /* Find a bblock which has a different in_stack */
1549                 found = FALSE;
1550                 while (bindex < bb->out_count) {
1551                         outb = bb->out_bb [bindex];
1552                         /* exception handlers are linked, but they should not be considered for stack args */
1553                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1554                                 bindex++;
1555                                 continue;
1556                         }
1557                         if (outb->in_stack != locals) {
1558                                 for (i = 0; i < count; ++i) {
1559                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1560                                         inst->cil_code = sp [i]->cil_code;
1561                                         sp [i] = locals [i];
1562                                         if (cfg->verbose_level > 3)
1563                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1564                                 }
1565                                 locals = outb->in_stack;
1566                                 found = TRUE;
1567                                 break;
1568                         }
1569                         bindex ++;
1570                 }
1571         }
1572 }
1573
1574 MonoInst*
1575 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1576 {
1577         MonoInst *ins;
1578
1579         if (cfg->compile_aot) {
1580                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1581         } else {
1582                 MonoJumpInfo ji;
1583                 gpointer target;
1584                 MonoError error;
1585
1586                 ji.type = patch_type;
1587                 ji.data.target = data;
1588                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1589                 mono_error_assert_ok (&error);
1590
1591                 EMIT_NEW_PCONST (cfg, ins, target);
1592         }
1593         return ins;
1594 }
1595
1596 static MonoInst*
1597 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1598 {
1599         int tls_offset = mono_tls_get_tls_offset (key);
1600
1601         if (cfg->compile_aot)
1602                 return NULL;
1603
1604         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1605                 MonoInst *ins;
1606                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1607                 ins->dreg = mono_alloc_preg (cfg);
1608                 ins->inst_offset = tls_offset;
1609                 return ins;
1610         }
1611         return NULL;
1612 }
1613
1614 static MonoInst*
1615 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1616 {
1617         int tls_offset = mono_tls_get_tls_offset (key);
1618
1619         if (cfg->compile_aot)
1620                 return NULL;
1621
1622         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1623                 MonoInst *ins;
1624                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1625                 ins->sreg1 = value->dreg;
1626                 ins->inst_offset = tls_offset;
1627                 return ins;
1628         }
1629         return NULL;
1630 }
1631
1632
1633 MonoInst*
1634 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1635 {
1636         MonoInst *fast_tls = NULL;
1637
1638         if (!mini_get_debug_options ()->use_fallback_tls)
1639                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1640
1641         if (fast_tls) {
1642                 MONO_ADD_INS (cfg->cbb, fast_tls);
1643                 return fast_tls;
1644         }
1645
1646         if (cfg->compile_aot) {
1647                 MonoInst *addr;
1648                 /*
1649                  * tls getters are critical pieces of code and we don't want to resolve them
1650                  * through the standard plt/tramp mechanism since we might expose ourselves
1651                  * to crashes and infinite recursions.
1652                  */
1653                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1654                 return mini_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1655         } else {
1656                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1657                 return mono_emit_jit_icall (cfg, getter, NULL);
1658         }
1659 }
1660
1661 static MonoInst*
1662 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1663 {
1664         MonoInst *fast_tls = NULL;
1665
1666         if (!mini_get_debug_options ()->use_fallback_tls)
1667                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1668
1669         if (fast_tls) {
1670                 MONO_ADD_INS (cfg->cbb, fast_tls);
1671                 return fast_tls;
1672         }
1673
1674         if (cfg->compile_aot) {
1675                 MonoInst *addr;
1676                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1677                 return mini_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1678         } else {
1679                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1680                 return mono_emit_jit_icall (cfg, setter, &value);
1681         }
1682 }
1683
1684 /*
1685  * emit_push_lmf:
1686  *
1687  *   Emit IR to push the current LMF onto the LMF stack.
1688  */
1689 static void
1690 emit_push_lmf (MonoCompile *cfg)
1691 {
1692         /*
1693          * Emit IR to push the LMF:
1694          * lmf_addr = <lmf_addr from tls>
1695          * lmf->lmf_addr = lmf_addr
1696          * lmf->prev_lmf = *lmf_addr
1697          * *lmf_addr = lmf
1698          */
1699         MonoInst *ins, *lmf_ins;
1700
1701         if (!cfg->lmf_ir)
1702                 return;
1703
1704         int lmf_reg, prev_lmf_reg;
1705         /*
1706          * Store lmf_addr in a variable, so it can be allocated to a global register.
1707          */
1708         if (!cfg->lmf_addr_var)
1709                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1710
1711 #ifdef HOST_WIN32
1712         ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1713         g_assert (ins);
1714         int jit_tls_dreg = ins->dreg;
1715
1716         lmf_reg = alloc_preg (cfg);
1717         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1718 #else
1719         lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1720         g_assert (lmf_ins);
1721 #endif
1722         lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1723
1724         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1725         lmf_reg = ins->dreg;
1726
1727         prev_lmf_reg = alloc_preg (cfg);
1728         /* Save previous_lmf */
1729         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1730         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1731         /* Set new lmf */
1732         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1733 }
1734
1735 /*
1736  * emit_pop_lmf:
1737  *
1738  *   Emit IR to pop the current LMF from the LMF stack.
1739  */
1740 static void
1741 emit_pop_lmf (MonoCompile *cfg)
1742 {
1743         int lmf_reg, lmf_addr_reg;
1744         MonoInst *ins;
1745
1746         if (!cfg->lmf_ir)
1747                 return;
1748
1749         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1750         lmf_reg = ins->dreg;
1751
1752         int prev_lmf_reg;
1753         /*
1754          * Emit IR to pop the LMF:
1755          * *(lmf->lmf_addr) = lmf->prev_lmf
1756          */
1757         /* This could be called before emit_push_lmf () */
1758         if (!cfg->lmf_addr_var)
1759                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1760         lmf_addr_reg = cfg->lmf_addr_var->dreg;
1761
1762         prev_lmf_reg = alloc_preg (cfg);
1763         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1764         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1765 }
1766
1767 static void
1768 emit_instrumentation_call (MonoCompile *cfg, void *func)
1769 {
1770         MonoInst *iargs [1];
1771
1772         /*
1773          * Avoid instrumenting inlined methods since it can
1774          * distort profiling results.
1775          */
1776         if (cfg->method != cfg->current_method)
1777                 return;
1778
1779         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1780                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1781                 mono_emit_jit_icall (cfg, func, iargs);
1782         }
1783 }
1784
1785 static int
1786 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1787 {
1788 handle_enum:
1789         type = mini_get_underlying_type (type);
1790         switch (type->type) {
1791         case MONO_TYPE_VOID:
1792                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1793         case MONO_TYPE_I1:
1794         case MONO_TYPE_U1:
1795         case MONO_TYPE_I2:
1796         case MONO_TYPE_U2:
1797         case MONO_TYPE_I4:
1798         case MONO_TYPE_U4:
1799                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1800         case MONO_TYPE_I:
1801         case MONO_TYPE_U:
1802         case MONO_TYPE_PTR:
1803         case MONO_TYPE_FNPTR:
1804                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1805         case MONO_TYPE_CLASS:
1806         case MONO_TYPE_STRING:
1807         case MONO_TYPE_OBJECT:
1808         case MONO_TYPE_SZARRAY:
1809         case MONO_TYPE_ARRAY:    
1810                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1811         case MONO_TYPE_I8:
1812         case MONO_TYPE_U8:
1813                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1814         case MONO_TYPE_R4:
1815                 if (cfg->r4fp)
1816                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1817                 else
1818                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1819         case MONO_TYPE_R8:
1820                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1821         case MONO_TYPE_VALUETYPE:
1822                 if (type->data.klass->enumtype) {
1823                         type = mono_class_enum_basetype (type->data.klass);
1824                         goto handle_enum;
1825                 } else
1826                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1827         case MONO_TYPE_TYPEDBYREF:
1828                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1829         case MONO_TYPE_GENERICINST:
1830                 type = &type->data.generic_class->container_class->byval_arg;
1831                 goto handle_enum;
1832         case MONO_TYPE_VAR:
1833         case MONO_TYPE_MVAR:
1834                 /* gsharedvt */
1835                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1836         default:
1837                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1838         }
1839         return -1;
1840 }
1841
1842 //XXX this ignores if t is byref
1843 #define MONO_TYPE_IS_PRIMITIVE_SCALAR(t) ((((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_U8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
1844
1845 /*
1846  * target_type_is_incompatible:
1847  * @cfg: MonoCompile context
1848  *
1849  * Check that the item @arg on the evaluation stack can be stored
1850  * in the target type (can be a local, or field, etc).
1851  * The cfg arg can be used to check if we need verification or just
1852  * validity checks.
1853  *
1854  * Returns: non-0 value if arg can't be stored on a target.
1855  */
1856 static int
1857 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1858 {
1859         MonoType *simple_type;
1860         MonoClass *klass;
1861
1862         if (target->byref) {
1863                 /* FIXME: check that the pointed to types match */
1864                 if (arg->type == STACK_MP) {
1865                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1866                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1867                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1868
1869                         /* if the target is native int& or same type */
1870                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
1871                                 return 0;
1872
1873                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
1874                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
1875                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
1876                                 return 0;
1877                         return 1;
1878                 }
1879                 if (arg->type == STACK_PTR)
1880                         return 0;
1881                 return 1;
1882         }
1883
1884         simple_type = mini_get_underlying_type (target);
1885         switch (simple_type->type) {
1886         case MONO_TYPE_VOID:
1887                 return 1;
1888         case MONO_TYPE_I1:
1889         case MONO_TYPE_U1:
1890         case MONO_TYPE_I2:
1891         case MONO_TYPE_U2:
1892         case MONO_TYPE_I4:
1893         case MONO_TYPE_U4:
1894                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
1895                         return 1;
1896                 return 0;
1897         case MONO_TYPE_PTR:
1898                 /* STACK_MP is needed when setting pinned locals */
1899                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1900                         return 1;
1901                 return 0;
1902         case MONO_TYPE_I:
1903         case MONO_TYPE_U:
1904         case MONO_TYPE_FNPTR:
1905                 /* 
1906                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
1907                  * in native int. (#688008).
1908                  */
1909                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1910                         return 1;
1911                 return 0;
1912         case MONO_TYPE_CLASS:
1913         case MONO_TYPE_STRING:
1914         case MONO_TYPE_OBJECT:
1915         case MONO_TYPE_SZARRAY:
1916         case MONO_TYPE_ARRAY:    
1917                 if (arg->type != STACK_OBJ)
1918                         return 1;
1919                 /* FIXME: check type compatibility */
1920                 return 0;
1921         case MONO_TYPE_I8:
1922         case MONO_TYPE_U8:
1923                 if (arg->type != STACK_I8)
1924                         return 1;
1925                 return 0;
1926         case MONO_TYPE_R4:
1927                 if (arg->type != cfg->r4_stack_type)
1928                         return 1;
1929                 return 0;
1930         case MONO_TYPE_R8:
1931                 if (arg->type != STACK_R8)
1932                         return 1;
1933                 return 0;
1934         case MONO_TYPE_VALUETYPE:
1935                 if (arg->type != STACK_VTYPE)
1936                         return 1;
1937                 klass = mono_class_from_mono_type (simple_type);
1938                 if (klass != arg->klass)
1939                         return 1;
1940                 return 0;
1941         case MONO_TYPE_TYPEDBYREF:
1942                 if (arg->type != STACK_VTYPE)
1943                         return 1;
1944                 klass = mono_class_from_mono_type (simple_type);
1945                 if (klass != arg->klass)
1946                         return 1;
1947                 return 0;
1948         case MONO_TYPE_GENERICINST:
1949                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
1950                         MonoClass *target_class;
1951                         if (arg->type != STACK_VTYPE)
1952                                 return 1;
1953                         klass = mono_class_from_mono_type (simple_type);
1954                         target_class = mono_class_from_mono_type (target);
1955                         /* The second cases is needed when doing partial sharing */
1956                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
1957                                 return 1;
1958                         return 0;
1959                 } else {
1960                         if (arg->type != STACK_OBJ)
1961                                 return 1;
1962                         /* FIXME: check type compatibility */
1963                         return 0;
1964                 }
1965         case MONO_TYPE_VAR:
1966         case MONO_TYPE_MVAR:
1967                 g_assert (cfg->gshared);
1968                 if (mini_type_var_is_vt (simple_type)) {
1969                         if (arg->type != STACK_VTYPE)
1970                                 return 1;
1971                 } else {
1972                         if (arg->type != STACK_OBJ)
1973                                 return 1;
1974                 }
1975                 return 0;
1976         default:
1977                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
1978         }
1979         return 1;
1980 }
1981
1982 /*
1983  * Prepare arguments for passing to a function call.
1984  * Return a non-zero value if the arguments can't be passed to the given
1985  * signature.
1986  * The type checks are not yet complete and some conversions may need
1987  * casts on 32 or 64 bit architectures.
1988  *
1989  * FIXME: implement this using target_type_is_incompatible ()
1990  */
1991 static int
1992 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
1993 {
1994         MonoType *simple_type;
1995         int i;
1996
1997         if (sig->hasthis) {
1998                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
1999                         return 1;
2000                 args++;
2001         }
2002         for (i = 0; i < sig->param_count; ++i) {
2003                 if (sig->params [i]->byref) {
2004                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2005                                 return 1;
2006                         continue;
2007                 }
2008                 simple_type = mini_get_underlying_type (sig->params [i]);
2009 handle_enum:
2010                 switch (simple_type->type) {
2011                 case MONO_TYPE_VOID:
2012                         return 1;
2013                         continue;
2014                 case MONO_TYPE_I1:
2015                 case MONO_TYPE_U1:
2016                 case MONO_TYPE_I2:
2017                 case MONO_TYPE_U2:
2018                 case MONO_TYPE_I4:
2019                 case MONO_TYPE_U4:
2020                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2021                                 return 1;
2022                         continue;
2023                 case MONO_TYPE_I:
2024                 case MONO_TYPE_U:
2025                 case MONO_TYPE_PTR:
2026                 case MONO_TYPE_FNPTR:
2027                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2028                                 return 1;
2029                         continue;
2030                 case MONO_TYPE_CLASS:
2031                 case MONO_TYPE_STRING:
2032                 case MONO_TYPE_OBJECT:
2033                 case MONO_TYPE_SZARRAY:
2034                 case MONO_TYPE_ARRAY:    
2035                         if (args [i]->type != STACK_OBJ)
2036                                 return 1;
2037                         continue;
2038                 case MONO_TYPE_I8:
2039                 case MONO_TYPE_U8:
2040                         if (args [i]->type != STACK_I8)
2041                                 return 1;
2042                         continue;
2043                 case MONO_TYPE_R4:
2044                         if (args [i]->type != cfg->r4_stack_type)
2045                                 return 1;
2046                         continue;
2047                 case MONO_TYPE_R8:
2048                         if (args [i]->type != STACK_R8)
2049                                 return 1;
2050                         continue;
2051                 case MONO_TYPE_VALUETYPE:
2052                         if (simple_type->data.klass->enumtype) {
2053                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2054                                 goto handle_enum;
2055                         }
2056                         if (args [i]->type != STACK_VTYPE)
2057                                 return 1;
2058                         continue;
2059                 case MONO_TYPE_TYPEDBYREF:
2060                         if (args [i]->type != STACK_VTYPE)
2061                                 return 1;
2062                         continue;
2063                 case MONO_TYPE_GENERICINST:
2064                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2065                         goto handle_enum;
2066                 case MONO_TYPE_VAR:
2067                 case MONO_TYPE_MVAR:
2068                         /* gsharedvt */
2069                         if (args [i]->type != STACK_VTYPE)
2070                                 return 1;
2071                         continue;
2072                 default:
2073                         g_error ("unknown type 0x%02x in check_call_signature",
2074                                  simple_type->type);
2075                 }
2076         }
2077         return 0;
2078 }
2079
2080 static int
2081 callvirt_to_call (int opcode)
2082 {
2083         switch (opcode) {
2084         case OP_CALL_MEMBASE:
2085                 return OP_CALL;
2086         case OP_VOIDCALL_MEMBASE:
2087                 return OP_VOIDCALL;
2088         case OP_FCALL_MEMBASE:
2089                 return OP_FCALL;
2090         case OP_RCALL_MEMBASE:
2091                 return OP_RCALL;
2092         case OP_VCALL_MEMBASE:
2093                 return OP_VCALL;
2094         case OP_LCALL_MEMBASE:
2095                 return OP_LCALL;
2096         default:
2097                 g_assert_not_reached ();
2098         }
2099
2100         return -1;
2101 }
2102
2103 static int
2104 callvirt_to_call_reg (int opcode)
2105 {
2106         switch (opcode) {
2107         case OP_CALL_MEMBASE:
2108                 return OP_CALL_REG;
2109         case OP_VOIDCALL_MEMBASE:
2110                 return OP_VOIDCALL_REG;
2111         case OP_FCALL_MEMBASE:
2112                 return OP_FCALL_REG;
2113         case OP_RCALL_MEMBASE:
2114                 return OP_RCALL_REG;
2115         case OP_VCALL_MEMBASE:
2116                 return OP_VCALL_REG;
2117         case OP_LCALL_MEMBASE:
2118                 return OP_LCALL_REG;
2119         default:
2120                 g_assert_not_reached ();
2121         }
2122
2123         return -1;
2124 }
2125
2126 /* Either METHOD or IMT_ARG needs to be set */
2127 static void
2128 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2129 {
2130         int method_reg;
2131
2132         if (COMPILE_LLVM (cfg)) {
2133                 if (imt_arg) {
2134                         method_reg = alloc_preg (cfg);
2135                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2136                 } else {
2137                         MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2138                         method_reg = ins->dreg;
2139                 }
2140
2141 #ifdef ENABLE_LLVM
2142                 call->imt_arg_reg = method_reg;
2143 #endif
2144                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2145                 return;
2146         }
2147
2148         if (imt_arg) {
2149                 method_reg = alloc_preg (cfg);
2150                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2151         } else {
2152                 MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2153                 method_reg = ins->dreg;
2154         }
2155
2156         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2157 }
2158
2159 static MonoJumpInfo *
2160 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2161 {
2162         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2163
2164         ji->ip.i = ip;
2165         ji->type = type;
2166         ji->data.target = target;
2167
2168         return ji;
2169 }
2170
2171 int
2172 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2173 {
2174         if (cfg->gshared)
2175                 return mono_class_check_context_used (klass);
2176         else
2177                 return 0;
2178 }
2179
2180 static int
2181 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2182 {
2183         if (cfg->gshared)
2184                 return mono_method_check_context_used (method);
2185         else
2186                 return 0;
2187 }
2188
2189 /*
2190  * check_method_sharing:
2191  *
2192  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2193  */
2194 static void
2195 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2196 {
2197         gboolean pass_vtable = FALSE;
2198         gboolean pass_mrgctx = FALSE;
2199
2200         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2201                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2202                 gboolean sharable = FALSE;
2203
2204                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2205                         sharable = TRUE;
2206
2207                 /*
2208                  * Pass vtable iff target method might
2209                  * be shared, which means that sharing
2210                  * is enabled for its class and its
2211                  * context is sharable (and it's not a
2212                  * generic method).
2213                  */
2214                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2215                         pass_vtable = TRUE;
2216         }
2217
2218         if (mini_method_get_context (cmethod) &&
2219                 mini_method_get_context (cmethod)->method_inst) {
2220                 g_assert (!pass_vtable);
2221
2222                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2223                         pass_mrgctx = TRUE;
2224                 } else {
2225                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2226                                 pass_mrgctx = TRUE;
2227                 }
2228         }
2229
2230         if (out_pass_vtable)
2231                 *out_pass_vtable = pass_vtable;
2232         if (out_pass_mrgctx)
2233                 *out_pass_mrgctx = pass_mrgctx;
2234 }
2235
2236 inline static MonoCallInst *
2237 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2238                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2239 {
2240         MonoType *sig_ret;
2241         MonoCallInst *call;
2242 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2243         int i;
2244 #endif
2245
2246         if (cfg->llvm_only)
2247                 tail = FALSE;
2248
2249         if (tail) {
2250                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2251
2252                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2253         } else
2254                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2255
2256         call->args = args;
2257         call->signature = sig;
2258         call->rgctx_reg = rgctx;
2259         sig_ret = mini_get_underlying_type (sig->ret);
2260
2261         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2262
2263         if (tail) {
2264                 if (mini_type_is_vtype (sig_ret)) {
2265                         call->vret_var = cfg->vret_addr;
2266                         //g_assert_not_reached ();
2267                 }
2268         } else if (mini_type_is_vtype (sig_ret)) {
2269                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2270                 MonoInst *loada;
2271
2272                 temp->backend.is_pinvoke = sig->pinvoke;
2273
2274                 /*
2275                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2276                  * address of return value to increase optimization opportunities.
2277                  * Before vtype decomposition, the dreg of the call ins itself represents the
2278                  * fact the call modifies the return value. After decomposition, the call will
2279                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2280                  * will be transformed into an LDADDR.
2281                  */
2282                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2283                 loada->dreg = alloc_preg (cfg);
2284                 loada->inst_p0 = temp;
2285                 /* We reference the call too since call->dreg could change during optimization */
2286                 loada->inst_p1 = call;
2287                 MONO_ADD_INS (cfg->cbb, loada);
2288
2289                 call->inst.dreg = temp->dreg;
2290
2291                 call->vret_var = loada;
2292         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2293                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2294
2295 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2296         if (COMPILE_SOFT_FLOAT (cfg)) {
2297                 /* 
2298                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2299                  * an icall, but that cannot be done during the call sequence since it would clobber
2300                  * the call registers + the stack. So we do it before emitting the call.
2301                  */
2302                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2303                         MonoType *t;
2304                         MonoInst *in = call->args [i];
2305
2306                         if (i >= sig->hasthis)
2307                                 t = sig->params [i - sig->hasthis];
2308                         else
2309                                 t = &mono_defaults.int_class->byval_arg;
2310                         t = mono_type_get_underlying_type (t);
2311
2312                         if (!t->byref && t->type == MONO_TYPE_R4) {
2313                                 MonoInst *iargs [1];
2314                                 MonoInst *conv;
2315
2316                                 iargs [0] = in;
2317                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2318
2319                                 /* The result will be in an int vreg */
2320                                 call->args [i] = conv;
2321                         }
2322                 }
2323         }
2324 #endif
2325
2326         call->need_unbox_trampoline = unbox_trampoline;
2327
2328 #ifdef ENABLE_LLVM
2329         if (COMPILE_LLVM (cfg))
2330                 mono_llvm_emit_call (cfg, call);
2331         else
2332                 mono_arch_emit_call (cfg, call);
2333 #else
2334         mono_arch_emit_call (cfg, call);
2335 #endif
2336
2337         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2338         cfg->flags |= MONO_CFG_HAS_CALLS;
2339         
2340         return call;
2341 }
2342
2343 static void
2344 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2345 {
2346         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2347         cfg->uses_rgctx_reg = TRUE;
2348         call->rgctx_reg = TRUE;
2349 #ifdef ENABLE_LLVM
2350         call->rgctx_arg_reg = rgctx_reg;
2351 #endif
2352 }       
2353
2354 MonoInst*
2355 mini_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2356 {
2357         MonoCallInst *call;
2358         MonoInst *ins;
2359         int rgctx_reg = -1;
2360         gboolean check_sp = FALSE;
2361
2362         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2363                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2364
2365                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2366                         check_sp = TRUE;
2367         }
2368
2369         if (rgctx_arg) {
2370                 rgctx_reg = mono_alloc_preg (cfg);
2371                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2372         }
2373
2374         if (check_sp) {
2375                 if (!cfg->stack_inbalance_var)
2376                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2377
2378                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2379                 ins->dreg = cfg->stack_inbalance_var->dreg;
2380                 MONO_ADD_INS (cfg->cbb, ins);
2381         }
2382
2383         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2384
2385         call->inst.sreg1 = addr->dreg;
2386
2387         if (imt_arg)
2388                 emit_imt_argument (cfg, call, NULL, imt_arg);
2389
2390         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2391
2392         if (check_sp) {
2393                 int sp_reg;
2394
2395                 sp_reg = mono_alloc_preg (cfg);
2396
2397                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2398                 ins->dreg = sp_reg;
2399                 MONO_ADD_INS (cfg->cbb, ins);
2400
2401                 /* Restore the stack so we don't crash when throwing the exception */
2402                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2403                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2404                 MONO_ADD_INS (cfg->cbb, ins);
2405
2406                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2407                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2408         }
2409
2410         if (rgctx_arg)
2411                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2412
2413         return (MonoInst*)call;
2414 }
2415
2416 static MonoInst*
2417 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2418
2419 static MonoInst*
2420 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2421                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2422 {
2423 #ifndef DISABLE_REMOTING
2424         gboolean might_be_remote = FALSE;
2425 #endif
2426         gboolean virtual_ = this_ins != NULL;
2427         gboolean enable_for_aot = TRUE;
2428         int context_used;
2429         MonoCallInst *call;
2430         MonoInst *call_target = NULL;
2431         int rgctx_reg = 0;
2432         gboolean need_unbox_trampoline;
2433
2434         if (!sig)
2435                 sig = mono_method_signature (method);
2436
2437         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2438                 g_assert_not_reached ();
2439
2440         if (rgctx_arg) {
2441                 rgctx_reg = mono_alloc_preg (cfg);
2442                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2443         }
2444
2445         if (method->string_ctor) {
2446                 /* Create the real signature */
2447                 /* FIXME: Cache these */
2448                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2449                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2450
2451                 sig = ctor_sig;
2452         }
2453
2454         context_used = mini_method_check_context_used (cfg, method);
2455
2456 #ifndef DISABLE_REMOTING
2457         might_be_remote = this_ins && sig->hasthis &&
2458                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2459                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2460
2461         if (might_be_remote && context_used) {
2462                 MonoInst *addr;
2463
2464                 g_assert (cfg->gshared);
2465
2466                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2467
2468                 return mini_emit_calli (cfg, sig, args, addr, NULL, NULL);
2469         }
2470 #endif
2471
2472         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2473                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2474
2475         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2476
2477         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2478
2479 #ifndef DISABLE_REMOTING
2480         if (might_be_remote)
2481                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2482         else
2483 #endif
2484                 call->method = method;
2485         call->inst.flags |= MONO_INST_HAS_METHOD;
2486         call->inst.inst_left = this_ins;
2487         call->tail_call = tail;
2488
2489         if (virtual_) {
2490                 int vtable_reg, slot_reg, this_reg;
2491                 int offset;
2492
2493                 this_reg = this_ins->dreg;
2494
2495                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2496                         MonoInst *dummy_use;
2497
2498                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2499
2500                         /* Make a call to delegate->invoke_impl */
2501                         call->inst.inst_basereg = this_reg;
2502                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2503                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2504
2505                         /* We must emit a dummy use here because the delegate trampoline will
2506                         replace the 'this' argument with the delegate target making this activation
2507                         no longer a root for the delegate.
2508                         This is an issue for delegates that target collectible code such as dynamic
2509                         methods of GC'able assemblies.
2510
2511                         For a test case look into #667921.
2512
2513                         FIXME: a dummy use is not the best way to do it as the local register allocator
2514                         will put it on a caller save register and spil it around the call. 
2515                         Ideally, we would either put it on a callee save register or only do the store part.  
2516                          */
2517                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2518
2519                         return (MonoInst*)call;
2520                 }
2521
2522                 if ((!cfg->compile_aot || enable_for_aot) && 
2523                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2524                          (MONO_METHOD_IS_FINAL (method) &&
2525                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2526                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2527                         /* 
2528                          * the method is not virtual, we just need to ensure this is not null
2529                          * and then we can call the method directly.
2530                          */
2531 #ifndef DISABLE_REMOTING
2532                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2533                                 /* 
2534                                  * The check above ensures method is not gshared, this is needed since
2535                                  * gshared methods can't have wrappers.
2536                                  */
2537                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2538                         }
2539 #endif
2540
2541                         if (!method->string_ctor)
2542                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2543
2544                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2545                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2546                         /*
2547                          * the method is virtual, but we can statically dispatch since either
2548                          * it's class or the method itself are sealed.
2549                          * But first we need to ensure it's not a null reference.
2550                          */
2551                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2552
2553                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2554                 } else if (call_target) {
2555                         vtable_reg = alloc_preg (cfg);
2556                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2557
2558                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2559                         call->inst.sreg1 = call_target->dreg;
2560                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2561                 } else {
2562                         vtable_reg = alloc_preg (cfg);
2563                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2564                         if (mono_class_is_interface (method->klass)) {
2565                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2566                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2567                                 slot_reg = vtable_reg;
2568                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2569                         } else {
2570                                 slot_reg = vtable_reg;
2571                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2572                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2573                                 if (imt_arg) {
2574                                         g_assert (mono_method_signature (method)->generic_param_count);
2575                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2576                                 }
2577                         }
2578
2579                         call->inst.sreg1 = slot_reg;
2580                         call->inst.inst_offset = offset;
2581                         call->is_virtual = TRUE;
2582                 }
2583         }
2584
2585         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2586
2587         if (rgctx_arg)
2588                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2589
2590         return (MonoInst*)call;
2591 }
2592
2593 MonoInst*
2594 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2595 {
2596         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2597 }
2598
2599 MonoInst*
2600 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2601                                            MonoInst **args)
2602 {
2603         MonoCallInst *call;
2604
2605         g_assert (sig);
2606
2607         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2608         call->fptr = func;
2609
2610         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2611
2612         return (MonoInst*)call;
2613 }
2614
2615 MonoInst*
2616 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2617 {
2618         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2619
2620         g_assert (info);
2621
2622         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2623 }
2624
2625 /*
2626  * mono_emit_abs_call:
2627  *
2628  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2629  */
2630 inline static MonoInst*
2631 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2632                                         MonoMethodSignature *sig, MonoInst **args)
2633 {
2634         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2635         MonoInst *ins;
2636
2637         /* 
2638          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2639          * handle it.
2640          */
2641         if (cfg->abs_patches == NULL)
2642                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2643         g_hash_table_insert (cfg->abs_patches, ji, ji);
2644         ins = mono_emit_native_call (cfg, ji, sig, args);
2645         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2646         return ins;
2647 }
2648
2649 static MonoMethodSignature*
2650 sig_to_rgctx_sig (MonoMethodSignature *sig)
2651 {
2652         // FIXME: memory allocation
2653         MonoMethodSignature *res;
2654         int i;
2655
2656         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2657         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2658         res->param_count = sig->param_count + 1;
2659         for (i = 0; i < sig->param_count; ++i)
2660                 res->params [i] = sig->params [i];
2661         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2662         return res;
2663 }
2664
2665 /* Make an indirect call to FSIG passing an additional argument */
2666 static MonoInst*
2667 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2668 {
2669         MonoMethodSignature *csig;
2670         MonoInst *args_buf [16];
2671         MonoInst **args;
2672         int i, pindex, tmp_reg;
2673
2674         /* Make a call with an rgctx/extra arg */
2675         if (fsig->param_count + 2 < 16)
2676                 args = args_buf;
2677         else
2678                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2679         pindex = 0;
2680         if (fsig->hasthis)
2681                 args [pindex ++] = orig_args [0];
2682         for (i = 0; i < fsig->param_count; ++i)
2683                 args [pindex ++] = orig_args [fsig->hasthis + i];
2684         tmp_reg = alloc_preg (cfg);
2685         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2686         csig = sig_to_rgctx_sig (fsig);
2687         return mini_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2688 }
2689
2690 /* Emit an indirect call to the function descriptor ADDR */
2691 static MonoInst*
2692 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2693 {
2694         int addr_reg, arg_reg;
2695         MonoInst *call_target;
2696
2697         g_assert (cfg->llvm_only);
2698
2699         /*
2700          * addr points to a <addr, arg> pair, load both of them, and
2701          * make a call to addr, passing arg as an extra arg.
2702          */
2703         addr_reg = alloc_preg (cfg);
2704         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2705         arg_reg = alloc_preg (cfg);
2706         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2707
2708         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2709 }
2710
2711 static gboolean
2712 direct_icalls_enabled (MonoCompile *cfg)
2713 {
2714         return FALSE;
2715
2716         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2717 #ifdef TARGET_AMD64
2718         if (cfg->compile_llvm && !cfg->llvm_only)
2719                 return FALSE;
2720 #endif
2721         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2722                 return FALSE;
2723         return TRUE;
2724 }
2725
2726 MonoInst*
2727 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2728 {
2729         /*
2730          * Call the jit icall without a wrapper if possible.
2731          * The wrapper is needed for the following reasons:
2732          * - to handle exceptions thrown using mono_raise_exceptions () from the
2733          *   icall function. The EH code needs the lmf frame pushed by the
2734          *   wrapper to be able to unwind back to managed code.
2735          * - to be able to do stack walks for asynchronously suspended
2736          *   threads when debugging.
2737          */
2738         if (info->no_raise && direct_icalls_enabled (cfg)) {
2739                 char *name;
2740                 int costs;
2741
2742                 if (!info->wrapper_method) {
2743                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2744                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2745                         g_free (name);
2746                         mono_memory_barrier ();
2747                 }
2748
2749                 /*
2750                  * Inline the wrapper method, which is basically a call to the C icall, and
2751                  * an exception check.
2752                  */
2753                 costs = inline_method (cfg, info->wrapper_method, NULL,
2754                                                            args, NULL, il_offset, TRUE);
2755                 g_assert (costs > 0);
2756                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2757
2758                 return args [0];
2759         } else {
2760                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2761         }
2762 }
2763  
2764 static MonoInst*
2765 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2766 {
2767         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2768                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2769                         int widen_op = -1;
2770
2771                         /* 
2772                          * Native code might return non register sized integers 
2773                          * without initializing the upper bits.
2774                          */
2775                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2776                         case OP_LOADI1_MEMBASE:
2777                                 widen_op = OP_ICONV_TO_I1;
2778                                 break;
2779                         case OP_LOADU1_MEMBASE:
2780                                 widen_op = OP_ICONV_TO_U1;
2781                                 break;
2782                         case OP_LOADI2_MEMBASE:
2783                                 widen_op = OP_ICONV_TO_I2;
2784                                 break;
2785                         case OP_LOADU2_MEMBASE:
2786                                 widen_op = OP_ICONV_TO_U2;
2787                                 break;
2788                         default:
2789                                 break;
2790                         }
2791
2792                         if (widen_op != -1) {
2793                                 int dreg = alloc_preg (cfg);
2794                                 MonoInst *widen;
2795
2796                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2797                                 widen->type = ins->type;
2798                                 ins = widen;
2799                         }
2800                 }
2801         }
2802
2803         return ins;
2804 }
2805
2806
2807 static void
2808 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2809 {
2810         MonoInst *args [16];
2811
2812         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2813         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2814
2815         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2816 }
2817
2818 MonoMethod*
2819 mini_get_memcpy_method (void)
2820 {
2821         static MonoMethod *memcpy_method = NULL;
2822         if (!memcpy_method) {
2823                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2824                 if (!memcpy_method)
2825                         g_error ("Old corlib found. Install a new one");
2826         }
2827         return memcpy_method;
2828 }
2829
2830 void
2831 mini_emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2832 {
2833         int card_table_shift_bits;
2834         gpointer card_table_mask;
2835         guint8 *card_table;
2836         MonoInst *dummy_use;
2837         int nursery_shift_bits;
2838         size_t nursery_size;
2839
2840         if (!cfg->gen_write_barriers)
2841                 return;
2842
2843         //method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1])
2844
2845         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2846
2847         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
2848
2849         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
2850                 MonoInst *wbarrier;
2851
2852                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
2853                 wbarrier->sreg1 = ptr->dreg;
2854                 wbarrier->sreg2 = value->dreg;
2855                 MONO_ADD_INS (cfg->cbb, wbarrier);
2856         } else if (card_table) {
2857                 int offset_reg = alloc_preg (cfg);
2858                 int card_reg;
2859                 MonoInst *ins;
2860
2861                 /*
2862                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
2863                  * collector case, so, for the serial collector, it might slightly slow down nursery
2864                  * collections. We also expect that the host system and the target system have the same card
2865                  * table configuration, which is the case if they have the same pointer size.
2866                  */
2867
2868                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
2869                 if (card_table_mask)
2870                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
2871
2872                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
2873                  * IMM's larger than 32bits.
2874                  */
2875                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
2876                 card_reg = ins->dreg;
2877
2878                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
2879                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
2880         } else {
2881                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
2882                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
2883         }
2884
2885         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
2886 }
2887
2888 MonoMethod*
2889 mini_get_memset_method (void)
2890 {
2891         static MonoMethod *memset_method = NULL;
2892         if (!memset_method) {
2893                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2894                 if (!memset_method)
2895                         g_error ("Old corlib found. Install a new one");
2896         }
2897         return memset_method;
2898 }
2899
2900 void
2901 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
2902 {
2903         MonoInst *iargs [3];
2904         int n;
2905         guint32 align;
2906         MonoMethod *memset_method;
2907         MonoInst *size_ins = NULL;
2908         MonoInst *bzero_ins = NULL;
2909         static MonoMethod *bzero_method;
2910
2911         /* FIXME: Optimize this for the case when dest is an LDADDR */
2912         mono_class_init (klass);
2913         if (mini_is_gsharedvt_klass (klass)) {
2914                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
2915                 bzero_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
2916                 if (!bzero_method)
2917                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
2918                 g_assert (bzero_method);
2919                 iargs [0] = dest;
2920                 iargs [1] = size_ins;
2921                 mini_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
2922                 return;
2923         }
2924
2925         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
2926
2927         n = mono_class_value_size (klass, &align);
2928
2929         if (n <= sizeof (gpointer) * 8) {
2930                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
2931         }
2932         else {
2933                 memset_method = mini_get_memset_method ();
2934                 iargs [0] = dest;
2935                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
2936                 EMIT_NEW_ICONST (cfg, iargs [2], n);
2937                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
2938         }
2939 }
2940
2941 /*
2942  * emit_get_rgctx:
2943  *
2944  *   Emit IR to return either the this pointer for instance method,
2945  * or the mrgctx for static methods.
2946  */
2947 static MonoInst*
2948 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
2949 {
2950         MonoInst *this_ins = NULL;
2951
2952         g_assert (cfg->gshared);
2953
2954         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
2955                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
2956                 !method->klass->valuetype)
2957                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
2958
2959         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
2960                 MonoInst *mrgctx_loc, *mrgctx_var;
2961
2962                 g_assert (!this_ins);
2963                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
2964
2965                 mrgctx_loc = mono_get_vtable_var (cfg);
2966                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2967
2968                 return mrgctx_var;
2969         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
2970                 MonoInst *mrgctx_loc, *mrgctx_var;
2971
2972                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
2973                 mrgctx_loc = mono_get_vtable_var (cfg);
2974                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2975
2976                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
2977
2978                 return mrgctx_var;
2979         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
2980                 MonoInst *vtable_loc, *vtable_var;
2981
2982                 g_assert (!this_ins);
2983
2984                 vtable_loc = mono_get_vtable_var (cfg);
2985                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
2986
2987                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
2988                         MonoInst *mrgctx_var = vtable_var;
2989                         int vtable_reg;
2990
2991                         vtable_reg = alloc_preg (cfg);
2992                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
2993                         vtable_var->type = STACK_PTR;
2994                 }
2995
2996                 return vtable_var;
2997         } else {
2998                 MonoInst *ins;
2999                 int vtable_reg;
3000         
3001                 vtable_reg = alloc_preg (cfg);
3002                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3003                 return ins;
3004         }
3005 }
3006
3007 static MonoJumpInfoRgctxEntry *
3008 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3009 {
3010         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3011         res->method = method;
3012         res->in_mrgctx = in_mrgctx;
3013         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3014         res->data->type = patch_type;
3015         res->data->data.target = patch_data;
3016         res->info_type = info_type;
3017
3018         return res;
3019 }
3020
3021 static inline MonoInst*
3022 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3023 {
3024         MonoInst *args [16];
3025         MonoInst *call;
3026
3027         // FIXME: No fastpath since the slot is not a compile time constant
3028         args [0] = rgctx;
3029         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3030         if (entry->in_mrgctx)
3031                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3032         else
3033                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3034         return call;
3035 #if 0
3036         /*
3037          * FIXME: This can be called during decompose, which is a problem since it creates
3038          * new bblocks.
3039          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3040          */
3041         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3042         gboolean mrgctx;
3043         MonoBasicBlock *is_null_bb, *end_bb;
3044         MonoInst *res, *ins, *call;
3045         MonoInst *args[16];
3046
3047         slot = mini_get_rgctx_entry_slot (entry);
3048
3049         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3050         index = MONO_RGCTX_SLOT_INDEX (slot);
3051         if (mrgctx)
3052                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3053         for (depth = 0; ; ++depth) {
3054                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3055
3056                 if (index < size - 1)
3057                         break;
3058                 index -= size - 1;
3059         }
3060
3061         NEW_BBLOCK (cfg, end_bb);
3062         NEW_BBLOCK (cfg, is_null_bb);
3063
3064         if (mrgctx) {
3065                 rgctx_reg = rgctx->dreg;
3066         } else {
3067                 rgctx_reg = alloc_preg (cfg);
3068
3069                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3070                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3071                 NEW_BBLOCK (cfg, is_null_bb);
3072
3073                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3074                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3075         }
3076
3077         for (i = 0; i < depth; ++i) {
3078                 int array_reg = alloc_preg (cfg);
3079
3080                 /* load ptr to next array */
3081                 if (mrgctx && i == 0)
3082                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3083                 else
3084                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3085                 rgctx_reg = array_reg;
3086                 /* is the ptr null? */
3087                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3088                 /* if yes, jump to actual trampoline */
3089                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3090         }
3091
3092         /* fetch slot */
3093         val_reg = alloc_preg (cfg);
3094         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3095         /* is the slot null? */
3096         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3097         /* if yes, jump to actual trampoline */
3098         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3099
3100         /* Fastpath */
3101         res_reg = alloc_preg (cfg);
3102         MONO_INST_NEW (cfg, ins, OP_MOVE);
3103         ins->dreg = res_reg;
3104         ins->sreg1 = val_reg;
3105         MONO_ADD_INS (cfg->cbb, ins);
3106         res = ins;
3107         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3108
3109         /* Slowpath */
3110         MONO_START_BB (cfg, is_null_bb);
3111         args [0] = rgctx;
3112         EMIT_NEW_ICONST (cfg, args [1], index);
3113         if (mrgctx)
3114                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3115         else
3116                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3117         MONO_INST_NEW (cfg, ins, OP_MOVE);
3118         ins->dreg = res_reg;
3119         ins->sreg1 = call->dreg;
3120         MONO_ADD_INS (cfg->cbb, ins);
3121         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3122
3123         MONO_START_BB (cfg, end_bb);
3124
3125         return res;
3126 #endif
3127 }
3128
3129 /*
3130  * emit_rgctx_fetch:
3131  *
3132  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3133  * given by RGCTX.
3134  */
3135 static inline MonoInst*
3136 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3137 {
3138         if (cfg->llvm_only)
3139                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3140         else
3141                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3142 }
3143
3144 MonoInst*
3145 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3146                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3147 {
3148         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3149         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3150
3151         return emit_rgctx_fetch (cfg, rgctx, entry);
3152 }
3153
3154 static MonoInst*
3155 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3156                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3157 {
3158         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3159         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3160
3161         return emit_rgctx_fetch (cfg, rgctx, entry);
3162 }
3163
3164 static MonoInst*
3165 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3166                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3167 {
3168         MonoJumpInfoGSharedVtCall *call_info;
3169         MonoJumpInfoRgctxEntry *entry;
3170         MonoInst *rgctx;
3171
3172         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3173         call_info->sig = sig;
3174         call_info->method = cmethod;
3175
3176         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3177         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3178
3179         return emit_rgctx_fetch (cfg, rgctx, entry);
3180 }
3181
3182 /*
3183  * emit_get_rgctx_virt_method:
3184  *
3185  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3186  */
3187 static MonoInst*
3188 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3189                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3190 {
3191         MonoJumpInfoVirtMethod *info;
3192         MonoJumpInfoRgctxEntry *entry;
3193         MonoInst *rgctx;
3194
3195         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3196         info->klass = klass;
3197         info->method = virt_method;
3198
3199         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3200         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3201
3202         return emit_rgctx_fetch (cfg, rgctx, entry);
3203 }
3204
3205 static MonoInst*
3206 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3207                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3208 {
3209         MonoJumpInfoRgctxEntry *entry;
3210         MonoInst *rgctx;
3211
3212         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3213         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3214
3215         return emit_rgctx_fetch (cfg, rgctx, entry);
3216 }
3217
3218 /*
3219  * emit_get_rgctx_method:
3220  *
3221  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3222  * normal constants, else emit a load from the rgctx.
3223  */
3224 static MonoInst*
3225 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3226                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3227 {
3228         if (!context_used) {
3229                 MonoInst *ins;
3230
3231                 switch (rgctx_type) {
3232                 case MONO_RGCTX_INFO_METHOD:
3233                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3234                         return ins;
3235                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3236                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3237                         return ins;
3238                 default:
3239                         g_assert_not_reached ();
3240                 }
3241         } else {
3242                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3243                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3244
3245                 return emit_rgctx_fetch (cfg, rgctx, entry);
3246         }
3247 }
3248
3249 static MonoInst*
3250 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3251                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3252 {
3253         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3254         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3255
3256         return emit_rgctx_fetch (cfg, rgctx, entry);
3257 }
3258
3259 static int
3260 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3261 {
3262         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3263         MonoRuntimeGenericContextInfoTemplate *template_;
3264         int i, idx;
3265
3266         g_assert (info);
3267
3268         for (i = 0; i < info->num_entries; ++i) {
3269                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3270
3271                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3272                         return i;
3273         }
3274
3275         if (info->num_entries == info->count_entries) {
3276                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3277                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3278
3279                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3280
3281                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3282                 info->entries = new_entries;
3283                 info->count_entries = new_count_entries;
3284         }
3285
3286         idx = info->num_entries;
3287         template_ = &info->entries [idx];
3288         template_->info_type = rgctx_type;
3289         template_->data = data;
3290
3291         info->num_entries ++;
3292
3293         return idx;
3294 }
3295
3296 /*
3297  * emit_get_gsharedvt_info:
3298  *
3299  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3300  */
3301 static MonoInst*
3302 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3303 {
3304         MonoInst *ins;
3305         int idx, dreg;
3306
3307         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3308         /* Load info->entries [idx] */
3309         dreg = alloc_preg (cfg);
3310         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3311
3312         return ins;
3313 }
3314
3315 MonoInst*
3316 mini_emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3317 {
3318         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3319 }
3320
3321 /*
3322  * On return the caller must check @klass for load errors.
3323  */
3324 static void
3325 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3326 {
3327         MonoInst *vtable_arg;
3328         int context_used;
3329
3330         context_used = mini_class_check_context_used (cfg, klass);
3331
3332         if (context_used) {
3333                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3334                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3335         } else {
3336                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3337
3338                 if (!vtable)
3339                         return;
3340                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3341         }
3342
3343         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3344                 MonoInst *ins;
3345
3346                 /*
3347                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3348                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3349                  */
3350                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3351                 ins->sreg1 = vtable_arg->dreg;
3352                 MONO_ADD_INS (cfg->cbb, ins);
3353         } else {
3354                 int inited_reg;
3355                 MonoBasicBlock *inited_bb;
3356                 MonoInst *args [16];
3357
3358                 inited_reg = alloc_ireg (cfg);
3359
3360                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3361
3362                 NEW_BBLOCK (cfg, inited_bb);
3363
3364                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3365                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3366
3367                 args [0] = vtable_arg;
3368                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3369
3370                 MONO_START_BB (cfg, inited_bb);
3371         }
3372 }
3373
3374 static void
3375 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3376 {
3377         MonoInst *ins;
3378
3379         if (cfg->gen_seq_points && cfg->method == method) {
3380                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3381                 if (nonempty_stack)
3382                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3383                 MONO_ADD_INS (cfg->cbb, ins);
3384         }
3385 }
3386
3387 void
3388 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3389 {
3390         if (mini_get_debug_options ()->better_cast_details) {
3391                 int vtable_reg = alloc_preg (cfg);
3392                 int klass_reg = alloc_preg (cfg);
3393                 MonoBasicBlock *is_null_bb = NULL;
3394                 MonoInst *tls_get;
3395                 int to_klass_reg, context_used;
3396
3397                 if (null_check) {
3398                         NEW_BBLOCK (cfg, is_null_bb);
3399
3400                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3401                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3402                 }
3403
3404                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3405                 if (!tls_get) {
3406                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3407                         exit (1);
3408                 }
3409
3410                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3411                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3412
3413                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3414
3415                 context_used = mini_class_check_context_used (cfg, klass);
3416                 if (context_used) {
3417                         MonoInst *class_ins;
3418
3419                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3420                         to_klass_reg = class_ins->dreg;
3421                 } else {
3422                         to_klass_reg = alloc_preg (cfg);
3423                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3424                 }
3425                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3426
3427                 if (null_check)
3428                         MONO_START_BB (cfg, is_null_bb);
3429         }
3430 }
3431
3432 void
3433 mini_reset_cast_details (MonoCompile *cfg)
3434 {
3435         /* Reset the variables holding the cast details */
3436         if (mini_get_debug_options ()->better_cast_details) {
3437                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3438                 /* It is enough to reset the from field */
3439                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3440         }
3441 }
3442
3443 /*
3444  * On return the caller must check @array_class for load errors
3445  */
3446 static void
3447 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3448 {
3449         int vtable_reg = alloc_preg (cfg);
3450         int context_used;
3451
3452         context_used = mini_class_check_context_used (cfg, array_class);
3453
3454         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3455
3456         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3457
3458         if (cfg->opt & MONO_OPT_SHARED) {
3459                 int class_reg = alloc_preg (cfg);
3460                 MonoInst *ins;
3461
3462                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3463                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3464                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3465         } else if (context_used) {
3466                 MonoInst *vtable_ins;
3467
3468                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3469                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3470         } else {
3471                 if (cfg->compile_aot) {
3472                         int vt_reg;
3473                         MonoVTable *vtable;
3474
3475                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3476                                 return;
3477                         vt_reg = alloc_preg (cfg);
3478                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3479                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3480                 } else {
3481                         MonoVTable *vtable;
3482                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3483                                 return;
3484                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3485                 }
3486         }
3487         
3488         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3489
3490         mini_reset_cast_details (cfg);
3491 }
3492
3493 /**
3494  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3495  * generic code is generated.
3496  */
3497 static MonoInst*
3498 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3499 {
3500         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3501
3502         if (context_used) {
3503                 MonoInst *rgctx, *addr;
3504
3505                 /* FIXME: What if the class is shared?  We might not
3506                    have to get the address of the method from the
3507                    RGCTX. */
3508                 addr = emit_get_rgctx_method (cfg, context_used, method,
3509                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3510                 if (cfg->llvm_only) {
3511                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3512                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3513                 } else {
3514                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3515
3516                         return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3517                 }
3518         } else {
3519                 gboolean pass_vtable, pass_mrgctx;
3520                 MonoInst *rgctx_arg = NULL;
3521
3522                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3523                 g_assert (!pass_mrgctx);
3524
3525                 if (pass_vtable) {
3526                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3527
3528                         g_assert (vtable);
3529                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3530                 }
3531
3532                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3533         }
3534 }
3535
3536 static MonoInst*
3537 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3538 {
3539         MonoInst *add;
3540         int obj_reg;
3541         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3542         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3543         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3544         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3545
3546         obj_reg = sp [0]->dreg;
3547         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3548         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3549
3550         /* FIXME: generics */
3551         g_assert (klass->rank == 0);
3552                         
3553         // Check rank == 0
3554         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3555         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3556
3557         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3558         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3559
3560         if (context_used) {
3561                 MonoInst *element_class;
3562
3563                 /* This assertion is from the unboxcast insn */
3564                 g_assert (klass->rank == 0);
3565
3566                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3567                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3568
3569                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3570                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3571         } else {
3572                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3573                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3574                 mini_reset_cast_details (cfg);
3575         }
3576
3577         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3578         MONO_ADD_INS (cfg->cbb, add);
3579         add->type = STACK_MP;
3580         add->klass = klass;
3581
3582         return add;
3583 }
3584
3585 static MonoInst*
3586 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3587 {
3588         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3589         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3590         MonoInst *ins;
3591         int dreg, addr_reg;
3592
3593         klass_inst = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3594
3595         /* obj */
3596         args [0] = obj;
3597
3598         /* klass */
3599         args [1] = klass_inst;
3600
3601         /* CASTCLASS */
3602         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3603
3604         NEW_BBLOCK (cfg, is_ref_bb);
3605         NEW_BBLOCK (cfg, is_nullable_bb);
3606         NEW_BBLOCK (cfg, end_bb);
3607         is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3608         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3609         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3610
3611         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3612         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3613
3614         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3615         addr_reg = alloc_dreg (cfg, STACK_MP);
3616
3617         /* Non-ref case */
3618         /* UNBOX */
3619         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3620         MONO_ADD_INS (cfg->cbb, addr);
3621
3622         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3623
3624         /* Ref case */
3625         MONO_START_BB (cfg, is_ref_bb);
3626
3627         /* Save the ref to a temporary */
3628         dreg = alloc_ireg (cfg);
3629         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3630         addr->dreg = addr_reg;
3631         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3632         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3633
3634         /* Nullable case */
3635         MONO_START_BB (cfg, is_nullable_bb);
3636
3637         {
3638                 MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3639                 MonoInst *unbox_call;
3640                 MonoMethodSignature *unbox_sig;
3641
3642                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3643                 unbox_sig->ret = &klass->byval_arg;
3644                 unbox_sig->param_count = 1;
3645                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3646
3647                 if (cfg->llvm_only)
3648                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3649                 else
3650                         unbox_call = mini_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3651
3652                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3653                 addr->dreg = addr_reg;
3654         }
3655
3656         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3657
3658         /* End */
3659         MONO_START_BB (cfg, end_bb);
3660
3661         /* LDOBJ */
3662         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3663
3664         return ins;
3665 }
3666
3667 /*
3668  * Returns NULL and set the cfg exception on error.
3669  */
3670 static MonoInst*
3671 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3672 {
3673         MonoInst *iargs [2];
3674         void *alloc_ftn;
3675
3676         if (context_used) {
3677                 MonoInst *data;
3678                 MonoRgctxInfoType rgctx_info;
3679                 MonoInst *iargs [2];
3680                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
3681
3682                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
3683
3684                 if (cfg->opt & MONO_OPT_SHARED)
3685                         rgctx_info = MONO_RGCTX_INFO_KLASS;
3686                 else
3687                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
3688                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
3689
3690                 if (cfg->opt & MONO_OPT_SHARED) {
3691                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3692                         iargs [1] = data;
3693                         alloc_ftn = ves_icall_object_new;
3694                 } else {
3695                         iargs [0] = data;
3696                         alloc_ftn = ves_icall_object_new_specific;
3697                 }
3698
3699                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
3700                         if (known_instance_size) {
3701                                 int size = mono_class_instance_size (klass);
3702                                 if (size < sizeof (MonoObject))
3703                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3704
3705                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
3706                         }
3707                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3708                 }
3709
3710                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3711         }
3712
3713         if (cfg->opt & MONO_OPT_SHARED) {
3714                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3715                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
3716
3717                 alloc_ftn = ves_icall_object_new;
3718         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
3719                 /* This happens often in argument checking code, eg. throw new FooException... */
3720                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
3721                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3722                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
3723         } else {
3724                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3725                 MonoMethod *managed_alloc = NULL;
3726                 gboolean pass_lw;
3727
3728                 if (!vtable) {
3729                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
3730                         cfg->exception_ptr = klass;
3731                         return NULL;
3732                 }
3733
3734                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
3735
3736                 if (managed_alloc) {
3737                         int size = mono_class_instance_size (klass);
3738                         if (size < sizeof (MonoObject))
3739                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3740
3741                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3742                         EMIT_NEW_ICONST (cfg, iargs [1], size);
3743                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3744                 }
3745                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3746                 if (pass_lw) {
3747                         guint32 lw = vtable->klass->instance_size;
3748                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3749                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
3750                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
3751                 }
3752                 else {
3753                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3754                 }
3755         }
3756
3757         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3758 }
3759         
3760 /*
3761  * Returns NULL and set the cfg exception on error.
3762  */     
3763 static MonoInst*
3764 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
3765 {
3766         MonoInst *alloc, *ins;
3767
3768         if (mono_class_is_nullable (klass)) {
3769                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3770
3771                 if (context_used) {
3772                         if (cfg->llvm_only && cfg->gsharedvt) {
3773                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3774                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3775                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3776                         } else {
3777                                 /* FIXME: What if the class is shared?  We might not
3778                                    have to get the method address from the RGCTX. */
3779                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3780                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3781                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3782
3783                                 return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3784                         }
3785                 } else {
3786                         gboolean pass_vtable, pass_mrgctx;
3787                         MonoInst *rgctx_arg = NULL;
3788
3789                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3790                         g_assert (!pass_mrgctx);
3791
3792                         if (pass_vtable) {
3793                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3794
3795                                 g_assert (vtable);
3796                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3797                         }
3798
3799                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3800                 }
3801         }
3802
3803         if (mini_is_gsharedvt_klass (klass)) {
3804                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3805                 MonoInst *res, *is_ref, *src_var, *addr;
3806                 int dreg;
3807
3808                 dreg = alloc_ireg (cfg);
3809
3810                 NEW_BBLOCK (cfg, is_ref_bb);
3811                 NEW_BBLOCK (cfg, is_nullable_bb);
3812                 NEW_BBLOCK (cfg, end_bb);
3813                 is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3814                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3815                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3816
3817                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3818                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3819
3820                 /* Non-ref case */
3821                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3822                 if (!alloc)
3823                         return NULL;
3824                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3825                 ins->opcode = OP_STOREV_MEMBASE;
3826
3827                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
3828                 res->type = STACK_OBJ;
3829                 res->klass = klass;
3830                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3831                 
3832                 /* Ref case */
3833                 MONO_START_BB (cfg, is_ref_bb);
3834
3835                 /* val is a vtype, so has to load the value manually */
3836                 src_var = get_vreg_to_inst (cfg, val->dreg);
3837                 if (!src_var)
3838                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
3839                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
3840                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
3841                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3842
3843                 /* Nullable case */
3844                 MONO_START_BB (cfg, is_nullable_bb);
3845
3846                 {
3847                         MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass,
3848                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
3849                         MonoInst *box_call;
3850                         MonoMethodSignature *box_sig;
3851
3852                         /*
3853                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
3854                          * construct that method at JIT time, so have to do things by hand.
3855                          */
3856                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3857                         box_sig->ret = &mono_defaults.object_class->byval_arg;
3858                         box_sig->param_count = 1;
3859                         box_sig->params [0] = &klass->byval_arg;
3860
3861                         if (cfg->llvm_only)
3862                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
3863                         else
3864                                 box_call = mini_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
3865                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
3866                         res->type = STACK_OBJ;
3867                         res->klass = klass;
3868                 }
3869
3870                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3871
3872                 MONO_START_BB (cfg, end_bb);
3873
3874                 return res;
3875         } else {
3876                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3877                 if (!alloc)
3878                         return NULL;
3879
3880                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3881                 return alloc;
3882         }
3883 }
3884
3885 static GHashTable* direct_icall_type_hash;
3886
3887 static gboolean
3888 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
3889 {
3890         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
3891         if (!direct_icalls_enabled (cfg))
3892                 return FALSE;
3893
3894         /*
3895          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
3896          * Whitelist a few icalls for now.
3897          */
3898         if (!direct_icall_type_hash) {
3899                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
3900
3901                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
3902                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
3903                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
3904                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
3905                 mono_memory_barrier ();
3906                 direct_icall_type_hash = h;
3907         }
3908
3909         if (cmethod->klass == mono_defaults.math_class)
3910                 return TRUE;
3911         /* No locking needed */
3912         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
3913                 return TRUE;
3914         return FALSE;
3915 }
3916
3917 static gboolean
3918 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
3919 {
3920         if (cmethod->klass == mono_defaults.systemtype_class) {
3921                 if (!strcmp (cmethod->name, "GetType"))
3922                         return TRUE;
3923         }
3924         return FALSE;
3925 }
3926
3927 static G_GNUC_UNUSED MonoInst*
3928 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
3929 {
3930         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
3931         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
3932         gboolean is_i4;
3933
3934         switch (enum_type->type) {
3935         case MONO_TYPE_I8:
3936         case MONO_TYPE_U8:
3937 #if SIZEOF_REGISTER == 8
3938         case MONO_TYPE_I:
3939         case MONO_TYPE_U:
3940 #endif
3941                 is_i4 = FALSE;
3942                 break;
3943         default:
3944                 is_i4 = TRUE;
3945                 break;
3946         }
3947
3948         {
3949                 MonoInst *load, *and_, *cmp, *ceq;
3950                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3951                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3952                 int dest_reg = alloc_ireg (cfg);
3953
3954                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
3955                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
3956                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
3957                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
3958
3959                 ceq->type = STACK_I4;
3960
3961                 if (!is_i4) {
3962                         load = mono_decompose_opcode (cfg, load);
3963                         and_ = mono_decompose_opcode (cfg, and_);
3964                         cmp = mono_decompose_opcode (cfg, cmp);
3965                         ceq = mono_decompose_opcode (cfg, ceq);
3966                 }
3967
3968                 return ceq;
3969         }
3970 }
3971
3972 /*
3973  * Returns NULL and set the cfg exception on error.
3974  */
3975 static G_GNUC_UNUSED MonoInst*
3976 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
3977 {
3978         MonoInst *ptr;
3979         int dreg;
3980         gpointer trampoline;
3981         MonoInst *obj, *method_ins, *tramp_ins;
3982         MonoDomain *domain;
3983         guint8 **code_slot;
3984
3985         if (virtual_ && !cfg->llvm_only) {
3986                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
3987                 g_assert (invoke);
3988
3989                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
3990                         return NULL;
3991         }
3992
3993         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
3994         if (!obj)
3995                 return NULL;
3996
3997         /* Inline the contents of mono_delegate_ctor */
3998
3999         /* Set target field */
4000         /* Optimize away setting of NULL target */
4001         if (!MONO_INS_IS_PCONST_NULL (target)) {
4002                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4003                 if (cfg->gen_write_barriers) {
4004                         dreg = alloc_preg (cfg);
4005                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4006                         mini_emit_write_barrier (cfg, ptr, target);
4007                 }
4008         }
4009
4010         /* Set method field */
4011         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4012         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4013
4014         /* 
4015          * To avoid looking up the compiled code belonging to the target method
4016          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4017          * store it, and we fill it after the method has been compiled.
4018          */
4019         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4020                 MonoInst *code_slot_ins;
4021
4022                 if (context_used) {
4023                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4024                 } else {
4025                         domain = mono_domain_get ();
4026                         mono_domain_lock (domain);
4027                         if (!domain_jit_info (domain)->method_code_hash)
4028                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4029                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4030                         if (!code_slot) {
4031                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4032                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4033                         }
4034                         mono_domain_unlock (domain);
4035
4036                         code_slot_ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4037                 }
4038                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4039         }
4040
4041         if (cfg->llvm_only) {
4042                 MonoInst *args [16];
4043
4044                 if (virtual_) {
4045                         args [0] = obj;
4046                         args [1] = target;
4047                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4048                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4049                 } else {
4050                         args [0] = obj;
4051                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4052                 }
4053
4054                 return obj;
4055         }
4056
4057         if (cfg->compile_aot) {
4058                 MonoDelegateClassMethodPair *del_tramp;
4059
4060                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4061                 del_tramp->klass = klass;
4062                 del_tramp->method = context_used ? NULL : method;
4063                 del_tramp->is_virtual = virtual_;
4064                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4065         } else {
4066                 if (virtual_)
4067                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4068                 else
4069                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4070                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4071         }
4072
4073         /* Set invoke_impl field */
4074         if (virtual_) {
4075                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4076         } else {
4077                 dreg = alloc_preg (cfg);
4078                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4079                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4080
4081                 dreg = alloc_preg (cfg);
4082                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4083                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4084         }
4085
4086         dreg = alloc_preg (cfg);
4087         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4088         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4089
4090         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4091
4092         return obj;
4093 }
4094
4095 static MonoInst*
4096 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4097 {
4098         MonoJitICallInfo *info;
4099
4100         /* Need to register the icall so it gets an icall wrapper */
4101         info = mono_get_array_new_va_icall (rank);
4102
4103         cfg->flags |= MONO_CFG_HAS_VARARGS;
4104
4105         /* mono_array_new_va () needs a vararg calling convention */
4106         cfg->exception_message = g_strdup ("array-new");
4107         cfg->disable_llvm = TRUE;
4108
4109         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4110         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4111 }
4112
4113 /*
4114  * handle_constrained_gsharedvt_call:
4115  *
4116  *   Handle constrained calls where the receiver is a gsharedvt type.
4117  * Return the instruction representing the call. Set the cfg exception on failure.
4118  */
4119 static MonoInst*
4120 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4121                                                                    gboolean *ref_emit_widen)
4122 {
4123         MonoInst *ins = NULL;
4124         gboolean emit_widen = *ref_emit_widen;
4125
4126         /*
4127          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4128          * This is hard to do with the current call code, since we would have to emit a branch and two different calls. So instead, we
4129          * pack the arguments into an array, and do the rest of the work in in an icall.
4130          */
4131         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4132                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret)) || mini_is_gsharedvt_type (fsig->ret)) &&
4133                 (fsig->param_count == 0 || (!fsig->hasthis && fsig->param_count == 1) || (fsig->param_count == 1 && (MONO_TYPE_IS_REFERENCE (fsig->params [0]) || fsig->params [0]->byref || mini_is_gsharedvt_type (fsig->params [0]))))) {
4134                 MonoInst *args [16];
4135
4136                 /*
4137                  * This case handles calls to
4138                  * - object:ToString()/Equals()/GetHashCode(),
4139                  * - System.IComparable<T>:CompareTo()
4140                  * - System.IEquatable<T>:Equals ()
4141                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4142                  */
4143
4144                 args [0] = sp [0];
4145                 if (mono_method_check_context_used (cmethod))
4146                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4147                 else
4148                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4149                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4150
4151                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4152                 if (fsig->hasthis && fsig->param_count) {
4153                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4154                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4155                         ins->dreg = alloc_preg (cfg);
4156                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4157                         MONO_ADD_INS (cfg->cbb, ins);
4158                         args [4] = ins;
4159
4160                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4161                                 int addr_reg, deref_arg_reg;
4162
4163                                 ins = mini_emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4164                                 deref_arg_reg = alloc_preg (cfg);
4165                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4166                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4167
4168                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4169                                 addr_reg = ins->dreg;
4170                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4171                         } else {
4172                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4173                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4174                         }
4175                 } else {
4176                         EMIT_NEW_ICONST (cfg, args [3], 0);
4177                         EMIT_NEW_ICONST (cfg, args [4], 0);
4178                 }
4179                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4180                 emit_widen = FALSE;
4181
4182                 if (mini_is_gsharedvt_type (fsig->ret)) {
4183                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4184                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4185                         MonoInst *add;
4186
4187                         /* Unbox */
4188                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4189                         MONO_ADD_INS (cfg->cbb, add);
4190                         /* Load value */
4191                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4192                         MONO_ADD_INS (cfg->cbb, ins);
4193                         /* ins represents the call result */
4194                 }
4195         } else {
4196                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4197         }
4198
4199         *ref_emit_widen = emit_widen;
4200
4201         return ins;
4202
4203  exception_exit:
4204         return NULL;
4205 }
4206
4207 static void
4208 mono_emit_load_got_addr (MonoCompile *cfg)
4209 {
4210         MonoInst *getaddr, *dummy_use;
4211
4212         if (!cfg->got_var || cfg->got_var_allocated)
4213                 return;
4214
4215         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4216         getaddr->cil_code = cfg->header->code;
4217         getaddr->dreg = cfg->got_var->dreg;
4218
4219         /* Add it to the start of the first bblock */
4220         if (cfg->bb_entry->code) {
4221                 getaddr->next = cfg->bb_entry->code;
4222                 cfg->bb_entry->code = getaddr;
4223         }
4224         else
4225                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4226
4227         cfg->got_var_allocated = TRUE;
4228
4229         /* 
4230          * Add a dummy use to keep the got_var alive, since real uses might
4231          * only be generated by the back ends.
4232          * Add it to end_bblock, so the variable's lifetime covers the whole
4233          * method.
4234          * It would be better to make the usage of the got var explicit in all
4235          * cases when the backend needs it (i.e. calls, throw etc.), so this
4236          * wouldn't be needed.
4237          */
4238         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4239         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4240 }
4241
4242 static int inline_limit;
4243 static gboolean inline_limit_inited;
4244
4245 static gboolean
4246 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4247 {
4248         MonoMethodHeaderSummary header;
4249         MonoVTable *vtable;
4250 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4251         MonoMethodSignature *sig = mono_method_signature (method);
4252         int i;
4253 #endif
4254
4255         if (cfg->disable_inline)
4256                 return FALSE;
4257         if (cfg->gsharedvt)
4258                 return FALSE;
4259
4260         if (cfg->inline_depth > 10)
4261                 return FALSE;
4262
4263         if (!mono_method_get_header_summary (method, &header))
4264                 return FALSE;
4265
4266         /*runtime, icall and pinvoke are checked by summary call*/
4267         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4268             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4269             (mono_class_is_marshalbyref (method->klass)) ||
4270             header.has_clauses)
4271                 return FALSE;
4272
4273         /* also consider num_locals? */
4274         /* Do the size check early to avoid creating vtables */
4275         if (!inline_limit_inited) {
4276                 char *inlinelimit;
4277                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4278                         inline_limit = atoi (inlinelimit);
4279                         g_free (inlinelimit);
4280                 } else
4281                         inline_limit = INLINE_LENGTH_LIMIT;
4282                 inline_limit_inited = TRUE;
4283         }
4284         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4285                 return FALSE;
4286
4287         /*
4288          * if we can initialize the class of the method right away, we do,
4289          * otherwise we don't allow inlining if the class needs initialization,
4290          * since it would mean inserting a call to mono_runtime_class_init()
4291          * inside the inlined code
4292          */
4293         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4294                 return FALSE;
4295
4296         if (!(cfg->opt & MONO_OPT_SHARED)) {
4297                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4298                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4299                         if (method->klass->has_cctor) {
4300                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4301                                 if (!vtable)
4302                                         return FALSE;
4303                                 if (!cfg->compile_aot) {
4304                                         MonoError error;
4305                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4306                                                 mono_error_cleanup (&error);
4307                                                 return FALSE;
4308                                         }
4309                                 }
4310                         }
4311                 } else if (mono_class_is_before_field_init (method->klass)) {
4312                         if (cfg->run_cctors && method->klass->has_cctor) {
4313                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4314                                 if (!method->klass->runtime_info)
4315                                         /* No vtable created yet */
4316                                         return FALSE;
4317                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4318                                 if (!vtable)
4319                                         return FALSE;
4320                                 /* This makes so that inline cannot trigger */
4321                                 /* .cctors: too many apps depend on them */
4322                                 /* running with a specific order... */
4323                                 if (! vtable->initialized)
4324                                         return FALSE;
4325                                 MonoError error;
4326                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4327                                         mono_error_cleanup (&error);
4328                                         return FALSE;
4329                                 }
4330                         }
4331                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4332                         if (!method->klass->runtime_info)
4333                                 /* No vtable created yet */
4334                                 return FALSE;
4335                         vtable = mono_class_vtable (cfg->domain, method->klass);
4336                         if (!vtable)
4337                                 return FALSE;
4338                         if (!vtable->initialized)
4339                                 return FALSE;
4340                 }
4341         } else {
4342                 /* 
4343                  * If we're compiling for shared code
4344                  * the cctor will need to be run at aot method load time, for example,
4345                  * or at the end of the compilation of the inlining method.
4346                  */
4347                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4348                         return FALSE;
4349         }
4350
4351 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4352         if (mono_arch_is_soft_float ()) {
4353                 /* FIXME: */
4354                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4355                         return FALSE;
4356                 for (i = 0; i < sig->param_count; ++i)
4357                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4358                                 return FALSE;
4359         }
4360 #endif
4361
4362         if (g_list_find (cfg->dont_inline, method))
4363                 return FALSE;
4364
4365         return TRUE;
4366 }
4367
4368 static gboolean
4369 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4370 {
4371         if (!cfg->compile_aot) {
4372                 g_assert (vtable);
4373                 if (vtable->initialized)
4374                         return FALSE;
4375         }
4376
4377         if (mono_class_is_before_field_init (klass)) {
4378                 if (cfg->method == method)
4379                         return FALSE;
4380         }
4381
4382         if (!mono_class_needs_cctor_run (klass, method))
4383                 return FALSE;
4384
4385         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4386                 /* The initialization is already done before the method is called */
4387                 return FALSE;
4388
4389         return TRUE;
4390 }
4391
4392 MonoInst*
4393 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4394 {
4395         MonoInst *ins;
4396         guint32 size;
4397         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4398         int context_used;
4399
4400         if (mini_is_gsharedvt_variable_klass (klass)) {
4401                 size = -1;
4402         } else {
4403                 mono_class_init (klass);
4404                 size = mono_class_array_element_size (klass);
4405         }
4406
4407         mult_reg = alloc_preg (cfg);
4408         array_reg = arr->dreg;
4409         index_reg = index->dreg;
4410
4411 #if SIZEOF_REGISTER == 8
4412         /* The array reg is 64 bits but the index reg is only 32 */
4413         if (COMPILE_LLVM (cfg)) {
4414                 /*
4415                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4416                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4417                  * of OP_X86_LEA for llvm.
4418                  */
4419                 index2_reg = index_reg;
4420         } else {
4421                 index2_reg = alloc_preg (cfg);
4422                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4423         }
4424 #else
4425         if (index->type == STACK_I8) {
4426                 index2_reg = alloc_preg (cfg);
4427                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4428         } else {
4429                 index2_reg = index_reg;
4430         }
4431 #endif
4432
4433         if (bcheck)
4434                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4435
4436 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4437         if (size == 1 || size == 2 || size == 4 || size == 8) {
4438                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4439
4440                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4441                 ins->klass = mono_class_get_element_class (klass);
4442                 ins->type = STACK_MP;
4443
4444                 return ins;
4445         }
4446 #endif          
4447
4448         add_reg = alloc_ireg_mp (cfg);
4449
4450         if (size == -1) {
4451                 MonoInst *rgctx_ins;
4452
4453                 /* gsharedvt */
4454                 g_assert (cfg->gshared);
4455                 context_used = mini_class_check_context_used (cfg, klass);
4456                 g_assert (context_used);
4457                 rgctx_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4458                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4459         } else {
4460                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4461         }
4462         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4463         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4464         ins->klass = mono_class_get_element_class (klass);
4465         ins->type = STACK_MP;
4466         MONO_ADD_INS (cfg->cbb, ins);
4467
4468         return ins;
4469 }
4470
4471 static MonoInst*
4472 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4473 {
4474         int bounds_reg = alloc_preg (cfg);
4475         int add_reg = alloc_ireg_mp (cfg);
4476         int mult_reg = alloc_preg (cfg);
4477         int mult2_reg = alloc_preg (cfg);
4478         int low1_reg = alloc_preg (cfg);
4479         int low2_reg = alloc_preg (cfg);
4480         int high1_reg = alloc_preg (cfg);
4481         int high2_reg = alloc_preg (cfg);
4482         int realidx1_reg = alloc_preg (cfg);
4483         int realidx2_reg = alloc_preg (cfg);
4484         int sum_reg = alloc_preg (cfg);
4485         int index1, index2, tmpreg;
4486         MonoInst *ins;
4487         guint32 size;
4488
4489         mono_class_init (klass);
4490         size = mono_class_array_element_size (klass);
4491
4492         index1 = index_ins1->dreg;
4493         index2 = index_ins2->dreg;
4494
4495 #if SIZEOF_REGISTER == 8
4496         /* The array reg is 64 bits but the index reg is only 32 */
4497         if (COMPILE_LLVM (cfg)) {
4498                 /* Not needed */
4499         } else {
4500                 tmpreg = alloc_preg (cfg);
4501                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4502                 index1 = tmpreg;
4503                 tmpreg = alloc_preg (cfg);
4504                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4505                 index2 = tmpreg;
4506         }
4507 #else
4508         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4509         tmpreg = -1;
4510 #endif
4511
4512         /* range checking */
4513         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4514                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4515
4516         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4517                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4518         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4519         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4520                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4521         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4522         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4523
4524         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4525                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4526         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4527         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4528                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4529         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4530         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4531
4532         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4533         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4534         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4535         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4536         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4537
4538         ins->type = STACK_MP;
4539         ins->klass = klass;
4540         MONO_ADD_INS (cfg->cbb, ins);
4541
4542         return ins;
4543 }
4544
4545 static MonoInst*
4546 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4547 {
4548         int rank;
4549         MonoInst *addr;
4550         MonoMethod *addr_method;
4551         int element_size;
4552         MonoClass *eclass = cmethod->klass->element_class;
4553
4554         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4555
4556         if (rank == 1)
4557                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4558
4559         /* emit_ldelema_2 depends on OP_LMUL */
4560         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4561                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4562         }
4563
4564         if (mini_is_gsharedvt_variable_klass (eclass))
4565                 element_size = 0;
4566         else
4567                 element_size = mono_class_array_element_size (eclass);
4568         addr_method = mono_marshal_get_array_address (rank, element_size);
4569         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4570
4571         return addr;
4572 }
4573
4574 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4575 static MonoInst*
4576 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4577 {
4578         MonoInst *addr, *store, *load;
4579         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4580
4581         /* the bounds check is already done by the callers */
4582         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4583         if (is_set) {
4584                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4585                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4586                 if (mini_type_is_reference (&eklass->byval_arg))
4587                         mini_emit_write_barrier (cfg, addr, load);
4588         } else {
4589                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4590                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4591         }
4592         return store;
4593 }
4594
4595
4596 static gboolean
4597 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4598 {
4599         return mini_type_is_reference (&klass->byval_arg);
4600 }
4601
4602 static MonoInst*
4603 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4604 {
4605         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4606                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4607                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4608                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4609                 MonoInst *iargs [3];
4610
4611                 if (!helper->slot)
4612                         mono_class_setup_vtable (obj_array);
4613                 g_assert (helper->slot);
4614
4615                 if (sp [0]->type != STACK_OBJ)
4616                         return NULL;
4617                 if (sp [2]->type != STACK_OBJ)
4618                         return NULL;
4619
4620                 iargs [2] = sp [2];
4621                 iargs [1] = sp [1];
4622                 iargs [0] = sp [0];
4623
4624                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4625         } else {
4626                 MonoInst *ins;
4627
4628                 if (mini_is_gsharedvt_variable_klass (klass)) {
4629                         MonoInst *addr;
4630
4631                         // FIXME-VT: OP_ICONST optimization
4632                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4633                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4634                         ins->opcode = OP_STOREV_MEMBASE;
4635                 } else if (sp [1]->opcode == OP_ICONST) {
4636                         int array_reg = sp [0]->dreg;
4637                         int index_reg = sp [1]->dreg;
4638                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
4639
4640                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
4641                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
4642
4643                         if (safety_checks)
4644                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
4645                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
4646                 } else {
4647                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
4648                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4649                         if (generic_class_is_reference_type (cfg, klass))
4650                                 mini_emit_write_barrier (cfg, addr, sp [2]);
4651                 }
4652                 return ins;
4653         }
4654 }
4655
4656 static MonoInst*
4657 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4658 {
4659         MonoClass *eklass;
4660         
4661         if (is_set)
4662                 eklass = mono_class_from_mono_type (fsig->params [2]);
4663         else
4664                 eklass = mono_class_from_mono_type (fsig->ret);
4665
4666         if (is_set) {
4667                 return emit_array_store (cfg, eklass, args, FALSE);
4668         } else {
4669                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4670                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
4671                 return ins;
4672         }
4673 }
4674
4675 static gboolean
4676 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
4677 {
4678         uint32_t align;
4679         int param_size, return_size;
4680
4681         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
4682         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
4683
4684         if (cfg->verbose_level > 3)
4685                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
4686
4687         //Don't allow mixing reference types with value types
4688         if (param_klass->valuetype != return_klass->valuetype) {
4689                 if (cfg->verbose_level > 3)
4690                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
4691                 return FALSE;
4692         }
4693
4694         if (!param_klass->valuetype) {
4695                 if (cfg->verbose_level > 3)
4696                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
4697                 return TRUE;
4698         }
4699
4700         //That are blitable
4701         if (param_klass->has_references || return_klass->has_references)
4702                 return FALSE;
4703
4704         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
4705         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
4706                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
4707                         if (cfg->verbose_level > 3)
4708                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
4709                 return FALSE;
4710         }
4711
4712         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
4713                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
4714                 if (cfg->verbose_level > 3)
4715                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
4716                 return FALSE;
4717         }
4718
4719         param_size = mono_class_value_size (param_klass, &align);
4720         return_size = mono_class_value_size (return_klass, &align);
4721
4722         //We can do it if sizes match
4723         if (param_size == return_size) {
4724                 if (cfg->verbose_level > 3)
4725                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
4726                 return TRUE;
4727         }
4728
4729         //No simple way to handle struct if sizes don't match
4730         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
4731                 if (cfg->verbose_level > 3)
4732                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
4733                 return FALSE;
4734         }
4735
4736         /*
4737          * Same reg size category.
4738          * A quick note on why we don't require widening here.
4739          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
4740          *
4741          * Since the source value comes from a function argument, the JIT will already have
4742          * the value in a VREG and performed any widening needed before (say, when loading from a field).
4743          */
4744         if (param_size <= 4 && return_size <= 4) {
4745                 if (cfg->verbose_level > 3)
4746                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
4747                 return TRUE;
4748         }
4749
4750         return FALSE;
4751 }
4752
4753 static MonoInst*
4754 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
4755 {
4756         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
4757         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
4758
4759         if (mini_is_gsharedvt_variable_type (fsig->ret))
4760                 return NULL;
4761
4762         //Valuetypes that are semantically equivalent or numbers than can be widened to
4763         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
4764                 return args [0];
4765
4766         //Arrays of valuetypes that are semantically equivalent
4767         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
4768                 return args [0];
4769
4770         return NULL;
4771 }
4772
4773 static MonoInst*
4774 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4775 {
4776 #ifdef MONO_ARCH_SIMD_INTRINSICS
4777         MonoInst *ins = NULL;
4778
4779         if (cfg->opt & MONO_OPT_SIMD) {
4780                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
4781                 if (ins)
4782                         return ins;
4783         }
4784 #endif
4785
4786         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
4787 }
4788
4789 MonoInst*
4790 mini_emit_memory_barrier (MonoCompile *cfg, int kind)
4791 {
4792         MonoInst *ins = NULL;
4793         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
4794         MONO_ADD_INS (cfg->cbb, ins);
4795         ins->backend.memory_barrier_kind = kind;
4796
4797         return ins;
4798 }
4799
4800 static MonoInst*
4801 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4802 {
4803         MonoInst *ins = NULL;
4804         int opcode = 0;
4805
4806         /* The LLVM backend supports these intrinsics */
4807         if (cmethod->klass == mono_defaults.math_class) {
4808                 if (strcmp (cmethod->name, "Sin") == 0) {
4809                         opcode = OP_SIN;
4810                 } else if (strcmp (cmethod->name, "Cos") == 0) {
4811                         opcode = OP_COS;
4812                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
4813                         opcode = OP_SQRT;
4814                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
4815                         opcode = OP_ABS;
4816                 }
4817
4818                 if (opcode && fsig->param_count == 1) {
4819                         MONO_INST_NEW (cfg, ins, opcode);
4820                         ins->type = STACK_R8;
4821                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4822                         ins->sreg1 = args [0]->dreg;
4823                         MONO_ADD_INS (cfg->cbb, ins);
4824                 }
4825
4826                 opcode = 0;
4827                 if (cfg->opt & MONO_OPT_CMOV) {
4828                         if (strcmp (cmethod->name, "Min") == 0) {
4829                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4830                                         opcode = OP_IMIN;
4831                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4832                                         opcode = OP_IMIN_UN;
4833                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4834                                         opcode = OP_LMIN;
4835                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4836                                         opcode = OP_LMIN_UN;
4837                         } else if (strcmp (cmethod->name, "Max") == 0) {
4838                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4839                                         opcode = OP_IMAX;
4840                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4841                                         opcode = OP_IMAX_UN;
4842                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4843                                         opcode = OP_LMAX;
4844                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4845                                         opcode = OP_LMAX_UN;
4846                         }
4847                 }
4848
4849                 if (opcode && fsig->param_count == 2) {
4850                         MONO_INST_NEW (cfg, ins, opcode);
4851                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
4852                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4853                         ins->sreg1 = args [0]->dreg;
4854                         ins->sreg2 = args [1]->dreg;
4855                         MONO_ADD_INS (cfg->cbb, ins);
4856                 }
4857         }
4858
4859         return ins;
4860 }
4861
4862 static MonoInst*
4863 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4864 {
4865         if (cmethod->klass == mono_defaults.array_class) {
4866                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
4867                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
4868                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
4869                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
4870                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
4871                         return emit_array_unsafe_mov (cfg, fsig, args);
4872         }
4873
4874         return NULL;
4875 }
4876
4877
4878 static gboolean
4879 mono_type_is_native_blittable (MonoType *t)
4880 {
4881         if (MONO_TYPE_IS_REFERENCE (t))
4882                 return FALSE;
4883
4884         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (t))
4885                 return TRUE;
4886
4887         MonoClass *klass = mono_class_from_mono_type (t);
4888
4889         //MonoClass::blitable depends on mono_class_setup_fields being done.
4890         mono_class_setup_fields (klass);
4891         if (!klass->blittable)
4892                 return FALSE;
4893
4894         // If the native marshal size is different we can't convert PtrToStructure to a type load
4895         if (mono_class_native_size (klass, NULL) != mono_class_value_size (klass, NULL))
4896                 return FALSE;
4897
4898         return TRUE;
4899 }
4900
4901
4902 static MonoInst*
4903 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4904 {
4905         MonoInst *ins = NULL;
4906         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
4907
4908         if (cmethod->klass == mono_defaults.string_class) {
4909                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
4910                         int dreg = alloc_ireg (cfg);
4911                         int index_reg = alloc_preg (cfg);
4912                         int add_reg = alloc_preg (cfg);
4913
4914 #if SIZEOF_REGISTER == 8
4915                         if (COMPILE_LLVM (cfg)) {
4916                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
4917                         } else {
4918                                 /* The array reg is 64 bits but the index reg is only 32 */
4919                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
4920                         }
4921 #else
4922                         index_reg = args [1]->dreg;
4923 #endif  
4924                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
4925
4926 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4927                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
4928                         add_reg = ins->dreg;
4929                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4930                                                                    add_reg, 0);
4931 #else
4932                         int mult_reg = alloc_preg (cfg);
4933                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
4934                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
4935                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4936                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
4937 #endif
4938                         type_from_op (cfg, ins, NULL, NULL);
4939                         return ins;
4940                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
4941                         int dreg = alloc_ireg (cfg);
4942                         /* Decompose later to allow more optimizations */
4943                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
4944                         ins->type = STACK_I4;
4945                         ins->flags |= MONO_INST_FAULT;
4946                         cfg->cbb->has_array_access = TRUE;
4947                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
4948
4949                         return ins;
4950                 } else 
4951                         return NULL;
4952         } else if (cmethod->klass == mono_defaults.object_class) {
4953                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
4954                         int dreg = alloc_ireg_ref (cfg);
4955                         int vt_reg = alloc_preg (cfg);
4956                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4957                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
4958                         type_from_op (cfg, ins, NULL, NULL);
4959
4960                         return ins;
4961                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
4962                         int dreg = alloc_ireg (cfg);
4963                         int t1 = alloc_ireg (cfg);
4964         
4965                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
4966                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
4967                         ins->type = STACK_I4;
4968
4969                         return ins;
4970                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
4971                         MONO_INST_NEW (cfg, ins, OP_NOP);
4972                         MONO_ADD_INS (cfg->cbb, ins);
4973                         return ins;
4974                 } else
4975                         return NULL;
4976         } else if (cmethod->klass == mono_defaults.array_class) {
4977                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4978                         return emit_array_generic_access (cfg, fsig, args, FALSE);
4979                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4980                         return emit_array_generic_access (cfg, fsig, args, TRUE);
4981
4982 #ifndef MONO_BIG_ARRAYS
4983                 /*
4984                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
4985                  * Array methods.
4986                  */
4987                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
4988                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
4989                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
4990                         int dreg = alloc_ireg (cfg);
4991                         int bounds_reg = alloc_ireg_mp (cfg);
4992                         MonoBasicBlock *end_bb, *szarray_bb;
4993                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
4994
4995                         NEW_BBLOCK (cfg, end_bb);
4996                         NEW_BBLOCK (cfg, szarray_bb);
4997
4998                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
4999                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5000                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5001                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5002                         /* Non-szarray case */
5003                         if (get_length)
5004                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5005                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5006                         else
5007                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5008                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5009                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5010                         MONO_START_BB (cfg, szarray_bb);
5011                         /* Szarray case */
5012                         if (get_length)
5013                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5014                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5015                         else
5016                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5017                         MONO_START_BB (cfg, end_bb);
5018
5019                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5020                         ins->type = STACK_I4;
5021                         
5022                         return ins;
5023                 }
5024 #endif
5025
5026                 if (cmethod->name [0] != 'g')
5027                         return NULL;
5028
5029                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5030                         int dreg = alloc_ireg (cfg);
5031                         int vtable_reg = alloc_preg (cfg);
5032                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5033                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5034                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5035                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5036                         type_from_op (cfg, ins, NULL, NULL);
5037
5038                         return ins;
5039                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5040                         int dreg = alloc_ireg (cfg);
5041
5042                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5043                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5044                         type_from_op (cfg, ins, NULL, NULL);
5045
5046                         return ins;
5047                 } else
5048                         return NULL;
5049         } else if (cmethod->klass == runtime_helpers_class) {
5050                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5051                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5052                         return ins;
5053                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5054                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5055                         g_assert (ctx);
5056                         g_assert (ctx->method_inst);
5057                         g_assert (ctx->method_inst->type_argc == 1);
5058                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5059                         MonoClass *klass = mono_class_from_mono_type (t);
5060
5061                         ins = NULL;
5062
5063                         mono_class_init (klass);
5064                         if (MONO_TYPE_IS_REFERENCE (t))
5065                                 EMIT_NEW_ICONST (cfg, ins, 1);
5066                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5067                                 EMIT_NEW_ICONST (cfg, ins, 0);
5068                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5069                                 EMIT_NEW_ICONST (cfg, ins, 1);
5070                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5071                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5072                         else {
5073                                 g_assert (cfg->gshared);
5074
5075                                 int context_used = mini_class_check_context_used (cfg, klass);
5076
5077                                 /* This returns 1 or 2 */
5078                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5079                                 int dreg = alloc_ireg (cfg);
5080                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5081                         }
5082
5083                         return ins;
5084                 } else
5085                         return NULL;
5086         } else if (cmethod->klass == mono_defaults.monitor_class) {
5087                 gboolean is_enter = FALSE;
5088                 gboolean is_v4 = FALSE;
5089
5090                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5091                         is_enter = TRUE;
5092                         is_v4 = TRUE;
5093                 }
5094                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5095                         is_enter = TRUE;
5096
5097                 if (is_enter) {
5098                         /*
5099                          * To make async stack traces work, icalls which can block should have a wrapper.
5100                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5101                          */
5102                         MonoBasicBlock *end_bb;
5103
5104                         NEW_BBLOCK (cfg, end_bb);
5105
5106                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5107                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5108                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5109                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5110                         MONO_START_BB (cfg, end_bb);
5111                         return ins;
5112                 }
5113         } else if (cmethod->klass == mono_defaults.thread_class) {
5114                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5115                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5116                         MONO_ADD_INS (cfg->cbb, ins);
5117                         return ins;
5118                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5119                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5120                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5121                         guint32 opcode = 0;
5122                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5123
5124                         if (fsig->params [0]->type == MONO_TYPE_I1)
5125                                 opcode = OP_LOADI1_MEMBASE;
5126                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5127                                 opcode = OP_LOADU1_MEMBASE;
5128                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5129                                 opcode = OP_LOADI2_MEMBASE;
5130                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5131                                 opcode = OP_LOADU2_MEMBASE;
5132                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5133                                 opcode = OP_LOADI4_MEMBASE;
5134                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5135                                 opcode = OP_LOADU4_MEMBASE;
5136                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5137                                 opcode = OP_LOADI8_MEMBASE;
5138                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5139                                 opcode = OP_LOADR4_MEMBASE;
5140                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5141                                 opcode = OP_LOADR8_MEMBASE;
5142                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5143                                 opcode = OP_LOAD_MEMBASE;
5144
5145                         if (opcode) {
5146                                 MONO_INST_NEW (cfg, ins, opcode);
5147                                 ins->inst_basereg = args [0]->dreg;
5148                                 ins->inst_offset = 0;
5149                                 MONO_ADD_INS (cfg->cbb, ins);
5150
5151                                 switch (fsig->params [0]->type) {
5152                                 case MONO_TYPE_I1:
5153                                 case MONO_TYPE_U1:
5154                                 case MONO_TYPE_I2:
5155                                 case MONO_TYPE_U2:
5156                                 case MONO_TYPE_I4:
5157                                 case MONO_TYPE_U4:
5158                                         ins->dreg = mono_alloc_ireg (cfg);
5159                                         ins->type = STACK_I4;
5160                                         break;
5161                                 case MONO_TYPE_I8:
5162                                 case MONO_TYPE_U8:
5163                                         ins->dreg = mono_alloc_lreg (cfg);
5164                                         ins->type = STACK_I8;
5165                                         break;
5166                                 case MONO_TYPE_I:
5167                                 case MONO_TYPE_U:
5168                                         ins->dreg = mono_alloc_ireg (cfg);
5169 #if SIZEOF_REGISTER == 8
5170                                         ins->type = STACK_I8;
5171 #else
5172                                         ins->type = STACK_I4;
5173 #endif
5174                                         break;
5175                                 case MONO_TYPE_R4:
5176                                 case MONO_TYPE_R8:
5177                                         ins->dreg = mono_alloc_freg (cfg);
5178                                         ins->type = STACK_R8;
5179                                         break;
5180                                 default:
5181                                         g_assert (mini_type_is_reference (fsig->params [0]));
5182                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5183                                         ins->type = STACK_OBJ;
5184                                         break;
5185                                 }
5186
5187                                 if (opcode == OP_LOADI8_MEMBASE)
5188                                         ins = mono_decompose_opcode (cfg, ins);
5189
5190                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5191
5192                                 return ins;
5193                         }
5194                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5195                         guint32 opcode = 0;
5196                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5197
5198                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5199                                 opcode = OP_STOREI1_MEMBASE_REG;
5200                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5201                                 opcode = OP_STOREI2_MEMBASE_REG;
5202                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5203                                 opcode = OP_STOREI4_MEMBASE_REG;
5204                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5205                                 opcode = OP_STOREI8_MEMBASE_REG;
5206                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5207                                 opcode = OP_STORER4_MEMBASE_REG;
5208                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5209                                 opcode = OP_STORER8_MEMBASE_REG;
5210                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5211                                 opcode = OP_STORE_MEMBASE_REG;
5212
5213                         if (opcode) {
5214                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5215
5216                                 MONO_INST_NEW (cfg, ins, opcode);
5217                                 ins->sreg1 = args [1]->dreg;
5218                                 ins->inst_destbasereg = args [0]->dreg;
5219                                 ins->inst_offset = 0;
5220                                 MONO_ADD_INS (cfg->cbb, ins);
5221
5222                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5223                                         ins = mono_decompose_opcode (cfg, ins);
5224
5225                                 return ins;
5226                         }
5227                 }
5228         } else if (cmethod->klass->image == mono_defaults.corlib &&
5229                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5230                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5231                 ins = NULL;
5232
5233 #if SIZEOF_REGISTER == 8
5234                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5235                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5236                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5237                                 ins->dreg = mono_alloc_preg (cfg);
5238                                 ins->sreg1 = args [0]->dreg;
5239                                 ins->type = STACK_I8;
5240                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5241                                 MONO_ADD_INS (cfg->cbb, ins);
5242                         } else {
5243                                 MonoInst *load_ins;
5244
5245                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5246
5247                                 /* 64 bit reads are already atomic */
5248                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5249                                 load_ins->dreg = mono_alloc_preg (cfg);
5250                                 load_ins->inst_basereg = args [0]->dreg;
5251                                 load_ins->inst_offset = 0;
5252                                 load_ins->type = STACK_I8;
5253                                 MONO_ADD_INS (cfg->cbb, load_ins);
5254
5255                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5256
5257                                 ins = load_ins;
5258                         }
5259                 }
5260 #endif
5261
5262                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5263                         MonoInst *ins_iconst;
5264                         guint32 opcode = 0;
5265
5266                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5267                                 opcode = OP_ATOMIC_ADD_I4;
5268                                 cfg->has_atomic_add_i4 = TRUE;
5269                         }
5270 #if SIZEOF_REGISTER == 8
5271                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5272                                 opcode = OP_ATOMIC_ADD_I8;
5273 #endif
5274                         if (opcode) {
5275                                 if (!mono_arch_opcode_supported (opcode))
5276                                         return NULL;
5277                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5278                                 ins_iconst->inst_c0 = 1;
5279                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5280                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5281
5282                                 MONO_INST_NEW (cfg, ins, opcode);
5283                                 ins->dreg = mono_alloc_ireg (cfg);
5284                                 ins->inst_basereg = args [0]->dreg;
5285                                 ins->inst_offset = 0;
5286                                 ins->sreg2 = ins_iconst->dreg;
5287                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5288                                 MONO_ADD_INS (cfg->cbb, ins);
5289                         }
5290                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5291                         MonoInst *ins_iconst;
5292                         guint32 opcode = 0;
5293
5294                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5295                                 opcode = OP_ATOMIC_ADD_I4;
5296                                 cfg->has_atomic_add_i4 = TRUE;
5297                         }
5298 #if SIZEOF_REGISTER == 8
5299                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5300                                 opcode = OP_ATOMIC_ADD_I8;
5301 #endif
5302                         if (opcode) {
5303                                 if (!mono_arch_opcode_supported (opcode))
5304                                         return NULL;
5305                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5306                                 ins_iconst->inst_c0 = -1;
5307                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5308                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5309
5310                                 MONO_INST_NEW (cfg, ins, opcode);
5311                                 ins->dreg = mono_alloc_ireg (cfg);
5312                                 ins->inst_basereg = args [0]->dreg;
5313                                 ins->inst_offset = 0;
5314                                 ins->sreg2 = ins_iconst->dreg;
5315                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5316                                 MONO_ADD_INS (cfg->cbb, ins);
5317                         }
5318                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5319                         guint32 opcode = 0;
5320
5321                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5322                                 opcode = OP_ATOMIC_ADD_I4;
5323                                 cfg->has_atomic_add_i4 = TRUE;
5324                         }
5325 #if SIZEOF_REGISTER == 8
5326                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5327                                 opcode = OP_ATOMIC_ADD_I8;
5328 #endif
5329                         if (opcode) {
5330                                 if (!mono_arch_opcode_supported (opcode))
5331                                         return NULL;
5332                                 MONO_INST_NEW (cfg, ins, opcode);
5333                                 ins->dreg = mono_alloc_ireg (cfg);
5334                                 ins->inst_basereg = args [0]->dreg;
5335                                 ins->inst_offset = 0;
5336                                 ins->sreg2 = args [1]->dreg;
5337                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5338                                 MONO_ADD_INS (cfg->cbb, ins);
5339                         }
5340                 }
5341                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5342                         MonoInst *f2i = NULL, *i2f;
5343                         guint32 opcode, f2i_opcode, i2f_opcode;
5344                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5345                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5346
5347                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5348                             fsig->params [0]->type == MONO_TYPE_R4) {
5349                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5350                                 f2i_opcode = OP_MOVE_F_TO_I4;
5351                                 i2f_opcode = OP_MOVE_I4_TO_F;
5352                                 cfg->has_atomic_exchange_i4 = TRUE;
5353                         }
5354 #if SIZEOF_REGISTER == 8
5355                         else if (is_ref ||
5356                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5357                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5358                                  fsig->params [0]->type == MONO_TYPE_I) {
5359                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5360                                 f2i_opcode = OP_MOVE_F_TO_I8;
5361                                 i2f_opcode = OP_MOVE_I8_TO_F;
5362                         }
5363 #else
5364                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5365                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5366                                 cfg->has_atomic_exchange_i4 = TRUE;
5367                         }
5368 #endif
5369                         else
5370                                 return NULL;
5371
5372                         if (!mono_arch_opcode_supported (opcode))
5373                                 return NULL;
5374
5375                         if (is_float) {
5376                                 /* TODO: Decompose these opcodes instead of bailing here. */
5377                                 if (COMPILE_SOFT_FLOAT (cfg))
5378                                         return NULL;
5379
5380                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5381                                 f2i->dreg = mono_alloc_ireg (cfg);
5382                                 f2i->sreg1 = args [1]->dreg;
5383                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5384                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5385                                 MONO_ADD_INS (cfg->cbb, f2i);
5386                         }
5387
5388                         MONO_INST_NEW (cfg, ins, opcode);
5389                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5390                         ins->inst_basereg = args [0]->dreg;
5391                         ins->inst_offset = 0;
5392                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5393                         MONO_ADD_INS (cfg->cbb, ins);
5394
5395                         switch (fsig->params [0]->type) {
5396                         case MONO_TYPE_I4:
5397                                 ins->type = STACK_I4;
5398                                 break;
5399                         case MONO_TYPE_I8:
5400                                 ins->type = STACK_I8;
5401                                 break;
5402                         case MONO_TYPE_I:
5403 #if SIZEOF_REGISTER == 8
5404                                 ins->type = STACK_I8;
5405 #else
5406                                 ins->type = STACK_I4;
5407 #endif
5408                                 break;
5409                         case MONO_TYPE_R4:
5410                         case MONO_TYPE_R8:
5411                                 ins->type = STACK_R8;
5412                                 break;
5413                         default:
5414                                 g_assert (mini_type_is_reference (fsig->params [0]));
5415                                 ins->type = STACK_OBJ;
5416                                 break;
5417                         }
5418
5419                         if (is_float) {
5420                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5421                                 i2f->dreg = mono_alloc_freg (cfg);
5422                                 i2f->sreg1 = ins->dreg;
5423                                 i2f->type = STACK_R8;
5424                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5425                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5426                                 MONO_ADD_INS (cfg->cbb, i2f);
5427
5428                                 ins = i2f;
5429                         }
5430
5431                         if (cfg->gen_write_barriers && is_ref)
5432                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5433                 }
5434                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5435                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5436                         guint32 opcode, f2i_opcode, i2f_opcode;
5437                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5438                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5439
5440                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5441                             fsig->params [1]->type == MONO_TYPE_R4) {
5442                                 opcode = OP_ATOMIC_CAS_I4;
5443                                 f2i_opcode = OP_MOVE_F_TO_I4;
5444                                 i2f_opcode = OP_MOVE_I4_TO_F;
5445                                 cfg->has_atomic_cas_i4 = TRUE;
5446                         }
5447 #if SIZEOF_REGISTER == 8
5448                         else if (is_ref ||
5449                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5450                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5451                                  fsig->params [1]->type == MONO_TYPE_I) {
5452                                 opcode = OP_ATOMIC_CAS_I8;
5453                                 f2i_opcode = OP_MOVE_F_TO_I8;
5454                                 i2f_opcode = OP_MOVE_I8_TO_F;
5455                         }
5456 #else
5457                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5458                                 opcode = OP_ATOMIC_CAS_I4;
5459                                 cfg->has_atomic_cas_i4 = TRUE;
5460                         }
5461 #endif
5462                         else
5463                                 return NULL;
5464
5465                         if (!mono_arch_opcode_supported (opcode))
5466                                 return NULL;
5467
5468                         if (is_float) {
5469                                 /* TODO: Decompose these opcodes instead of bailing here. */
5470                                 if (COMPILE_SOFT_FLOAT (cfg))
5471                                         return NULL;
5472
5473                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5474                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5475                                 f2i_new->sreg1 = args [1]->dreg;
5476                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5477                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5478                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5479
5480                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5481                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5482                                 f2i_cmp->sreg1 = args [2]->dreg;
5483                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5484                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5485                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5486                         }
5487
5488                         MONO_INST_NEW (cfg, ins, opcode);
5489                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5490                         ins->sreg1 = args [0]->dreg;
5491                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5492                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5493                         MONO_ADD_INS (cfg->cbb, ins);
5494
5495                         switch (fsig->params [1]->type) {
5496                         case MONO_TYPE_I4:
5497                                 ins->type = STACK_I4;
5498                                 break;
5499                         case MONO_TYPE_I8:
5500                                 ins->type = STACK_I8;
5501                                 break;
5502                         case MONO_TYPE_I:
5503 #if SIZEOF_REGISTER == 8
5504                                 ins->type = STACK_I8;
5505 #else
5506                                 ins->type = STACK_I4;
5507 #endif
5508                                 break;
5509                         case MONO_TYPE_R4:
5510                                 ins->type = cfg->r4_stack_type;
5511                                 break;
5512                         case MONO_TYPE_R8:
5513                                 ins->type = STACK_R8;
5514                                 break;
5515                         default:
5516                                 g_assert (mini_type_is_reference (fsig->params [1]));
5517                                 ins->type = STACK_OBJ;
5518                                 break;
5519                         }
5520
5521                         if (is_float) {
5522                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5523                                 i2f->dreg = mono_alloc_freg (cfg);
5524                                 i2f->sreg1 = ins->dreg;
5525                                 i2f->type = STACK_R8;
5526                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5527                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5528                                 MONO_ADD_INS (cfg->cbb, i2f);
5529
5530                                 ins = i2f;
5531                         }
5532
5533                         if (cfg->gen_write_barriers && is_ref)
5534                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5535                 }
5536                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5537                          fsig->params [1]->type == MONO_TYPE_I4) {
5538                         MonoInst *cmp, *ceq;
5539
5540                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5541                                 return NULL;
5542
5543                         /* int32 r = CAS (location, value, comparand); */
5544                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5545                         ins->dreg = alloc_ireg (cfg);
5546                         ins->sreg1 = args [0]->dreg;
5547                         ins->sreg2 = args [1]->dreg;
5548                         ins->sreg3 = args [2]->dreg;
5549                         ins->type = STACK_I4;
5550                         MONO_ADD_INS (cfg->cbb, ins);
5551
5552                         /* bool result = r == comparand; */
5553                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5554                         cmp->sreg1 = ins->dreg;
5555                         cmp->sreg2 = args [2]->dreg;
5556                         cmp->type = STACK_I4;
5557                         MONO_ADD_INS (cfg->cbb, cmp);
5558
5559                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5560                         ceq->dreg = alloc_ireg (cfg);
5561                         ceq->type = STACK_I4;
5562                         MONO_ADD_INS (cfg->cbb, ceq);
5563
5564                         /* *success = result; */
5565                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5566
5567                         cfg->has_atomic_cas_i4 = TRUE;
5568                 }
5569                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5570                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5571
5572                 if (ins)
5573                         return ins;
5574         } else if (cmethod->klass->image == mono_defaults.corlib &&
5575                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5576                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5577                 ins = NULL;
5578
5579                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5580                         guint32 opcode = 0;
5581                         MonoType *t = fsig->params [0];
5582                         gboolean is_ref;
5583                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5584
5585                         g_assert (t->byref);
5586                         /* t is a byref type, so the reference check is more complicated */
5587                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5588                         if (t->type == MONO_TYPE_I1)
5589                                 opcode = OP_ATOMIC_LOAD_I1;
5590                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5591                                 opcode = OP_ATOMIC_LOAD_U1;
5592                         else if (t->type == MONO_TYPE_I2)
5593                                 opcode = OP_ATOMIC_LOAD_I2;
5594                         else if (t->type == MONO_TYPE_U2)
5595                                 opcode = OP_ATOMIC_LOAD_U2;
5596                         else if (t->type == MONO_TYPE_I4)
5597                                 opcode = OP_ATOMIC_LOAD_I4;
5598                         else if (t->type == MONO_TYPE_U4)
5599                                 opcode = OP_ATOMIC_LOAD_U4;
5600                         else if (t->type == MONO_TYPE_R4)
5601                                 opcode = OP_ATOMIC_LOAD_R4;
5602                         else if (t->type == MONO_TYPE_R8)
5603                                 opcode = OP_ATOMIC_LOAD_R8;
5604 #if SIZEOF_REGISTER == 8
5605                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5606                                 opcode = OP_ATOMIC_LOAD_I8;
5607                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5608                                 opcode = OP_ATOMIC_LOAD_U8;
5609 #else
5610                         else if (t->type == MONO_TYPE_I)
5611                                 opcode = OP_ATOMIC_LOAD_I4;
5612                         else if (is_ref || t->type == MONO_TYPE_U)
5613                                 opcode = OP_ATOMIC_LOAD_U4;
5614 #endif
5615
5616                         if (opcode) {
5617                                 if (!mono_arch_opcode_supported (opcode))
5618                                         return NULL;
5619
5620                                 MONO_INST_NEW (cfg, ins, opcode);
5621                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5622                                 ins->sreg1 = args [0]->dreg;
5623                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5624                                 MONO_ADD_INS (cfg->cbb, ins);
5625
5626                                 switch (t->type) {
5627                                 case MONO_TYPE_BOOLEAN:
5628                                 case MONO_TYPE_I1:
5629                                 case MONO_TYPE_U1:
5630                                 case MONO_TYPE_I2:
5631                                 case MONO_TYPE_U2:
5632                                 case MONO_TYPE_I4:
5633                                 case MONO_TYPE_U4:
5634                                         ins->type = STACK_I4;
5635                                         break;
5636                                 case MONO_TYPE_I8:
5637                                 case MONO_TYPE_U8:
5638                                         ins->type = STACK_I8;
5639                                         break;
5640                                 case MONO_TYPE_I:
5641                                 case MONO_TYPE_U:
5642 #if SIZEOF_REGISTER == 8
5643                                         ins->type = STACK_I8;
5644 #else
5645                                         ins->type = STACK_I4;
5646 #endif
5647                                         break;
5648                                 case MONO_TYPE_R4:
5649                                         ins->type = cfg->r4_stack_type;
5650                                         break;
5651                                 case MONO_TYPE_R8:
5652                                         ins->type = STACK_R8;
5653                                         break;
5654                                 default:
5655                                         g_assert (is_ref);
5656                                         ins->type = STACK_OBJ;
5657                                         break;
5658                                 }
5659                         }
5660                 }
5661
5662                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5663                         guint32 opcode = 0;
5664                         MonoType *t = fsig->params [0];
5665                         gboolean is_ref;
5666
5667                         g_assert (t->byref);
5668                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5669                         if (t->type == MONO_TYPE_I1)
5670                                 opcode = OP_ATOMIC_STORE_I1;
5671                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5672                                 opcode = OP_ATOMIC_STORE_U1;
5673                         else if (t->type == MONO_TYPE_I2)
5674                                 opcode = OP_ATOMIC_STORE_I2;
5675                         else if (t->type == MONO_TYPE_U2)
5676                                 opcode = OP_ATOMIC_STORE_U2;
5677                         else if (t->type == MONO_TYPE_I4)
5678                                 opcode = OP_ATOMIC_STORE_I4;
5679                         else if (t->type == MONO_TYPE_U4)
5680                                 opcode = OP_ATOMIC_STORE_U4;
5681                         else if (t->type == MONO_TYPE_R4)
5682                                 opcode = OP_ATOMIC_STORE_R4;
5683                         else if (t->type == MONO_TYPE_R8)
5684                                 opcode = OP_ATOMIC_STORE_R8;
5685 #if SIZEOF_REGISTER == 8
5686                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5687                                 opcode = OP_ATOMIC_STORE_I8;
5688                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5689                                 opcode = OP_ATOMIC_STORE_U8;
5690 #else
5691                         else if (t->type == MONO_TYPE_I)
5692                                 opcode = OP_ATOMIC_STORE_I4;
5693                         else if (is_ref || t->type == MONO_TYPE_U)
5694                                 opcode = OP_ATOMIC_STORE_U4;
5695 #endif
5696
5697                         if (opcode) {
5698                                 if (!mono_arch_opcode_supported (opcode))
5699                                         return NULL;
5700
5701                                 MONO_INST_NEW (cfg, ins, opcode);
5702                                 ins->dreg = args [0]->dreg;
5703                                 ins->sreg1 = args [1]->dreg;
5704                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5705                                 MONO_ADD_INS (cfg->cbb, ins);
5706
5707                                 if (cfg->gen_write_barriers && is_ref)
5708                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5709                         }
5710                 }
5711
5712                 if (ins)
5713                         return ins;
5714         } else if (cmethod->klass->image == mono_defaults.corlib &&
5715                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5716                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5717                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5718                         if (mini_should_insert_breakpoint (cfg->method)) {
5719                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5720                         } else {
5721                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5722                                 MONO_ADD_INS (cfg->cbb, ins);
5723                         }
5724                         return ins;
5725                 }
5726         } else if (cmethod->klass->image == mono_defaults.corlib &&
5727                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5728                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5729                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5730 #ifdef TARGET_WIN32
5731                         EMIT_NEW_ICONST (cfg, ins, 1);
5732 #else
5733                         EMIT_NEW_ICONST (cfg, ins, 0);
5734 #endif
5735                 }
5736         } else if (cmethod->klass->image == mono_defaults.corlib &&
5737                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5738                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5739                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5740                         /* No stack walks are currently available, so implement this as an intrinsic */
5741                         MonoInst *assembly_ins;
5742
5743                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5744                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5745                         return ins;
5746                 }
5747         } else if (cmethod->klass->image == mono_defaults.corlib &&
5748                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5749                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5750                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5751                         /* No stack walks are currently available, so implement this as an intrinsic */
5752                         MonoInst *method_ins;
5753                         MonoMethod *declaring = cfg->method;
5754
5755                         /* This returns the declaring generic method */
5756                         if (declaring->is_inflated)
5757                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5758                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5759                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
5760                         cfg->no_inline = TRUE;
5761                         if (cfg->method != cfg->current_method)
5762                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
5763                         return ins;
5764                 }
5765         } else if (cmethod->klass == mono_defaults.math_class) {
5766                 /* 
5767                  * There is general branchless code for Min/Max, but it does not work for 
5768                  * all inputs:
5769                  * http://everything2.com/?node_id=1051618
5770                  */
5771         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
5772                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
5773                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
5774                 ins->dreg = alloc_preg (cfg);
5775                 ins->type = STACK_I4;
5776                 MONO_ADD_INS (cfg->cbb, ins);
5777                 return ins;
5778         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
5779                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
5780                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
5781                                 !strcmp (cmethod->klass->name, "Selector")) ||
5782                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
5783                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
5784                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
5785                                 !strcmp (cmethod->klass->name, "Selector"))
5786                            ) {
5787                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
5788                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
5789                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
5790                     cfg->compile_aot) {
5791                         MonoInst *pi;
5792                         MonoJumpInfoToken *ji;
5793                         char *s;
5794
5795                         if (args [0]->opcode == OP_GOT_ENTRY) {
5796                                 pi = (MonoInst *)args [0]->inst_p1;
5797                                 g_assert (pi->opcode == OP_PATCH_INFO);
5798                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
5799                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
5800                         } else {
5801                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
5802                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
5803                         }
5804
5805                         NULLIFY_INS (args [0]);
5806
5807                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
5808                         return_val_if_nok (&cfg->error, NULL);
5809
5810                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
5811                         ins->dreg = mono_alloc_ireg (cfg);
5812                         // FIXME: Leaks
5813                         ins->inst_p0 = s;
5814                         MONO_ADD_INS (cfg->cbb, ins);
5815                         return ins;
5816                 }
5817         } else if (cmethod->klass->image == mono_defaults.corlib &&
5818                         (strcmp (cmethod->klass->name_space, "System.Runtime.InteropServices") == 0) &&
5819                         (strcmp (cmethod->klass->name, "Marshal") == 0)) {
5820                 //Convert Marshal.PtrToStructure<T> of blittable T to direct loads
5821                 if (strcmp (cmethod->name, "PtrToStructure") == 0 &&
5822                                 cmethod->is_inflated &&
5823                                 fsig->param_count == 1 &&
5824                                 !mini_method_check_context_used (cfg, cmethod)) {
5825
5826                         MonoGenericContext *method_context = mono_method_get_context (cmethod);
5827                         MonoType *arg0 = method_context->method_inst->type_argv [0];
5828                         if (mono_type_is_native_blittable (arg0))
5829                                 return mini_emit_memory_load (cfg, arg0, args [0], 0, 0);
5830                 }
5831         }
5832
5833 #ifdef MONO_ARCH_SIMD_INTRINSICS
5834         if (cfg->opt & MONO_OPT_SIMD) {
5835                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5836                 if (ins)
5837                         return ins;
5838         }
5839 #endif
5840
5841         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5842         if (ins)
5843                 return ins;
5844
5845         if (COMPILE_LLVM (cfg)) {
5846                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
5847                 if (ins)
5848                         return ins;
5849         }
5850
5851         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
5852 }
5853
5854 /*
5855  * This entry point could be used later for arbitrary method
5856  * redirection.
5857  */
5858 inline static MonoInst*
5859 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
5860                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
5861 {
5862         if (method->klass == mono_defaults.string_class) {
5863                 /* managed string allocation support */
5864                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
5865                         MonoInst *iargs [2];
5866                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
5867                         MonoMethod *managed_alloc = NULL;
5868
5869                         g_assert (vtable); /*Should not fail since it System.String*/
5870 #ifndef MONO_CROSS_COMPILE
5871                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
5872 #endif
5873                         if (!managed_alloc)
5874                                 return NULL;
5875                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
5876                         iargs [1] = args [0];
5877                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
5878                 }
5879         }
5880         return NULL;
5881 }
5882
5883 static void
5884 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
5885 {
5886         MonoInst *store, *temp;
5887         int i;
5888
5889         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5890                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
5891
5892                 /*
5893                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
5894                  * would be different than the MonoInst's used to represent arguments, and
5895                  * the ldelema implementation can't deal with that.
5896                  * Solution: When ldelema is used on an inline argument, create a var for 
5897                  * it, emit ldelema on that var, and emit the saving code below in
5898                  * inline_method () if needed.
5899                  */
5900                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
5901                 cfg->args [i] = temp;
5902                 /* This uses cfg->args [i] which is set by the preceeding line */
5903                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
5904                 store->cil_code = sp [0]->cil_code;
5905                 sp++;
5906         }
5907 }
5908
5909 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
5910 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
5911
5912 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
5913 static gboolean
5914 check_inline_called_method_name_limit (MonoMethod *called_method)
5915 {
5916         int strncmp_result;
5917         static const char *limit = NULL;
5918         
5919         if (limit == NULL) {
5920                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
5921
5922                 if (limit_string != NULL)
5923                         limit = limit_string;
5924                 else
5925                         limit = "";
5926         }
5927
5928         if (limit [0] != '\0') {
5929                 char *called_method_name = mono_method_full_name (called_method, TRUE);
5930
5931                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
5932                 g_free (called_method_name);
5933         
5934                 //return (strncmp_result <= 0);
5935                 return (strncmp_result == 0);
5936         } else {
5937                 return TRUE;
5938         }
5939 }
5940 #endif
5941
5942 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
5943 static gboolean
5944 check_inline_caller_method_name_limit (MonoMethod *caller_method)
5945 {
5946         int strncmp_result;
5947         static const char *limit = NULL;
5948         
5949         if (limit == NULL) {
5950                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
5951                 if (limit_string != NULL) {
5952                         limit = limit_string;
5953                 } else {
5954                         limit = "";
5955                 }
5956         }
5957
5958         if (limit [0] != '\0') {
5959                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
5960
5961                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
5962                 g_free (caller_method_name);
5963         
5964                 //return (strncmp_result <= 0);
5965                 return (strncmp_result == 0);
5966         } else {
5967                 return TRUE;
5968         }
5969 }
5970 #endif
5971
5972 static void
5973 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5974 {
5975         static double r8_0 = 0.0;
5976         static float r4_0 = 0.0;
5977         MonoInst *ins;
5978         int t;
5979
5980         rtype = mini_get_underlying_type (rtype);
5981         t = rtype->type;
5982
5983         if (rtype->byref) {
5984                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5985         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5986                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5987         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5988                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
5989         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
5990                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
5991                 ins->type = STACK_R4;
5992                 ins->inst_p0 = (void*)&r4_0;
5993                 ins->dreg = dreg;
5994                 MONO_ADD_INS (cfg->cbb, ins);
5995         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5996                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5997                 ins->type = STACK_R8;
5998                 ins->inst_p0 = (void*)&r8_0;
5999                 ins->dreg = dreg;
6000                 MONO_ADD_INS (cfg->cbb, ins);
6001         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6002                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6003                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6004         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6005                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6006         } else {
6007                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6008         }
6009 }
6010
6011 static void
6012 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6013 {
6014         int t;
6015
6016         rtype = mini_get_underlying_type (rtype);
6017         t = rtype->type;
6018
6019         if (rtype->byref) {
6020                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6021         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6022                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6023         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6024                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6025         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6026                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6027         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6028                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6029         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6030                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6031                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6032         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6033                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6034         } else {
6035                 emit_init_rvar (cfg, dreg, rtype);
6036         }
6037 }
6038
6039 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6040 static void
6041 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6042 {
6043         MonoInst *var = cfg->locals [local];
6044         if (COMPILE_SOFT_FLOAT (cfg)) {
6045                 MonoInst *store;
6046                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6047                 emit_init_rvar (cfg, reg, type);
6048                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6049         } else {
6050                 if (init)
6051                         emit_init_rvar (cfg, var->dreg, type);
6052                 else
6053                         emit_dummy_init_rvar (cfg, var->dreg, type);
6054         }
6055 }
6056
6057 int
6058 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6059 {
6060         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6061 }
6062
6063 /*
6064  * inline_method:
6065  *
6066  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6067  */
6068 static int
6069 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6070                guchar *ip, guint real_offset, gboolean inline_always)
6071 {
6072         MonoError error;
6073         MonoInst *ins, *rvar = NULL;
6074         MonoMethodHeader *cheader;
6075         MonoBasicBlock *ebblock, *sbblock;
6076         int i, costs;
6077         MonoMethod *prev_inlined_method;
6078         MonoInst **prev_locals, **prev_args;
6079         MonoType **prev_arg_types;
6080         guint prev_real_offset;
6081         GHashTable *prev_cbb_hash;
6082         MonoBasicBlock **prev_cil_offset_to_bb;
6083         MonoBasicBlock *prev_cbb;
6084         const unsigned char *prev_ip;
6085         unsigned char *prev_cil_start;
6086         guint32 prev_cil_offset_to_bb_len;
6087         MonoMethod *prev_current_method;
6088         MonoGenericContext *prev_generic_context;
6089         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6090
6091         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6092
6093 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6094         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6095                 return 0;
6096 #endif
6097 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6098         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6099                 return 0;
6100 #endif
6101
6102         if (!fsig)
6103                 fsig = mono_method_signature (cmethod);
6104
6105         if (cfg->verbose_level > 2)
6106                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6107
6108         if (!cmethod->inline_info) {
6109                 cfg->stat_inlineable_methods++;
6110                 cmethod->inline_info = 1;
6111         }
6112
6113         /* allocate local variables */
6114         cheader = mono_method_get_header_checked (cmethod, &error);
6115         if (!cheader) {
6116                 if (inline_always) {
6117                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6118                         mono_error_move (&cfg->error, &error);
6119                 } else {
6120                         mono_error_cleanup (&error);
6121                 }
6122                 return 0;
6123         }
6124
6125         /*Must verify before creating locals as it can cause the JIT to assert.*/
6126         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6127                 mono_metadata_free_mh (cheader);
6128                 return 0;
6129         }
6130
6131         /* allocate space to store the return value */
6132         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6133                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6134         }
6135
6136         prev_locals = cfg->locals;
6137         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6138         for (i = 0; i < cheader->num_locals; ++i)
6139                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6140
6141         /* allocate start and end blocks */
6142         /* This is needed so if the inline is aborted, we can clean up */
6143         NEW_BBLOCK (cfg, sbblock);
6144         sbblock->real_offset = real_offset;
6145
6146         NEW_BBLOCK (cfg, ebblock);
6147         ebblock->block_num = cfg->num_bblocks++;
6148         ebblock->real_offset = real_offset;
6149
6150         prev_args = cfg->args;
6151         prev_arg_types = cfg->arg_types;
6152         prev_inlined_method = cfg->inlined_method;
6153         cfg->inlined_method = cmethod;
6154         cfg->ret_var_set = FALSE;
6155         cfg->inline_depth ++;
6156         prev_real_offset = cfg->real_offset;
6157         prev_cbb_hash = cfg->cbb_hash;
6158         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6159         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6160         prev_cil_start = cfg->cil_start;
6161         prev_ip = cfg->ip;
6162         prev_cbb = cfg->cbb;
6163         prev_current_method = cfg->current_method;
6164         prev_generic_context = cfg->generic_context;
6165         prev_ret_var_set = cfg->ret_var_set;
6166         prev_disable_inline = cfg->disable_inline;
6167
6168         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6169                 virtual_ = TRUE;
6170
6171         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6172
6173         ret_var_set = cfg->ret_var_set;
6174
6175         cfg->inlined_method = prev_inlined_method;
6176         cfg->real_offset = prev_real_offset;
6177         cfg->cbb_hash = prev_cbb_hash;
6178         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6179         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6180         cfg->cil_start = prev_cil_start;
6181         cfg->ip = prev_ip;
6182         cfg->locals = prev_locals;
6183         cfg->args = prev_args;
6184         cfg->arg_types = prev_arg_types;
6185         cfg->current_method = prev_current_method;
6186         cfg->generic_context = prev_generic_context;
6187         cfg->ret_var_set = prev_ret_var_set;
6188         cfg->disable_inline = prev_disable_inline;
6189         cfg->inline_depth --;
6190
6191         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6192                 if (cfg->verbose_level > 2)
6193                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6194
6195                 cfg->stat_inlined_methods++;
6196
6197                 /* always add some code to avoid block split failures */
6198                 MONO_INST_NEW (cfg, ins, OP_NOP);
6199                 MONO_ADD_INS (prev_cbb, ins);
6200
6201                 prev_cbb->next_bb = sbblock;
6202                 link_bblock (cfg, prev_cbb, sbblock);
6203
6204                 /* 
6205                  * Get rid of the begin and end bblocks if possible to aid local
6206                  * optimizations.
6207                  */
6208                 if (prev_cbb->out_count == 1)
6209                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6210
6211                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6212                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6213
6214                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6215                         MonoBasicBlock *prev = ebblock->in_bb [0];
6216
6217                         if (prev->next_bb == ebblock) {
6218                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6219                                 cfg->cbb = prev;
6220                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6221                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6222                                         cfg->cbb = prev_cbb;
6223                                 }
6224                         } else {
6225                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6226                                 cfg->cbb = ebblock;
6227                         }
6228                 } else {
6229                         /* 
6230                          * Its possible that the rvar is set in some prev bblock, but not in others.
6231                          * (#1835).
6232                          */
6233                         if (rvar) {
6234                                 MonoBasicBlock *bb;
6235
6236                                 for (i = 0; i < ebblock->in_count; ++i) {
6237                                         bb = ebblock->in_bb [i];
6238
6239                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6240                                                 cfg->cbb = bb;
6241
6242                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6243                                         }
6244                                 }
6245                         }
6246
6247                         cfg->cbb = ebblock;
6248                 }
6249
6250                 if (rvar) {
6251                         /*
6252                          * If the inlined method contains only a throw, then the ret var is not 
6253                          * set, so set it to a dummy value.
6254                          */
6255                         if (!ret_var_set)
6256                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6257
6258                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6259                         *sp++ = ins;
6260                 }
6261                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6262                 return costs + 1;
6263         } else {
6264                 if (cfg->verbose_level > 2)
6265                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6266                 cfg->exception_type = MONO_EXCEPTION_NONE;
6267
6268                 /* This gets rid of the newly added bblocks */
6269                 cfg->cbb = prev_cbb;
6270         }
6271         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6272         return 0;
6273 }
6274
6275 /*
6276  * Some of these comments may well be out-of-date.
6277  * Design decisions: we do a single pass over the IL code (and we do bblock 
6278  * splitting/merging in the few cases when it's required: a back jump to an IL
6279  * address that was not already seen as bblock starting point).
6280  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6281  * Complex operations are decomposed in simpler ones right away. We need to let the 
6282  * arch-specific code peek and poke inside this process somehow (except when the 
6283  * optimizations can take advantage of the full semantic info of coarse opcodes).
6284  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6285  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6286  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6287  * opcode with value bigger than OP_LAST.
6288  * At this point the IR can be handed over to an interpreter, a dumb code generator
6289  * or to the optimizing code generator that will translate it to SSA form.
6290  *
6291  * Profiling directed optimizations.
6292  * We may compile by default with few or no optimizations and instrument the code
6293  * or the user may indicate what methods to optimize the most either in a config file
6294  * or through repeated runs where the compiler applies offline the optimizations to 
6295  * each method and then decides if it was worth it.
6296  */
6297
6298 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6299 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6300 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6301 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6302 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6303 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6304 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6305 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6306
6307 /* offset from br.s -> br like opcodes */
6308 #define BIG_BRANCH_OFFSET 13
6309
6310 static gboolean
6311 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6312 {
6313         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6314
6315         return b == NULL || b == bb;
6316 }
6317
6318 static int
6319 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6320 {
6321         unsigned char *ip = start;
6322         unsigned char *target;
6323         int i;
6324         guint cli_addr;
6325         MonoBasicBlock *bblock;
6326         const MonoOpcode *opcode;
6327
6328         while (ip < end) {
6329                 cli_addr = ip - start;
6330                 i = mono_opcode_value ((const guint8 **)&ip, end);
6331                 if (i < 0)
6332                         UNVERIFIED;
6333                 opcode = &mono_opcodes [i];
6334                 switch (opcode->argument) {
6335                 case MonoInlineNone:
6336                         ip++; 
6337                         break;
6338                 case MonoInlineString:
6339                 case MonoInlineType:
6340                 case MonoInlineField:
6341                 case MonoInlineMethod:
6342                 case MonoInlineTok:
6343                 case MonoInlineSig:
6344                 case MonoShortInlineR:
6345                 case MonoInlineI:
6346                         ip += 5;
6347                         break;
6348                 case MonoInlineVar:
6349                         ip += 3;
6350                         break;
6351                 case MonoShortInlineVar:
6352                 case MonoShortInlineI:
6353                         ip += 2;
6354                         break;
6355                 case MonoShortInlineBrTarget:
6356                         target = start + cli_addr + 2 + (signed char)ip [1];
6357                         GET_BBLOCK (cfg, bblock, target);
6358                         ip += 2;
6359                         if (ip < end)
6360                                 GET_BBLOCK (cfg, bblock, ip);
6361                         break;
6362                 case MonoInlineBrTarget:
6363                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6364                         GET_BBLOCK (cfg, bblock, target);
6365                         ip += 5;
6366                         if (ip < end)
6367                                 GET_BBLOCK (cfg, bblock, ip);
6368                         break;
6369                 case MonoInlineSwitch: {
6370                         guint32 n = read32 (ip + 1);
6371                         guint32 j;
6372                         ip += 5;
6373                         cli_addr += 5 + 4 * n;
6374                         target = start + cli_addr;
6375                         GET_BBLOCK (cfg, bblock, target);
6376                         
6377                         for (j = 0; j < n; ++j) {
6378                                 target = start + cli_addr + (gint32)read32 (ip);
6379                                 GET_BBLOCK (cfg, bblock, target);
6380                                 ip += 4;
6381                         }
6382                         break;
6383                 }
6384                 case MonoInlineR:
6385                 case MonoInlineI8:
6386                         ip += 9;
6387                         break;
6388                 default:
6389                         g_assert_not_reached ();
6390                 }
6391
6392                 if (i == CEE_THROW) {
6393                         unsigned char *bb_start = ip - 1;
6394                         
6395                         /* Find the start of the bblock containing the throw */
6396                         bblock = NULL;
6397                         while ((bb_start >= start) && !bblock) {
6398                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6399                                 bb_start --;
6400                         }
6401                         if (bblock)
6402                                 bblock->out_of_line = 1;
6403                 }
6404         }
6405         return 0;
6406 unverified:
6407 exception_exit:
6408         *pos = ip;
6409         return 1;
6410 }
6411
6412 static inline MonoMethod *
6413 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6414 {
6415         MonoMethod *method;
6416
6417         error_init (error);
6418
6419         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6420                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6421                 if (context) {
6422                         method = mono_class_inflate_generic_method_checked (method, context, error);
6423                 }
6424         } else {
6425                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6426         }
6427
6428         return method;
6429 }
6430
6431 static inline MonoMethod *
6432 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6433 {
6434         MonoError error;
6435         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6436
6437         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6438                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6439                 method = NULL;
6440         }
6441
6442         if (!method && !cfg)
6443                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6444
6445         return method;
6446 }
6447
6448 MonoClass*
6449 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6450 {
6451         MonoError error;
6452         MonoClass *klass;
6453
6454         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6455                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6456                 if (context) {
6457                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6458                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6459                 }
6460         } else {
6461                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6462                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6463         }
6464         if (klass)
6465                 mono_class_init (klass);
6466         return klass;
6467 }
6468
6469 static inline MonoMethodSignature*
6470 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6471 {
6472         MonoMethodSignature *fsig;
6473
6474         error_init (error);
6475         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6476                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6477         } else {
6478                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6479                 return_val_if_nok (error, NULL);
6480         }
6481         if (context) {
6482                 fsig = mono_inflate_generic_signature(fsig, context, error);
6483         }
6484         return fsig;
6485 }
6486
6487 static MonoMethod*
6488 throw_exception (void)
6489 {
6490         static MonoMethod *method = NULL;
6491
6492         if (!method) {
6493                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6494                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6495         }
6496         g_assert (method);
6497         return method;
6498 }
6499
6500 static void
6501 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6502 {
6503         MonoMethod *thrower = throw_exception ();
6504         MonoInst *args [1];
6505
6506         EMIT_NEW_PCONST (cfg, args [0], ex);
6507         mono_emit_method_call (cfg, thrower, args, NULL);
6508 }
6509
6510 /*
6511  * Return the original method is a wrapper is specified. We can only access 
6512  * the custom attributes from the original method.
6513  */
6514 static MonoMethod*
6515 get_original_method (MonoMethod *method)
6516 {
6517         if (method->wrapper_type == MONO_WRAPPER_NONE)
6518                 return method;
6519
6520         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6521         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6522                 return NULL;
6523
6524         /* in other cases we need to find the original method */
6525         return mono_marshal_method_from_wrapper (method);
6526 }
6527
6528 static void
6529 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6530 {
6531         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6532         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6533         if (ex)
6534                 emit_throw_exception (cfg, ex);
6535 }
6536
6537 static void
6538 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6539 {
6540         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6541         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6542         if (ex)
6543                 emit_throw_exception (cfg, ex);
6544 }
6545
6546 /*
6547  * Check that the IL instructions at ip are the array initialization
6548  * sequence and return the pointer to the data and the size.
6549  */
6550 static const char*
6551 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6552 {
6553         /*
6554          * newarr[System.Int32]
6555          * dup
6556          * ldtoken field valuetype ...
6557          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6558          */
6559         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6560                 MonoError error;
6561                 guint32 token = read32 (ip + 7);
6562                 guint32 field_token = read32 (ip + 2);
6563                 guint32 field_index = field_token & 0xffffff;
6564                 guint32 rva;
6565                 const char *data_ptr;
6566                 int size = 0;
6567                 MonoMethod *cmethod;
6568                 MonoClass *dummy_class;
6569                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6570                 int dummy_align;
6571
6572                 if (!field) {
6573                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6574                         return NULL;
6575                 }
6576
6577                 *out_field_token = field_token;
6578
6579                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6580                 if (!cmethod)
6581                         return NULL;
6582                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6583                         return NULL;
6584                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6585                 case MONO_TYPE_I1:
6586                 case MONO_TYPE_U1:
6587                         size = 1; break;
6588                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6589 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6590                 case MONO_TYPE_I2:
6591                 case MONO_TYPE_U2:
6592                         size = 2; break;
6593                 case MONO_TYPE_I4:
6594                 case MONO_TYPE_U4:
6595                 case MONO_TYPE_R4:
6596                         size = 4; break;
6597                 case MONO_TYPE_R8:
6598                 case MONO_TYPE_I8:
6599                 case MONO_TYPE_U8:
6600                         size = 8; break;
6601 #endif
6602                 default:
6603                         return NULL;
6604                 }
6605                 size *= len;
6606                 if (size > mono_type_size (field->type, &dummy_align))
6607                     return NULL;
6608                 *out_size = size;
6609                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6610                 if (!image_is_dynamic (method->klass->image)) {
6611                         field_index = read32 (ip + 2) & 0xffffff;
6612                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6613                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6614                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6615                         /* for aot code we do the lookup on load */
6616                         if (aot && data_ptr)
6617                                 return (const char *)GUINT_TO_POINTER (rva);
6618                 } else {
6619                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6620                         g_assert (!aot);
6621                         data_ptr = mono_field_get_data (field);
6622                 }
6623                 return data_ptr;
6624         }
6625         return NULL;
6626 }
6627
6628 static void
6629 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6630 {
6631         MonoError error;
6632         char *method_fname = mono_method_full_name (method, TRUE);
6633         char *method_code;
6634         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6635
6636         if (!header) {
6637                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6638                 mono_error_cleanup (&error);
6639         } else if (header->code_size == 0)
6640                 method_code = g_strdup ("method body is empty.");
6641         else
6642                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6643         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6644         g_free (method_fname);
6645         g_free (method_code);
6646         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6647 }
6648
6649 static void
6650 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6651 {
6652         MonoInst *ins;
6653         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6654         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6655                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6656                 /* Optimize reg-reg moves away */
6657                 /* 
6658                  * Can't optimize other opcodes, since sp[0] might point to
6659                  * the last ins of a decomposed opcode.
6660                  */
6661                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6662         } else {
6663                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6664         }
6665 }
6666
6667 /*
6668  * ldloca inhibits many optimizations so try to get rid of it in common
6669  * cases.
6670  */
6671 static inline unsigned char *
6672 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6673 {
6674         int local, token;
6675         MonoClass *klass;
6676         MonoType *type;
6677
6678         if (size == 1) {
6679                 local = ip [1];
6680                 ip += 2;
6681         } else {
6682                 local = read16 (ip + 2);
6683                 ip += 4;
6684         }
6685         
6686         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6687                 /* From the INITOBJ case */
6688                 token = read32 (ip + 2);
6689                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6690                 CHECK_TYPELOAD (klass);
6691                 type = mini_get_underlying_type (&klass->byval_arg);
6692                 emit_init_local (cfg, local, type, TRUE);
6693                 return ip + 6;
6694         }
6695  exception_exit:
6696         return NULL;
6697 }
6698
6699 static MonoInst*
6700 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6701 {
6702         MonoInst *icall_args [16];
6703         MonoInst *call_target, *ins, *vtable_ins;
6704         int arg_reg, this_reg, vtable_reg;
6705         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6706         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6707         gboolean variant_iface = FALSE;
6708         guint32 slot;
6709         int offset;
6710         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6711
6712         /*
6713          * In llvm-only mode, vtables contain function descriptors instead of
6714          * method addresses/trampolines.
6715          */
6716         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6717
6718         if (is_iface)
6719                 slot = mono_method_get_imt_slot (cmethod);
6720         else
6721                 slot = mono_method_get_vtable_index (cmethod);
6722
6723         this_reg = sp [0]->dreg;
6724
6725         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6726                 variant_iface = TRUE;
6727
6728         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6729                 /*
6730                  * The simplest case, a normal virtual call.
6731                  */
6732                 int slot_reg = alloc_preg (cfg);
6733                 int addr_reg = alloc_preg (cfg);
6734                 int arg_reg = alloc_preg (cfg);
6735                 MonoBasicBlock *non_null_bb;
6736
6737                 vtable_reg = alloc_preg (cfg);
6738                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6739                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6740
6741                 /* Load the vtable slot, which contains a function descriptor. */
6742                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6743
6744                 NEW_BBLOCK (cfg, non_null_bb);
6745
6746                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6747                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6748                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6749
6750                 /* Slow path */
6751                 // FIXME: Make the wrapper use the preserveall cconv
6752                 // FIXME: Use one icall per slot for small slot numbers ?
6753                 icall_args [0] = vtable_ins;
6754                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6755                 /* Make the icall return the vtable slot value to save some code space */
6756                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6757                 ins->dreg = slot_reg;
6758                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6759
6760                 /* Fastpath */
6761                 MONO_START_BB (cfg, non_null_bb);
6762                 /* Load the address + arg from the vtable slot */
6763                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6764                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
6765
6766                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6767         }
6768
6769         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
6770                 /*
6771                  * A simple interface call
6772                  *
6773                  * We make a call through an imt slot to obtain the function descriptor we need to call.
6774                  * The imt slot contains a function descriptor for a runtime function + arg.
6775                  */
6776                 int slot_reg = alloc_preg (cfg);
6777                 int addr_reg = alloc_preg (cfg);
6778                 int arg_reg = alloc_preg (cfg);
6779                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6780
6781                 vtable_reg = alloc_preg (cfg);
6782                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6783                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6784
6785                 /*
6786                  * The slot is already initialized when the vtable is created so there is no need
6787                  * to check it here.
6788                  */
6789
6790                 /* Load the imt slot, which contains a function descriptor. */
6791                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6792
6793                 /* Load the address + arg of the imt thunk from the imt slot */
6794                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6795                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6796                 /*
6797                  * IMT thunks in llvm-only mode are C functions which take an info argument
6798                  * plus the imt method and return the ftndesc to call.
6799                  */
6800                 icall_args [0] = thunk_arg_ins;
6801                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6802                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6803                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6804
6805                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6806         }
6807
6808         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
6809                 /*
6810                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
6811                  * dynamically extended as more instantiations are discovered.
6812                  * This handles generic virtual methods both on classes and interfaces.
6813                  */
6814                 int slot_reg = alloc_preg (cfg);
6815                 int addr_reg = alloc_preg (cfg);
6816                 int arg_reg = alloc_preg (cfg);
6817                 int ftndesc_reg = alloc_preg (cfg);
6818                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6819                 MonoBasicBlock *slowpath_bb, *end_bb;
6820
6821                 NEW_BBLOCK (cfg, slowpath_bb);
6822                 NEW_BBLOCK (cfg, end_bb);
6823
6824                 vtable_reg = alloc_preg (cfg);
6825                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6826                 if (is_iface)
6827                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6828                 else
6829                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6830
6831                 /* Load the slot, which contains a function descriptor. */
6832                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6833
6834                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
6835                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
6836                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6837                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6838
6839                 /* Fastpath */
6840                 /* Same as with iface calls */
6841                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6842                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6843                 icall_args [0] = thunk_arg_ins;
6844                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6845                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6846                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6847                 ftndesc_ins->dreg = ftndesc_reg;
6848                 /*
6849                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
6850                  * they don't know about yet. Fall back to the slowpath in that case.
6851                  */
6852                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
6853                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6854
6855                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6856
6857                 /* Slowpath */
6858                 MONO_START_BB (cfg, slowpath_bb);
6859                 icall_args [0] = vtable_ins;
6860                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6861                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6862                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6863                 if (is_iface)
6864                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
6865                 else
6866                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
6867                 ftndesc_ins->dreg = ftndesc_reg;
6868                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6869
6870                 /* Common case */
6871                 MONO_START_BB (cfg, end_bb);
6872                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6873         }
6874
6875         /*
6876          * Non-optimized cases
6877          */
6878         icall_args [0] = sp [0];
6879         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6880
6881         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6882                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
6883
6884         arg_reg = alloc_preg (cfg);
6885         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
6886         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
6887
6888         g_assert (is_gsharedvt);
6889         if (is_iface)
6890                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
6891         else
6892                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
6893
6894         /*
6895          * Pass the extra argument even if the callee doesn't receive it, most
6896          * calling conventions allow this.
6897          */
6898         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6899 }
6900
6901 static gboolean
6902 is_exception_class (MonoClass *klass)
6903 {
6904         while (klass) {
6905                 if (klass == mono_defaults.exception_class)
6906                         return TRUE;
6907                 klass = klass->parent;
6908         }
6909         return FALSE;
6910 }
6911
6912 /*
6913  * is_jit_optimizer_disabled:
6914  *
6915  *   Determine whenever M's assembly has a DebuggableAttribute with the
6916  * IsJITOptimizerDisabled flag set.
6917  */
6918 static gboolean
6919 is_jit_optimizer_disabled (MonoMethod *m)
6920 {
6921         MonoError error;
6922         MonoAssembly *ass = m->klass->image->assembly;
6923         MonoCustomAttrInfo* attrs;
6924         MonoClass *klass;
6925         int i;
6926         gboolean val = FALSE;
6927
6928         g_assert (ass);
6929         if (ass->jit_optimizer_disabled_inited)
6930                 return ass->jit_optimizer_disabled;
6931
6932         klass = mono_class_try_get_debuggable_attribute_class ();
6933
6934         if (!klass) {
6935                 /* Linked away */
6936                 ass->jit_optimizer_disabled = FALSE;
6937                 mono_memory_barrier ();
6938                 ass->jit_optimizer_disabled_inited = TRUE;
6939                 return FALSE;
6940         }
6941
6942         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
6943         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6944         if (attrs) {
6945                 for (i = 0; i < attrs->num_attrs; ++i) {
6946                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
6947                         const gchar *p;
6948                         MonoMethodSignature *sig;
6949
6950                         if (!attr->ctor || attr->ctor->klass != klass)
6951                                 continue;
6952                         /* Decode the attribute. See reflection.c */
6953                         p = (const char*)attr->data;
6954                         g_assert (read16 (p) == 0x0001);
6955                         p += 2;
6956
6957                         // FIXME: Support named parameters
6958                         sig = mono_method_signature (attr->ctor);
6959                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
6960                                 continue;
6961                         /* Two boolean arguments */
6962                         p ++;
6963                         val = *p;
6964                 }
6965                 mono_custom_attrs_free (attrs);
6966         }
6967
6968         ass->jit_optimizer_disabled = val;
6969         mono_memory_barrier ();
6970         ass->jit_optimizer_disabled_inited = TRUE;
6971
6972         return val;
6973 }
6974
6975 static gboolean
6976 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
6977 {
6978         gboolean supported_tail_call;
6979         int i;
6980
6981         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
6982
6983         for (i = 0; i < fsig->param_count; ++i) {
6984                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
6985                         /* These can point to the current method's stack */
6986                         supported_tail_call = FALSE;
6987         }
6988         if (fsig->hasthis && cmethod->klass->valuetype)
6989                 /* this might point to the current method's stack */
6990                 supported_tail_call = FALSE;
6991         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
6992                 supported_tail_call = FALSE;
6993         if (cfg->method->save_lmf)
6994                 supported_tail_call = FALSE;
6995         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
6996                 supported_tail_call = FALSE;
6997         if (call_opcode != CEE_CALL)
6998                 supported_tail_call = FALSE;
6999
7000         /* Debugging support */
7001 #if 0
7002         if (supported_tail_call) {
7003                 if (!mono_debug_count ())
7004                         supported_tail_call = FALSE;
7005         }
7006 #endif
7007
7008         return supported_tail_call;
7009 }
7010
7011 /*
7012  * handle_ctor_call:
7013  *
7014  *   Handle calls made to ctors from NEWOBJ opcodes.
7015  */
7016 static void
7017 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7018                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7019 {
7020         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7021
7022         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7023                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7024                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7025                         mono_class_vtable (cfg->domain, cmethod->klass);
7026                         CHECK_TYPELOAD (cmethod->klass);
7027
7028                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7029                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7030                 } else {
7031                         if (context_used) {
7032                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7033                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7034                         } else {
7035                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7036
7037                                 CHECK_TYPELOAD (cmethod->klass);
7038                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7039                         }
7040                 }
7041         }
7042
7043         /* Avoid virtual calls to ctors if possible */
7044         if (mono_class_is_marshalbyref (cmethod->klass))
7045                 callvirt_this_arg = sp [0];
7046
7047         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7048                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7049                 CHECK_CFG_EXCEPTION;
7050         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7051                            mono_method_check_inlining (cfg, cmethod) &&
7052                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7053                 int costs;
7054
7055                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7056                         cfg->real_offset += 5;
7057
7058                         *inline_costs += costs - 5;
7059                 } else {
7060                         INLINE_FAILURE ("inline failure");
7061                         // FIXME-VT: Clean this up
7062                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7063                                 GSHAREDVT_FAILURE(*ip);
7064                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7065                 }
7066         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7067                 MonoInst *addr;
7068
7069                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7070
7071                 if (cfg->llvm_only) {
7072                         // FIXME: Avoid initializing vtable_arg
7073                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7074                 } else {
7075                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7076                 }
7077         } else if (context_used &&
7078                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7079                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7080                 MonoInst *cmethod_addr;
7081
7082                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7083
7084                 if (cfg->llvm_only) {
7085                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7086                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7087                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7088                 } else {
7089                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7090                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7091
7092                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7093                 }
7094         } else {
7095                 INLINE_FAILURE ("ctor call");
7096                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7097                                                                                   callvirt_this_arg, NULL, vtable_arg);
7098         }
7099  exception_exit:
7100         return;
7101 }
7102
7103 static void
7104 emit_setret (MonoCompile *cfg, MonoInst *val)
7105 {
7106         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7107         MonoInst *ins;
7108
7109         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7110                 MonoInst *ret_addr;
7111
7112                 if (!cfg->vret_addr) {
7113                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7114                 } else {
7115                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7116
7117                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7118                         ins->klass = mono_class_from_mono_type (ret_type);
7119                 }
7120         } else {
7121 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7122                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7123                         MonoInst *iargs [1];
7124                         MonoInst *conv;
7125
7126                         iargs [0] = val;
7127                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7128                         mono_arch_emit_setret (cfg, cfg->method, conv);
7129                 } else {
7130                         mono_arch_emit_setret (cfg, cfg->method, val);
7131                 }
7132 #else
7133                 mono_arch_emit_setret (cfg, cfg->method, val);
7134 #endif
7135         }
7136 }
7137
7138 /*
7139  * mono_method_to_ir:
7140  *
7141  * Translate the .net IL into linear IR.
7142  *
7143  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7144  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7145  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7146  * @inline_args: if not NULL, contains the arguments to the inline call
7147  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7148  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7149  *
7150  * This method is used to turn ECMA IL into Mono's internal Linear IR
7151  * reprensetation.  It is used both for entire methods, as well as
7152  * inlining existing methods.  In the former case, the @start_bblock,
7153  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7154  * inline_offset is set to zero.
7155  * 
7156  * Returns: the inline cost, or -1 if there was an error processing this method.
7157  */
7158 int
7159 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7160                    MonoInst *return_var, MonoInst **inline_args, 
7161                    guint inline_offset, gboolean is_virtual_call)
7162 {
7163         MonoError error;
7164         MonoInst *ins, **sp, **stack_start;
7165         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7166         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7167         MonoMethod *cmethod, *method_definition;
7168         MonoInst **arg_array;
7169         MonoMethodHeader *header;
7170         MonoImage *image;
7171         guint32 token, ins_flag;
7172         MonoClass *klass;
7173         MonoClass *constrained_class = NULL;
7174         unsigned char *ip, *end, *target, *err_pos;
7175         MonoMethodSignature *sig;
7176         MonoGenericContext *generic_context = NULL;
7177         MonoGenericContainer *generic_container = NULL;
7178         MonoType **param_types;
7179         int i, n, start_new_bblock, dreg;
7180         int num_calls = 0, inline_costs = 0;
7181         int breakpoint_id = 0;
7182         guint num_args;
7183         GSList *class_inits = NULL;
7184         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7185         int context_used;
7186         gboolean init_locals, seq_points, skip_dead_blocks;
7187         gboolean sym_seq_points = FALSE;
7188         MonoDebugMethodInfo *minfo;
7189         MonoBitSet *seq_point_locs = NULL;
7190         MonoBitSet *seq_point_set_locs = NULL;
7191
7192         cfg->disable_inline = is_jit_optimizer_disabled (method);
7193
7194         /* serialization and xdomain stuff may need access to private fields and methods */
7195         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7196         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7197         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7198         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7199         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7200         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7201
7202         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7203         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7204         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7205         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7206         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7207
7208         image = method->klass->image;
7209         header = mono_method_get_header_checked (method, &cfg->error);
7210         if (!header) {
7211                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7212                 goto exception_exit;
7213         } else {
7214                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7215         }
7216
7217         generic_container = mono_method_get_generic_container (method);
7218         sig = mono_method_signature (method);
7219         num_args = sig->hasthis + sig->param_count;
7220         ip = (unsigned char*)header->code;
7221         cfg->cil_start = ip;
7222         end = ip + header->code_size;
7223         cfg->stat_cil_code_size += header->code_size;
7224
7225         seq_points = cfg->gen_seq_points && cfg->method == method;
7226
7227         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7228                 /* We could hit a seq point before attaching to the JIT (#8338) */
7229                 seq_points = FALSE;
7230         }
7231
7232         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7233                 minfo = mono_debug_lookup_method (method);
7234                 if (minfo) {
7235                         MonoSymSeqPoint *sps;
7236                         int i, n_il_offsets;
7237
7238                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7239                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7240                         seq_point_set_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7241                         sym_seq_points = TRUE;
7242                         for (i = 0; i < n_il_offsets; ++i) {
7243                                 if (sps [i].il_offset < header->code_size)
7244                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7245                         }
7246                         g_free (sps);
7247
7248                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7249                         if (asyncMethod) {
7250                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7251                                 {
7252                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7253                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7254                                 }
7255                                 mono_debug_free_method_async_debug_info (asyncMethod);
7256                         }
7257                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7258                         /* Methods without line number info like auto-generated property accessors */
7259                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7260                         seq_point_set_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7261                         sym_seq_points = TRUE;
7262                 }
7263         }
7264
7265         /* 
7266          * Methods without init_locals set could cause asserts in various passes
7267          * (#497220). To work around this, we emit dummy initialization opcodes
7268          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7269          * on some platforms.
7270          */
7271         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7272                 init_locals = header->init_locals;
7273         else
7274                 init_locals = TRUE;
7275
7276         method_definition = method;
7277         while (method_definition->is_inflated) {
7278                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7279                 method_definition = imethod->declaring;
7280         }
7281
7282         /* SkipVerification is not allowed if core-clr is enabled */
7283         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7284                 dont_verify = TRUE;
7285                 dont_verify_stloc = TRUE;
7286         }
7287
7288         if (sig->is_inflated)
7289                 generic_context = mono_method_get_context (method);
7290         else if (generic_container)
7291                 generic_context = &generic_container->context;
7292         cfg->generic_context = generic_context;
7293
7294         if (!cfg->gshared)
7295                 g_assert (!sig->has_type_parameters);
7296
7297         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7298                 g_assert (method->is_inflated);
7299                 g_assert (mono_method_get_context (method)->method_inst);
7300         }
7301         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7302                 g_assert (sig->generic_param_count);
7303
7304         if (cfg->method == method) {
7305                 cfg->real_offset = 0;
7306         } else {
7307                 cfg->real_offset = inline_offset;
7308         }
7309
7310         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7311         cfg->cil_offset_to_bb_len = header->code_size;
7312
7313         cfg->current_method = method;
7314
7315         if (cfg->verbose_level > 2)
7316                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7317
7318         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7319         if (sig->hasthis)
7320                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7321         for (n = 0; n < sig->param_count; ++n)
7322                 param_types [n + sig->hasthis] = sig->params [n];
7323         cfg->arg_types = param_types;
7324
7325         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7326         if (cfg->method == method) {
7327
7328                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7329                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7330
7331                 /* ENTRY BLOCK */
7332                 NEW_BBLOCK (cfg, start_bblock);
7333                 cfg->bb_entry = start_bblock;
7334                 start_bblock->cil_code = NULL;
7335                 start_bblock->cil_length = 0;
7336
7337                 /* EXIT BLOCK */
7338                 NEW_BBLOCK (cfg, end_bblock);
7339                 cfg->bb_exit = end_bblock;
7340                 end_bblock->cil_code = NULL;
7341                 end_bblock->cil_length = 0;
7342                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7343                 g_assert (cfg->num_bblocks == 2);
7344
7345                 arg_array = cfg->args;
7346
7347                 if (header->num_clauses) {
7348                         cfg->spvars = g_hash_table_new (NULL, NULL);
7349                         cfg->exvars = g_hash_table_new (NULL, NULL);
7350                 }
7351                 /* handle exception clauses */
7352                 for (i = 0; i < header->num_clauses; ++i) {
7353                         MonoBasicBlock *try_bb;
7354                         MonoExceptionClause *clause = &header->clauses [i];
7355                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7356
7357                         try_bb->real_offset = clause->try_offset;
7358                         try_bb->try_start = TRUE;
7359                         try_bb->region = ((i + 1) << 8) | clause->flags;
7360                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7361                         tblock->real_offset = clause->handler_offset;
7362                         tblock->flags |= BB_EXCEPTION_HANDLER;
7363
7364                         /*
7365                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7366                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7367                          */
7368                         if (COMPILE_LLVM (cfg))
7369                                 link_bblock (cfg, try_bb, tblock);
7370
7371                         if (*(ip + clause->handler_offset) == CEE_POP)
7372                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7373
7374                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7375                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7376                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7377                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7378                                 MONO_ADD_INS (tblock, ins);
7379
7380                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7381                                         /* finally clauses already have a seq point */
7382                                         /* seq points for filter clauses are emitted below */
7383                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7384                                         MONO_ADD_INS (tblock, ins);
7385                                 }
7386
7387                                 /* todo: is a fault block unsafe to optimize? */
7388                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7389                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7390                         }
7391
7392                         /*printf ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
7393                           while (p < end) {
7394                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7395                           }*/
7396                         /* catch and filter blocks get the exception object on the stack */
7397                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7398                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7399
7400                                 /* mostly like handle_stack_args (), but just sets the input args */
7401                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7402                                 tblock->in_scount = 1;
7403                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7404                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7405
7406                                 cfg->cbb = tblock;
7407
7408 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7409                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7410                                 if (!cfg->compile_llvm) {
7411                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7412                                         ins->dreg = tblock->in_stack [0]->dreg;
7413                                         MONO_ADD_INS (tblock, ins);
7414                                 }
7415 #else
7416                                 MonoInst *dummy_use;
7417
7418                                 /* 
7419                                  * Add a dummy use for the exvar so its liveness info will be
7420                                  * correct.
7421                                  */
7422                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7423 #endif
7424
7425                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7426                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7427                                         MONO_ADD_INS (tblock, ins);
7428                                 }
7429                                 
7430                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7431                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7432                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7433                                         tblock->real_offset = clause->data.filter_offset;
7434                                         tblock->in_scount = 1;
7435                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7436                                         /* The filter block shares the exvar with the handler block */
7437                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7438                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7439                                         MONO_ADD_INS (tblock, ins);
7440                                 }
7441                         }
7442
7443                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7444                                         clause->data.catch_class &&
7445                                         cfg->gshared &&
7446                                         mono_class_check_context_used (clause->data.catch_class)) {
7447                                 /*
7448                                  * In shared generic code with catch
7449                                  * clauses containing type variables
7450                                  * the exception handling code has to
7451                                  * be able to get to the rgctx.
7452                                  * Therefore we have to make sure that
7453                                  * the vtable/mrgctx argument (for
7454                                  * static or generic methods) or the
7455                                  * "this" argument (for non-static
7456                                  * methods) are live.
7457                                  */
7458                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7459                                                 mini_method_get_context (method)->method_inst ||
7460                                                 method->klass->valuetype) {
7461                                         mono_get_vtable_var (cfg);
7462                                 } else {
7463                                         MonoInst *dummy_use;
7464
7465                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7466                                 }
7467                         }
7468                 }
7469         } else {
7470                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7471                 cfg->cbb = start_bblock;
7472                 cfg->args = arg_array;
7473                 mono_save_args (cfg, sig, inline_args);
7474         }
7475
7476         /* FIRST CODE BLOCK */
7477         NEW_BBLOCK (cfg, tblock);
7478         tblock->cil_code = ip;
7479         cfg->cbb = tblock;
7480         cfg->ip = ip;
7481
7482         ADD_BBLOCK (cfg, tblock);
7483
7484         if (cfg->method == method) {
7485                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7486                 if (breakpoint_id) {
7487                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7488                         MONO_ADD_INS (cfg->cbb, ins);
7489                 }
7490         }
7491
7492         /* we use a separate basic block for the initialization code */
7493         NEW_BBLOCK (cfg, init_localsbb);
7494         if (cfg->method == method)
7495                 cfg->bb_init = init_localsbb;
7496         init_localsbb->real_offset = cfg->real_offset;
7497         start_bblock->next_bb = init_localsbb;
7498         init_localsbb->next_bb = cfg->cbb;
7499         link_bblock (cfg, start_bblock, init_localsbb);
7500         link_bblock (cfg, init_localsbb, cfg->cbb);
7501                 
7502         cfg->cbb = init_localsbb;
7503
7504         if (cfg->gsharedvt && cfg->method == method) {
7505                 MonoGSharedVtMethodInfo *info;
7506                 MonoInst *var, *locals_var;
7507                 int dreg;
7508
7509                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7510                 info->method = cfg->method;
7511                 info->count_entries = 16;
7512                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7513                 cfg->gsharedvt_info = info;
7514
7515                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7516                 /* prevent it from being register allocated */
7517                 //var->flags |= MONO_INST_VOLATILE;
7518                 cfg->gsharedvt_info_var = var;
7519
7520                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7521                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7522
7523                 /* Allocate locals */
7524                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7525                 /* prevent it from being register allocated */
7526                 //locals_var->flags |= MONO_INST_VOLATILE;
7527                 cfg->gsharedvt_locals_var = locals_var;
7528
7529                 dreg = alloc_ireg (cfg);
7530                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7531
7532                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7533                 ins->dreg = locals_var->dreg;
7534                 ins->sreg1 = dreg;
7535                 MONO_ADD_INS (cfg->cbb, ins);
7536                 cfg->gsharedvt_locals_var_ins = ins;
7537                 
7538                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7539                 /*
7540                 if (init_locals)
7541                         ins->flags |= MONO_INST_INIT;
7542                 */
7543         }
7544
7545         if (mono_security_core_clr_enabled ()) {
7546                 /* check if this is native code, e.g. an icall or a p/invoke */
7547                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7548                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7549                         if (wrapped) {
7550                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7551                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7552
7553                                 /* if this ia a native call then it can only be JITted from platform code */
7554                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7555                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7556                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7557                                                         mono_get_exception_method_access ();
7558                                                 emit_throw_exception (cfg, ex);
7559                                         }
7560                                 }
7561                         }
7562                 }
7563         }
7564
7565         CHECK_CFG_EXCEPTION;
7566
7567         if (header->code_size == 0)
7568                 UNVERIFIED;
7569
7570         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7571                 ip = err_pos;
7572                 UNVERIFIED;
7573         }
7574
7575         if (cfg->method == method)
7576                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7577
7578         for (n = 0; n < header->num_locals; ++n) {
7579                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7580                         UNVERIFIED;
7581         }
7582         class_inits = NULL;
7583
7584         /* We force the vtable variable here for all shared methods
7585            for the possibility that they might show up in a stack
7586            trace where their exact instantiation is needed. */
7587         if (cfg->gshared && method == cfg->method) {
7588                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7589                                 mini_method_get_context (method)->method_inst ||
7590                                 method->klass->valuetype) {
7591                         mono_get_vtable_var (cfg);
7592                 } else {
7593                         /* FIXME: Is there a better way to do this?
7594                            We need the variable live for the duration
7595                            of the whole method. */
7596                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7597                 }
7598         }
7599
7600         /* add a check for this != NULL to inlined methods */
7601         if (is_virtual_call) {
7602                 MonoInst *arg_ins;
7603
7604                 NEW_ARGLOAD (cfg, arg_ins, 0);
7605                 MONO_ADD_INS (cfg->cbb, arg_ins);
7606                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7607         }
7608
7609         skip_dead_blocks = !dont_verify;
7610         if (skip_dead_blocks) {
7611                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7612                 CHECK_CFG_ERROR;
7613                 g_assert (bb);
7614         }
7615
7616         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7617         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7618
7619         ins_flag = 0;
7620         start_new_bblock = 0;
7621         while (ip < end) {
7622                 if (cfg->method == method)
7623                         cfg->real_offset = ip - header->code;
7624                 else
7625                         cfg->real_offset = inline_offset;
7626                 cfg->ip = ip;
7627
7628                 context_used = 0;
7629
7630                 if (start_new_bblock) {
7631                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7632                         if (start_new_bblock == 2) {
7633                                 g_assert (ip == tblock->cil_code);
7634                         } else {
7635                                 GET_BBLOCK (cfg, tblock, ip);
7636                         }
7637                         cfg->cbb->next_bb = tblock;
7638                         cfg->cbb = tblock;
7639                         start_new_bblock = 0;
7640                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7641                                 if (cfg->verbose_level > 3)
7642                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7643                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7644                                 *sp++ = ins;
7645                         }
7646                         if (class_inits)
7647                                 g_slist_free (class_inits);
7648                         class_inits = NULL;
7649                 } else {
7650                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7651                                 link_bblock (cfg, cfg->cbb, tblock);
7652                                 if (sp != stack_start) {
7653                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7654                                         sp = stack_start;
7655                                         CHECK_UNVERIFIABLE (cfg);
7656                                 }
7657                                 cfg->cbb->next_bb = tblock;
7658                                 cfg->cbb = tblock;
7659                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7660                                         if (cfg->verbose_level > 3)
7661                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7662                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7663                                         *sp++ = ins;
7664                                 }
7665                                 g_slist_free (class_inits);
7666                                 class_inits = NULL;
7667                         }
7668                 }
7669
7670                 if (skip_dead_blocks) {
7671                         int ip_offset = ip - header->code;
7672
7673                         if (ip_offset == bb->end)
7674                                 bb = bb->next;
7675
7676                         if (bb->dead) {
7677                                 int op_size = mono_opcode_size (ip, end);
7678                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7679
7680                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7681
7682                                 if (ip_offset + op_size == bb->end) {
7683                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7684                                         MONO_ADD_INS (cfg->cbb, ins);
7685                                         start_new_bblock = 1;
7686                                 }
7687
7688                                 ip += op_size;
7689                                 continue;
7690                         }
7691                 }
7692                 /*
7693                  * Sequence points are points where the debugger can place a breakpoint.
7694                  * Currently, we generate these automatically at points where the IL
7695                  * stack is empty.
7696                  */
7697                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7698                         /*
7699                          * Make methods interruptable at the beginning, and at the targets of
7700                          * backward branches.
7701                          * Also, do this at the start of every bblock in methods with clauses too,
7702                          * to be able to handle instructions with inprecise control flow like
7703                          * throw/endfinally.
7704                          * Backward branches are handled at the end of method-to-ir ().
7705                          */
7706                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7707                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7708
7709                         /* Avoid sequence points on empty IL like .volatile */
7710                         // FIXME: Enable this
7711                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7712                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7713                         if ((sp != stack_start) && !sym_seq_point)
7714                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7715                         MONO_ADD_INS (cfg->cbb, ins);
7716
7717                         if (sym_seq_points)
7718                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7719                 }
7720
7721                 cfg->cbb->real_offset = cfg->real_offset;
7722
7723                 if ((cfg->method == method) && cfg->coverage_info) {
7724                         guint32 cil_offset = ip - header->code;
7725                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7726
7727                         /* TODO: Use an increment here */
7728 #if defined(TARGET_X86)
7729                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
7730                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
7731                         ins->inst_imm = 1;
7732                         MONO_ADD_INS (cfg->cbb, ins);
7733 #else
7734                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
7735                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7736 #endif
7737                 }
7738
7739                 if (cfg->verbose_level > 3)
7740                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7741
7742                 switch (*ip) {
7743                 case CEE_NOP:
7744                         if (seq_points && !sym_seq_points && sp != stack_start) {
7745                                 /*
7746                                  * The C# compiler uses these nops to notify the JIT that it should
7747                                  * insert seq points.
7748                                  */
7749                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7750                                 MONO_ADD_INS (cfg->cbb, ins);
7751                         }
7752                         if (cfg->keep_cil_nops)
7753                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7754                         else
7755                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7756                         ip++;
7757                         MONO_ADD_INS (cfg->cbb, ins);
7758                         break;
7759                 case CEE_BREAK:
7760                         if (mini_should_insert_breakpoint (cfg->method)) {
7761                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
7762                         } else {
7763                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7764                         }
7765                         ip++;
7766                         MONO_ADD_INS (cfg->cbb, ins);
7767                         break;
7768                 case CEE_LDARG_0:
7769                 case CEE_LDARG_1:
7770                 case CEE_LDARG_2:
7771                 case CEE_LDARG_3:
7772                         CHECK_STACK_OVF (1);
7773                         n = (*ip)-CEE_LDARG_0;
7774                         CHECK_ARG (n);
7775                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7776                         ip++;
7777                         *sp++ = ins;
7778                         break;
7779                 case CEE_LDLOC_0:
7780                 case CEE_LDLOC_1:
7781                 case CEE_LDLOC_2:
7782                 case CEE_LDLOC_3:
7783                         CHECK_STACK_OVF (1);
7784                         n = (*ip)-CEE_LDLOC_0;
7785                         CHECK_LOCAL (n);
7786                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7787                         ip++;
7788                         *sp++ = ins;
7789                         break;
7790                 case CEE_STLOC_0:
7791                 case CEE_STLOC_1:
7792                 case CEE_STLOC_2:
7793                 case CEE_STLOC_3: {
7794                         CHECK_STACK (1);
7795                         n = (*ip)-CEE_STLOC_0;
7796                         CHECK_LOCAL (n);
7797                         --sp;
7798                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
7799                                 UNVERIFIED;
7800                         emit_stloc_ir (cfg, sp, header, n);
7801                         ++ip;
7802                         inline_costs += 1;
7803                         break;
7804                         }
7805                 case CEE_LDARG_S:
7806                         CHECK_OPSIZE (2);
7807                         CHECK_STACK_OVF (1);
7808                         n = ip [1];
7809                         CHECK_ARG (n);
7810                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7811                         *sp++ = ins;
7812                         ip += 2;
7813                         break;
7814                 case CEE_LDARGA_S:
7815                         CHECK_OPSIZE (2);
7816                         CHECK_STACK_OVF (1);
7817                         n = ip [1];
7818                         CHECK_ARG (n);
7819                         NEW_ARGLOADA (cfg, ins, n);
7820                         MONO_ADD_INS (cfg->cbb, ins);
7821                         *sp++ = ins;
7822                         ip += 2;
7823                         break;
7824                 case CEE_STARG_S:
7825                         CHECK_OPSIZE (2);
7826                         CHECK_STACK (1);
7827                         --sp;
7828                         n = ip [1];
7829                         CHECK_ARG (n);
7830                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
7831                                 UNVERIFIED;
7832                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
7833                         ip += 2;
7834                         break;
7835                 case CEE_LDLOC_S:
7836                         CHECK_OPSIZE (2);
7837                         CHECK_STACK_OVF (1);
7838                         n = ip [1];
7839                         CHECK_LOCAL (n);
7840                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7841                         *sp++ = ins;
7842                         ip += 2;
7843                         break;
7844                 case CEE_LDLOCA_S: {
7845                         unsigned char *tmp_ip;
7846                         CHECK_OPSIZE (2);
7847                         CHECK_STACK_OVF (1);
7848                         CHECK_LOCAL (ip [1]);
7849
7850                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
7851                                 ip = tmp_ip;
7852                                 inline_costs += 1;
7853                                 break;
7854                         }
7855
7856                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
7857                         *sp++ = ins;
7858                         ip += 2;
7859                         break;
7860                 }
7861                 case CEE_STLOC_S:
7862                         CHECK_OPSIZE (2);
7863                         CHECK_STACK (1);
7864                         --sp;
7865                         CHECK_LOCAL (ip [1]);
7866                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
7867                                 UNVERIFIED;
7868                         emit_stloc_ir (cfg, sp, header, ip [1]);
7869                         ip += 2;
7870                         inline_costs += 1;
7871                         break;
7872                 case CEE_LDNULL:
7873                         CHECK_STACK_OVF (1);
7874                         EMIT_NEW_PCONST (cfg, ins, NULL);
7875                         ins->type = STACK_OBJ;
7876                         ++ip;
7877                         *sp++ = ins;
7878                         break;
7879                 case CEE_LDC_I4_M1:
7880                         CHECK_STACK_OVF (1);
7881                         EMIT_NEW_ICONST (cfg, ins, -1);
7882                         ++ip;
7883                         *sp++ = ins;
7884                         break;
7885                 case CEE_LDC_I4_0:
7886                 case CEE_LDC_I4_1:
7887                 case CEE_LDC_I4_2:
7888                 case CEE_LDC_I4_3:
7889                 case CEE_LDC_I4_4:
7890                 case CEE_LDC_I4_5:
7891                 case CEE_LDC_I4_6:
7892                 case CEE_LDC_I4_7:
7893                 case CEE_LDC_I4_8:
7894                         CHECK_STACK_OVF (1);
7895                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
7896                         ++ip;
7897                         *sp++ = ins;
7898                         break;
7899                 case CEE_LDC_I4_S:
7900                         CHECK_OPSIZE (2);
7901                         CHECK_STACK_OVF (1);
7902                         ++ip;
7903                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
7904                         ++ip;
7905                         *sp++ = ins;
7906                         break;
7907                 case CEE_LDC_I4:
7908                         CHECK_OPSIZE (5);
7909                         CHECK_STACK_OVF (1);
7910                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
7911                         ip += 5;
7912                         *sp++ = ins;
7913                         break;
7914                 case CEE_LDC_I8:
7915                         CHECK_OPSIZE (9);
7916                         CHECK_STACK_OVF (1);
7917                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
7918                         ins->type = STACK_I8;
7919                         ins->dreg = alloc_dreg (cfg, STACK_I8);
7920                         ++ip;
7921                         ins->inst_l = (gint64)read64 (ip);
7922                         MONO_ADD_INS (cfg->cbb, ins);
7923                         ip += 8;
7924                         *sp++ = ins;
7925                         break;
7926                 case CEE_LDC_R4: {
7927                         float *f;
7928                         gboolean use_aotconst = FALSE;
7929
7930 #ifdef TARGET_POWERPC
7931                         /* FIXME: Clean this up */
7932                         if (cfg->compile_aot)
7933                                 use_aotconst = TRUE;
7934 #endif
7935
7936                         /* FIXME: we should really allocate this only late in the compilation process */
7937                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
7938                         CHECK_OPSIZE (5);
7939                         CHECK_STACK_OVF (1);
7940
7941                         if (use_aotconst) {
7942                                 MonoInst *cons;
7943                                 int dreg;
7944
7945                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
7946
7947                                 dreg = alloc_freg (cfg);
7948                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
7949                                 ins->type = cfg->r4_stack_type;
7950                         } else {
7951                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
7952                                 ins->type = cfg->r4_stack_type;
7953                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
7954                                 ins->inst_p0 = f;
7955                                 MONO_ADD_INS (cfg->cbb, ins);
7956                         }
7957                         ++ip;
7958                         readr4 (ip, f);
7959                         ip += 4;
7960                         *sp++ = ins;                    
7961                         break;
7962                 }
7963                 case CEE_LDC_R8: {
7964                         double *d;
7965                         gboolean use_aotconst = FALSE;
7966
7967 #ifdef TARGET_POWERPC
7968                         /* FIXME: Clean this up */
7969                         if (cfg->compile_aot)
7970                                 use_aotconst = TRUE;
7971 #endif
7972
7973                         /* FIXME: we should really allocate this only late in the compilation process */
7974                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
7975                         CHECK_OPSIZE (9);
7976                         CHECK_STACK_OVF (1);
7977
7978                         if (use_aotconst) {
7979                                 MonoInst *cons;
7980                                 int dreg;
7981
7982                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
7983
7984                                 dreg = alloc_freg (cfg);
7985                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
7986                                 ins->type = STACK_R8;
7987                         } else {
7988                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7989                                 ins->type = STACK_R8;
7990                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
7991                                 ins->inst_p0 = d;
7992                                 MONO_ADD_INS (cfg->cbb, ins);
7993                         }
7994                         ++ip;
7995                         readr8 (ip, d);
7996                         ip += 8;
7997                         *sp++ = ins;
7998                         break;
7999                 }
8000                 case CEE_DUP: {
8001                         MonoInst *temp, *store;
8002                         CHECK_STACK (1);
8003                         CHECK_STACK_OVF (1);
8004                         sp--;
8005                         ins = *sp;
8006
8007                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8008                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8009
8010                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8011                         *sp++ = ins;
8012
8013                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8014                         *sp++ = ins;
8015
8016                         ++ip;
8017                         inline_costs += 2;
8018                         break;
8019                 }
8020                 case CEE_POP:
8021                         CHECK_STACK (1);
8022                         ip++;
8023                         --sp;
8024
8025 #ifdef TARGET_X86
8026                         if (sp [0]->type == STACK_R8)
8027                                 /* we need to pop the value from the x86 FP stack */
8028                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8029 #endif
8030                         break;
8031                 case CEE_JMP: {
8032                         MonoCallInst *call;
8033                         MonoMethodSignature *fsig;
8034                         int i, n;
8035
8036                         INLINE_FAILURE ("jmp");
8037                         GSHAREDVT_FAILURE (*ip);
8038
8039                         CHECK_OPSIZE (5);
8040                         if (stack_start != sp)
8041                                 UNVERIFIED;
8042                         token = read32 (ip + 1);
8043                         /* FIXME: check the signature matches */
8044                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8045                         CHECK_CFG_ERROR;
8046  
8047                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8048                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8049
8050                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8051
8052                         fsig = mono_method_signature (cmethod);
8053                         n = fsig->param_count + fsig->hasthis;
8054                         if (cfg->llvm_only) {
8055                                 MonoInst **args;
8056
8057                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8058                                 for (i = 0; i < n; ++i)
8059                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8060                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8061                                 /*
8062                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8063                                  * have to emit a normal return since llvm expects it.
8064                                  */
8065                                 if (cfg->ret)
8066                                         emit_setret (cfg, ins);
8067                                 MONO_INST_NEW (cfg, ins, OP_BR);
8068                                 ins->inst_target_bb = end_bblock;
8069                                 MONO_ADD_INS (cfg->cbb, ins);
8070                                 link_bblock (cfg, cfg->cbb, end_bblock);
8071                                 ip += 5;
8072                                 break;
8073                         } else if (cfg->backend->have_op_tail_call) {
8074                                 /* Handle tail calls similarly to calls */
8075                                 DISABLE_AOT (cfg);
8076
8077                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8078                                 call->method = cmethod;
8079                                 call->tail_call = TRUE;
8080                                 call->signature = mono_method_signature (cmethod);
8081                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8082                                 call->inst.inst_p0 = cmethod;
8083                                 for (i = 0; i < n; ++i)
8084                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8085
8086                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8087                                         call->vret_var = cfg->vret_addr;
8088
8089                                 mono_arch_emit_call (cfg, call);
8090                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8091                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8092                         } else {
8093                                 for (i = 0; i < num_args; ++i)
8094                                         /* Prevent arguments from being optimized away */
8095                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8096
8097                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8098                                 ins = (MonoInst*)call;
8099                                 ins->inst_p0 = cmethod;
8100                                 MONO_ADD_INS (cfg->cbb, ins);
8101                         }
8102
8103                         ip += 5;
8104                         start_new_bblock = 1;
8105                         break;
8106                 }
8107                 case CEE_CALLI: {
8108                         MonoInst *addr;
8109                         MonoMethodSignature *fsig;
8110
8111                         CHECK_OPSIZE (5);
8112                         token = read32 (ip + 1);
8113
8114                         ins = NULL;
8115
8116                         //GSHAREDVT_FAILURE (*ip);
8117                         cmethod = NULL;
8118                         CHECK_STACK (1);
8119                         --sp;
8120                         addr = *sp;
8121                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8122                         CHECK_CFG_ERROR;
8123
8124                         if (method->dynamic && fsig->pinvoke) {
8125                                 MonoInst *args [3];
8126
8127                                 /*
8128                                  * This is a call through a function pointer using a pinvoke
8129                                  * signature. Have to create a wrapper and call that instead.
8130                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8131                                  * instead based on the signature.
8132                                  */
8133                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8134                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8135                                 args [2] = addr;
8136                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8137                         }
8138
8139                         n = fsig->param_count + fsig->hasthis;
8140
8141                         CHECK_STACK (n);
8142
8143                         //g_assert (!virtual_ || fsig->hasthis);
8144
8145                         sp -= n;
8146
8147                         inline_costs += 10 * num_calls++;
8148
8149                         /*
8150                          * Making generic calls out of gsharedvt methods.
8151                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8152                          * patching gshared method addresses into a gsharedvt method.
8153                          */
8154                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8155                                 /*
8156                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8157                                  */
8158                                 MonoInst *callee = addr;
8159
8160                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8161                                         /* Not tested */
8162                                         GSHAREDVT_FAILURE (*ip);
8163
8164                                 if (cfg->llvm_only)
8165                                         // FIXME:
8166                                         GSHAREDVT_FAILURE (*ip);
8167
8168                                 addr = emit_get_rgctx_sig (cfg, context_used,
8169                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8170                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8171                                 goto calli_end;
8172                         }
8173
8174                         /* Prevent inlining of methods with indirect calls */
8175                         INLINE_FAILURE ("indirect call");
8176
8177                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8178                                 MonoJumpInfoType info_type;
8179                                 gpointer info_data;
8180
8181                                 /*
8182                                  * Instead of emitting an indirect call, emit a direct call
8183                                  * with the contents of the aotconst as the patch info.
8184                                  */
8185                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8186                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8187                                         info_data = addr->inst_p0;
8188                                 } else {
8189                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8190                                         info_data = addr->inst_right->inst_left;
8191                                 }
8192
8193                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8194                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8195                                         NULLIFY_INS (addr);
8196                                         goto calli_end;
8197                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8198                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8199                                         NULLIFY_INS (addr);
8200                                         goto calli_end;
8201                                 }
8202                         }
8203                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8204
8205                         calli_end:
8206
8207                         /* End of call, INS should contain the result of the call, if any */
8208
8209                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8210                                 g_assert (ins);
8211                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8212                         }
8213
8214                         CHECK_CFG_EXCEPTION;
8215
8216                         ip += 5;
8217                         ins_flag = 0;
8218                         constrained_class = NULL;
8219                         break;
8220                 }
8221                 case CEE_CALL:
8222                 case CEE_CALLVIRT: {
8223                         MonoInst *addr = NULL;
8224                         MonoMethodSignature *fsig = NULL;
8225                         int array_rank = 0;
8226                         int virtual_ = *ip == CEE_CALLVIRT;
8227                         gboolean pass_imt_from_rgctx = FALSE;
8228                         MonoInst *imt_arg = NULL;
8229                         MonoInst *keep_this_alive = NULL;
8230                         gboolean pass_vtable = FALSE;
8231                         gboolean pass_mrgctx = FALSE;
8232                         MonoInst *vtable_arg = NULL;
8233                         gboolean check_this = FALSE;
8234                         gboolean supported_tail_call = FALSE;
8235                         gboolean tail_call = FALSE;
8236                         gboolean need_seq_point = FALSE;
8237                         guint32 call_opcode = *ip;
8238                         gboolean emit_widen = TRUE;
8239                         gboolean push_res = TRUE;
8240                         gboolean skip_ret = FALSE;
8241                         gboolean delegate_invoke = FALSE;
8242                         gboolean direct_icall = FALSE;
8243                         gboolean constrained_partial_call = FALSE;
8244                         MonoMethod *cil_method;
8245
8246                         CHECK_OPSIZE (5);
8247                         token = read32 (ip + 1);
8248
8249                         ins = NULL;
8250
8251                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8252                         CHECK_CFG_ERROR;
8253
8254                         cil_method = cmethod;
8255                                 
8256                         if (constrained_class) {
8257                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8258                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8259                                                 g_assert (!cmethod->klass->valuetype);
8260                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8261                                                         constrained_partial_call = TRUE;
8262                                         }
8263                                 }
8264
8265                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8266                                         if (cfg->verbose_level > 2)
8267                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8268                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8269                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8270                                                   cfg->gshared)) {
8271                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8272                                                 CHECK_CFG_ERROR;
8273                                         }
8274                                 } else {
8275                                         if (cfg->verbose_level > 2)
8276                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8277
8278                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8279                                                 /* 
8280                                                  * This is needed since get_method_constrained can't find 
8281                                                  * the method in klass representing a type var.
8282                                                  * The type var is guaranteed to be a reference type in this
8283                                                  * case.
8284                                                  */
8285                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8286                                                         g_assert (!cmethod->klass->valuetype);
8287                                         } else {
8288                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8289                                                 CHECK_CFG_ERROR;
8290                                         }
8291                                 }
8292
8293                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8294                                         /* Use the corresponding method from the base type to avoid boxing */
8295                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8296                                         g_assert (base_type);
8297                                         constrained_class = mono_class_from_mono_type (base_type);
8298                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8299                                         g_assert (cmethod);
8300                                 }
8301                         }
8302                                         
8303                         if (!dont_verify && !cfg->skip_visibility) {
8304                                 MonoMethod *target_method = cil_method;
8305                                 if (method->is_inflated) {
8306                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8307                                         CHECK_CFG_ERROR;
8308                                 }
8309                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8310                                         !mono_method_can_access_method (method, cil_method))
8311                                         emit_method_access_failure (cfg, method, cil_method);
8312                         }
8313
8314                         if (mono_security_core_clr_enabled ())
8315                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8316
8317                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8318                                 /* MS.NET seems to silently convert this to a callvirt */
8319                                 virtual_ = 1;
8320
8321                         {
8322                                 /*
8323                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8324                                  * converts to a callvirt.
8325                                  *
8326                                  * tests/bug-515884.il is an example of this behavior
8327                                  */
8328                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8329                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8330                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8331                                         virtual_ = 1;
8332                         }
8333
8334                         if (!cmethod->klass->inited)
8335                                 if (!mono_class_init (cmethod->klass))
8336                                         TYPE_LOAD_ERROR (cmethod->klass);
8337
8338                         fsig = mono_method_signature (cmethod);
8339                         if (!fsig)
8340                                 LOAD_ERROR;
8341                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8342                                 mini_class_is_system_array (cmethod->klass)) {
8343                                 array_rank = cmethod->klass->rank;
8344                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8345                                 direct_icall = TRUE;
8346                         } else if (fsig->pinvoke) {
8347                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8348                                 fsig = mono_method_signature (wrapper);
8349                         } else if (constrained_class) {
8350                         } else {
8351                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8352                                 CHECK_CFG_ERROR;
8353                         }
8354
8355                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8356                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8357
8358                         /* See code below */
8359                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8360                                 MonoBasicBlock *tbb;
8361
8362                                 GET_BBLOCK (cfg, tbb, ip + 5);
8363                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8364                                         /*
8365                                          * We want to extend the try block to cover the call, but we can't do it if the
8366                                          * call is made directly since its followed by an exception check.
8367                                          */
8368                                         direct_icall = FALSE;
8369                                 }
8370                         }
8371
8372                         mono_save_token_info (cfg, image, token, cil_method);
8373
8374                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8375                                 need_seq_point = TRUE;
8376
8377                         /* Don't support calls made using type arguments for now */
8378                         /*
8379                           if (cfg->gsharedvt) {
8380                           if (mini_is_gsharedvt_signature (fsig))
8381                           GSHAREDVT_FAILURE (*ip);
8382                           }
8383                         */
8384
8385                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8386                                 g_assert_not_reached ();
8387
8388                         n = fsig->param_count + fsig->hasthis;
8389
8390                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8391                                 UNVERIFIED;
8392
8393                         if (!cfg->gshared)
8394                                 g_assert (!mono_method_check_context_used (cmethod));
8395
8396                         CHECK_STACK (n);
8397
8398                         //g_assert (!virtual_ || fsig->hasthis);
8399
8400                         sp -= n;
8401
8402                         if (cmethod && cmethod->klass->image == mono_defaults.corlib && !strcmp (cmethod->klass->name, "ThrowHelper"))
8403                                 cfg->cbb->out_of_line = TRUE;
8404
8405                         /*
8406                          * We have the `constrained.' prefix opcode.
8407                          */
8408                         if (constrained_class) {
8409                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8410                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8411                                                 /* The 'Own method' case below */
8412                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8413                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8414                                         } else {
8415                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8416                                                 CHECK_CFG_EXCEPTION;
8417                                                 g_assert (ins);
8418                                                 goto call_end;
8419                                         }
8420                                 }
8421
8422                                 if (constrained_partial_call) {
8423                                         gboolean need_box = TRUE;
8424
8425                                         /*
8426                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8427                                          * called method is not known at compile time either. The called method could end up being
8428                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8429                                          * to box the receiver.
8430                                          * A simple solution would be to box always and make a normal virtual call, but that would
8431                                          * be bad performance wise.
8432                                          */
8433                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8434                                                 /*
8435                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8436                                                  */
8437                                                 need_box = FALSE;
8438                                         }
8439
8440                                         if (!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8441                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8442                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8443                                                 ins->klass = constrained_class;
8444                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8445                                                 CHECK_CFG_EXCEPTION;
8446                                         } else if (need_box) {
8447                                                 MonoInst *box_type;
8448                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8449                                                 MonoInst *nonbox_call;
8450
8451                                                 /*
8452                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8453                                                  * if needed.
8454                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8455                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8456                                                  */
8457                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8458
8459                                                 NEW_BBLOCK (cfg, is_ref_bb);
8460                                                 NEW_BBLOCK (cfg, end_bb);
8461
8462                                                 box_type = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_BOX_TYPE);
8463                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8464                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8465
8466                                                 /* Non-ref case */
8467                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8468
8469                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8470
8471                                                 /* Ref case */
8472                                                 MONO_START_BB (cfg, is_ref_bb);
8473                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8474                                                 ins->klass = constrained_class;
8475                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8476                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8477
8478                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8479
8480                                                 MONO_START_BB (cfg, end_bb);
8481                                                 cfg->cbb = end_bb;
8482
8483                                                 nonbox_call->dreg = ins->dreg;
8484                                                 goto call_end;
8485                                         } else {
8486                                                 g_assert (mono_class_is_interface (cmethod->klass));
8487                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8488                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8489                                                 goto call_end;
8490                                         }
8491                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8492                                         /*
8493                                          * The type parameter is instantiated as a valuetype,
8494                                          * but that type doesn't override the method we're
8495                                          * calling, so we need to box `this'.
8496                                          */
8497                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8498                                         ins->klass = constrained_class;
8499                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8500                                         CHECK_CFG_EXCEPTION;
8501                                 } else if (!constrained_class->valuetype) {
8502                                         int dreg = alloc_ireg_ref (cfg);
8503
8504                                         /*
8505                                          * The type parameter is instantiated as a reference
8506                                          * type.  We have a managed pointer on the stack, so
8507                                          * we need to dereference it here.
8508                                          */
8509                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8510                                         ins->type = STACK_OBJ;
8511                                         sp [0] = ins;
8512                                 } else {
8513                                         if (cmethod->klass->valuetype) {
8514                                                 /* Own method */
8515                                         } else {
8516                                                 /* Interface method */
8517                                                 int ioffset, slot;
8518
8519                                                 mono_class_setup_vtable (constrained_class);
8520                                                 CHECK_TYPELOAD (constrained_class);
8521                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8522                                                 if (ioffset == -1)
8523                                                         TYPE_LOAD_ERROR (constrained_class);
8524                                                 slot = mono_method_get_vtable_slot (cmethod);
8525                                                 if (slot == -1)
8526                                                         TYPE_LOAD_ERROR (cmethod->klass);
8527                                                 cmethod = constrained_class->vtable [ioffset + slot];
8528
8529                                                 if (cmethod->klass == mono_defaults.enum_class) {
8530                                                         /* Enum implements some interfaces, so treat this as the first case */
8531                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8532                                                         ins->klass = constrained_class;
8533                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8534                                                         CHECK_CFG_EXCEPTION;
8535                                                 }
8536                                         }
8537                                         virtual_ = 0;
8538                                 }
8539                                 constrained_class = NULL;
8540                         }
8541
8542                         if (check_call_signature (cfg, fsig, sp))
8543                                 UNVERIFIED;
8544
8545                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8546                                 delegate_invoke = TRUE;
8547
8548                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8549                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8550                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8551                                         emit_widen = FALSE;
8552                                 }
8553
8554                                 goto call_end;
8555                         }
8556
8557                         /* 
8558                          * If the callee is a shared method, then its static cctor
8559                          * might not get called after the call was patched.
8560                          */
8561                         if (cfg->gshared && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
8562                                 emit_class_init (cfg, cmethod->klass);
8563                                 CHECK_TYPELOAD (cmethod->klass);
8564                         }
8565
8566                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8567
8568                         if (cfg->gshared) {
8569                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8570
8571                                 context_used = mini_method_check_context_used (cfg, cmethod);
8572
8573                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8574                                         /* Generic method interface
8575                                            calls are resolved via a
8576                                            helper function and don't
8577                                            need an imt. */
8578                                         if (!cmethod_context || !cmethod_context->method_inst)
8579                                                 pass_imt_from_rgctx = TRUE;
8580                                 }
8581
8582                                 /*
8583                                  * If a shared method calls another
8584                                  * shared method then the caller must
8585                                  * have a generic sharing context
8586                                  * because the magic trampoline
8587                                  * requires it.  FIXME: We shouldn't
8588                                  * have to force the vtable/mrgctx
8589                                  * variable here.  Instead there
8590                                  * should be a flag in the cfg to
8591                                  * request a generic sharing context.
8592                                  */
8593                                 if (context_used &&
8594                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8595                                         mono_get_vtable_var (cfg);
8596                         }
8597
8598                         if (pass_vtable) {
8599                                 if (context_used) {
8600                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8601                                 } else {
8602                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8603
8604                                         CHECK_TYPELOAD (cmethod->klass);
8605                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8606                                 }
8607                         }
8608
8609                         if (pass_mrgctx) {
8610                                 g_assert (!vtable_arg);
8611
8612                                 if (!cfg->compile_aot) {
8613                                         /* 
8614                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8615                                          * for type load errors before.
8616                                          */
8617                                         mono_class_setup_vtable (cmethod->klass);
8618                                         CHECK_TYPELOAD (cmethod->klass);
8619                                 }
8620
8621                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8622
8623                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8624                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8625                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8626                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8627                                         if (virtual_)
8628                                                 check_this = TRUE;
8629                                         virtual_ = 0;
8630                                 }
8631                         }
8632
8633                         if (pass_imt_from_rgctx) {
8634                                 g_assert (!pass_vtable);
8635
8636                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8637                                         cmethod, MONO_RGCTX_INFO_METHOD);
8638                         }
8639
8640                         if (check_this)
8641                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8642
8643                         /* Calling virtual generic methods */
8644                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8645                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8646                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8647                             fsig->generic_param_count && 
8648                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8649                                 !cfg->llvm_only) {
8650                                 MonoInst *this_temp, *this_arg_temp, *store;
8651                                 MonoInst *iargs [4];
8652
8653                                 g_assert (fsig->is_inflated);
8654
8655                                 /* Prevent inlining of methods that contain indirect calls */
8656                                 INLINE_FAILURE ("virtual generic call");
8657
8658                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8659                                         GSHAREDVT_FAILURE (*ip);
8660
8661                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8662                                         g_assert (!imt_arg);
8663                                         if (!context_used)
8664                                                 g_assert (cmethod->is_inflated);
8665                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8666                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8667                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8668                                 } else {
8669                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8670                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8671                                         MONO_ADD_INS (cfg->cbb, store);
8672
8673                                         /* FIXME: This should be a managed pointer */
8674                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8675
8676                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8677                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8678                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8679                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8680                                         addr = mono_emit_jit_icall (cfg,
8681                                                                                                 mono_helper_compile_generic_method, iargs);
8682
8683                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8684
8685                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8686                                 }
8687
8688                                 goto call_end;
8689                         }
8690
8691                         /*
8692                          * Implement a workaround for the inherent races involved in locking:
8693                          * Monitor.Enter ()
8694                          * try {
8695                          * } finally {
8696                          *    Monitor.Exit ()
8697                          * }
8698                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8699                          * try block, the Exit () won't be executed, see:
8700                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8701                          * To work around this, we extend such try blocks to include the last x bytes
8702                          * of the Monitor.Enter () call.
8703                          */
8704                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8705                                 MonoBasicBlock *tbb;
8706
8707                                 GET_BBLOCK (cfg, tbb, ip + 5);
8708                                 /* 
8709                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8710                                  * from Monitor.Enter like ArgumentNullException.
8711                                  */
8712                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8713                                         /* Mark this bblock as needing to be extended */
8714                                         tbb->extend_try_block = TRUE;
8715                                 }
8716                         }
8717
8718                         /* Conversion to a JIT intrinsic */
8719                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8720                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8721                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8722                                         emit_widen = FALSE;
8723                                 }
8724                                 goto call_end;
8725                         }
8726                         CHECK_CFG_ERROR;
8727                         
8728                         /* Inlining */
8729                         if ((cfg->opt & MONO_OPT_INLINE) &&
8730                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8731                             mono_method_check_inlining (cfg, cmethod)) {
8732                                 int costs;
8733                                 gboolean always = FALSE;
8734
8735                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8736                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8737                                         /* Prevent inlining of methods that call wrappers */
8738                                         INLINE_FAILURE ("wrapper call");
8739                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8740                                         always = TRUE;
8741                                 }
8742
8743                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8744                                 if (costs) {
8745                                         cfg->real_offset += 5;
8746
8747                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8748                                                 /* *sp is already set by inline_method */
8749                                                 sp++;
8750                                                 push_res = FALSE;
8751                                         }
8752
8753                                         inline_costs += costs;
8754
8755                                         goto call_end;
8756                                 }
8757                         }
8758
8759                         /* Tail recursion elimination */
8760                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
8761                                 gboolean has_vtargs = FALSE;
8762                                 int i;
8763
8764                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8765                                 INLINE_FAILURE ("tail call");
8766
8767                                 /* keep it simple */
8768                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
8769                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
8770                                                 has_vtargs = TRUE;
8771                                 }
8772
8773                                 if (!has_vtargs) {
8774                                         if (need_seq_point) {
8775                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
8776                                                 need_seq_point = FALSE;
8777                                         }
8778                                         for (i = 0; i < n; ++i)
8779                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8780                                         MONO_INST_NEW (cfg, ins, OP_BR);
8781                                         MONO_ADD_INS (cfg->cbb, ins);
8782                                         tblock = start_bblock->out_bb [0];
8783                                         link_bblock (cfg, cfg->cbb, tblock);
8784                                         ins->inst_target_bb = tblock;
8785                                         start_new_bblock = 1;
8786
8787                                         /* skip the CEE_RET, too */
8788                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
8789                                                 skip_ret = TRUE;
8790                                         push_res = FALSE;
8791                                         goto call_end;
8792                                 }
8793                         }
8794
8795                         inline_costs += 10 * num_calls++;
8796
8797                         /*
8798                          * Synchronized wrappers.
8799                          * Its hard to determine where to replace a method with its synchronized
8800                          * wrapper without causing an infinite recursion. The current solution is
8801                          * to add the synchronized wrapper in the trampolines, and to
8802                          * change the called method to a dummy wrapper, and resolve that wrapper
8803                          * to the real method in mono_jit_compile_method ().
8804                          */
8805                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
8806                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
8807                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
8808                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
8809                         }
8810
8811                         /*
8812                          * Making generic calls out of gsharedvt methods.
8813                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8814                          * patching gshared method addresses into a gsharedvt method.
8815                          */
8816                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
8817                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
8818                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
8819                                 MonoRgctxInfoType info_type;
8820
8821                                 if (virtual_) {
8822                                         //if (mono_class_is_interface (cmethod->klass))
8823                                                 //GSHAREDVT_FAILURE (*ip);
8824                                         // disable for possible remoting calls
8825                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
8826                                                 GSHAREDVT_FAILURE (*ip);
8827                                         if (fsig->generic_param_count) {
8828                                                 /* virtual generic call */
8829                                                 g_assert (!imt_arg);
8830                                                 /* Same as the virtual generic case above */
8831                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8832                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8833                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
8834                                                 vtable_arg = NULL;
8835                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
8836                                                 /* This can happen when we call a fully instantiated iface method */
8837                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8838                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8839                                                 vtable_arg = NULL;
8840                                         }
8841                                 }
8842
8843                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
8844                                         keep_this_alive = sp [0];
8845
8846                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
8847                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
8848                                 else
8849                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
8850                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
8851
8852                                 if (cfg->llvm_only) {
8853                                         // FIXME: Avoid initializing vtable_arg
8854                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8855                                 } else {
8856                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8857                                 }
8858                                 goto call_end;
8859                         }
8860
8861                         /* Generic sharing */
8862
8863                         /*
8864                          * Use this if the callee is gsharedvt sharable too, since
8865                          * at runtime we might find an instantiation so the call cannot
8866                          * be patched (the 'no_patch' code path in mini-trampolines.c).
8867                          */
8868                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
8869                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8870                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
8871                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
8872                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
8873                                 INLINE_FAILURE ("gshared");
8874
8875                                 g_assert (cfg->gshared && cmethod);
8876                                 g_assert (!addr);
8877
8878                                 /*
8879                                  * We are compiling a call to a
8880                                  * generic method from shared code,
8881                                  * which means that we have to look up
8882                                  * the method in the rgctx and do an
8883                                  * indirect call.
8884                                  */
8885                                 if (fsig->hasthis)
8886                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8887
8888                                 if (cfg->llvm_only) {
8889                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
8890                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
8891                                         else
8892                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8893                                         // FIXME: Avoid initializing imt_arg/vtable_arg
8894                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8895                                 } else {
8896                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8897                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8898                                 }
8899                                 goto call_end;
8900                         }
8901
8902                         /* Direct calls to icalls */
8903                         if (direct_icall) {
8904                                 MonoMethod *wrapper;
8905                                 int costs;
8906
8907                                 /* Inline the wrapper */
8908                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8909
8910                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
8911                                 g_assert (costs > 0);
8912                                 cfg->real_offset += 5;
8913
8914                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8915                                         /* *sp is already set by inline_method */
8916                                         sp++;
8917                                         push_res = FALSE;
8918                                 }
8919
8920                                 inline_costs += costs;
8921
8922                                 goto call_end;
8923                         }
8924                                         
8925                         /* Array methods */
8926                         if (array_rank) {
8927                                 MonoInst *addr;
8928
8929                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
8930                                         MonoInst *val = sp [fsig->param_count];
8931
8932                                         if (val->type == STACK_OBJ) {
8933                                                 MonoInst *iargs [2];
8934
8935                                                 iargs [0] = sp [0];
8936                                                 iargs [1] = val;
8937                                                 
8938                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
8939                                         }
8940                                         
8941                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
8942                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
8943                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
8944                                                 mini_emit_write_barrier (cfg, addr, val);
8945                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
8946                                                 GSHAREDVT_FAILURE (*ip);
8947                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
8948                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8949
8950                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
8951                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
8952                                         if (!cmethod->klass->element_class->valuetype && !readonly)
8953                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
8954                                         CHECK_TYPELOAD (cmethod->klass);
8955                                         
8956                                         readonly = FALSE;
8957                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8958                                         ins = addr;
8959                                 } else {
8960                                         g_assert_not_reached ();
8961                                 }
8962
8963                                 emit_widen = FALSE;
8964                                 goto call_end;
8965                         }
8966
8967                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
8968                         if (ins)
8969                                 goto call_end;
8970
8971                         /* Tail prefix / tail call optimization */
8972
8973                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
8974                         /* FIXME: runtime generic context pointer for jumps? */
8975                         /* FIXME: handle this for generic sharing eventually */
8976                         if ((ins_flag & MONO_INST_TAILCALL) &&
8977                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
8978                                 supported_tail_call = TRUE;
8979
8980                         if (supported_tail_call) {
8981                                 MonoCallInst *call;
8982
8983                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8984                                 INLINE_FAILURE ("tail call");
8985
8986                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
8987
8988                                 if (cfg->backend->have_op_tail_call) {
8989                                         /* Handle tail calls similarly to normal calls */
8990                                         tail_call = TRUE;
8991                                 } else {
8992                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8993
8994                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8995                                         call->tail_call = TRUE;
8996                                         call->method = cmethod;
8997                                         call->signature = mono_method_signature (cmethod);
8998
8999                                         /*
9000                                          * We implement tail calls by storing the actual arguments into the 
9001                                          * argument variables, then emitting a CEE_JMP.
9002                                          */
9003                                         for (i = 0; i < n; ++i) {
9004                                                 /* Prevent argument from being register allocated */
9005                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9006                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9007                                         }
9008                                         ins = (MonoInst*)call;
9009                                         ins->inst_p0 = cmethod;
9010                                         ins->inst_p1 = arg_array [0];
9011                                         MONO_ADD_INS (cfg->cbb, ins);
9012                                         link_bblock (cfg, cfg->cbb, end_bblock);
9013                                         start_new_bblock = 1;
9014
9015                                         // FIXME: Eliminate unreachable epilogs
9016
9017                                         /*
9018                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9019                                          * only reachable from this call.
9020                                          */
9021                                         GET_BBLOCK (cfg, tblock, ip + 5);
9022                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9023                                                 skip_ret = TRUE;
9024                                         push_res = FALSE;
9025
9026                                         goto call_end;
9027                                 }
9028                         }
9029
9030                         /*
9031                          * Virtual calls in llvm-only mode.
9032                          */
9033                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9034                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9035                                 goto call_end;
9036                         }
9037
9038                         /* Common call */
9039                         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) && !(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9040                                 INLINE_FAILURE ("call");
9041                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9042                                                                                           imt_arg, vtable_arg);
9043
9044                         if (tail_call && !cfg->llvm_only) {
9045                                 link_bblock (cfg, cfg->cbb, end_bblock);
9046                                 start_new_bblock = 1;
9047
9048                                 // FIXME: Eliminate unreachable epilogs
9049
9050                                 /*
9051                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9052                                  * only reachable from this call.
9053                                  */
9054                                 GET_BBLOCK (cfg, tblock, ip + 5);
9055                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9056                                         skip_ret = TRUE;
9057                                 push_res = FALSE;
9058                         }
9059
9060                         call_end:
9061
9062                         /* End of call, INS should contain the result of the call, if any */
9063
9064                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9065                                 g_assert (ins);
9066                                 if (emit_widen)
9067                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9068                                 else
9069                                         *sp++ = ins;
9070                         }
9071
9072                         if (keep_this_alive) {
9073                                 MonoInst *dummy_use;
9074
9075                                 /* See mono_emit_method_call_full () */
9076                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9077                         }
9078
9079                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9080                                 /*
9081                                  * Clang can convert these calls to tail calls which screw up the stack
9082                                  * walk. This happens even when the -fno-optimize-sibling-calls
9083                                  * option is passed to clang.
9084                                  * Work around this by emitting a dummy call.
9085                                  */
9086                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9087                         }
9088
9089                         CHECK_CFG_EXCEPTION;
9090
9091                         ip += 5;
9092                         if (skip_ret) {
9093                                 g_assert (*ip == CEE_RET);
9094                                 ip += 1;
9095                         }
9096                         ins_flag = 0;
9097                         constrained_class = NULL;
9098                         if (need_seq_point)
9099                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9100                         break;
9101                 }
9102                 case CEE_RET:
9103                         if (cfg->method != method) {
9104                                 /* return from inlined method */
9105                                 /* 
9106                                  * If in_count == 0, that means the ret is unreachable due to
9107                                  * being preceeded by a throw. In that case, inline_method () will
9108                                  * handle setting the return value 
9109                                  * (test case: test_0_inline_throw ()).
9110                                  */
9111                                 if (return_var && cfg->cbb->in_count) {
9112                                         MonoType *ret_type = mono_method_signature (method)->ret;
9113
9114                                         MonoInst *store;
9115                                         CHECK_STACK (1);
9116                                         --sp;
9117
9118                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9119                                                 UNVERIFIED;
9120
9121                                         //g_assert (returnvar != -1);
9122                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9123                                         cfg->ret_var_set = TRUE;
9124                                 } 
9125                         } else {
9126                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9127
9128                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9129                                         emit_pop_lmf (cfg);
9130
9131                                 if (cfg->ret) {
9132                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9133
9134                                         if (seq_points && !sym_seq_points) {
9135                                                 /* 
9136                                                  * Place a seq point here too even through the IL stack is not
9137                                                  * empty, so a step over on
9138                                                  * call <FOO>
9139                                                  * ret
9140                                                  * will work correctly.
9141                                                  */
9142                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9143                                                 MONO_ADD_INS (cfg->cbb, ins);
9144                                         }
9145
9146                                         g_assert (!return_var);
9147                                         CHECK_STACK (1);
9148                                         --sp;
9149
9150                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9151                                                 UNVERIFIED;
9152
9153                                         emit_setret (cfg, *sp);
9154                                 }
9155                         }
9156                         if (sp != stack_start)
9157                                 UNVERIFIED;
9158                         MONO_INST_NEW (cfg, ins, OP_BR);
9159                         ip++;
9160                         ins->inst_target_bb = end_bblock;
9161                         MONO_ADD_INS (cfg->cbb, ins);
9162                         link_bblock (cfg, cfg->cbb, end_bblock);
9163                         start_new_bblock = 1;
9164                         break;
9165                 case CEE_BR_S:
9166                         CHECK_OPSIZE (2);
9167                         MONO_INST_NEW (cfg, ins, OP_BR);
9168                         ip++;
9169                         target = ip + 1 + (signed char)(*ip);
9170                         ++ip;
9171                         GET_BBLOCK (cfg, tblock, target);
9172                         link_bblock (cfg, cfg->cbb, tblock);
9173                         ins->inst_target_bb = tblock;
9174                         if (sp != stack_start) {
9175                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9176                                 sp = stack_start;
9177                                 CHECK_UNVERIFIABLE (cfg);
9178                         }
9179                         MONO_ADD_INS (cfg->cbb, ins);
9180                         start_new_bblock = 1;
9181                         inline_costs += BRANCH_COST;
9182                         break;
9183                 case CEE_BEQ_S:
9184                 case CEE_BGE_S:
9185                 case CEE_BGT_S:
9186                 case CEE_BLE_S:
9187                 case CEE_BLT_S:
9188                 case CEE_BNE_UN_S:
9189                 case CEE_BGE_UN_S:
9190                 case CEE_BGT_UN_S:
9191                 case CEE_BLE_UN_S:
9192                 case CEE_BLT_UN_S:
9193                         CHECK_OPSIZE (2);
9194                         CHECK_STACK (2);
9195                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9196                         ip++;
9197                         target = ip + 1 + *(signed char*)ip;
9198                         ip++;
9199
9200                         ADD_BINCOND (NULL);
9201
9202                         sp = stack_start;
9203                         inline_costs += BRANCH_COST;
9204                         break;
9205                 case CEE_BR:
9206                         CHECK_OPSIZE (5);
9207                         MONO_INST_NEW (cfg, ins, OP_BR);
9208                         ip++;
9209
9210                         target = ip + 4 + (gint32)read32(ip);
9211                         ip += 4;
9212                         GET_BBLOCK (cfg, tblock, target);
9213                         link_bblock (cfg, cfg->cbb, tblock);
9214                         ins->inst_target_bb = tblock;
9215                         if (sp != stack_start) {
9216                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9217                                 sp = stack_start;
9218                                 CHECK_UNVERIFIABLE (cfg);
9219                         }
9220
9221                         MONO_ADD_INS (cfg->cbb, ins);
9222
9223                         start_new_bblock = 1;
9224                         inline_costs += BRANCH_COST;
9225                         break;
9226                 case CEE_BRFALSE_S:
9227                 case CEE_BRTRUE_S:
9228                 case CEE_BRFALSE:
9229                 case CEE_BRTRUE: {
9230                         MonoInst *cmp;
9231                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9232                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9233                         guint32 opsize = is_short ? 1 : 4;
9234
9235                         CHECK_OPSIZE (opsize);
9236                         CHECK_STACK (1);
9237                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9238                                 UNVERIFIED;
9239                         ip ++;
9240                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9241                         ip += opsize;
9242
9243                         sp--;
9244
9245                         GET_BBLOCK (cfg, tblock, target);
9246                         link_bblock (cfg, cfg->cbb, tblock);
9247                         GET_BBLOCK (cfg, tblock, ip);
9248                         link_bblock (cfg, cfg->cbb, tblock);
9249
9250                         if (sp != stack_start) {
9251                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9252                                 CHECK_UNVERIFIABLE (cfg);
9253                         }
9254
9255                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9256                         cmp->sreg1 = sp [0]->dreg;
9257                         type_from_op (cfg, cmp, sp [0], NULL);
9258                         CHECK_TYPE (cmp);
9259
9260 #if SIZEOF_REGISTER == 4
9261                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9262                                 /* Convert it to OP_LCOMPARE */
9263                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9264                                 ins->type = STACK_I8;
9265                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9266                                 ins->inst_l = 0;
9267                                 MONO_ADD_INS (cfg->cbb, ins);
9268                                 cmp->opcode = OP_LCOMPARE;
9269                                 cmp->sreg2 = ins->dreg;
9270                         }
9271 #endif
9272                         MONO_ADD_INS (cfg->cbb, cmp);
9273
9274                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9275                         type_from_op (cfg, ins, sp [0], NULL);
9276                         MONO_ADD_INS (cfg->cbb, ins);
9277                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9278                         GET_BBLOCK (cfg, tblock, target);
9279                         ins->inst_true_bb = tblock;
9280                         GET_BBLOCK (cfg, tblock, ip);
9281                         ins->inst_false_bb = tblock;
9282                         start_new_bblock = 2;
9283
9284                         sp = stack_start;
9285                         inline_costs += BRANCH_COST;
9286                         break;
9287                 }
9288                 case CEE_BEQ:
9289                 case CEE_BGE:
9290                 case CEE_BGT:
9291                 case CEE_BLE:
9292                 case CEE_BLT:
9293                 case CEE_BNE_UN:
9294                 case CEE_BGE_UN:
9295                 case CEE_BGT_UN:
9296                 case CEE_BLE_UN:
9297                 case CEE_BLT_UN:
9298                         CHECK_OPSIZE (5);
9299                         CHECK_STACK (2);
9300                         MONO_INST_NEW (cfg, ins, *ip);
9301                         ip++;
9302                         target = ip + 4 + (gint32)read32(ip);
9303                         ip += 4;
9304
9305                         ADD_BINCOND (NULL);
9306
9307                         sp = stack_start;
9308                         inline_costs += BRANCH_COST;
9309                         break;
9310                 case CEE_SWITCH: {
9311                         MonoInst *src1;
9312                         MonoBasicBlock **targets;
9313                         MonoBasicBlock *default_bblock;
9314                         MonoJumpInfoBBTable *table;
9315                         int offset_reg = alloc_preg (cfg);
9316                         int target_reg = alloc_preg (cfg);
9317                         int table_reg = alloc_preg (cfg);
9318                         int sum_reg = alloc_preg (cfg);
9319                         gboolean use_op_switch;
9320
9321                         CHECK_OPSIZE (5);
9322                         CHECK_STACK (1);
9323                         n = read32 (ip + 1);
9324                         --sp;
9325                         src1 = sp [0];
9326                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9327                                 UNVERIFIED;
9328
9329                         ip += 5;
9330                         CHECK_OPSIZE (n * sizeof (guint32));
9331                         target = ip + n * sizeof (guint32);
9332
9333                         GET_BBLOCK (cfg, default_bblock, target);
9334                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9335
9336                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9337                         for (i = 0; i < n; ++i) {
9338                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9339                                 targets [i] = tblock;
9340                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9341                                 ip += 4;
9342                         }
9343
9344                         if (sp != stack_start) {
9345                                 /* 
9346                                  * Link the current bb with the targets as well, so handle_stack_args
9347                                  * will set their in_stack correctly.
9348                                  */
9349                                 link_bblock (cfg, cfg->cbb, default_bblock);
9350                                 for (i = 0; i < n; ++i)
9351                                         link_bblock (cfg, cfg->cbb, targets [i]);
9352
9353                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9354                                 sp = stack_start;
9355                                 CHECK_UNVERIFIABLE (cfg);
9356
9357                                 /* Undo the links */
9358                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9359                                 for (i = 0; i < n; ++i)
9360                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9361                         }
9362
9363                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9364                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9365
9366                         for (i = 0; i < n; ++i)
9367                                 link_bblock (cfg, cfg->cbb, targets [i]);
9368
9369                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9370                         table->table = targets;
9371                         table->table_size = n;
9372
9373                         use_op_switch = FALSE;
9374 #ifdef TARGET_ARM
9375                         /* ARM implements SWITCH statements differently */
9376                         /* FIXME: Make it use the generic implementation */
9377                         if (!cfg->compile_aot)
9378                                 use_op_switch = TRUE;
9379 #endif
9380
9381                         if (COMPILE_LLVM (cfg))
9382                                 use_op_switch = TRUE;
9383
9384                         cfg->cbb->has_jump_table = 1;
9385
9386                         if (use_op_switch) {
9387                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9388                                 ins->sreg1 = src1->dreg;
9389                                 ins->inst_p0 = table;
9390                                 ins->inst_many_bb = targets;
9391                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9392                                 MONO_ADD_INS (cfg->cbb, ins);
9393                         } else {
9394                                 if (sizeof (gpointer) == 8)
9395                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9396                                 else
9397                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9398
9399 #if SIZEOF_REGISTER == 8
9400                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9401                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9402 #endif
9403
9404                                 if (cfg->compile_aot) {
9405                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9406                                 } else {
9407                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9408                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9409                                         ins->inst_p0 = table;
9410                                         ins->dreg = table_reg;
9411                                         MONO_ADD_INS (cfg->cbb, ins);
9412                                 }
9413
9414                                 /* FIXME: Use load_memindex */
9415                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9416                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9417                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9418                         }
9419                         start_new_bblock = 1;
9420                         inline_costs += (BRANCH_COST * 2);
9421                         break;
9422                 }
9423                 case CEE_LDIND_I1:
9424                 case CEE_LDIND_U1:
9425                 case CEE_LDIND_I2:
9426                 case CEE_LDIND_U2:
9427                 case CEE_LDIND_I4:
9428                 case CEE_LDIND_U4:
9429                 case CEE_LDIND_I8:
9430                 case CEE_LDIND_I:
9431                 case CEE_LDIND_R4:
9432                 case CEE_LDIND_R8:
9433                 case CEE_LDIND_REF:
9434                         CHECK_STACK (1);
9435                         --sp;
9436
9437                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9438                         *sp++ = ins;
9439                         ins_flag = 0;
9440                         ++ip;
9441                         break;
9442                 case CEE_STIND_REF:
9443                 case CEE_STIND_I1:
9444                 case CEE_STIND_I2:
9445                 case CEE_STIND_I4:
9446                 case CEE_STIND_I8:
9447                 case CEE_STIND_R4:
9448                 case CEE_STIND_R8:
9449                 case CEE_STIND_I:
9450                         CHECK_STACK (2);
9451                         sp -= 2;
9452
9453                         if (ins_flag & MONO_INST_VOLATILE) {
9454                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9455                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9456                         }
9457
9458                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9459                         ins->flags |= ins_flag;
9460                         ins_flag = 0;
9461
9462                         MONO_ADD_INS (cfg->cbb, ins);
9463
9464                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9465                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9466
9467                         inline_costs += 1;
9468                         ++ip;
9469                         break;
9470
9471                 case CEE_MUL:
9472                         CHECK_STACK (2);
9473
9474                         MONO_INST_NEW (cfg, ins, (*ip));
9475                         sp -= 2;
9476                         ins->sreg1 = sp [0]->dreg;
9477                         ins->sreg2 = sp [1]->dreg;
9478                         type_from_op (cfg, ins, sp [0], sp [1]);
9479                         CHECK_TYPE (ins);
9480                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9481
9482                         /* Use the immediate opcodes if possible */
9483                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9484                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9485                                 if (imm_opcode != -1) {
9486                                         ins->opcode = imm_opcode;
9487                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9488                                         ins->sreg2 = -1;
9489
9490                                         NULLIFY_INS (sp [1]);
9491                                 }
9492                         }
9493
9494                         MONO_ADD_INS ((cfg)->cbb, (ins));
9495
9496                         *sp++ = mono_decompose_opcode (cfg, ins);
9497                         ip++;
9498                         break;
9499                 case CEE_ADD:
9500                 case CEE_SUB:
9501                 case CEE_DIV:
9502                 case CEE_DIV_UN:
9503                 case CEE_REM:
9504                 case CEE_REM_UN:
9505                 case CEE_AND:
9506                 case CEE_OR:
9507                 case CEE_XOR:
9508                 case CEE_SHL:
9509                 case CEE_SHR:
9510                 case CEE_SHR_UN:
9511                         CHECK_STACK (2);
9512
9513                         MONO_INST_NEW (cfg, ins, (*ip));
9514                         sp -= 2;
9515                         ins->sreg1 = sp [0]->dreg;
9516                         ins->sreg2 = sp [1]->dreg;
9517                         type_from_op (cfg, ins, sp [0], sp [1]);
9518                         CHECK_TYPE (ins);
9519                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9520                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9521
9522                         /* FIXME: Pass opcode to is_inst_imm */
9523
9524                         /* Use the immediate opcodes if possible */
9525                         if (((sp [1]->opcode == OP_ICONST) || (sp [1]->opcode == OP_I8CONST)) && mono_arch_is_inst_imm (sp [1]->opcode == OP_ICONST ? sp [1]->inst_c0 : sp [1]->inst_l)) {
9526                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9527                                 if (imm_opcode != -1) {
9528                                         ins->opcode = imm_opcode;
9529                                         if (sp [1]->opcode == OP_I8CONST) {
9530 #if SIZEOF_REGISTER == 8
9531                                                 ins->inst_imm = sp [1]->inst_l;
9532 #else
9533                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9534                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9535 #endif
9536                                         }
9537                                         else
9538                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9539                                         ins->sreg2 = -1;
9540
9541                                         /* Might be followed by an instruction added by add_widen_op */
9542                                         if (sp [1]->next == NULL)
9543                                                 NULLIFY_INS (sp [1]);
9544                                 }
9545                         }
9546                         MONO_ADD_INS ((cfg)->cbb, (ins));
9547
9548                         *sp++ = mono_decompose_opcode (cfg, ins);
9549                         ip++;
9550                         break;
9551                 case CEE_NEG:
9552                 case CEE_NOT:
9553                 case CEE_CONV_I1:
9554                 case CEE_CONV_I2:
9555                 case CEE_CONV_I4:
9556                 case CEE_CONV_R4:
9557                 case CEE_CONV_R8:
9558                 case CEE_CONV_U4:
9559                 case CEE_CONV_I8:
9560                 case CEE_CONV_U8:
9561                 case CEE_CONV_OVF_I8:
9562                 case CEE_CONV_OVF_U8:
9563                 case CEE_CONV_R_UN:
9564                         CHECK_STACK (1);
9565
9566                         /* Special case this earlier so we have long constants in the IR */
9567                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9568                                 int data = sp [-1]->inst_c0;
9569                                 sp [-1]->opcode = OP_I8CONST;
9570                                 sp [-1]->type = STACK_I8;
9571 #if SIZEOF_REGISTER == 8
9572                                 if ((*ip) == CEE_CONV_U8)
9573                                         sp [-1]->inst_c0 = (guint32)data;
9574                                 else
9575                                         sp [-1]->inst_c0 = data;
9576 #else
9577                                 sp [-1]->inst_ls_word = data;
9578                                 if ((*ip) == CEE_CONV_U8)
9579                                         sp [-1]->inst_ms_word = 0;
9580                                 else
9581                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9582 #endif
9583                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9584                         }
9585                         else {
9586                                 ADD_UNOP (*ip);
9587                         }
9588                         ip++;
9589                         break;
9590                 case CEE_CONV_OVF_I4:
9591                 case CEE_CONV_OVF_I1:
9592                 case CEE_CONV_OVF_I2:
9593                 case CEE_CONV_OVF_I:
9594                 case CEE_CONV_OVF_U:
9595                         CHECK_STACK (1);
9596
9597                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9598                                 ADD_UNOP (CEE_CONV_OVF_I8);
9599                                 ADD_UNOP (*ip);
9600                         } else {
9601                                 ADD_UNOP (*ip);
9602                         }
9603                         ip++;
9604                         break;
9605                 case CEE_CONV_OVF_U1:
9606                 case CEE_CONV_OVF_U2:
9607                 case CEE_CONV_OVF_U4:
9608                         CHECK_STACK (1);
9609
9610                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9611                                 ADD_UNOP (CEE_CONV_OVF_U8);
9612                                 ADD_UNOP (*ip);
9613                         } else {
9614                                 ADD_UNOP (*ip);
9615                         }
9616                         ip++;
9617                         break;
9618                 case CEE_CONV_OVF_I1_UN:
9619                 case CEE_CONV_OVF_I2_UN:
9620                 case CEE_CONV_OVF_I4_UN:
9621                 case CEE_CONV_OVF_I8_UN:
9622                 case CEE_CONV_OVF_U1_UN:
9623                 case CEE_CONV_OVF_U2_UN:
9624                 case CEE_CONV_OVF_U4_UN:
9625                 case CEE_CONV_OVF_U8_UN:
9626                 case CEE_CONV_OVF_I_UN:
9627                 case CEE_CONV_OVF_U_UN:
9628                 case CEE_CONV_U2:
9629                 case CEE_CONV_U1:
9630                 case CEE_CONV_I:
9631                 case CEE_CONV_U:
9632                         CHECK_STACK (1);
9633                         ADD_UNOP (*ip);
9634                         CHECK_CFG_EXCEPTION;
9635                         ip++;
9636                         break;
9637                 case CEE_ADD_OVF:
9638                 case CEE_ADD_OVF_UN:
9639                 case CEE_MUL_OVF:
9640                 case CEE_MUL_OVF_UN:
9641                 case CEE_SUB_OVF:
9642                 case CEE_SUB_OVF_UN:
9643                         CHECK_STACK (2);
9644                         ADD_BINOP (*ip);
9645                         ip++;
9646                         break;
9647                 case CEE_CPOBJ:
9648                         GSHAREDVT_FAILURE (*ip);
9649                         CHECK_OPSIZE (5);
9650                         CHECK_STACK (2);
9651                         token = read32 (ip + 1);
9652                         klass = mini_get_class (method, token, generic_context);
9653                         CHECK_TYPELOAD (klass);
9654                         sp -= 2;
9655                         mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9656                         ins_flag = 0;
9657                         ip += 5;
9658                         break;
9659                 case CEE_LDOBJ: {
9660                         int loc_index = -1;
9661                         int stloc_len = 0;
9662
9663                         CHECK_OPSIZE (5);
9664                         CHECK_STACK (1);
9665                         --sp;
9666                         token = read32 (ip + 1);
9667                         klass = mini_get_class (method, token, generic_context);
9668                         CHECK_TYPELOAD (klass);
9669
9670                         /* Optimize the common ldobj+stloc combination */
9671                         switch (ip [5]) {
9672                         case CEE_STLOC_S:
9673                                 loc_index = ip [6];
9674                                 stloc_len = 2;
9675                                 break;
9676                         case CEE_STLOC_0:
9677                         case CEE_STLOC_1:
9678                         case CEE_STLOC_2:
9679                         case CEE_STLOC_3:
9680                                 loc_index = ip [5] - CEE_STLOC_0;
9681                                 stloc_len = 1;
9682                                 break;
9683                         default:
9684                                 break;
9685                         }
9686
9687                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9688                                 CHECK_LOCAL (loc_index);
9689
9690                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9691                                 ins->dreg = cfg->locals [loc_index]->dreg;
9692                                 ins->flags |= ins_flag;
9693                                 ip += 5;
9694                                 ip += stloc_len;
9695                                 if (ins_flag & MONO_INST_VOLATILE) {
9696                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9697                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9698                                 }
9699                                 ins_flag = 0;
9700                                 break;
9701                         }
9702
9703                         /* Optimize the ldobj+stobj combination */
9704                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token)) {
9705                                 CHECK_STACK (1);
9706
9707                                 sp --;
9708
9709                                 mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9710
9711                                 ip += 5 + 5;
9712                                 ins_flag = 0;
9713                                 break;
9714                         }
9715
9716                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9717                         *sp++ = ins;
9718
9719                         ip += 5;
9720                         ins_flag = 0;
9721                         inline_costs += 1;
9722                         break;
9723                 }
9724                 case CEE_LDSTR:
9725                         CHECK_STACK_OVF (1);
9726                         CHECK_OPSIZE (5);
9727                         n = read32 (ip + 1);
9728
9729                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9730                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9731                                 ins->type = STACK_OBJ;
9732                                 *sp = ins;
9733                         }
9734                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9735                                 MonoInst *iargs [1];
9736                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9737
9738                                 if (cfg->compile_aot)
9739                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9740                                 else
9741                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
9742                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
9743                         } else {
9744                                 if (cfg->opt & MONO_OPT_SHARED) {
9745                                         MonoInst *iargs [3];
9746
9747                                         if (cfg->compile_aot) {
9748                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
9749                                         }
9750                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
9751                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
9752                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
9753                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
9754                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9755                                         CHECK_CFG_ERROR;
9756                                 } else {
9757                                         if (cfg->cbb->out_of_line) {
9758                                                 MonoInst *iargs [2];
9759
9760                                                 if (image == mono_defaults.corlib) {
9761                                                         /* 
9762                                                          * Avoid relocations in AOT and save some space by using a 
9763                                                          * version of helper_ldstr specialized to mscorlib.
9764                                                          */
9765                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
9766                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
9767                                                 } else {
9768                                                         /* Avoid creating the string object */
9769                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
9770                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
9771                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
9772                                                 }
9773                                         } 
9774                                         else
9775                                         if (cfg->compile_aot) {
9776                                                 NEW_LDSTRCONST (cfg, ins, image, n);
9777                                                 *sp = ins;
9778                                                 MONO_ADD_INS (cfg->cbb, ins);
9779                                         } 
9780                                         else {
9781                                                 NEW_PCONST (cfg, ins, NULL);
9782                                                 ins->type = STACK_OBJ;
9783                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9784                                                 CHECK_CFG_ERROR;
9785                                                 
9786                                                 if (!ins->inst_p0)
9787                                                         OUT_OF_MEMORY_FAILURE;
9788
9789                                                 *sp = ins;
9790                                                 MONO_ADD_INS (cfg->cbb, ins);
9791                                         }
9792                                 }
9793                         }
9794
9795                         sp++;
9796                         ip += 5;
9797                         break;
9798                 case CEE_NEWOBJ: {
9799                         MonoInst *iargs [2];
9800                         MonoMethodSignature *fsig;
9801                         MonoInst this_ins;
9802                         MonoInst *alloc;
9803                         MonoInst *vtable_arg = NULL;
9804
9805                         CHECK_OPSIZE (5);
9806                         token = read32 (ip + 1);
9807                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9808                         CHECK_CFG_ERROR;
9809
9810                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9811                         CHECK_CFG_ERROR;
9812
9813                         mono_save_token_info (cfg, image, token, cmethod);
9814
9815                         if (!mono_class_init (cmethod->klass))
9816                                 TYPE_LOAD_ERROR (cmethod->klass);
9817
9818                         context_used = mini_method_check_context_used (cfg, cmethod);
9819                                         
9820                         if (!dont_verify && !cfg->skip_visibility) {
9821                                 MonoMethod *cil_method = cmethod;
9822                                 MonoMethod *target_method = cil_method;
9823
9824                                 if (method->is_inflated) {
9825                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
9826                                         CHECK_CFG_ERROR;
9827                                 }
9828                                 
9829                                 if (!mono_method_can_access_method (method_definition, target_method) &&
9830                                         !mono_method_can_access_method (method, cil_method))
9831                                         emit_method_access_failure (cfg, method, cil_method);
9832                         }
9833
9834                         if (mono_security_core_clr_enabled ())
9835                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
9836
9837                         if (cfg->gshared && cmethod && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
9838                                 emit_class_init (cfg, cmethod->klass);
9839                                 CHECK_TYPELOAD (cmethod->klass);
9840                         }
9841
9842                         /*
9843                         if (cfg->gsharedvt) {
9844                                 if (mini_is_gsharedvt_variable_signature (sig))
9845                                         GSHAREDVT_FAILURE (*ip);
9846                         }
9847                         */
9848
9849                         n = fsig->param_count;
9850                         CHECK_STACK (n);
9851
9852                         /* 
9853                          * Generate smaller code for the common newobj <exception> instruction in
9854                          * argument checking code.
9855                          */
9856                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
9857                                 is_exception_class (cmethod->klass) && n <= 2 &&
9858                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
9859                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
9860                                 MonoInst *iargs [3];
9861
9862                                 sp -= n;
9863
9864                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
9865                                 switch (n) {
9866                                 case 0:
9867                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
9868                                         break;
9869                                 case 1:
9870                                         iargs [1] = sp [0];
9871                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
9872                                         break;
9873                                 case 2:
9874                                         iargs [1] = sp [0];
9875                                         iargs [2] = sp [1];
9876                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
9877                                         break;
9878                                 default:
9879                                         g_assert_not_reached ();
9880                                 }
9881
9882                                 ip += 5;
9883                                 inline_costs += 5;
9884                                 break;
9885                         }
9886
9887                         /* move the args to allow room for 'this' in the first position */
9888                         while (n--) {
9889                                 --sp;
9890                                 sp [1] = sp [0];
9891                         }
9892
9893                         /* check_call_signature () requires sp[0] to be set */
9894                         this_ins.type = STACK_OBJ;
9895                         sp [0] = &this_ins;
9896                         if (check_call_signature (cfg, fsig, sp))
9897                                 UNVERIFIED;
9898
9899                         iargs [0] = NULL;
9900
9901                         if (mini_class_is_system_array (cmethod->klass)) {
9902                                 *sp = emit_get_rgctx_method (cfg, context_used,
9903                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9904
9905                                 /* Avoid varargs in the common case */
9906                                 if (fsig->param_count == 1)
9907                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
9908                                 else if (fsig->param_count == 2)
9909                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
9910                                 else if (fsig->param_count == 3)
9911                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
9912                                 else if (fsig->param_count == 4)
9913                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
9914                                 else
9915                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
9916                         } else if (cmethod->string_ctor) {
9917                                 g_assert (!context_used);
9918                                 g_assert (!vtable_arg);
9919                                 /* we simply pass a null pointer */
9920                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
9921                                 /* now call the string ctor */
9922                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
9923                         } else {
9924                                 if (cmethod->klass->valuetype) {
9925                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
9926                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
9927                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
9928
9929                                         alloc = NULL;
9930
9931                                         /* 
9932                                          * The code generated by mini_emit_virtual_call () expects
9933                                          * iargs [0] to be a boxed instance, but luckily the vcall
9934                                          * will be transformed into a normal call there.
9935                                          */
9936                                 } else if (context_used) {
9937                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
9938                                         *sp = alloc;
9939                                 } else {
9940                                         MonoVTable *vtable = NULL;
9941
9942                                         if (!cfg->compile_aot)
9943                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
9944                                         CHECK_TYPELOAD (cmethod->klass);
9945
9946                                         /*
9947                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
9948                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
9949                                          * As a workaround, we call class cctors before allocating objects.
9950                                          */
9951                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
9952                                                 emit_class_init (cfg, cmethod->klass);
9953                                                 if (cfg->verbose_level > 2)
9954                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
9955                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
9956                                         }
9957
9958                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
9959                                         *sp = alloc;
9960                                 }
9961                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
9962
9963                                 if (alloc)
9964                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
9965
9966                                 /* Now call the actual ctor */
9967                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
9968                                 CHECK_CFG_EXCEPTION;
9969                         }
9970
9971                         if (alloc == NULL) {
9972                                 /* Valuetype */
9973                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
9974                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
9975                                 *sp++= ins;
9976                         } else {
9977                                 *sp++ = alloc;
9978                         }
9979                         
9980                         ip += 5;
9981                         inline_costs += 5;
9982                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
9983                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9984                         break;
9985                 }
9986                 case CEE_CASTCLASS:
9987                 case CEE_ISINST: {
9988                         CHECK_STACK (1);
9989                         --sp;
9990                         CHECK_OPSIZE (5);
9991                         token = read32 (ip + 1);
9992                         klass = mini_get_class (method, token, generic_context);
9993                         CHECK_TYPELOAD (klass);
9994                         if (sp [0]->type != STACK_OBJ)
9995                                 UNVERIFIED;
9996
9997                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
9998                         ins->dreg = alloc_preg (cfg);
9999                         ins->sreg1 = (*sp)->dreg;
10000                         ins->klass = klass;
10001                         ins->type = STACK_OBJ;
10002                         MONO_ADD_INS (cfg->cbb, ins);
10003
10004                         CHECK_CFG_EXCEPTION;
10005                         *sp++ = ins;
10006                         ip += 5;
10007
10008                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10009                         break;
10010                 }
10011                 case CEE_UNBOX_ANY: {
10012                         MonoInst *res, *addr;
10013
10014                         CHECK_STACK (1);
10015                         --sp;
10016                         CHECK_OPSIZE (5);
10017                         token = read32 (ip + 1);
10018                         klass = mini_get_class (method, token, generic_context);
10019                         CHECK_TYPELOAD (klass);
10020
10021                         mono_save_token_info (cfg, image, token, klass);
10022
10023                         context_used = mini_class_check_context_used (cfg, klass);
10024
10025                         if (mini_is_gsharedvt_klass (klass)) {
10026                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10027                                 inline_costs += 2;
10028                         } else if (generic_class_is_reference_type (cfg, klass)) {
10029                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10030                                         EMIT_NEW_PCONST (cfg, res, NULL);
10031                                         res->type = STACK_OBJ;
10032                                 } else {
10033                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10034                                         res->dreg = alloc_preg (cfg);
10035                                         res->sreg1 = (*sp)->dreg;
10036                                         res->klass = klass;
10037                                         res->type = STACK_OBJ;
10038                                         MONO_ADD_INS (cfg->cbb, res);
10039                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10040                                 }
10041                         } else if (mono_class_is_nullable (klass)) {
10042                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10043                         } else {
10044                                 addr = handle_unbox (cfg, klass, sp, context_used);
10045                                 /* LDOBJ */
10046                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10047                                 res = ins;
10048                                 inline_costs += 2;
10049                         }
10050
10051                         *sp ++ = res;
10052                         ip += 5;
10053                         break;
10054                 }
10055                 case CEE_BOX: {
10056                         MonoInst *val;
10057                         MonoClass *enum_class;
10058                         MonoMethod *has_flag;
10059
10060                         CHECK_STACK (1);
10061                         --sp;
10062                         val = *sp;
10063                         CHECK_OPSIZE (5);
10064                         token = read32 (ip + 1);
10065                         klass = mini_get_class (method, token, generic_context);
10066                         CHECK_TYPELOAD (klass);
10067
10068                         mono_save_token_info (cfg, image, token, klass);
10069
10070                         context_used = mini_class_check_context_used (cfg, klass);
10071
10072                         if (generic_class_is_reference_type (cfg, klass)) {
10073                                 *sp++ = val;
10074                                 ip += 5;
10075                                 break;
10076                         }
10077
10078                         if (klass == mono_defaults.void_class)
10079                                 UNVERIFIED;
10080                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10081                                 UNVERIFIED;
10082                         /* frequent check in generic code: box (struct), brtrue */
10083
10084                         /*
10085                          * Look for:
10086                          *
10087                          *   <push int/long ptr>
10088                          *   <push int/long>
10089                          *   box MyFlags
10090                          *   constrained. MyFlags
10091                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10092                          *
10093                          * If we find this sequence and the operand types on box and constrained
10094                          * are equal, we can emit a specialized instruction sequence instead of
10095                          * the very slow HasFlag () call.
10096                          */
10097                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10098                             /* Cheap checks first. */
10099                             ip + 5 + 6 + 5 < end &&
10100                             ip [5] == CEE_PREFIX1 &&
10101                             ip [6] == CEE_CONSTRAINED_ &&
10102                             ip [11] == CEE_CALLVIRT &&
10103                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10104                             mono_class_is_enum (klass) &&
10105                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10106                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10107                             has_flag->klass == mono_defaults.enum_class &&
10108                             !strcmp (has_flag->name, "HasFlag") &&
10109                             has_flag->signature->hasthis &&
10110                             has_flag->signature->param_count == 1) {
10111                                 CHECK_TYPELOAD (enum_class);
10112
10113                                 if (enum_class == klass) {
10114                                         MonoInst *enum_this, *enum_flag;
10115
10116                                         ip += 5 + 6 + 5;
10117                                         --sp;
10118
10119                                         enum_this = sp [0];
10120                                         enum_flag = sp [1];
10121
10122                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10123                                         break;
10124                                 }
10125                         }
10126
10127                         // FIXME: LLVM can't handle the inconsistent bb linking
10128                         if (!mono_class_is_nullable (klass) &&
10129                                 !mini_is_gsharedvt_klass (klass) &&
10130                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10131                                 (ip [5] == CEE_BRTRUE || 
10132                                  ip [5] == CEE_BRTRUE_S ||
10133                                  ip [5] == CEE_BRFALSE ||
10134                                  ip [5] == CEE_BRFALSE_S)) {
10135                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10136                                 int dreg;
10137                                 MonoBasicBlock *true_bb, *false_bb;
10138
10139                                 ip += 5;
10140
10141                                 if (cfg->verbose_level > 3) {
10142                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10143                                         printf ("<box+brtrue opt>\n");
10144                                 }
10145
10146                                 switch (*ip) {
10147                                 case CEE_BRTRUE_S:
10148                                 case CEE_BRFALSE_S:
10149                                         CHECK_OPSIZE (2);
10150                                         ip++;
10151                                         target = ip + 1 + (signed char)(*ip);
10152                                         ip++;
10153                                         break;
10154                                 case CEE_BRTRUE:
10155                                 case CEE_BRFALSE:
10156                                         CHECK_OPSIZE (5);
10157                                         ip++;
10158                                         target = ip + 4 + (gint)(read32 (ip));
10159                                         ip += 4;
10160                                         break;
10161                                 default:
10162                                         g_assert_not_reached ();
10163                                 }
10164
10165                                 /* 
10166                                  * We need to link both bblocks, since it is needed for handling stack
10167                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10168                                  * Branching to only one of them would lead to inconsistencies, so
10169                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10170                                  */
10171                                 GET_BBLOCK (cfg, true_bb, target);
10172                                 GET_BBLOCK (cfg, false_bb, ip);
10173
10174                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10175                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10176
10177                                 if (sp != stack_start) {
10178                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10179                                         sp = stack_start;
10180                                         CHECK_UNVERIFIABLE (cfg);
10181                                 }
10182
10183                                 if (COMPILE_LLVM (cfg)) {
10184                                         dreg = alloc_ireg (cfg);
10185                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10186                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10187
10188                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10189                                 } else {
10190                                         /* The JIT can't eliminate the iconst+compare */
10191                                         MONO_INST_NEW (cfg, ins, OP_BR);
10192                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10193                                         MONO_ADD_INS (cfg->cbb, ins);
10194                                 }
10195
10196                                 start_new_bblock = 1;
10197                                 break;
10198                         }
10199
10200                         *sp++ = handle_box (cfg, val, klass, context_used);
10201
10202                         CHECK_CFG_EXCEPTION;
10203                         ip += 5;
10204                         inline_costs += 1;
10205                         break;
10206                 }
10207                 case CEE_UNBOX: {
10208                         CHECK_STACK (1);
10209                         --sp;
10210                         CHECK_OPSIZE (5);
10211                         token = read32 (ip + 1);
10212                         klass = mini_get_class (method, token, generic_context);
10213                         CHECK_TYPELOAD (klass);
10214
10215                         mono_save_token_info (cfg, image, token, klass);
10216
10217                         context_used = mini_class_check_context_used (cfg, klass);
10218
10219                         if (mono_class_is_nullable (klass)) {
10220                                 MonoInst *val;
10221
10222                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10223                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10224
10225                                 *sp++= ins;
10226                         } else {
10227                                 ins = handle_unbox (cfg, klass, sp, context_used);
10228                                 *sp++ = ins;
10229                         }
10230                         ip += 5;
10231                         inline_costs += 2;
10232                         break;
10233                 }
10234                 case CEE_LDFLD:
10235                 case CEE_LDFLDA:
10236                 case CEE_STFLD:
10237                 case CEE_LDSFLD:
10238                 case CEE_LDSFLDA:
10239                 case CEE_STSFLD: {
10240                         MonoClassField *field;
10241 #ifndef DISABLE_REMOTING
10242                         int costs;
10243 #endif
10244                         guint foffset;
10245                         gboolean is_instance;
10246                         int op;
10247                         gpointer addr = NULL;
10248                         gboolean is_special_static;
10249                         MonoType *ftype;
10250                         MonoInst *store_val = NULL;
10251                         MonoInst *thread_ins;
10252
10253                         op = *ip;
10254                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10255                         if (is_instance) {
10256                                 if (op == CEE_STFLD) {
10257                                         CHECK_STACK (2);
10258                                         sp -= 2;
10259                                         store_val = sp [1];
10260                                 } else {
10261                                         CHECK_STACK (1);
10262                                         --sp;
10263                                 }
10264                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10265                                         UNVERIFIED;
10266                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10267                                         UNVERIFIED;
10268                         } else {
10269                                 if (op == CEE_STSFLD) {
10270                                         CHECK_STACK (1);
10271                                         sp--;
10272                                         store_val = sp [0];
10273                                 }
10274                         }
10275
10276                         CHECK_OPSIZE (5);
10277                         token = read32 (ip + 1);
10278                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10279                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10280                                 klass = field->parent;
10281                         }
10282                         else {
10283                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10284                                 CHECK_CFG_ERROR;
10285                         }
10286                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10287                                 FIELD_ACCESS_FAILURE (method, field);
10288                         mono_class_init (klass);
10289
10290                         /* if the class is Critical then transparent code cannot access it's fields */
10291                         if (!is_instance && mono_security_core_clr_enabled ())
10292                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10293
10294                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10295                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10296                         if (mono_security_core_clr_enabled ())
10297                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10298                         */
10299
10300                         ftype = mono_field_get_type (field);
10301
10302                         /*
10303                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10304                          * the static case.
10305                          */
10306                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10307                                 switch (op) {
10308                                 case CEE_LDFLD:
10309                                         op = CEE_LDSFLD;
10310                                         break;
10311                                 case CEE_STFLD:
10312                                         op = CEE_STSFLD;
10313                                         break;
10314                                 case CEE_LDFLDA:
10315                                         op = CEE_LDSFLDA;
10316                                         break;
10317                                 default:
10318                                         g_assert_not_reached ();
10319                                 }
10320                                 is_instance = FALSE;
10321                         }
10322
10323                         context_used = mini_class_check_context_used (cfg, klass);
10324
10325                         /* INSTANCE CASE */
10326
10327                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10328                         if (op == CEE_STFLD) {
10329                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10330                                         UNVERIFIED;
10331 #ifndef DISABLE_REMOTING
10332                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10333                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10334                                         MonoInst *iargs [5];
10335
10336                                         GSHAREDVT_FAILURE (op);
10337
10338                                         iargs [0] = sp [0];
10339                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10340                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10341                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10342                                                     field->offset);
10343                                         iargs [4] = sp [1];
10344
10345                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10346                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10347                                                                                            iargs, ip, cfg->real_offset, TRUE);
10348                                                 CHECK_CFG_EXCEPTION;
10349                                                 g_assert (costs > 0);
10350                                                       
10351                                                 cfg->real_offset += 5;
10352
10353                                                 inline_costs += costs;
10354                                         } else {
10355                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10356                                         }
10357                                 } else
10358 #endif
10359                                 {
10360                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10361
10362                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10363
10364                                         if (ins_flag & MONO_INST_VOLATILE) {
10365                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10366                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10367                                         }
10368
10369                                         if (mini_is_gsharedvt_klass (klass)) {
10370                                                 MonoInst *offset_ins;
10371
10372                                                 context_used = mini_class_check_context_used (cfg, klass);
10373
10374                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10375                                                 /* The value is offset by 1 */
10376                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10377                                                 dreg = alloc_ireg_mp (cfg);
10378                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10379                                                 wbarrier_ptr_ins = ins;
10380                                                 /* The decomposition will call mini_emit_memory_copy () which will emit a wbarrier if needed */
10381                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10382                                         } else {
10383                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10384                                         }
10385                                         if (sp [0]->opcode != OP_LDADDR)
10386                                                 store->flags |= MONO_INST_FAULT;
10387
10388                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10389                                                 if (mini_is_gsharedvt_klass (klass)) {
10390                                                         g_assert (wbarrier_ptr_ins);
10391                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10392                                                 } else {
10393                                                         /* insert call to write barrier */
10394                                                         MonoInst *ptr;
10395                                                         int dreg;
10396
10397                                                         dreg = alloc_ireg_mp (cfg);
10398                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10399                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10400                                                 }
10401                                         }
10402
10403                                         store->flags |= ins_flag;
10404                                 }
10405                                 ins_flag = 0;
10406                                 ip += 5;
10407                                 break;
10408                         }
10409
10410 #ifndef DISABLE_REMOTING
10411                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10412                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10413                                 MonoInst *iargs [4];
10414
10415                                 GSHAREDVT_FAILURE (op);
10416
10417                                 iargs [0] = sp [0];
10418                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10419                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10420                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10421                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10422                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10423                                                                                    iargs, ip, cfg->real_offset, TRUE);
10424                                         CHECK_CFG_EXCEPTION;
10425                                         g_assert (costs > 0);
10426                                                       
10427                                         cfg->real_offset += 5;
10428
10429                                         *sp++ = iargs [0];
10430
10431                                         inline_costs += costs;
10432                                 } else {
10433                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10434                                         *sp++ = ins;
10435                                 }
10436                         } else 
10437 #endif
10438                         if (is_instance) {
10439                                 if (sp [0]->type == STACK_VTYPE) {
10440                                         MonoInst *var;
10441
10442                                         /* Have to compute the address of the variable */
10443
10444                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10445                                         if (!var)
10446                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10447                                         else
10448                                                 g_assert (var->klass == klass);
10449                                         
10450                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10451                                         sp [0] = ins;
10452                                 }
10453
10454                                 if (op == CEE_LDFLDA) {
10455                                         if (sp [0]->type == STACK_OBJ) {
10456                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10457                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10458                                         }
10459
10460                                         dreg = alloc_ireg_mp (cfg);
10461
10462                                         if (mini_is_gsharedvt_klass (klass)) {
10463                                                 MonoInst *offset_ins;
10464
10465                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10466                                                 /* The value is offset by 1 */
10467                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10468                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10469                                         } else {
10470                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10471                                         }
10472                                         ins->klass = mono_class_from_mono_type (field->type);
10473                                         ins->type = STACK_MP;
10474                                         *sp++ = ins;
10475                                 } else {
10476                                         MonoInst *load;
10477
10478                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10479
10480                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10481                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10482                                                 if (ins) {
10483                                                         *sp++ = ins;
10484                                                         ins_flag = 0;
10485                                                         ip += 5;
10486                                                         break;
10487                                                 }
10488                                         }
10489
10490                                         MonoInst *field_add_inst = sp [0];
10491                                         if (mini_is_gsharedvt_klass (klass)) {
10492                                                 MonoInst *offset_ins;
10493
10494                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10495                                                 /* The value is offset by 1 */
10496                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10497                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10498                                                 foffset = 0;
10499                                         }
10500
10501                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10502
10503                                         if (sp [0]->opcode != OP_LDADDR)
10504                                                 load->flags |= MONO_INST_FAULT;
10505                                         *sp++ = load;
10506                                 }
10507                         }
10508
10509                         if (is_instance) {
10510                                 ins_flag = 0;
10511                                 ip += 5;
10512                                 break;
10513                         }
10514
10515                         /* STATIC CASE */
10516                         context_used = mini_class_check_context_used (cfg, klass);
10517
10518                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10519                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10520                                 CHECK_CFG_ERROR;
10521                         }
10522
10523                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10524                          * to be called here.
10525                          */
10526                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10527                                 mono_class_vtable (cfg->domain, klass);
10528                                 CHECK_TYPELOAD (klass);
10529                         }
10530                         mono_domain_lock (cfg->domain);
10531                         if (cfg->domain->special_static_fields)
10532                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10533                         mono_domain_unlock (cfg->domain);
10534
10535                         is_special_static = mono_class_field_is_special_static (field);
10536
10537                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10538                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10539                         else
10540                                 thread_ins = NULL;
10541
10542                         /* Generate IR to compute the field address */
10543                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10544                                 /*
10545                                  * Fast access to TLS data
10546                                  * Inline version of get_thread_static_data () in
10547                                  * threads.c.
10548                                  */
10549                                 guint32 offset;
10550                                 int idx, static_data_reg, array_reg, dreg;
10551
10552                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10553                                         GSHAREDVT_FAILURE (op);
10554
10555                                 static_data_reg = alloc_ireg (cfg);
10556                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10557
10558                                 if (cfg->compile_aot) {
10559                                         int offset_reg, offset2_reg, idx_reg;
10560
10561                                         /* For TLS variables, this will return the TLS offset */
10562                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10563                                         offset_reg = ins->dreg;
10564                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10565                                         idx_reg = alloc_ireg (cfg);
10566                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10567                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10568                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10569                                         array_reg = alloc_ireg (cfg);
10570                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10571                                         offset2_reg = alloc_ireg (cfg);
10572                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10573                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10574                                         dreg = alloc_ireg (cfg);
10575                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10576                                 } else {
10577                                         offset = (gsize)addr & 0x7fffffff;
10578                                         idx = offset & 0x3f;
10579
10580                                         array_reg = alloc_ireg (cfg);
10581                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10582                                         dreg = alloc_ireg (cfg);
10583                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10584                                 }
10585                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10586                                         (cfg->compile_aot && is_special_static) ||
10587                                         (context_used && is_special_static)) {
10588                                 MonoInst *iargs [2];
10589
10590                                 g_assert (field->parent);
10591                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10592                                 if (context_used) {
10593                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10594                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10595                                 } else {
10596                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10597                                 }
10598                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10599                         } else if (context_used) {
10600                                 MonoInst *static_data;
10601
10602                                 /*
10603                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10604                                         method->klass->name_space, method->klass->name, method->name,
10605                                         depth, field->offset);
10606                                 */
10607
10608                                 if (mono_class_needs_cctor_run (klass, method))
10609                                         emit_class_init (cfg, klass);
10610
10611                                 /*
10612                                  * The pointer we're computing here is
10613                                  *
10614                                  *   super_info.static_data + field->offset
10615                                  */
10616                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10617                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10618
10619                                 if (mini_is_gsharedvt_klass (klass)) {
10620                                         MonoInst *offset_ins;
10621
10622                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10623                                         /* The value is offset by 1 */
10624                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10625                                         dreg = alloc_ireg_mp (cfg);
10626                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10627                                 } else if (field->offset == 0) {
10628                                         ins = static_data;
10629                                 } else {
10630                                         int addr_reg = mono_alloc_preg (cfg);
10631                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10632                                 }
10633                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10634                                 MonoInst *iargs [2];
10635
10636                                 g_assert (field->parent);
10637                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10638                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10639                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10640                         } else {
10641                                 MonoVTable *vtable = NULL;
10642
10643                                 if (!cfg->compile_aot)
10644                                         vtable = mono_class_vtable (cfg->domain, klass);
10645                                 CHECK_TYPELOAD (klass);
10646
10647                                 if (!addr) {
10648                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10649                                                 if (!(g_slist_find (class_inits, klass))) {
10650                                                         emit_class_init (cfg, klass);
10651                                                         if (cfg->verbose_level > 2)
10652                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10653                                                         class_inits = g_slist_prepend (class_inits, klass);
10654                                                 }
10655                                         } else {
10656                                                 if (cfg->run_cctors) {
10657                                                         /* This makes so that inline cannot trigger */
10658                                                         /* .cctors: too many apps depend on them */
10659                                                         /* running with a specific order... */
10660                                                         g_assert (vtable);
10661                                                         if (! vtable->initialized)
10662                                                                 INLINE_FAILURE ("class init");
10663                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10664                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10665                                                                 goto exception_exit;
10666                                                         }
10667                                                 }
10668                                         }
10669                                         if (cfg->compile_aot)
10670                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10671                                         else {
10672                                                 g_assert (vtable);
10673                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10674                                                 g_assert (addr);
10675                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10676                                         }
10677                                 } else {
10678                                         MonoInst *iargs [1];
10679                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10680                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10681                                 }
10682                         }
10683
10684                         /* Generate IR to do the actual load/store operation */
10685
10686                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10687                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10688                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10689                         }
10690
10691                         if (op == CEE_LDSFLDA) {
10692                                 ins->klass = mono_class_from_mono_type (ftype);
10693                                 ins->type = STACK_PTR;
10694                                 *sp++ = ins;
10695                         } else if (op == CEE_STSFLD) {
10696                                 MonoInst *store;
10697
10698                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10699                                 store->flags |= ins_flag;
10700                         } else {
10701                                 gboolean is_const = FALSE;
10702                                 MonoVTable *vtable = NULL;
10703                                 gpointer addr = NULL;
10704
10705                                 if (!context_used) {
10706                                         vtable = mono_class_vtable (cfg->domain, klass);
10707                                         CHECK_TYPELOAD (klass);
10708                                 }
10709                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10710                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10711                                         int ro_type = ftype->type;
10712                                         if (!addr)
10713                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10714                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10715                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10716                                         }
10717
10718                                         GSHAREDVT_FAILURE (op);
10719
10720                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10721                                         is_const = TRUE;
10722                                         switch (ro_type) {
10723                                         case MONO_TYPE_BOOLEAN:
10724                                         case MONO_TYPE_U1:
10725                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10726                                                 sp++;
10727                                                 break;
10728                                         case MONO_TYPE_I1:
10729                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10730                                                 sp++;
10731                                                 break;                                          
10732                                         case MONO_TYPE_CHAR:
10733                                         case MONO_TYPE_U2:
10734                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10735                                                 sp++;
10736                                                 break;
10737                                         case MONO_TYPE_I2:
10738                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10739                                                 sp++;
10740                                                 break;
10741                                                 break;
10742                                         case MONO_TYPE_I4:
10743                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
10744                                                 sp++;
10745                                                 break;                                          
10746                                         case MONO_TYPE_U4:
10747                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
10748                                                 sp++;
10749                                                 break;
10750                                         case MONO_TYPE_I:
10751                                         case MONO_TYPE_U:
10752                                         case MONO_TYPE_PTR:
10753                                         case MONO_TYPE_FNPTR:
10754                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10755                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
10756                                                 sp++;
10757                                                 break;
10758                                         case MONO_TYPE_STRING:
10759                                         case MONO_TYPE_OBJECT:
10760                                         case MONO_TYPE_CLASS:
10761                                         case MONO_TYPE_SZARRAY:
10762                                         case MONO_TYPE_ARRAY:
10763                                                 if (!mono_gc_is_moving ()) {
10764                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10765                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
10766                                                         sp++;
10767                                                 } else {
10768                                                         is_const = FALSE;
10769                                                 }
10770                                                 break;
10771                                         case MONO_TYPE_I8:
10772                                         case MONO_TYPE_U8:
10773                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
10774                                                 sp++;
10775                                                 break;
10776                                         case MONO_TYPE_R4:
10777                                         case MONO_TYPE_R8:
10778                                         case MONO_TYPE_VALUETYPE:
10779                                         default:
10780                                                 is_const = FALSE;
10781                                                 break;
10782                                         }
10783                                 }
10784
10785                                 if (!is_const) {
10786                                         MonoInst *load;
10787
10788                                         CHECK_STACK_OVF (1);
10789
10790                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
10791                                         load->flags |= ins_flag;
10792                                         ins_flag = 0;
10793                                         *sp++ = load;
10794                                 }
10795                         }
10796
10797                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10798                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10799                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10800                         }
10801
10802                         ins_flag = 0;
10803                         ip += 5;
10804                         break;
10805                 }
10806                 case CEE_STOBJ:
10807                         CHECK_STACK (2);
10808                         sp -= 2;
10809                         CHECK_OPSIZE (5);
10810                         token = read32 (ip + 1);
10811                         klass = mini_get_class (method, token, generic_context);
10812                         CHECK_TYPELOAD (klass);
10813
10814                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
10815                         mini_emit_memory_store (cfg, &klass->byval_arg, sp [0], sp [1], ins_flag);
10816                         ins_flag = 0;
10817                         ip += 5;
10818                         inline_costs += 1;
10819                         break;
10820
10821                         /*
10822                          * Array opcodes
10823                          */
10824                 case CEE_NEWARR: {
10825                         MonoInst *len_ins;
10826                         const char *data_ptr;
10827                         int data_size = 0;
10828                         guint32 field_token;
10829
10830                         CHECK_STACK (1);
10831                         --sp;
10832
10833                         CHECK_OPSIZE (5);
10834                         token = read32 (ip + 1);
10835
10836                         klass = mini_get_class (method, token, generic_context);
10837                         CHECK_TYPELOAD (klass);
10838                         if (klass->byval_arg.type == MONO_TYPE_VOID)
10839                                 UNVERIFIED;
10840
10841                         context_used = mini_class_check_context_used (cfg, klass);
10842
10843                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
10844                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
10845                                 ins->sreg1 = sp [0]->dreg;
10846                                 ins->type = STACK_I4;
10847                                 ins->dreg = alloc_ireg (cfg);
10848                                 MONO_ADD_INS (cfg->cbb, ins);
10849                                 *sp = mono_decompose_opcode (cfg, ins);
10850                         }
10851
10852                         if (context_used) {
10853                                 MonoInst *args [3];
10854                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10855                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
10856
10857                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
10858
10859                                 /* vtable */
10860                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
10861                                         array_class, MONO_RGCTX_INFO_VTABLE);
10862                                 /* array len */
10863                                 args [1] = sp [0];
10864
10865                                 if (managed_alloc)
10866                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
10867                                 else
10868                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
10869                         } else {
10870                                 if (cfg->opt & MONO_OPT_SHARED) {
10871                                         /* Decompose now to avoid problems with references to the domainvar */
10872                                         MonoInst *iargs [3];
10873
10874                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10875                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10876                                         iargs [2] = sp [0];
10877
10878                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
10879                                 } else {
10880                                         /* Decompose later since it is needed by abcrem */
10881                                         MonoClass *array_type = mono_array_class_get (klass, 1);
10882                                         mono_class_vtable (cfg->domain, array_type);
10883                                         CHECK_TYPELOAD (array_type);
10884
10885                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
10886                                         ins->dreg = alloc_ireg_ref (cfg);
10887                                         ins->sreg1 = sp [0]->dreg;
10888                                         ins->inst_newa_class = klass;
10889                                         ins->type = STACK_OBJ;
10890                                         ins->klass = array_type;
10891                                         MONO_ADD_INS (cfg->cbb, ins);
10892                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10893                                         cfg->cbb->has_array_access = TRUE;
10894
10895                                         /* Needed so mono_emit_load_get_addr () gets called */
10896                                         mono_get_got_var (cfg);
10897                                 }
10898                         }
10899
10900                         len_ins = sp [0];
10901                         ip += 5;
10902                         *sp++ = ins;
10903                         inline_costs += 1;
10904
10905                         /* 
10906                          * we inline/optimize the initialization sequence if possible.
10907                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
10908                          * for small sizes open code the memcpy
10909                          * ensure the rva field is big enough
10910                          */
10911                         if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, cfg->cbb, ip + 6) && (len_ins->opcode == OP_ICONST) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, klass, len_ins->inst_c0, &data_size, &field_token))) {
10912                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
10913                                 MonoInst *iargs [3];
10914                                 int add_reg = alloc_ireg_mp (cfg);
10915
10916                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
10917                                 if (cfg->compile_aot) {
10918                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
10919                                 } else {
10920                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
10921                                 }
10922                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
10923                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
10924                                 ip += 11;
10925                         }
10926
10927                         break;
10928                 }
10929                 case CEE_LDLEN:
10930                         CHECK_STACK (1);
10931                         --sp;
10932                         if (sp [0]->type != STACK_OBJ)
10933                                 UNVERIFIED;
10934
10935                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
10936                         ins->dreg = alloc_preg (cfg);
10937                         ins->sreg1 = sp [0]->dreg;
10938                         ins->type = STACK_I4;
10939                         /* This flag will be inherited by the decomposition */
10940                         ins->flags |= MONO_INST_FAULT;
10941                         MONO_ADD_INS (cfg->cbb, ins);
10942                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10943                         cfg->cbb->has_array_access = TRUE;
10944                         ip ++;
10945                         *sp++ = ins;
10946                         break;
10947                 case CEE_LDELEMA:
10948                         CHECK_STACK (2);
10949                         sp -= 2;
10950                         CHECK_OPSIZE (5);
10951                         if (sp [0]->type != STACK_OBJ)
10952                                 UNVERIFIED;
10953
10954                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
10955
10956                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
10957                         CHECK_TYPELOAD (klass);
10958                         /* we need to make sure that this array is exactly the type it needs
10959                          * to be for correctness. the wrappers are lax with their usage
10960                          * so we need to ignore them here
10961                          */
10962                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
10963                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10964                                 mini_emit_check_array_type (cfg, sp [0], array_class);
10965                                 CHECK_TYPELOAD (array_class);
10966                         }
10967
10968                         readonly = FALSE;
10969                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
10970                         *sp++ = ins;
10971                         ip += 5;
10972                         break;
10973                 case CEE_LDELEM:
10974                 case CEE_LDELEM_I1:
10975                 case CEE_LDELEM_U1:
10976                 case CEE_LDELEM_I2:
10977                 case CEE_LDELEM_U2:
10978                 case CEE_LDELEM_I4:
10979                 case CEE_LDELEM_U4:
10980                 case CEE_LDELEM_I8:
10981                 case CEE_LDELEM_I:
10982                 case CEE_LDELEM_R4:
10983                 case CEE_LDELEM_R8:
10984                 case CEE_LDELEM_REF: {
10985                         MonoInst *addr;
10986
10987                         CHECK_STACK (2);
10988                         sp -= 2;
10989
10990                         if (*ip == CEE_LDELEM) {
10991                                 CHECK_OPSIZE (5);
10992                                 token = read32 (ip + 1);
10993                                 klass = mini_get_class (method, token, generic_context);
10994                                 CHECK_TYPELOAD (klass);
10995                                 mono_class_init (klass);
10996                         }
10997                         else
10998                                 klass = array_access_to_klass (*ip);
10999
11000                         if (sp [0]->type != STACK_OBJ)
11001                                 UNVERIFIED;
11002
11003                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11004
11005                         if (mini_is_gsharedvt_variable_klass (klass)) {
11006                                 // FIXME-VT: OP_ICONST optimization
11007                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11008                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11009                                 ins->opcode = OP_LOADV_MEMBASE;
11010                         } else if (sp [1]->opcode == OP_ICONST) {
11011                                 int array_reg = sp [0]->dreg;
11012                                 int index_reg = sp [1]->dreg;
11013                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11014
11015                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11016                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11017
11018                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11019                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11020                         } else {
11021                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11022                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11023                         }
11024                         *sp++ = ins;
11025                         if (*ip == CEE_LDELEM)
11026                                 ip += 5;
11027                         else
11028                                 ++ip;
11029                         break;
11030                 }
11031                 case CEE_STELEM_I:
11032                 case CEE_STELEM_I1:
11033                 case CEE_STELEM_I2:
11034                 case CEE_STELEM_I4:
11035                 case CEE_STELEM_I8:
11036                 case CEE_STELEM_R4:
11037                 case CEE_STELEM_R8:
11038                 case CEE_STELEM_REF:
11039                 case CEE_STELEM: {
11040                         CHECK_STACK (3);
11041                         sp -= 3;
11042
11043                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11044
11045                         if (*ip == CEE_STELEM) {
11046                                 CHECK_OPSIZE (5);
11047                                 token = read32 (ip + 1);
11048                                 klass = mini_get_class (method, token, generic_context);
11049                                 CHECK_TYPELOAD (klass);
11050                                 mono_class_init (klass);
11051                         }
11052                         else
11053                                 klass = array_access_to_klass (*ip);
11054
11055                         if (sp [0]->type != STACK_OBJ)
11056                                 UNVERIFIED;
11057
11058                         emit_array_store (cfg, klass, sp, TRUE);
11059
11060                         if (*ip == CEE_STELEM)
11061                                 ip += 5;
11062                         else
11063                                 ++ip;
11064                         inline_costs += 1;
11065                         break;
11066                 }
11067                 case CEE_CKFINITE: {
11068                         CHECK_STACK (1);
11069                         --sp;
11070
11071                         if (cfg->llvm_only) {
11072                                 MonoInst *iargs [1];
11073
11074                                 iargs [0] = sp [0];
11075                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11076                         } else  {
11077                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11078                                 ins->sreg1 = sp [0]->dreg;
11079                                 ins->dreg = alloc_freg (cfg);
11080                                 ins->type = STACK_R8;
11081                                 MONO_ADD_INS (cfg->cbb, ins);
11082
11083                                 *sp++ = mono_decompose_opcode (cfg, ins);
11084                         }
11085
11086                         ++ip;
11087                         break;
11088                 }
11089                 case CEE_REFANYVAL: {
11090                         MonoInst *src_var, *src;
11091
11092                         int klass_reg = alloc_preg (cfg);
11093                         int dreg = alloc_preg (cfg);
11094
11095                         GSHAREDVT_FAILURE (*ip);
11096
11097                         CHECK_STACK (1);
11098                         MONO_INST_NEW (cfg, ins, *ip);
11099                         --sp;
11100                         CHECK_OPSIZE (5);
11101                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11102                         CHECK_TYPELOAD (klass);
11103
11104                         context_used = mini_class_check_context_used (cfg, klass);
11105
11106                         // FIXME:
11107                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11108                         if (!src_var)
11109                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11110                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11111                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11112
11113                         if (context_used) {
11114                                 MonoInst *klass_ins;
11115
11116                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11117                                                 klass, MONO_RGCTX_INFO_KLASS);
11118
11119                                 // FIXME:
11120                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11121                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11122                         } else {
11123                                 mini_emit_class_check (cfg, klass_reg, klass);
11124                         }
11125                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11126                         ins->type = STACK_MP;
11127                         ins->klass = klass;
11128                         *sp++ = ins;
11129                         ip += 5;
11130                         break;
11131                 }
11132                 case CEE_MKREFANY: {
11133                         MonoInst *loc, *addr;
11134
11135                         GSHAREDVT_FAILURE (*ip);
11136
11137                         CHECK_STACK (1);
11138                         MONO_INST_NEW (cfg, ins, *ip);
11139                         --sp;
11140                         CHECK_OPSIZE (5);
11141                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11142                         CHECK_TYPELOAD (klass);
11143
11144                         context_used = mini_class_check_context_used (cfg, klass);
11145
11146                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11147                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11148
11149                         if (context_used) {
11150                                 MonoInst *const_ins;
11151                                 int type_reg = alloc_preg (cfg);
11152
11153                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11154                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11155                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11156                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11157                         } else {
11158                                 int const_reg = alloc_preg (cfg);
11159                                 int type_reg = alloc_preg (cfg);
11160
11161                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11162                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11163                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11164                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11165                         }
11166                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11167
11168                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11169                         ins->type = STACK_VTYPE;
11170                         ins->klass = mono_defaults.typed_reference_class;
11171                         *sp++ = ins;
11172                         ip += 5;
11173                         break;
11174                 }
11175                 case CEE_LDTOKEN: {
11176                         gpointer handle;
11177                         MonoClass *handle_class;
11178
11179                         CHECK_STACK_OVF (1);
11180
11181                         CHECK_OPSIZE (5);
11182                         n = read32 (ip + 1);
11183
11184                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11185                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11186                                 handle = mono_method_get_wrapper_data (method, n);
11187                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11188                                 if (handle_class == mono_defaults.typehandle_class)
11189                                         handle = &((MonoClass*)handle)->byval_arg;
11190                         }
11191                         else {
11192                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11193                                 CHECK_CFG_ERROR;
11194                         }
11195                         if (!handle)
11196                                 LOAD_ERROR;
11197                         mono_class_init (handle_class);
11198                         if (cfg->gshared) {
11199                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11200                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11201                                         /* This case handles ldtoken
11202                                            of an open type, like for
11203                                            typeof(Gen<>). */
11204                                         context_used = 0;
11205                                 } else if (handle_class == mono_defaults.typehandle_class) {
11206                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11207                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11208                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11209                                 else if (handle_class == mono_defaults.methodhandle_class)
11210                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11211                                 else
11212                                         g_assert_not_reached ();
11213                         }
11214
11215                         if ((cfg->opt & MONO_OPT_SHARED) &&
11216                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11217                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11218                                 MonoInst *addr, *vtvar, *iargs [3];
11219                                 int method_context_used;
11220
11221                                 method_context_used = mini_method_check_context_used (cfg, method);
11222
11223                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11224
11225                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11226                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11227                                 if (method_context_used) {
11228                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11229                                                 method, MONO_RGCTX_INFO_METHOD);
11230                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11231                                 } else {
11232                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11233                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11234                                 }
11235                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11236
11237                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11238
11239                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11240                         } else {
11241                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11242                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11243                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11244                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11245                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11246                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11247
11248                                         mono_class_init (tclass);
11249                                         if (context_used) {
11250                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11251                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11252                                         } else if (cfg->compile_aot) {
11253                                                 if (method->wrapper_type) {
11254                                                         error_init (&error); //got to do it since there are multiple conditionals below
11255                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11256                                                                 /* Special case for static synchronized wrappers */
11257                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11258                                                         } else {
11259                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11260                                                                 /* FIXME: n is not a normal token */
11261                                                                 DISABLE_AOT (cfg);
11262                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11263                                                         }
11264                                                 } else {
11265                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11266                                                 }
11267                                         } else {
11268                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11269                                                 CHECK_CFG_ERROR;
11270                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11271                                         }
11272                                         ins->type = STACK_OBJ;
11273                                         ins->klass = cmethod->klass;
11274                                         ip += 5;
11275                                 } else {
11276                                         MonoInst *addr, *vtvar;
11277
11278                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11279
11280                                         if (context_used) {
11281                                                 if (handle_class == mono_defaults.typehandle_class) {
11282                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11283                                                                         mono_class_from_mono_type ((MonoType *)handle),
11284                                                                         MONO_RGCTX_INFO_TYPE);
11285                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11286                                                         ins = emit_get_rgctx_method (cfg, context_used,
11287                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11288                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11289                                                         ins = emit_get_rgctx_field (cfg, context_used,
11290                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11291                                                 } else {
11292                                                         g_assert_not_reached ();
11293                                                 }
11294                                         } else if (cfg->compile_aot) {
11295                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11296                                         } else {
11297                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11298                                         }
11299                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11300                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11301                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11302                                 }
11303                         }
11304
11305                         *sp++ = ins;
11306                         ip += 5;
11307                         break;
11308                 }
11309                 case CEE_THROW:
11310                         CHECK_STACK (1);
11311                         if (sp [-1]->type != STACK_OBJ)
11312                                 UNVERIFIED;
11313
11314                         MONO_INST_NEW (cfg, ins, OP_THROW);
11315                         --sp;
11316                         ins->sreg1 = sp [0]->dreg;
11317                         ip++;
11318                         cfg->cbb->out_of_line = TRUE;
11319                         MONO_ADD_INS (cfg->cbb, ins);
11320                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11321                         MONO_ADD_INS (cfg->cbb, ins);
11322                         sp = stack_start;
11323                         
11324                         link_bblock (cfg, cfg->cbb, end_bblock);
11325                         start_new_bblock = 1;
11326                         /* This can complicate code generation for llvm since the return value might not be defined */
11327                         if (COMPILE_LLVM (cfg))
11328                                 INLINE_FAILURE ("throw");
11329                         break;
11330                 case CEE_ENDFINALLY:
11331                         if (!ip_in_finally_clause (cfg, ip - header->code))
11332                                 UNVERIFIED;
11333                         /* mono_save_seq_point_info () depends on this */
11334                         if (sp != stack_start)
11335                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11336                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11337                         MONO_ADD_INS (cfg->cbb, ins);
11338                         ip++;
11339                         start_new_bblock = 1;
11340
11341                         /*
11342                          * Control will leave the method so empty the stack, otherwise
11343                          * the next basic block will start with a nonempty stack.
11344                          */
11345                         while (sp != stack_start) {
11346                                 sp--;
11347                         }
11348                         break;
11349                 case CEE_LEAVE:
11350                 case CEE_LEAVE_S: {
11351                         GList *handlers;
11352
11353                         if (*ip == CEE_LEAVE) {
11354                                 CHECK_OPSIZE (5);
11355                                 target = ip + 5 + (gint32)read32(ip + 1);
11356                         } else {
11357                                 CHECK_OPSIZE (2);
11358                                 target = ip + 2 + (signed char)(ip [1]);
11359                         }
11360
11361                         /* empty the stack */
11362                         while (sp != stack_start) {
11363                                 sp--;
11364                         }
11365
11366                         /* 
11367                          * If this leave statement is in a catch block, check for a
11368                          * pending exception, and rethrow it if necessary.
11369                          * We avoid doing this in runtime invoke wrappers, since those are called
11370                          * by native code which excepts the wrapper to catch all exceptions.
11371                          */
11372                         for (i = 0; i < header->num_clauses; ++i) {
11373                                 MonoExceptionClause *clause = &header->clauses [i];
11374
11375                                 /* 
11376                                  * Use <= in the final comparison to handle clauses with multiple
11377                                  * leave statements, like in bug #78024.
11378                                  * The ordering of the exception clauses guarantees that we find the
11379                                  * innermost clause.
11380                                  */
11381                                 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) && (ip - header->code + ((*ip == CEE_LEAVE) ? 5 : 2)) <= (clause->handler_offset + clause->handler_len) && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
11382                                         MonoInst *exc_ins;
11383                                         MonoBasicBlock *dont_throw;
11384
11385                                         /*
11386                                           MonoInst *load;
11387
11388                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11389                                         */
11390
11391                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11392
11393                                         NEW_BBLOCK (cfg, dont_throw);
11394
11395                                         /*
11396                                          * Currently, we always rethrow the abort exception, despite the 
11397                                          * fact that this is not correct. See thread6.cs for an example. 
11398                                          * But propagating the abort exception is more important than 
11399                                          * getting the sematics right.
11400                                          */
11401                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11402                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11403                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11404
11405                                         MONO_START_BB (cfg, dont_throw);
11406                                 }
11407                         }
11408
11409 #ifdef ENABLE_LLVM
11410                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11411 #endif
11412
11413                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11414                                 GList *tmp;
11415                                 MonoExceptionClause *clause;
11416
11417                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11418                                         clause = (MonoExceptionClause *)tmp->data;
11419                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11420                                         g_assert (tblock);
11421                                         link_bblock (cfg, cfg->cbb, tblock);
11422                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11423                                         ins->inst_target_bb = tblock;
11424                                         ins->inst_eh_block = clause;
11425                                         MONO_ADD_INS (cfg->cbb, ins);
11426                                         cfg->cbb->has_call_handler = 1;
11427                                         if (COMPILE_LLVM (cfg)) {
11428                                                 MonoBasicBlock *target_bb;
11429
11430                                                 /* 
11431                                                  * Link the finally bblock with the target, since it will
11432                                                  * conceptually branch there.
11433                                                  */
11434                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11435                                                 GET_BBLOCK (cfg, target_bb, target);
11436                                                 link_bblock (cfg, tblock, target_bb);
11437                                         }
11438                                 }
11439                                 g_list_free (handlers);
11440                         } 
11441
11442                         MONO_INST_NEW (cfg, ins, OP_BR);
11443                         MONO_ADD_INS (cfg->cbb, ins);
11444                         GET_BBLOCK (cfg, tblock, target);
11445                         link_bblock (cfg, cfg->cbb, tblock);
11446                         ins->inst_target_bb = tblock;
11447
11448                         start_new_bblock = 1;
11449
11450                         if (*ip == CEE_LEAVE)
11451                                 ip += 5;
11452                         else
11453                                 ip += 2;
11454
11455                         break;
11456                 }
11457
11458                         /*
11459                          * Mono specific opcodes
11460                          */
11461                 case MONO_CUSTOM_PREFIX: {
11462
11463                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11464
11465                         CHECK_OPSIZE (2);
11466                         switch (ip [1]) {
11467                         case CEE_MONO_ICALL: {
11468                                 gpointer func;
11469                                 MonoJitICallInfo *info;
11470
11471                                 token = read32 (ip + 2);
11472                                 func = mono_method_get_wrapper_data (method, token);
11473                                 info = mono_find_jit_icall_by_addr (func);
11474                                 if (!info)
11475                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11476                                 g_assert (info);
11477
11478                                 CHECK_STACK (info->sig->param_count);
11479                                 sp -= info->sig->param_count;
11480
11481                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11482                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11483                                         *sp++ = ins;
11484
11485                                 ip += 6;
11486                                 inline_costs += 10 * num_calls++;
11487
11488                                 break;
11489                         }
11490                         case CEE_MONO_LDPTR_CARD_TABLE:
11491                         case CEE_MONO_LDPTR_NURSERY_START:
11492                         case CEE_MONO_LDPTR_NURSERY_BITS:
11493                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11494                                 CHECK_STACK_OVF (1);
11495
11496                                 switch (ip [1]) {
11497                                         case CEE_MONO_LDPTR_CARD_TABLE:
11498                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11499                                                 break;
11500                                         case CEE_MONO_LDPTR_NURSERY_START:
11501                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11502                                                 break;
11503                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11504                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11505                                                 break;
11506                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11507                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11508                                                 break;
11509                                 }
11510
11511                                 *sp++ = ins;
11512                                 ip += 2;
11513                                 inline_costs += 10 * num_calls++;
11514                                 break;
11515                         }
11516                         case CEE_MONO_LDPTR: {
11517                                 gpointer ptr;
11518
11519                                 CHECK_STACK_OVF (1);
11520                                 CHECK_OPSIZE (6);
11521                                 token = read32 (ip + 2);
11522
11523                                 ptr = mono_method_get_wrapper_data (method, token);
11524                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11525                                 *sp++ = ins;
11526                                 ip += 6;
11527                                 inline_costs += 10 * num_calls++;
11528                                 /* Can't embed random pointers into AOT code */
11529                                 DISABLE_AOT (cfg);
11530                                 break;
11531                         }
11532                         case CEE_MONO_JIT_ICALL_ADDR: {
11533                                 MonoJitICallInfo *callinfo;
11534                                 gpointer ptr;
11535
11536                                 CHECK_STACK_OVF (1);
11537                                 CHECK_OPSIZE (6);
11538                                 token = read32 (ip + 2);
11539
11540                                 ptr = mono_method_get_wrapper_data (method, token);
11541                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11542                                 g_assert (callinfo);
11543                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11544                                 *sp++ = ins;
11545                                 ip += 6;
11546                                 inline_costs += 10 * num_calls++;
11547                                 break;
11548                         }
11549                         case CEE_MONO_ICALL_ADDR: {
11550                                 MonoMethod *cmethod;
11551                                 gpointer ptr;
11552
11553                                 CHECK_STACK_OVF (1);
11554                                 CHECK_OPSIZE (6);
11555                                 token = read32 (ip + 2);
11556
11557                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11558
11559                                 if (cfg->compile_aot) {
11560                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11561                                                 /*
11562                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11563                                                  * before the call, its not needed when using direct pinvoke.
11564                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11565                                                  * on platforms which don't support dlopen ().
11566                                                  */
11567                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11568                                         } else {
11569                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11570                                         }
11571                                 } else {
11572                                         ptr = mono_lookup_internal_call (cmethod);
11573                                         g_assert (ptr);
11574                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11575                                 }
11576                                 *sp++ = ins;
11577                                 ip += 6;
11578                                 break;
11579                         }
11580                         case CEE_MONO_VTADDR: {
11581                                 MonoInst *src_var, *src;
11582
11583                                 CHECK_STACK (1);
11584                                 --sp;
11585
11586                                 // FIXME:
11587                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11588                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11589                                 *sp++ = src;
11590                                 ip += 2;
11591                                 break;
11592                         }
11593                         case CEE_MONO_NEWOBJ: {
11594                                 MonoInst *iargs [2];
11595
11596                                 CHECK_STACK_OVF (1);
11597                                 CHECK_OPSIZE (6);
11598                                 token = read32 (ip + 2);
11599                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11600                                 mono_class_init (klass);
11601                                 NEW_DOMAINCONST (cfg, iargs [0]);
11602                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11603                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11604                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11605                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11606                                 ip += 6;
11607                                 inline_costs += 10 * num_calls++;
11608                                 break;
11609                         }
11610                         case CEE_MONO_OBJADDR:
11611                                 CHECK_STACK (1);
11612                                 --sp;
11613                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11614                                 ins->dreg = alloc_ireg_mp (cfg);
11615                                 ins->sreg1 = sp [0]->dreg;
11616                                 ins->type = STACK_MP;
11617                                 MONO_ADD_INS (cfg->cbb, ins);
11618                                 *sp++ = ins;
11619                                 ip += 2;
11620                                 break;
11621                         case CEE_MONO_LDNATIVEOBJ:
11622                                 /*
11623                                  * Similar to LDOBJ, but instead load the unmanaged 
11624                                  * representation of the vtype to the stack.
11625                                  */
11626                                 CHECK_STACK (1);
11627                                 CHECK_OPSIZE (6);
11628                                 --sp;
11629                                 token = read32 (ip + 2);
11630                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11631                                 g_assert (klass->valuetype);
11632                                 mono_class_init (klass);
11633
11634                                 {
11635                                         MonoInst *src, *dest, *temp;
11636
11637                                         src = sp [0];
11638                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11639                                         temp->backend.is_pinvoke = 1;
11640                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11641                                         mini_emit_memory_copy (cfg, dest, src, klass, TRUE, 0);
11642
11643                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11644                                         dest->type = STACK_VTYPE;
11645                                         dest->klass = klass;
11646
11647                                         *sp ++ = dest;
11648                                         ip += 6;
11649                                 }
11650                                 break;
11651                         case CEE_MONO_RETOBJ: {
11652                                 /*
11653                                  * Same as RET, but return the native representation of a vtype
11654                                  * to the caller.
11655                                  */
11656                                 g_assert (cfg->ret);
11657                                 g_assert (mono_method_signature (method)->pinvoke); 
11658                                 CHECK_STACK (1);
11659                                 --sp;
11660                                 
11661                                 CHECK_OPSIZE (6);
11662                                 token = read32 (ip + 2);    
11663                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11664
11665                                 if (!cfg->vret_addr) {
11666                                         g_assert (cfg->ret_var_is_local);
11667
11668                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11669                                 } else {
11670                                         EMIT_NEW_RETLOADA (cfg, ins);
11671                                 }
11672                                 mini_emit_memory_copy (cfg, ins, sp [0], klass, TRUE, 0);
11673                                 
11674                                 if (sp != stack_start)
11675                                         UNVERIFIED;
11676                                 
11677                                 MONO_INST_NEW (cfg, ins, OP_BR);
11678                                 ins->inst_target_bb = end_bblock;
11679                                 MONO_ADD_INS (cfg->cbb, ins);
11680                                 link_bblock (cfg, cfg->cbb, end_bblock);
11681                                 start_new_bblock = 1;
11682                                 ip += 6;
11683                                 break;
11684                         }
11685                         case CEE_MONO_SAVE_LMF:
11686                         case CEE_MONO_RESTORE_LMF:
11687                                 ip += 2;
11688                                 break;
11689                         case CEE_MONO_CLASSCONST:
11690                                 CHECK_STACK_OVF (1);
11691                                 CHECK_OPSIZE (6);
11692                                 token = read32 (ip + 2);
11693                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11694                                 *sp++ = ins;
11695                                 ip += 6;
11696                                 inline_costs += 10 * num_calls++;
11697                                 break;
11698                         case CEE_MONO_NOT_TAKEN:
11699                                 cfg->cbb->out_of_line = TRUE;
11700                                 ip += 2;
11701                                 break;
11702                         case CEE_MONO_TLS: {
11703                                 MonoTlsKey key;
11704
11705                                 CHECK_STACK_OVF (1);
11706                                 CHECK_OPSIZE (6);
11707                                 key = (MonoTlsKey)read32 (ip + 2);
11708                                 g_assert (key < TLS_KEY_NUM);
11709
11710                                 ins = mono_create_tls_get (cfg, key);
11711                                 g_assert (ins);
11712                                 ins->type = STACK_PTR;
11713                                 *sp++ = ins;
11714                                 ip += 6;
11715                                 break;
11716                         }
11717                         case CEE_MONO_DYN_CALL: {
11718                                 MonoCallInst *call;
11719
11720                                 /* It would be easier to call a trampoline, but that would put an
11721                                  * extra frame on the stack, confusing exception handling. So
11722                                  * implement it inline using an opcode for now.
11723                                  */
11724
11725                                 if (!cfg->dyn_call_var) {
11726                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11727                                         /* prevent it from being register allocated */
11728                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11729                                 }
11730
11731                                 /* Has to use a call inst since it local regalloc expects it */
11732                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11733                                 ins = (MonoInst*)call;
11734                                 sp -= 2;
11735                                 ins->sreg1 = sp [0]->dreg;
11736                                 ins->sreg2 = sp [1]->dreg;
11737                                 MONO_ADD_INS (cfg->cbb, ins);
11738
11739                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11740
11741                                 ip += 2;
11742                                 inline_costs += 10 * num_calls++;
11743
11744                                 break;
11745                         }
11746                         case CEE_MONO_MEMORY_BARRIER: {
11747                                 CHECK_OPSIZE (6);
11748                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
11749                                 ip += 6;
11750                                 break;
11751                         }
11752                         case CEE_MONO_ATOMIC_STORE_I4: {
11753                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
11754
11755                                 CHECK_OPSIZE (6);
11756                                 CHECK_STACK (2);
11757                                 sp -= 2;
11758
11759                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
11760                                 ins->dreg = sp [0]->dreg;
11761                                 ins->sreg1 = sp [1]->dreg;
11762                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
11763                                 MONO_ADD_INS (cfg->cbb, ins);
11764
11765                                 ip += 6;
11766                                 break;
11767                         }
11768                         case CEE_MONO_JIT_ATTACH: {
11769                                 MonoInst *args [16], *domain_ins;
11770                                 MonoInst *ad_ins, *jit_tls_ins;
11771                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
11772
11773                                 g_assert (!mono_threads_is_coop_enabled ());
11774
11775                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11776
11777                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11778                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11779
11780                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
11781                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
11782
11783                                 if (ad_ins && jit_tls_ins) {
11784                                         NEW_BBLOCK (cfg, next_bb);
11785                                         NEW_BBLOCK (cfg, call_bb);
11786
11787                                         if (cfg->compile_aot) {
11788                                                 /* AOT code is only used in the root domain */
11789                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
11790                                         } else {
11791                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
11792                                         }
11793                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
11794                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
11795
11796                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
11797                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
11798
11799                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
11800                                         MONO_START_BB (cfg, call_bb);
11801                                 }
11802
11803                                 /* AOT code is only used in the root domain */
11804                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
11805                                 if (cfg->compile_aot) {
11806                                         MonoInst *addr;
11807
11808                                         /*
11809                                          * This is called on unattached threads, so it cannot go through the trampoline
11810                                          * infrastructure. Use an indirect call through a got slot initialized at load time
11811                                          * instead.
11812                                          */
11813                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
11814                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
11815                                 } else {
11816                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
11817                                 }
11818                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11819
11820                                 if (next_bb)
11821                                         MONO_START_BB (cfg, next_bb);
11822
11823                                 ip += 2;
11824                                 break;
11825                         }
11826                         case CEE_MONO_JIT_DETACH: {
11827                                 MonoInst *args [16];
11828
11829                                 /* Restore the original domain */
11830                                 dreg = alloc_ireg (cfg);
11831                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
11832                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
11833                                 ip += 2;
11834                                 break;
11835                         }
11836                         case CEE_MONO_CALLI_EXTRA_ARG: {
11837                                 MonoInst *addr;
11838                                 MonoMethodSignature *fsig;
11839                                 MonoInst *arg;
11840
11841                                 /*
11842                                  * This is the same as CEE_CALLI, but passes an additional argument
11843                                  * to the called method in llvmonly mode.
11844                                  * This is only used by delegate invoke wrappers to call the
11845                                  * actual delegate method.
11846                                  */
11847                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
11848
11849                                 CHECK_OPSIZE (6);
11850                                 token = read32 (ip + 2);
11851
11852                                 ins = NULL;
11853
11854                                 cmethod = NULL;
11855                                 CHECK_STACK (1);
11856                                 --sp;
11857                                 addr = *sp;
11858                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
11859                                 CHECK_CFG_ERROR;
11860
11861                                 if (cfg->llvm_only)
11862                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
11863
11864                                 n = fsig->param_count + fsig->hasthis + 1;
11865
11866                                 CHECK_STACK (n);
11867
11868                                 sp -= n;
11869                                 arg = sp [n - 1];
11870
11871                                 if (cfg->llvm_only) {
11872                                         /*
11873                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
11874                                          * cconv. This is set by mono_init_delegate ().
11875                                          */
11876                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
11877                                                 MonoInst *callee = addr;
11878                                                 MonoInst *call, *localloc_ins;
11879                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11880                                                 int low_bit_reg = alloc_preg (cfg);
11881
11882                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11883                                                 NEW_BBLOCK (cfg, end_bb);
11884
11885                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11886                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11887                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11888
11889                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
11890                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11891                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11892                                                 /*
11893                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
11894                                                  */
11895                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11896                                                 ins->dreg = alloc_preg (cfg);
11897                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11898                                                 MONO_ADD_INS (cfg->cbb, ins);
11899                                                 localloc_ins = ins;
11900                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11901                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11902                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11903
11904                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11905                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11906
11907                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
11908                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11909                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11910                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11911                                                 ins->dreg = call->dreg;
11912
11913                                                 MONO_START_BB (cfg, end_bb);
11914                                         } else {
11915                                                 /* Caller uses a normal calling conv */
11916
11917                                                 MonoInst *callee = addr;
11918                                                 MonoInst *call, *localloc_ins;
11919                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11920                                                 int low_bit_reg = alloc_preg (cfg);
11921
11922                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11923                                                 NEW_BBLOCK (cfg, end_bb);
11924
11925                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11926                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11927                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11928
11929                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
11930                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11931                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11932                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
11933                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11934                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11935                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
11936                                                 MONO_ADD_INS (cfg->cbb, addr);
11937                                                 /*
11938                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
11939                                                  */
11940                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11941                                                 ins->dreg = alloc_preg (cfg);
11942                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11943                                                 MONO_ADD_INS (cfg->cbb, ins);
11944                                                 localloc_ins = ins;
11945                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11946                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11947                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11948
11949                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11950                                                 ins->dreg = call->dreg;
11951                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11952
11953                                                 MONO_START_BB (cfg, end_bb);
11954                                         }
11955                                 } else {
11956                                         /* Same as CEE_CALLI */
11957                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
11958                                                 /*
11959                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
11960                                                  */
11961                                                 MonoInst *callee = addr;
11962
11963                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11964                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11965                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
11966                                         } else {
11967                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
11968                                         }
11969                                 }
11970
11971                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
11972                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
11973
11974                                 CHECK_CFG_EXCEPTION;
11975
11976                                 ip += 6;
11977                                 ins_flag = 0;
11978                                 constrained_class = NULL;
11979                                 break;
11980                         }
11981                         case CEE_MONO_LDDOMAIN:
11982                                 CHECK_STACK_OVF (1);
11983                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
11984                                 ip += 2;
11985                                 *sp++ = ins;
11986                                 break;
11987                         case CEE_MONO_GET_LAST_ERROR:
11988                                 CHECK_OPSIZE (2);
11989                                 CHECK_STACK_OVF (1);
11990
11991                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
11992                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
11993                                 ins->type = STACK_I4;
11994                                 MONO_ADD_INS (cfg->cbb, ins);
11995
11996                                 ip += 2;
11997                                 *sp++ = ins;
11998                                 break;
11999                         case CEE_MONO_GET_RGCTX_ARG:
12000                                 CHECK_OPSIZE (2);
12001                                 CHECK_STACK_OVF (1);
12002
12003                                 mono_create_rgctx_var (cfg);
12004
12005                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12006                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12007                                 ins->sreg1 = cfg->rgctx_var->dreg;
12008                                 ins->type = STACK_PTR;
12009                                 MONO_ADD_INS (cfg->cbb, ins);
12010
12011                                 ip += 2;
12012                                 *sp++ = ins;
12013                                 break;
12014                         default:
12015                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12016                                 break;
12017                         }
12018                         break;
12019                 }
12020
12021                 case CEE_PREFIX1: {
12022                         CHECK_OPSIZE (2);
12023                         switch (ip [1]) {
12024                         case CEE_ARGLIST: {
12025                                 /* somewhat similar to LDTOKEN */
12026                                 MonoInst *addr, *vtvar;
12027                                 CHECK_STACK_OVF (1);
12028                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12029
12030                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12031                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12032
12033                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12034                                 ins->type = STACK_VTYPE;
12035                                 ins->klass = mono_defaults.argumenthandle_class;
12036                                 *sp++ = ins;
12037                                 ip += 2;
12038                                 break;
12039                         }
12040                         case CEE_CEQ:
12041                         case CEE_CGT:
12042                         case CEE_CGT_UN:
12043                         case CEE_CLT:
12044                         case CEE_CLT_UN: {
12045                                 MonoInst *cmp, *arg1, *arg2;
12046
12047                                 CHECK_STACK (2);
12048                                 sp -= 2;
12049                                 arg1 = sp [0];
12050                                 arg2 = sp [1];
12051
12052                                 /*
12053                                  * The following transforms:
12054                                  *    CEE_CEQ    into OP_CEQ
12055                                  *    CEE_CGT    into OP_CGT
12056                                  *    CEE_CGT_UN into OP_CGT_UN
12057                                  *    CEE_CLT    into OP_CLT
12058                                  *    CEE_CLT_UN into OP_CLT_UN
12059                                  */
12060                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12061
12062                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12063                                 cmp->sreg1 = arg1->dreg;
12064                                 cmp->sreg2 = arg2->dreg;
12065                                 type_from_op (cfg, cmp, arg1, arg2);
12066                                 CHECK_TYPE (cmp);
12067                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12068                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12069                                         cmp->opcode = OP_LCOMPARE;
12070                                 else if (arg1->type == STACK_R4)
12071                                         cmp->opcode = OP_RCOMPARE;
12072                                 else if (arg1->type == STACK_R8)
12073                                         cmp->opcode = OP_FCOMPARE;
12074                                 else
12075                                         cmp->opcode = OP_ICOMPARE;
12076                                 MONO_ADD_INS (cfg->cbb, cmp);
12077                                 ins->type = STACK_I4;
12078                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12079                                 type_from_op (cfg, ins, arg1, arg2);
12080
12081                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12082                                         /*
12083                                          * The backends expect the fceq opcodes to do the
12084                                          * comparison too.
12085                                          */
12086                                         ins->sreg1 = cmp->sreg1;
12087                                         ins->sreg2 = cmp->sreg2;
12088                                         NULLIFY_INS (cmp);
12089                                 }
12090                                 MONO_ADD_INS (cfg->cbb, ins);
12091                                 *sp++ = ins;
12092                                 ip += 2;
12093                                 break;
12094                         }
12095                         case CEE_LDFTN: {
12096                                 MonoInst *argconst;
12097                                 MonoMethod *cil_method;
12098
12099                                 CHECK_STACK_OVF (1);
12100                                 CHECK_OPSIZE (6);
12101                                 n = read32 (ip + 2);
12102                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12103                                 CHECK_CFG_ERROR;
12104
12105                                 mono_class_init (cmethod->klass);
12106
12107                                 mono_save_token_info (cfg, image, n, cmethod);
12108
12109                                 context_used = mini_method_check_context_used (cfg, cmethod);
12110
12111                                 cil_method = cmethod;
12112                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12113                                         emit_method_access_failure (cfg, method, cil_method);
12114
12115                                 if (mono_security_core_clr_enabled ())
12116                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12117
12118                                 /* 
12119                                  * Optimize the common case of ldftn+delegate creation
12120                                  */
12121                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12122                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12123                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12124                                                 MonoInst *target_ins, *handle_ins;
12125                                                 MonoMethod *invoke;
12126                                                 int invoke_context_used;
12127
12128                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12129                                                 if (!invoke || !mono_method_signature (invoke))
12130                                                         LOAD_ERROR;
12131
12132                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12133
12134                                                 target_ins = sp [-1];
12135
12136                                                 if (mono_security_core_clr_enabled ())
12137                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12138
12139                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12140                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12141                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12142                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12143                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12144                                                         }
12145                                                 }
12146
12147                                                 /* FIXME: SGEN support */
12148                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12149                                                         ip += 6;
12150                                                         if (cfg->verbose_level > 3)
12151                                                                 g_print ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
12152                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12153                                                                 sp --;
12154                                                                 *sp = handle_ins;
12155                                                                 CHECK_CFG_EXCEPTION;
12156                                                                 ip += 5;
12157                                                                 sp ++;
12158                                                                 break;
12159                                                         }
12160                                                         ip -= 6;
12161                                                 }
12162                                         }
12163                                 }
12164
12165                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12166                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12167                                 *sp++ = ins;
12168                                 
12169                                 ip += 6;
12170                                 inline_costs += 10 * num_calls++;
12171                                 break;
12172                         }
12173                         case CEE_LDVIRTFTN: {
12174                                 MonoInst *args [2];
12175
12176                                 CHECK_STACK (1);
12177                                 CHECK_OPSIZE (6);
12178                                 n = read32 (ip + 2);
12179                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12180                                 CHECK_CFG_ERROR;
12181
12182                                 mono_class_init (cmethod->klass);
12183  
12184                                 context_used = mini_method_check_context_used (cfg, cmethod);
12185
12186                                 if (mono_security_core_clr_enabled ())
12187                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12188
12189                                 /*
12190                                  * Optimize the common case of ldvirtftn+delegate creation
12191                                  */
12192                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ip > header->code && ip [-1] == CEE_DUP)) {
12193                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12194                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12195                                                 MonoInst *target_ins, *handle_ins;
12196                                                 MonoMethod *invoke;
12197                                                 int invoke_context_used;
12198                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12199
12200                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12201                                                 if (!invoke || !mono_method_signature (invoke))
12202                                                         LOAD_ERROR;
12203
12204                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12205
12206                                                 target_ins = sp [-1];
12207
12208                                                 if (mono_security_core_clr_enabled ())
12209                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12210
12211                                                 /* FIXME: SGEN support */
12212                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12213                                                         ip += 6;
12214                                                         if (cfg->verbose_level > 3)
12215                                                                 g_print ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
12216                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12217                                                                 sp -= 2;
12218                                                                 *sp = handle_ins;
12219                                                                 CHECK_CFG_EXCEPTION;
12220                                                                 ip += 5;
12221                                                                 sp ++;
12222                                                                 break;
12223                                                         }
12224                                                         ip -= 6;
12225                                                 }
12226                                         }
12227                                 }
12228
12229                                 --sp;
12230                                 args [0] = *sp;
12231
12232                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12233                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12234
12235                                 if (context_used)
12236                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12237                                 else
12238                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12239
12240                                 ip += 6;
12241                                 inline_costs += 10 * num_calls++;
12242                                 break;
12243                         }
12244                         case CEE_LDARG:
12245                                 CHECK_STACK_OVF (1);
12246                                 CHECK_OPSIZE (4);
12247                                 n = read16 (ip + 2);
12248                                 CHECK_ARG (n);
12249                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12250                                 *sp++ = ins;
12251                                 ip += 4;
12252                                 break;
12253                         case CEE_LDARGA:
12254                                 CHECK_STACK_OVF (1);
12255                                 CHECK_OPSIZE (4);
12256                                 n = read16 (ip + 2);
12257                                 CHECK_ARG (n);
12258                                 NEW_ARGLOADA (cfg, ins, n);
12259                                 MONO_ADD_INS (cfg->cbb, ins);
12260                                 *sp++ = ins;
12261                                 ip += 4;
12262                                 break;
12263                         case CEE_STARG:
12264                                 CHECK_STACK (1);
12265                                 --sp;
12266                                 CHECK_OPSIZE (4);
12267                                 n = read16 (ip + 2);
12268                                 CHECK_ARG (n);
12269                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12270                                         UNVERIFIED;
12271                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12272                                 ip += 4;
12273                                 break;
12274                         case CEE_LDLOC:
12275                                 CHECK_STACK_OVF (1);
12276                                 CHECK_OPSIZE (4);
12277                                 n = read16 (ip + 2);
12278                                 CHECK_LOCAL (n);
12279                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12280                                 *sp++ = ins;
12281                                 ip += 4;
12282                                 break;
12283                         case CEE_LDLOCA: {
12284                                 unsigned char *tmp_ip;
12285                                 CHECK_STACK_OVF (1);
12286                                 CHECK_OPSIZE (4);
12287                                 n = read16 (ip + 2);
12288                                 CHECK_LOCAL (n);
12289
12290                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12291                                         ip = tmp_ip;
12292                                         inline_costs += 1;
12293                                         break;
12294                                 }                       
12295                                 
12296                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12297                                 *sp++ = ins;
12298                                 ip += 4;
12299                                 break;
12300                         }
12301                         case CEE_STLOC:
12302                                 CHECK_STACK (1);
12303                                 --sp;
12304                                 CHECK_OPSIZE (4);
12305                                 n = read16 (ip + 2);
12306                                 CHECK_LOCAL (n);
12307                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12308                                         UNVERIFIED;
12309                                 emit_stloc_ir (cfg, sp, header, n);
12310                                 ip += 4;
12311                                 inline_costs += 1;
12312                                 break;
12313                         case CEE_LOCALLOC: {
12314                                 CHECK_STACK (1);
12315                                 MonoBasicBlock *non_zero_bb, *end_bb;
12316                                 int alloc_ptr = alloc_preg (cfg);
12317                                 --sp;
12318                                 if (sp != stack_start) 
12319                                         UNVERIFIED;
12320                                 if (cfg->method != method) 
12321                                         /* 
12322                                          * Inlining this into a loop in a parent could lead to 
12323                                          * stack overflows which is different behavior than the
12324                                          * non-inlined case, thus disable inlining in this case.
12325                                          */
12326                                         INLINE_FAILURE("localloc");
12327
12328                                 NEW_BBLOCK (cfg, non_zero_bb);
12329                                 NEW_BBLOCK (cfg, end_bb);
12330
12331                                 /* if size != zero */
12332                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12333                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12334
12335                                 //size is zero, so result is NULL
12336                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12337                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12338
12339                                 MONO_START_BB (cfg, non_zero_bb);
12340                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12341                                 ins->dreg = alloc_ptr;
12342                                 ins->sreg1 = sp [0]->dreg;
12343                                 ins->type = STACK_PTR;
12344                                 MONO_ADD_INS (cfg->cbb, ins);
12345
12346                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12347                                 if (init_locals)
12348                                         ins->flags |= MONO_INST_INIT;
12349
12350                                 MONO_START_BB (cfg, end_bb);
12351                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12352                                 ins->type = STACK_PTR;
12353
12354                                 *sp++ = ins;
12355                                 ip += 2;
12356                                 break;
12357                         }
12358                         case CEE_ENDFILTER: {
12359                                 MonoExceptionClause *clause, *nearest;
12360                                 int cc;
12361
12362                                 CHECK_STACK (1);
12363                                 --sp;
12364                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12365                                         UNVERIFIED;
12366                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12367                                 ins->sreg1 = (*sp)->dreg;
12368                                 MONO_ADD_INS (cfg->cbb, ins);
12369                                 start_new_bblock = 1;
12370                                 ip += 2;
12371
12372                                 nearest = NULL;
12373                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12374                                         clause = &header->clauses [cc];
12375                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12376                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12377                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12378                                                 nearest = clause;
12379                                 }
12380                                 g_assert (nearest);
12381                                 if ((ip - header->code) != nearest->handler_offset)
12382                                         UNVERIFIED;
12383
12384                                 break;
12385                         }
12386                         case CEE_UNALIGNED_:
12387                                 ins_flag |= MONO_INST_UNALIGNED;
12388                                 /* FIXME: record alignment? we can assume 1 for now */
12389                                 CHECK_OPSIZE (3);
12390                                 ip += 3;
12391                                 break;
12392                         case CEE_VOLATILE_:
12393                                 ins_flag |= MONO_INST_VOLATILE;
12394                                 ip += 2;
12395                                 break;
12396                         case CEE_TAIL_:
12397                                 ins_flag   |= MONO_INST_TAILCALL;
12398                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12399                                 /* Can't inline tail calls at this time */
12400                                 inline_costs += 100000;
12401                                 ip += 2;
12402                                 break;
12403                         case CEE_INITOBJ:
12404                                 CHECK_STACK (1);
12405                                 --sp;
12406                                 CHECK_OPSIZE (6);
12407                                 token = read32 (ip + 2);
12408                                 klass = mini_get_class (method, token, generic_context);
12409                                 CHECK_TYPELOAD (klass);
12410                                 if (generic_class_is_reference_type (cfg, klass))
12411                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12412                                 else
12413                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12414                                 ip += 6;
12415                                 inline_costs += 1;
12416                                 break;
12417                         case CEE_CONSTRAINED_:
12418                                 CHECK_OPSIZE (6);
12419                                 token = read32 (ip + 2);
12420                                 constrained_class = mini_get_class (method, token, generic_context);
12421                                 CHECK_TYPELOAD (constrained_class);
12422                                 ip += 6;
12423                                 break;
12424                         case CEE_CPBLK:
12425                                 CHECK_STACK (3);
12426                                 sp -= 3;
12427                                 mini_emit_memory_copy_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12428                                 ip += 2;
12429                                 ins_flag = 0;
12430                                 inline_costs += 1;
12431                                 break;
12432                         case CEE_INITBLK:
12433                                 CHECK_STACK (3);
12434                                 sp -= 3;
12435                                 mini_emit_memory_init_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12436                                 ip += 2;
12437                                 ins_flag = 0;
12438                                 inline_costs += 1;
12439                                 break;
12440                         case CEE_NO_:
12441                                 CHECK_OPSIZE (3);
12442                                 if (ip [2] & 0x1)
12443                                         ins_flag |= MONO_INST_NOTYPECHECK;
12444                                 if (ip [2] & 0x2)
12445                                         ins_flag |= MONO_INST_NORANGECHECK;
12446                                 /* we ignore the no-nullcheck for now since we
12447                                  * really do it explicitly only when doing callvirt->call
12448                                  */
12449                                 ip += 3;
12450                                 break;
12451                         case CEE_RETHROW: {
12452                                 MonoInst *load;
12453                                 int handler_offset = -1;
12454
12455                                 for (i = 0; i < header->num_clauses; ++i) {
12456                                         MonoExceptionClause *clause = &header->clauses [i];
12457                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12458                                                 handler_offset = clause->handler_offset;
12459                                                 break;
12460                                         }
12461                                 }
12462
12463                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12464
12465                                 if (handler_offset == -1)
12466                                         UNVERIFIED;
12467
12468                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12469                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12470                                 ins->sreg1 = load->dreg;
12471                                 MONO_ADD_INS (cfg->cbb, ins);
12472
12473                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12474                                 MONO_ADD_INS (cfg->cbb, ins);
12475
12476                                 sp = stack_start;
12477                                 link_bblock (cfg, cfg->cbb, end_bblock);
12478                                 start_new_bblock = 1;
12479                                 ip += 2;
12480                                 break;
12481                         }
12482                         case CEE_SIZEOF: {
12483                                 guint32 val;
12484                                 int ialign;
12485
12486                                 CHECK_STACK_OVF (1);
12487                                 CHECK_OPSIZE (6);
12488                                 token = read32 (ip + 2);
12489                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12490                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12491                                         CHECK_CFG_ERROR;
12492
12493                                         val = mono_type_size (type, &ialign);
12494                                 } else {
12495                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12496                                         CHECK_TYPELOAD (klass);
12497
12498                                         val = mono_type_size (&klass->byval_arg, &ialign);
12499
12500                                         if (mini_is_gsharedvt_klass (klass))
12501                                                 GSHAREDVT_FAILURE (*ip);
12502                                 }
12503                                 EMIT_NEW_ICONST (cfg, ins, val);
12504                                 *sp++= ins;
12505                                 ip += 6;
12506                                 break;
12507                         }
12508                         case CEE_REFANYTYPE: {
12509                                 MonoInst *src_var, *src;
12510
12511                                 GSHAREDVT_FAILURE (*ip);
12512
12513                                 CHECK_STACK (1);
12514                                 --sp;
12515
12516                                 // FIXME:
12517                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12518                                 if (!src_var)
12519                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12520                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12521                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12522                                 *sp++ = ins;
12523                                 ip += 2;
12524                                 break;
12525                         }
12526                         case CEE_READONLY_:
12527                                 readonly = TRUE;
12528                                 ip += 2;
12529                                 break;
12530
12531                         case CEE_UNUSED56:
12532                         case CEE_UNUSED57:
12533                         case CEE_UNUSED70:
12534                         case CEE_UNUSED:
12535                         case CEE_UNUSED99:
12536                                 UNVERIFIED;
12537                                 
12538                         default:
12539                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12540                                 UNVERIFIED;
12541                         }
12542                         break;
12543                 }
12544                 case CEE_UNUSED58:
12545                 case CEE_UNUSED1:
12546                         UNVERIFIED;
12547
12548                 default:
12549                         g_warning ("opcode 0x%02x not handled", *ip);
12550                         UNVERIFIED;
12551                 }
12552         }
12553         if (start_new_bblock != 1)
12554                 UNVERIFIED;
12555
12556         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12557         if (cfg->cbb->next_bb) {
12558                 /* This could already be set because of inlining, #693905 */
12559                 MonoBasicBlock *bb = cfg->cbb;
12560
12561                 while (bb->next_bb)
12562                         bb = bb->next_bb;
12563                 bb->next_bb = end_bblock;
12564         } else {
12565                 cfg->cbb->next_bb = end_bblock;
12566         }
12567
12568         if (cfg->method == method && cfg->domainvar) {
12569                 MonoInst *store;
12570                 MonoInst *get_domain;
12571
12572                 cfg->cbb = init_localsbb;
12573
12574                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12575                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12576                 MONO_ADD_INS (cfg->cbb, store);
12577         }
12578
12579 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12580         if (cfg->compile_aot)
12581                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12582                 mono_get_got_var (cfg);
12583 #endif
12584
12585         if (cfg->method == method && cfg->got_var)
12586                 mono_emit_load_got_addr (cfg);
12587
12588         if (init_localsbb) {
12589                 cfg->cbb = init_localsbb;
12590                 cfg->ip = NULL;
12591                 for (i = 0; i < header->num_locals; ++i) {
12592                         emit_init_local (cfg, i, header->locals [i], init_locals);
12593                 }
12594         }
12595
12596         if (cfg->init_ref_vars && cfg->method == method) {
12597                 /* Emit initialization for ref vars */
12598                 // FIXME: Avoid duplication initialization for IL locals.
12599                 for (i = 0; i < cfg->num_varinfo; ++i) {
12600                         MonoInst *ins = cfg->varinfo [i];
12601
12602                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12603                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12604                 }
12605         }
12606
12607         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12608                 cfg->cbb = init_localsbb;
12609                 emit_push_lmf (cfg);
12610         }
12611
12612         cfg->cbb = init_localsbb;
12613         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12614
12615         if (seq_points) {
12616                 MonoBasicBlock *bb;
12617
12618                 /*
12619                  * Make seq points at backward branch targets interruptable.
12620                  */
12621                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12622                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12623                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12624         }
12625
12626         /* Add a sequence point for method entry/exit events */
12627         if (seq_points && cfg->gen_sdb_seq_points) {
12628                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12629                 MONO_ADD_INS (init_localsbb, ins);
12630                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12631                 MONO_ADD_INS (cfg->bb_exit, ins);
12632         }
12633
12634         /*
12635          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12636          * the code they refer to was dead (#11880).
12637          */
12638         if (sym_seq_points) {
12639                 for (i = 0; i < header->code_size; ++i) {
12640                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12641                                 MonoInst *ins;
12642
12643                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12644                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12645                         }
12646                 }
12647         }
12648
12649         cfg->ip = NULL;
12650
12651         if (cfg->method == method) {
12652                 MonoBasicBlock *bb;
12653                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12654                         if (bb == cfg->bb_init)
12655                                 bb->region = -1;
12656                         else
12657                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12658                         if (cfg->spvars)
12659                                 mono_create_spvar_for_region (cfg, bb->region);
12660                         if (cfg->verbose_level > 2)
12661                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12662                 }
12663         } else {
12664                 MonoBasicBlock *bb;
12665                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12666                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12667                         bb->real_offset = inline_offset;
12668                 }
12669         }
12670
12671         if (inline_costs < 0) {
12672                 char *mname;
12673
12674                 /* Method is too large */
12675                 mname = mono_method_full_name (method, TRUE);
12676                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12677                 g_free (mname);
12678         }
12679
12680         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12681                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12682
12683         goto cleanup;
12684
12685 mono_error_exit:
12686         g_assert (!mono_error_ok (&cfg->error));
12687         goto cleanup;
12688  
12689  exception_exit:
12690         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12691         goto cleanup;
12692
12693  unverified:
12694         set_exception_type_from_invalid_il (cfg, method, ip);
12695         goto cleanup;
12696
12697  cleanup:
12698         g_slist_free (class_inits);
12699         mono_basic_block_free (original_bb);
12700         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12701         if (cfg->exception_type)
12702                 return -1;
12703         else
12704                 return inline_costs;
12705 }
12706
12707 static int
12708 store_membase_reg_to_store_membase_imm (int opcode)
12709 {
12710         switch (opcode) {
12711         case OP_STORE_MEMBASE_REG:
12712                 return OP_STORE_MEMBASE_IMM;
12713         case OP_STOREI1_MEMBASE_REG:
12714                 return OP_STOREI1_MEMBASE_IMM;
12715         case OP_STOREI2_MEMBASE_REG:
12716                 return OP_STOREI2_MEMBASE_IMM;
12717         case OP_STOREI4_MEMBASE_REG:
12718                 return OP_STOREI4_MEMBASE_IMM;
12719         case OP_STOREI8_MEMBASE_REG:
12720                 return OP_STOREI8_MEMBASE_IMM;
12721         default:
12722                 g_assert_not_reached ();
12723         }
12724
12725         return -1;
12726 }               
12727
12728 int
12729 mono_op_to_op_imm (int opcode)
12730 {
12731         switch (opcode) {
12732         case OP_IADD:
12733                 return OP_IADD_IMM;
12734         case OP_ISUB:
12735                 return OP_ISUB_IMM;
12736         case OP_IDIV:
12737                 return OP_IDIV_IMM;
12738         case OP_IDIV_UN:
12739                 return OP_IDIV_UN_IMM;
12740         case OP_IREM:
12741                 return OP_IREM_IMM;
12742         case OP_IREM_UN:
12743                 return OP_IREM_UN_IMM;
12744         case OP_IMUL:
12745                 return OP_IMUL_IMM;
12746         case OP_IAND:
12747                 return OP_IAND_IMM;
12748         case OP_IOR:
12749                 return OP_IOR_IMM;
12750         case OP_IXOR:
12751                 return OP_IXOR_IMM;
12752         case OP_ISHL:
12753                 return OP_ISHL_IMM;
12754         case OP_ISHR:
12755                 return OP_ISHR_IMM;
12756         case OP_ISHR_UN:
12757                 return OP_ISHR_UN_IMM;
12758
12759         case OP_LADD:
12760                 return OP_LADD_IMM;
12761         case OP_LSUB:
12762                 return OP_LSUB_IMM;
12763         case OP_LAND:
12764                 return OP_LAND_IMM;
12765         case OP_LOR:
12766                 return OP_LOR_IMM;
12767         case OP_LXOR:
12768                 return OP_LXOR_IMM;
12769         case OP_LSHL:
12770                 return OP_LSHL_IMM;
12771         case OP_LSHR:
12772                 return OP_LSHR_IMM;
12773         case OP_LSHR_UN:
12774                 return OP_LSHR_UN_IMM;
12775 #if SIZEOF_REGISTER == 8
12776         case OP_LREM:
12777                 return OP_LREM_IMM;
12778 #endif
12779
12780         case OP_COMPARE:
12781                 return OP_COMPARE_IMM;
12782         case OP_ICOMPARE:
12783                 return OP_ICOMPARE_IMM;
12784         case OP_LCOMPARE:
12785                 return OP_LCOMPARE_IMM;
12786
12787         case OP_STORE_MEMBASE_REG:
12788                 return OP_STORE_MEMBASE_IMM;
12789         case OP_STOREI1_MEMBASE_REG:
12790                 return OP_STOREI1_MEMBASE_IMM;
12791         case OP_STOREI2_MEMBASE_REG:
12792                 return OP_STOREI2_MEMBASE_IMM;
12793         case OP_STOREI4_MEMBASE_REG:
12794                 return OP_STOREI4_MEMBASE_IMM;
12795
12796 #if defined(TARGET_X86) || defined (TARGET_AMD64)
12797         case OP_X86_PUSH:
12798                 return OP_X86_PUSH_IMM;
12799         case OP_X86_COMPARE_MEMBASE_REG:
12800                 return OP_X86_COMPARE_MEMBASE_IMM;
12801 #endif
12802 #if defined(TARGET_AMD64)
12803         case OP_AMD64_ICOMPARE_MEMBASE_REG:
12804                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
12805 #endif
12806         case OP_VOIDCALL_REG:
12807                 return OP_VOIDCALL;
12808         case OP_CALL_REG:
12809                 return OP_CALL;
12810         case OP_LCALL_REG:
12811                 return OP_LCALL;
12812         case OP_FCALL_REG:
12813                 return OP_FCALL;
12814         case OP_LOCALLOC:
12815                 return OP_LOCALLOC_IMM;
12816         }
12817
12818         return -1;
12819 }
12820
12821 static int
12822 ldind_to_load_membase (int opcode)
12823 {
12824         switch (opcode) {
12825         case CEE_LDIND_I1:
12826                 return OP_LOADI1_MEMBASE;
12827         case CEE_LDIND_U1:
12828                 return OP_LOADU1_MEMBASE;
12829         case CEE_LDIND_I2:
12830                 return OP_LOADI2_MEMBASE;
12831         case CEE_LDIND_U2:
12832                 return OP_LOADU2_MEMBASE;
12833         case CEE_LDIND_I4:
12834                 return OP_LOADI4_MEMBASE;
12835         case CEE_LDIND_U4:
12836                 return OP_LOADU4_MEMBASE;
12837         case CEE_LDIND_I:
12838                 return OP_LOAD_MEMBASE;
12839         case CEE_LDIND_REF:
12840                 return OP_LOAD_MEMBASE;
12841         case CEE_LDIND_I8:
12842                 return OP_LOADI8_MEMBASE;
12843         case CEE_LDIND_R4:
12844                 return OP_LOADR4_MEMBASE;
12845         case CEE_LDIND_R8:
12846                 return OP_LOADR8_MEMBASE;
12847         default:
12848                 g_assert_not_reached ();
12849         }
12850
12851         return -1;
12852 }
12853
12854 static int
12855 stind_to_store_membase (int opcode)
12856 {
12857         switch (opcode) {
12858         case CEE_STIND_I1:
12859                 return OP_STOREI1_MEMBASE_REG;
12860         case CEE_STIND_I2:
12861                 return OP_STOREI2_MEMBASE_REG;
12862         case CEE_STIND_I4:
12863                 return OP_STOREI4_MEMBASE_REG;
12864         case CEE_STIND_I:
12865         case CEE_STIND_REF:
12866                 return OP_STORE_MEMBASE_REG;
12867         case CEE_STIND_I8:
12868                 return OP_STOREI8_MEMBASE_REG;
12869         case CEE_STIND_R4:
12870                 return OP_STORER4_MEMBASE_REG;
12871         case CEE_STIND_R8:
12872                 return OP_STORER8_MEMBASE_REG;
12873         default:
12874                 g_assert_not_reached ();
12875         }
12876
12877         return -1;
12878 }
12879
12880 int
12881 mono_load_membase_to_load_mem (int opcode)
12882 {
12883         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
12884 #if defined(TARGET_X86) || defined(TARGET_AMD64)
12885         switch (opcode) {
12886         case OP_LOAD_MEMBASE:
12887                 return OP_LOAD_MEM;
12888         case OP_LOADU1_MEMBASE:
12889                 return OP_LOADU1_MEM;
12890         case OP_LOADU2_MEMBASE:
12891                 return OP_LOADU2_MEM;
12892         case OP_LOADI4_MEMBASE:
12893                 return OP_LOADI4_MEM;
12894         case OP_LOADU4_MEMBASE:
12895                 return OP_LOADU4_MEM;
12896 #if SIZEOF_REGISTER == 8
12897         case OP_LOADI8_MEMBASE:
12898                 return OP_LOADI8_MEM;
12899 #endif
12900         }
12901 #endif
12902
12903         return -1;
12904 }
12905
12906 static inline int
12907 op_to_op_dest_membase (int store_opcode, int opcode)
12908 {
12909 #if defined(TARGET_X86)
12910         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
12911                 return -1;
12912
12913         switch (opcode) {
12914         case OP_IADD:
12915                 return OP_X86_ADD_MEMBASE_REG;
12916         case OP_ISUB:
12917                 return OP_X86_SUB_MEMBASE_REG;
12918         case OP_IAND:
12919                 return OP_X86_AND_MEMBASE_REG;
12920         case OP_IOR:
12921                 return OP_X86_OR_MEMBASE_REG;
12922         case OP_IXOR:
12923                 return OP_X86_XOR_MEMBASE_REG;
12924         case OP_ADD_IMM:
12925         case OP_IADD_IMM:
12926                 return OP_X86_ADD_MEMBASE_IMM;
12927         case OP_SUB_IMM:
12928         case OP_ISUB_IMM:
12929                 return OP_X86_SUB_MEMBASE_IMM;
12930         case OP_AND_IMM:
12931         case OP_IAND_IMM:
12932                 return OP_X86_AND_MEMBASE_IMM;
12933         case OP_OR_IMM:
12934         case OP_IOR_IMM:
12935                 return OP_X86_OR_MEMBASE_IMM;
12936         case OP_XOR_IMM:
12937         case OP_IXOR_IMM:
12938                 return OP_X86_XOR_MEMBASE_IMM;
12939         case OP_MOVE:
12940                 return OP_NOP;
12941         }
12942 #endif
12943
12944 #if defined(TARGET_AMD64)
12945         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
12946                 return -1;
12947
12948         switch (opcode) {
12949         case OP_IADD:
12950                 return OP_X86_ADD_MEMBASE_REG;
12951         case OP_ISUB:
12952                 return OP_X86_SUB_MEMBASE_REG;
12953         case OP_IAND:
12954                 return OP_X86_AND_MEMBASE_REG;
12955         case OP_IOR:
12956                 return OP_X86_OR_MEMBASE_REG;
12957         case OP_IXOR:
12958                 return OP_X86_XOR_MEMBASE_REG;
12959         case OP_IADD_IMM:
12960                 return OP_X86_ADD_MEMBASE_IMM;
12961         case OP_ISUB_IMM:
12962                 return OP_X86_SUB_MEMBASE_IMM;
12963         case OP_IAND_IMM:
12964                 return OP_X86_AND_MEMBASE_IMM;
12965         case OP_IOR_IMM:
12966                 return OP_X86_OR_MEMBASE_IMM;
12967         case OP_IXOR_IMM:
12968                 return OP_X86_XOR_MEMBASE_IMM;
12969         case OP_LADD:
12970                 return OP_AMD64_ADD_MEMBASE_REG;
12971         case OP_LSUB:
12972                 return OP_AMD64_SUB_MEMBASE_REG;
12973         case OP_LAND:
12974                 return OP_AMD64_AND_MEMBASE_REG;
12975         case OP_LOR:
12976                 return OP_AMD64_OR_MEMBASE_REG;
12977         case OP_LXOR:
12978                 return OP_AMD64_XOR_MEMBASE_REG;
12979         case OP_ADD_IMM:
12980         case OP_LADD_IMM:
12981                 return OP_AMD64_ADD_MEMBASE_IMM;
12982         case OP_SUB_IMM:
12983         case OP_LSUB_IMM:
12984                 return OP_AMD64_SUB_MEMBASE_IMM;
12985         case OP_AND_IMM:
12986         case OP_LAND_IMM:
12987                 return OP_AMD64_AND_MEMBASE_IMM;
12988         case OP_OR_IMM:
12989         case OP_LOR_IMM:
12990                 return OP_AMD64_OR_MEMBASE_IMM;
12991         case OP_XOR_IMM:
12992         case OP_LXOR_IMM:
12993                 return OP_AMD64_XOR_MEMBASE_IMM;
12994         case OP_MOVE:
12995                 return OP_NOP;
12996         }
12997 #endif
12998
12999         return -1;
13000 }
13001
13002 static inline int
13003 op_to_op_store_membase (int store_opcode, int opcode)
13004 {
13005 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13006         switch (opcode) {
13007         case OP_ICEQ:
13008                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13009                         return OP_X86_SETEQ_MEMBASE;
13010         case OP_CNE:
13011                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13012                         return OP_X86_SETNE_MEMBASE;
13013         }
13014 #endif
13015
13016         return -1;
13017 }
13018
13019 static inline int
13020 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13021 {
13022 #ifdef TARGET_X86
13023         /* FIXME: This has sign extension issues */
13024         /*
13025         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13026                 return OP_X86_COMPARE_MEMBASE8_IMM;
13027         */
13028
13029         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13030                 return -1;
13031
13032         switch (opcode) {
13033         case OP_X86_PUSH:
13034                 return OP_X86_PUSH_MEMBASE;
13035         case OP_COMPARE_IMM:
13036         case OP_ICOMPARE_IMM:
13037                 return OP_X86_COMPARE_MEMBASE_IMM;
13038         case OP_COMPARE:
13039         case OP_ICOMPARE:
13040                 return OP_X86_COMPARE_MEMBASE_REG;
13041         }
13042 #endif
13043
13044 #ifdef TARGET_AMD64
13045         /* FIXME: This has sign extension issues */
13046         /*
13047         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13048                 return OP_X86_COMPARE_MEMBASE8_IMM;
13049         */
13050
13051         switch (opcode) {
13052         case OP_X86_PUSH:
13053                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13054                         return OP_X86_PUSH_MEMBASE;
13055                 break;
13056                 /* FIXME: This only works for 32 bit immediates
13057         case OP_COMPARE_IMM:
13058         case OP_LCOMPARE_IMM:
13059                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13060                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13061                 */
13062         case OP_ICOMPARE_IMM:
13063                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13064                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13065                 break;
13066         case OP_COMPARE:
13067         case OP_LCOMPARE:
13068                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13069                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13070                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13071                         return OP_AMD64_COMPARE_MEMBASE_REG;
13072                 break;
13073         case OP_ICOMPARE:
13074                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13075                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13076                 break;
13077         }
13078 #endif
13079
13080         return -1;
13081 }
13082
13083 static inline int
13084 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13085 {
13086 #ifdef TARGET_X86
13087         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13088                 return -1;
13089         
13090         switch (opcode) {
13091         case OP_COMPARE:
13092         case OP_ICOMPARE:
13093                 return OP_X86_COMPARE_REG_MEMBASE;
13094         case OP_IADD:
13095                 return OP_X86_ADD_REG_MEMBASE;
13096         case OP_ISUB:
13097                 return OP_X86_SUB_REG_MEMBASE;
13098         case OP_IAND:
13099                 return OP_X86_AND_REG_MEMBASE;
13100         case OP_IOR:
13101                 return OP_X86_OR_REG_MEMBASE;
13102         case OP_IXOR:
13103                 return OP_X86_XOR_REG_MEMBASE;
13104         }
13105 #endif
13106
13107 #ifdef TARGET_AMD64
13108         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13109                 switch (opcode) {
13110                 case OP_ICOMPARE:
13111                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13112                 case OP_IADD:
13113                         return OP_X86_ADD_REG_MEMBASE;
13114                 case OP_ISUB:
13115                         return OP_X86_SUB_REG_MEMBASE;
13116                 case OP_IAND:
13117                         return OP_X86_AND_REG_MEMBASE;
13118                 case OP_IOR:
13119                         return OP_X86_OR_REG_MEMBASE;
13120                 case OP_IXOR:
13121                         return OP_X86_XOR_REG_MEMBASE;
13122                 }
13123         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13124                 switch (opcode) {
13125                 case OP_COMPARE:
13126                 case OP_LCOMPARE:
13127                         return OP_AMD64_COMPARE_REG_MEMBASE;
13128                 case OP_LADD:
13129                         return OP_AMD64_ADD_REG_MEMBASE;
13130                 case OP_LSUB:
13131                         return OP_AMD64_SUB_REG_MEMBASE;
13132                 case OP_LAND:
13133                         return OP_AMD64_AND_REG_MEMBASE;
13134                 case OP_LOR:
13135                         return OP_AMD64_OR_REG_MEMBASE;
13136                 case OP_LXOR:
13137                         return OP_AMD64_XOR_REG_MEMBASE;
13138                 }
13139         }
13140 #endif
13141
13142         return -1;
13143 }
13144
13145 int
13146 mono_op_to_op_imm_noemul (int opcode)
13147 {
13148         switch (opcode) {
13149 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13150         case OP_LSHR:
13151         case OP_LSHL:
13152         case OP_LSHR_UN:
13153                 return -1;
13154 #endif
13155 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13156         case OP_IDIV:
13157         case OP_IDIV_UN:
13158         case OP_IREM:
13159         case OP_IREM_UN:
13160                 return -1;
13161 #endif
13162 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13163         case OP_IMUL:
13164                 return -1;
13165 #endif
13166         default:
13167                 return mono_op_to_op_imm (opcode);
13168         }
13169 }
13170
13171 /**
13172  * mono_handle_global_vregs:
13173  *
13174  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13175  * for them.
13176  */
13177 void
13178 mono_handle_global_vregs (MonoCompile *cfg)
13179 {
13180         gint32 *vreg_to_bb;
13181         MonoBasicBlock *bb;
13182         int i, pos;
13183
13184         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13185
13186 #ifdef MONO_ARCH_SIMD_INTRINSICS
13187         if (cfg->uses_simd_intrinsics)
13188                 mono_simd_simplify_indirection (cfg);
13189 #endif
13190
13191         /* Find local vregs used in more than one bb */
13192         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13193                 MonoInst *ins = bb->code;       
13194                 int block_num = bb->block_num;
13195
13196                 if (cfg->verbose_level > 2)
13197                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13198
13199                 cfg->cbb = bb;
13200                 for (; ins; ins = ins->next) {
13201                         const char *spec = INS_INFO (ins->opcode);
13202                         int regtype = 0, regindex;
13203                         gint32 prev_bb;
13204
13205                         if (G_UNLIKELY (cfg->verbose_level > 2))
13206                                 mono_print_ins (ins);
13207
13208                         g_assert (ins->opcode >= MONO_CEE_LAST);
13209
13210                         for (regindex = 0; regindex < 4; regindex ++) {
13211                                 int vreg = 0;
13212
13213                                 if (regindex == 0) {
13214                                         regtype = spec [MONO_INST_DEST];
13215                                         if (regtype == ' ')
13216                                                 continue;
13217                                         vreg = ins->dreg;
13218                                 } else if (regindex == 1) {
13219                                         regtype = spec [MONO_INST_SRC1];
13220                                         if (regtype == ' ')
13221                                                 continue;
13222                                         vreg = ins->sreg1;
13223                                 } else if (regindex == 2) {
13224                                         regtype = spec [MONO_INST_SRC2];
13225                                         if (regtype == ' ')
13226                                                 continue;
13227                                         vreg = ins->sreg2;
13228                                 } else if (regindex == 3) {
13229                                         regtype = spec [MONO_INST_SRC3];
13230                                         if (regtype == ' ')
13231                                                 continue;
13232                                         vreg = ins->sreg3;
13233                                 }
13234
13235 #if SIZEOF_REGISTER == 4
13236                                 /* In the LLVM case, the long opcodes are not decomposed */
13237                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13238                                         /*
13239                                          * Since some instructions reference the original long vreg,
13240                                          * and some reference the two component vregs, it is quite hard
13241                                          * to determine when it needs to be global. So be conservative.
13242                                          */
13243                                         if (!get_vreg_to_inst (cfg, vreg)) {
13244                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13245
13246                                                 if (cfg->verbose_level > 2)
13247                                                         printf ("LONG VREG R%d made global.\n", vreg);
13248                                         }
13249
13250                                         /*
13251                                          * Make the component vregs volatile since the optimizations can
13252                                          * get confused otherwise.
13253                                          */
13254                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13255                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13256                                 }
13257 #endif
13258
13259                                 g_assert (vreg != -1);
13260
13261                                 prev_bb = vreg_to_bb [vreg];
13262                                 if (prev_bb == 0) {
13263                                         /* 0 is a valid block num */
13264                                         vreg_to_bb [vreg] = block_num + 1;
13265                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13266                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13267                                                 continue;
13268
13269                                         if (!get_vreg_to_inst (cfg, vreg)) {
13270                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13271                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13272
13273                                                 switch (regtype) {
13274                                                 case 'i':
13275                                                         if (vreg_is_ref (cfg, vreg))
13276                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13277                                                         else
13278                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13279                                                         break;
13280                                                 case 'l':
13281                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13282                                                         break;
13283                                                 case 'f':
13284                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13285                                                         break;
13286                                                 case 'v':
13287                                                 case 'x':
13288                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13289                                                         break;
13290                                                 default:
13291                                                         g_assert_not_reached ();
13292                                                 }
13293                                         }
13294
13295                                         /* Flag as having been used in more than one bb */
13296                                         vreg_to_bb [vreg] = -1;
13297                                 }
13298                         }
13299                 }
13300         }
13301
13302         /* If a variable is used in only one bblock, convert it into a local vreg */
13303         for (i = 0; i < cfg->num_varinfo; i++) {
13304                 MonoInst *var = cfg->varinfo [i];
13305                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13306
13307                 switch (var->type) {
13308                 case STACK_I4:
13309                 case STACK_OBJ:
13310                 case STACK_PTR:
13311                 case STACK_MP:
13312                 case STACK_VTYPE:
13313 #if SIZEOF_REGISTER == 8
13314                 case STACK_I8:
13315 #endif
13316 #if !defined(TARGET_X86)
13317                 /* Enabling this screws up the fp stack on x86 */
13318                 case STACK_R8:
13319 #endif
13320                         if (mono_arch_is_soft_float ())
13321                                 break;
13322
13323                         /*
13324                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13325                                 break;
13326                         */
13327
13328                         /* Arguments are implicitly global */
13329                         /* Putting R4 vars into registers doesn't work currently */
13330                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13331                         if ((var->opcode != OP_ARG) && (var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && (vreg_to_bb [var->dreg] != -1) && (var->klass->byval_arg.type != MONO_TYPE_R4) && !cfg->disable_vreg_to_lvreg && var != cfg->gsharedvt_info_var && var != cfg->gsharedvt_locals_var && var != cfg->lmf_addr_var) {
13332                                 /* 
13333                                  * Make that the variable's liveness interval doesn't contain a call, since
13334                                  * that would cause the lvreg to be spilled, making the whole optimization
13335                                  * useless.
13336                                  */
13337                                 /* This is too slow for JIT compilation */
13338 #if 0
13339                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13340                                         MonoInst *ins;
13341                                         int def_index, call_index, ins_index;
13342                                         gboolean spilled = FALSE;
13343
13344                                         def_index = -1;
13345                                         call_index = -1;
13346                                         ins_index = 0;
13347                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13348                                                 const char *spec = INS_INFO (ins->opcode);
13349
13350                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13351                                                         def_index = ins_index;
13352
13353                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13354                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13355                                                         if (call_index > def_index) {
13356                                                                 spilled = TRUE;
13357                                                                 break;
13358                                                         }
13359                                                 }
13360
13361                                                 if (MONO_IS_CALL (ins))
13362                                                         call_index = ins_index;
13363
13364                                                 ins_index ++;
13365                                         }
13366
13367                                         if (spilled)
13368                                                 break;
13369                                 }
13370 #endif
13371
13372                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13373                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13374                                 var->flags |= MONO_INST_IS_DEAD;
13375                                 cfg->vreg_to_inst [var->dreg] = NULL;
13376                         }
13377                         break;
13378                 }
13379         }
13380
13381         /* 
13382          * Compress the varinfo and vars tables so the liveness computation is faster and
13383          * takes up less space.
13384          */
13385         pos = 0;
13386         for (i = 0; i < cfg->num_varinfo; ++i) {
13387                 MonoInst *var = cfg->varinfo [i];
13388                 if (pos < i && cfg->locals_start == i)
13389                         cfg->locals_start = pos;
13390                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13391                         if (pos < i) {
13392                                 cfg->varinfo [pos] = cfg->varinfo [i];
13393                                 cfg->varinfo [pos]->inst_c0 = pos;
13394                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13395                                 cfg->vars [pos].idx = pos;
13396 #if SIZEOF_REGISTER == 4
13397                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13398                                         /* Modify the two component vars too */
13399                                         MonoInst *var1;
13400
13401                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13402                                         var1->inst_c0 = pos;
13403                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13404                                         var1->inst_c0 = pos;
13405                                 }
13406 #endif
13407                         }
13408                         pos ++;
13409                 }
13410         }
13411         cfg->num_varinfo = pos;
13412         if (cfg->locals_start > cfg->num_varinfo)
13413                 cfg->locals_start = cfg->num_varinfo;
13414 }
13415
13416 /*
13417  * mono_allocate_gsharedvt_vars:
13418  *
13419  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13420  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13421  */
13422 void
13423 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13424 {
13425         int i;
13426
13427         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13428
13429         for (i = 0; i < cfg->num_varinfo; ++i) {
13430                 MonoInst *ins = cfg->varinfo [i];
13431                 int idx;
13432
13433                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13434                         if (i >= cfg->locals_start) {
13435                                 /* Local */
13436                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13437                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13438                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13439                                 ins->inst_imm = idx;
13440                         } else {
13441                                 /* Arg */
13442                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13443                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13444                         }
13445                 }
13446         }
13447 }
13448
13449 /**
13450  * mono_spill_global_vars:
13451  *
13452  *   Generate spill code for variables which are not allocated to registers, 
13453  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13454  * code is generated which could be optimized by the local optimization passes.
13455  */
13456 void
13457 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13458 {
13459         MonoBasicBlock *bb;
13460         char spec2 [16];
13461         int orig_next_vreg;
13462         guint32 *vreg_to_lvreg;
13463         guint32 *lvregs;
13464         guint32 i, lvregs_len, lvregs_size;
13465         gboolean dest_has_lvreg = FALSE;
13466         MonoStackType stacktypes [128];
13467         MonoInst **live_range_start, **live_range_end;
13468         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13469
13470         *need_local_opts = FALSE;
13471
13472         memset (spec2, 0, sizeof (spec2));
13473
13474         /* FIXME: Move this function to mini.c */
13475         stacktypes ['i'] = STACK_PTR;
13476         stacktypes ['l'] = STACK_I8;
13477         stacktypes ['f'] = STACK_R8;
13478 #ifdef MONO_ARCH_SIMD_INTRINSICS
13479         stacktypes ['x'] = STACK_VTYPE;
13480 #endif
13481
13482 #if SIZEOF_REGISTER == 4
13483         /* Create MonoInsts for longs */
13484         for (i = 0; i < cfg->num_varinfo; i++) {
13485                 MonoInst *ins = cfg->varinfo [i];
13486
13487                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13488                         switch (ins->type) {
13489                         case STACK_R8:
13490                         case STACK_I8: {
13491                                 MonoInst *tree;
13492
13493                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13494                                         break;
13495
13496                                 g_assert (ins->opcode == OP_REGOFFSET);
13497
13498                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13499                                 g_assert (tree);
13500                                 tree->opcode = OP_REGOFFSET;
13501                                 tree->inst_basereg = ins->inst_basereg;
13502                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13503
13504                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13505                                 g_assert (tree);
13506                                 tree->opcode = OP_REGOFFSET;
13507                                 tree->inst_basereg = ins->inst_basereg;
13508                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13509                                 break;
13510                         }
13511                         default:
13512                                 break;
13513                         }
13514                 }
13515         }
13516 #endif
13517
13518         if (cfg->compute_gc_maps) {
13519                 /* registers need liveness info even for !non refs */
13520                 for (i = 0; i < cfg->num_varinfo; i++) {
13521                         MonoInst *ins = cfg->varinfo [i];
13522
13523                         if (ins->opcode == OP_REGVAR)
13524                                 ins->flags |= MONO_INST_GC_TRACK;
13525                 }
13526         }
13527                 
13528         /* FIXME: widening and truncation */
13529
13530         /*
13531          * As an optimization, when a variable allocated to the stack is first loaded into 
13532          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13533          * the variable again.
13534          */
13535         orig_next_vreg = cfg->next_vreg;
13536         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13537         lvregs_size = 1024;
13538         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13539         lvregs_len = 0;
13540
13541         /* 
13542          * These arrays contain the first and last instructions accessing a given
13543          * variable.
13544          * Since we emit bblocks in the same order we process them here, and we
13545          * don't split live ranges, these will precisely describe the live range of
13546          * the variable, i.e. the instruction range where a valid value can be found
13547          * in the variables location.
13548          * The live range is computed using the liveness info computed by the liveness pass.
13549          * We can't use vmv->range, since that is an abstract live range, and we need
13550          * one which is instruction precise.
13551          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13552          */
13553         /* FIXME: Only do this if debugging info is requested */
13554         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13555         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13556         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13557         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13558         
13559         /* Add spill loads/stores */
13560         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13561                 MonoInst *ins;
13562
13563                 if (cfg->verbose_level > 2)
13564                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13565
13566                 /* Clear vreg_to_lvreg array */
13567                 for (i = 0; i < lvregs_len; i++)
13568                         vreg_to_lvreg [lvregs [i]] = 0;
13569                 lvregs_len = 0;
13570
13571                 cfg->cbb = bb;
13572                 MONO_BB_FOR_EACH_INS (bb, ins) {
13573                         const char *spec = INS_INFO (ins->opcode);
13574                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13575                         gboolean store, no_lvreg;
13576                         int sregs [MONO_MAX_SRC_REGS];
13577
13578                         if (G_UNLIKELY (cfg->verbose_level > 2))
13579                                 mono_print_ins (ins);
13580
13581                         if (ins->opcode == OP_NOP)
13582                                 continue;
13583
13584                         /* 
13585                          * We handle LDADDR here as well, since it can only be decomposed
13586                          * when variable addresses are known.
13587                          */
13588                         if (ins->opcode == OP_LDADDR) {
13589                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13590
13591                                 if (var->opcode == OP_VTARG_ADDR) {
13592                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13593                                         MonoInst *vtaddr = var->inst_left;
13594                                         if (vtaddr->opcode == OP_REGVAR) {
13595                                                 ins->opcode = OP_MOVE;
13596                                                 ins->sreg1 = vtaddr->dreg;
13597                                         }
13598                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13599                                                 ins->opcode = OP_LOAD_MEMBASE;
13600                                                 ins->inst_basereg = vtaddr->inst_basereg;
13601                                                 ins->inst_offset = vtaddr->inst_offset;
13602                                         } else
13603                                                 NOT_IMPLEMENTED;
13604                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13605                                         /* gsharedvt arg passed by ref */
13606                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13607
13608                                         ins->opcode = OP_LOAD_MEMBASE;
13609                                         ins->inst_basereg = var->inst_basereg;
13610                                         ins->inst_offset = var->inst_offset;
13611                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13612                                         MonoInst *load, *load2, *load3;
13613                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13614                                         int reg1, reg2, reg3;
13615                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13616                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13617
13618                                         /*
13619                                          * gsharedvt local.
13620                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13621                                          */
13622
13623                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13624
13625                                         g_assert (info_var);
13626                                         g_assert (locals_var);
13627
13628                                         /* Mark the instruction used to compute the locals var as used */
13629                                         cfg->gsharedvt_locals_var_ins = NULL;
13630
13631                                         /* Load the offset */
13632                                         if (info_var->opcode == OP_REGOFFSET) {
13633                                                 reg1 = alloc_ireg (cfg);
13634                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13635                                         } else if (info_var->opcode == OP_REGVAR) {
13636                                                 load = NULL;
13637                                                 reg1 = info_var->dreg;
13638                                         } else {
13639                                                 g_assert_not_reached ();
13640                                         }
13641                                         reg2 = alloc_ireg (cfg);
13642                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13643                                         /* Load the locals area address */
13644                                         reg3 = alloc_ireg (cfg);
13645                                         if (locals_var->opcode == OP_REGOFFSET) {
13646                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13647                                         } else if (locals_var->opcode == OP_REGVAR) {
13648                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13649                                         } else {
13650                                                 g_assert_not_reached ();
13651                                         }
13652                                         /* Compute the address */
13653                                         ins->opcode = OP_PADD;
13654                                         ins->sreg1 = reg3;
13655                                         ins->sreg2 = reg2;
13656
13657                                         mono_bblock_insert_before_ins (bb, ins, load3);
13658                                         mono_bblock_insert_before_ins (bb, load3, load2);
13659                                         if (load)
13660                                                 mono_bblock_insert_before_ins (bb, load2, load);
13661                                 } else {
13662                                         g_assert (var->opcode == OP_REGOFFSET);
13663
13664                                         ins->opcode = OP_ADD_IMM;
13665                                         ins->sreg1 = var->inst_basereg;
13666                                         ins->inst_imm = var->inst_offset;
13667                                 }
13668
13669                                 *need_local_opts = TRUE;
13670                                 spec = INS_INFO (ins->opcode);
13671                         }
13672
13673                         if (ins->opcode < MONO_CEE_LAST) {
13674                                 mono_print_ins (ins);
13675                                 g_assert_not_reached ();
13676                         }
13677
13678                         /*
13679                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13680                          * src register.
13681                          * FIXME:
13682                          */
13683                         if (MONO_IS_STORE_MEMBASE (ins)) {
13684                                 tmp_reg = ins->dreg;
13685                                 ins->dreg = ins->sreg2;
13686                                 ins->sreg2 = tmp_reg;
13687                                 store = TRUE;
13688
13689                                 spec2 [MONO_INST_DEST] = ' ';
13690                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13691                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13692                                 spec2 [MONO_INST_SRC3] = ' ';
13693                                 spec = spec2;
13694                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13695                                 g_assert_not_reached ();
13696                         else
13697                                 store = FALSE;
13698                         no_lvreg = FALSE;
13699
13700                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13701                                 printf ("\t %.3s %d", spec, ins->dreg);
13702                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13703                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13704                                         printf (" %d", sregs [srcindex]);
13705                                 printf ("\n");
13706                         }
13707
13708                         /***************/
13709                         /*    DREG     */
13710                         /***************/
13711                         regtype = spec [MONO_INST_DEST];
13712                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13713                         prev_dreg = -1;
13714
13715                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13716                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13717                                 MonoInst *store_ins;
13718                                 int store_opcode;
13719                                 MonoInst *def_ins = ins;
13720                                 int dreg = ins->dreg; /* The original vreg */
13721
13722                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13723
13724                                 if (var->opcode == OP_REGVAR) {
13725                                         ins->dreg = var->dreg;
13726                                 } else if ((ins->dreg == ins->sreg1) && (spec [MONO_INST_DEST] == 'i') && (spec [MONO_INST_SRC1] == 'i') && !vreg_to_lvreg [ins->dreg] && (op_to_op_dest_membase (store_opcode, ins->opcode) != -1)) {
13727                                         /* 
13728                                          * Instead of emitting a load+store, use a _membase opcode.
13729                                          */
13730                                         g_assert (var->opcode == OP_REGOFFSET);
13731                                         if (ins->opcode == OP_MOVE) {
13732                                                 NULLIFY_INS (ins);
13733                                                 def_ins = NULL;
13734                                         } else {
13735                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13736                                                 ins->inst_basereg = var->inst_basereg;
13737                                                 ins->inst_offset = var->inst_offset;
13738                                                 ins->dreg = -1;
13739                                         }
13740                                         spec = INS_INFO (ins->opcode);
13741                                 } else {
13742                                         guint32 lvreg;
13743
13744                                         g_assert (var->opcode == OP_REGOFFSET);
13745
13746                                         prev_dreg = ins->dreg;
13747
13748                                         /* Invalidate any previous lvreg for this vreg */
13749                                         vreg_to_lvreg [ins->dreg] = 0;
13750
13751                                         lvreg = 0;
13752
13753                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
13754                                                 regtype = 'l';
13755                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
13756                                         }
13757
13758                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
13759
13760 #if SIZEOF_REGISTER != 8
13761                                         if (regtype == 'l') {
13762                                                 NEW_STORE_MEMBASE (cfg, store_ins, OP_STOREI4_MEMBASE_REG, var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET, MONO_LVREG_LS (ins->dreg));
13763                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13764                                                 NEW_STORE_MEMBASE (cfg, store_ins, OP_STOREI4_MEMBASE_REG, var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET, MONO_LVREG_MS (ins->dreg));
13765                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13766                                                 def_ins = store_ins;
13767                                         }
13768                                         else
13769 #endif
13770                                         {
13771                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
13772
13773                                                 /* Try to fuse the store into the instruction itself */
13774                                                 /* FIXME: Add more instructions */
13775                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
13776                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
13777                                                         ins->inst_imm = ins->inst_c0;
13778                                                         ins->inst_destbasereg = var->inst_basereg;
13779                                                         ins->inst_offset = var->inst_offset;
13780                                                         spec = INS_INFO (ins->opcode);
13781                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
13782                                                         ins->opcode = store_opcode;
13783                                                         ins->inst_destbasereg = var->inst_basereg;
13784                                                         ins->inst_offset = var->inst_offset;
13785
13786                                                         no_lvreg = TRUE;
13787
13788                                                         tmp_reg = ins->dreg;
13789                                                         ins->dreg = ins->sreg2;
13790                                                         ins->sreg2 = tmp_reg;
13791                                                         store = TRUE;
13792
13793                                                         spec2 [MONO_INST_DEST] = ' ';
13794                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13795                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13796                                                         spec2 [MONO_INST_SRC3] = ' ';
13797                                                         spec = spec2;
13798                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
13799                                                         // FIXME: The backends expect the base reg to be in inst_basereg
13800                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
13801                                                         ins->dreg = -1;
13802                                                         ins->inst_basereg = var->inst_basereg;
13803                                                         ins->inst_offset = var->inst_offset;
13804                                                         spec = INS_INFO (ins->opcode);
13805                                                 } else {
13806                                                         /* printf ("INS: "); mono_print_ins (ins); */
13807                                                         /* Create a store instruction */
13808                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
13809
13810                                                         /* Insert it after the instruction */
13811                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
13812
13813                                                         def_ins = store_ins;
13814
13815                                                         /* 
13816                                                          * We can't assign ins->dreg to var->dreg here, since the
13817                                                          * sregs could use it. So set a flag, and do it after
13818                                                          * the sregs.
13819                                                          */
13820                                                         if ((!cfg->backend->use_fpstack || ((store_opcode != OP_STORER8_MEMBASE_REG) && (store_opcode != OP_STORER4_MEMBASE_REG))) && !((var)->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
13821                                                                 dest_has_lvreg = TRUE;
13822                                                 }
13823                                         }
13824                                 }
13825
13826                                 if (def_ins && !live_range_start [dreg]) {
13827                                         live_range_start [dreg] = def_ins;
13828                                         live_range_start_bb [dreg] = bb;
13829                                 }
13830
13831                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
13832                                         MonoInst *tmp;
13833
13834                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
13835                                         tmp->inst_c1 = dreg;
13836                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
13837                                 }
13838                         }
13839
13840                         /************/
13841                         /*  SREGS   */
13842                         /************/
13843                         num_sregs = mono_inst_get_src_registers (ins, sregs);
13844                         for (srcindex = 0; srcindex < 3; ++srcindex) {
13845                                 regtype = spec [MONO_INST_SRC1 + srcindex];
13846                                 sreg = sregs [srcindex];
13847
13848                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
13849                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
13850                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
13851                                         MonoInst *use_ins = ins;
13852                                         MonoInst *load_ins;
13853                                         guint32 load_opcode;
13854
13855                                         if (var->opcode == OP_REGVAR) {
13856                                                 sregs [srcindex] = var->dreg;
13857                                                 //mono_inst_set_src_registers (ins, sregs);
13858                                                 live_range_end [sreg] = use_ins;
13859                                                 live_range_end_bb [sreg] = bb;
13860
13861                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13862                                                         MonoInst *tmp;
13863
13864                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13865                                                         /* var->dreg is a hreg */
13866                                                         tmp->inst_c1 = sreg;
13867                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
13868                                                 }
13869
13870                                                 continue;
13871                                         }
13872
13873                                         g_assert (var->opcode == OP_REGOFFSET);
13874                                                 
13875                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
13876
13877                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
13878
13879                                         if (vreg_to_lvreg [sreg]) {
13880                                                 g_assert (vreg_to_lvreg [sreg] != -1);
13881
13882                                                 /* The variable is already loaded to an lvreg */
13883                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13884                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
13885                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
13886                                                 //mono_inst_set_src_registers (ins, sregs);
13887                                                 continue;
13888                                         }
13889
13890                                         /* Try to fuse the load into the instruction */
13891                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
13892                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
13893                                                 sregs [0] = var->inst_basereg;
13894                                                 //mono_inst_set_src_registers (ins, sregs);
13895                                                 ins->inst_offset = var->inst_offset;
13896                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
13897                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
13898                                                 sregs [1] = var->inst_basereg;
13899                                                 //mono_inst_set_src_registers (ins, sregs);
13900                                                 ins->inst_offset = var->inst_offset;
13901                                         } else {
13902                                                 if (MONO_IS_REAL_MOVE (ins)) {
13903                                                         ins->opcode = OP_NOP;
13904                                                         sreg = ins->dreg;
13905                                                 } else {
13906                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
13907
13908                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
13909
13910                                                         if ((!cfg->backend->use_fpstack || ((load_opcode != OP_LOADR8_MEMBASE) && (load_opcode != OP_LOADR4_MEMBASE))) && !((var)->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && !no_lvreg) {
13911                                                                 if (var->dreg == prev_dreg) {
13912                                                                         /*
13913                                                                          * sreg refers to the value loaded by the load
13914                                                                          * emitted below, but we need to use ins->dreg
13915                                                                          * since it refers to the store emitted earlier.
13916                                                                          */
13917                                                                         sreg = ins->dreg;
13918                                                                 }
13919                                                                 g_assert (sreg != -1);
13920                                                                 vreg_to_lvreg [var->dreg] = sreg;
13921                                                                 if (lvregs_len >= lvregs_size) {
13922                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13923                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13924                                                                         lvregs = new_lvregs;
13925                                                                         lvregs_size *= 2;
13926                                                                 }
13927                                                                 lvregs [lvregs_len ++] = var->dreg;
13928                                                         }
13929                                                 }
13930
13931                                                 sregs [srcindex] = sreg;
13932                                                 //mono_inst_set_src_registers (ins, sregs);
13933
13934 #if SIZEOF_REGISTER != 8
13935                                                 if (regtype == 'l') {
13936                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
13937                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13938                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
13939                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13940                                                         use_ins = load_ins;
13941                                                 }
13942                                                 else
13943 #endif
13944                                                 {
13945 #if SIZEOF_REGISTER == 4
13946                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
13947 #endif
13948                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
13949                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13950                                                         use_ins = load_ins;
13951                                                 }
13952                                         }
13953
13954                                         if (var->dreg < orig_next_vreg) {
13955                                                 live_range_end [var->dreg] = use_ins;
13956                                                 live_range_end_bb [var->dreg] = bb;
13957                                         }
13958
13959                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13960                                                 MonoInst *tmp;
13961
13962                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13963                                                 tmp->inst_c1 = var->dreg;
13964                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
13965                                         }
13966                                 }
13967                         }
13968                         mono_inst_set_src_registers (ins, sregs);
13969
13970                         if (dest_has_lvreg) {
13971                                 g_assert (ins->dreg != -1);
13972                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
13973                                 if (lvregs_len >= lvregs_size) {
13974                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13975                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13976                                         lvregs = new_lvregs;
13977                                         lvregs_size *= 2;
13978                                 }
13979                                 lvregs [lvregs_len ++] = prev_dreg;
13980                                 dest_has_lvreg = FALSE;
13981                         }
13982
13983                         if (store) {
13984                                 tmp_reg = ins->dreg;
13985                                 ins->dreg = ins->sreg2;
13986                                 ins->sreg2 = tmp_reg;
13987                         }
13988
13989                         if (MONO_IS_CALL (ins)) {
13990                                 /* Clear vreg_to_lvreg array */
13991                                 for (i = 0; i < lvregs_len; i++)
13992                                         vreg_to_lvreg [lvregs [i]] = 0;
13993                                 lvregs_len = 0;
13994                         } else if (ins->opcode == OP_NOP) {
13995                                 ins->dreg = -1;
13996                                 MONO_INST_NULLIFY_SREGS (ins);
13997                         }
13998
13999                         if (cfg->verbose_level > 2)
14000                                 mono_print_ins_index (1, ins);
14001                 }
14002
14003                 /* Extend the live range based on the liveness info */
14004                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14005                         for (i = 0; i < cfg->num_varinfo; i ++) {
14006                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14007
14008                                 if (vreg_is_volatile (cfg, vi->vreg))
14009                                         /* The liveness info is incomplete */
14010                                         continue;
14011
14012                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14013                                         /* Live from at least the first ins of this bb */
14014                                         live_range_start [vi->vreg] = bb->code;
14015                                         live_range_start_bb [vi->vreg] = bb;
14016                                 }
14017
14018                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14019                                         /* Live at least until the last ins of this bb */
14020                                         live_range_end [vi->vreg] = bb->last_ins;
14021                                         live_range_end_bb [vi->vreg] = bb;
14022                                 }
14023                         }
14024                 }
14025         }
14026         
14027         /*
14028          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14029          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14030          */
14031         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14032                 for (i = 0; i < cfg->num_varinfo; ++i) {
14033                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14034                         MonoInst *ins;
14035
14036                         if (live_range_start [vreg]) {
14037                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14038                                 ins->inst_c0 = i;
14039                                 ins->inst_c1 = vreg;
14040                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14041                         }
14042                         if (live_range_end [vreg]) {
14043                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14044                                 ins->inst_c0 = i;
14045                                 ins->inst_c1 = vreg;
14046                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14047                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14048                                 else
14049                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14050                         }
14051                 }
14052         }
14053
14054         if (cfg->gsharedvt_locals_var_ins) {
14055                 /* Nullify if unused */
14056                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14057                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14058         }
14059
14060         g_free (live_range_start);
14061         g_free (live_range_end);
14062         g_free (live_range_start_bb);
14063         g_free (live_range_end_bb);
14064 }
14065
14066
14067 /**
14068  * FIXME:
14069  * - use 'iadd' instead of 'int_add'
14070  * - handling ovf opcodes: decompose in method_to_ir.
14071  * - unify iregs/fregs
14072  *   -> partly done, the missing parts are:
14073  *   - a more complete unification would involve unifying the hregs as well, so
14074  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14075  *     would no longer map to the machine hregs, so the code generators would need to
14076  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14077  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14078  *     fp/non-fp branches speeds it up by about 15%.
14079  * - use sext/zext opcodes instead of shifts
14080  * - add OP_ICALL
14081  * - get rid of TEMPLOADs if possible and use vregs instead
14082  * - clean up usage of OP_P/OP_ opcodes
14083  * - cleanup usage of DUMMY_USE
14084  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14085  *   stack
14086  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14087  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14088  * - make sure handle_stack_args () is called before the branch is emitted
14089  * - when the new IR is done, get rid of all unused stuff
14090  * - COMPARE/BEQ as separate instructions or unify them ?
14091  *   - keeping them separate allows specialized compare instructions like
14092  *     compare_imm, compare_membase
14093  *   - most back ends unify fp compare+branch, fp compare+ceq
14094  * - integrate mono_save_args into inline_method
14095  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14096  * - handle long shift opts on 32 bit platforms somehow: they require 
14097  *   3 sregs (2 for arg1 and 1 for arg2)
14098  * - make byref a 'normal' type.
14099  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14100  *   variable if needed.
14101  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14102  *   like inline_method.
14103  * - remove inlining restrictions
14104  * - fix LNEG and enable cfold of INEG
14105  * - generalize x86 optimizations like ldelema as a peephole optimization
14106  * - add store_mem_imm for amd64
14107  * - optimize the loading of the interruption flag in the managed->native wrappers
14108  * - avoid special handling of OP_NOP in passes
14109  * - move code inserting instructions into one function/macro.
14110  * - try a coalescing phase after liveness analysis
14111  * - add float -> vreg conversion + local optimizations on !x86
14112  * - figure out how to handle decomposed branches during optimizations, ie.
14113  *   compare+branch, op_jump_table+op_br etc.
14114  * - promote RuntimeXHandles to vregs
14115  * - vtype cleanups:
14116  *   - add a NEW_VARLOADA_VREG macro
14117  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14118  *   accessing vtype fields.
14119  * - get rid of I8CONST on 64 bit platforms
14120  * - dealing with the increase in code size due to branches created during opcode
14121  *   decomposition:
14122  *   - use extended basic blocks
14123  *     - all parts of the JIT
14124  *     - handle_global_vregs () && local regalloc
14125  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14126  * - sources of increase in code size:
14127  *   - vtypes
14128  *   - long compares
14129  *   - isinst and castclass
14130  *   - lvregs not allocated to global registers even if used multiple times
14131  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14132  *   meaningful.
14133  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14134  * - add all micro optimizations from the old JIT
14135  * - put tree optimizations into the deadce pass
14136  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14137  *   specific function.
14138  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14139  *   fcompare + branchCC.
14140  * - create a helper function for allocating a stack slot, taking into account 
14141  *   MONO_CFG_HAS_SPILLUP.
14142  * - merge r68207.
14143  * - optimize mono_regstate2_alloc_int/float.
14144  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14145  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14146  *   parts of the tree could be separated by other instructions, killing the tree
14147  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14148  *   instructions if the result of the load is used multiple times ?
14149  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14150  * - LAST MERGE: 108395.
14151  * - when returning vtypes in registers, generate IR and append it to the end of the
14152  *   last bb instead of doing it in the epilog.
14153  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14154  */
14155
14156 /*
14157
14158 NOTES
14159 -----
14160
14161 - When to decompose opcodes:
14162   - earlier: this makes some optimizations hard to implement, since the low level IR
14163   no longer contains the neccessary information. But it is easier to do.
14164   - later: harder to implement, enables more optimizations.
14165 - Branches inside bblocks:
14166   - created when decomposing complex opcodes. 
14167     - branches to another bblock: harmless, but not tracked by the branch 
14168       optimizations, so need to branch to a label at the start of the bblock.
14169     - branches to inside the same bblock: very problematic, trips up the local
14170       reg allocator. Can be fixed by spitting the current bblock, but that is a
14171       complex operation, since some local vregs can become global vregs etc.
14172 - Local/global vregs:
14173   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14174     local register allocator.
14175   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14176     structure, created by mono_create_var (). Assigned to hregs or the stack by
14177     the global register allocator.
14178 - When to do optimizations like alu->alu_imm:
14179   - earlier -> saves work later on since the IR will be smaller/simpler
14180   - later -> can work on more instructions
14181 - Handling of valuetypes:
14182   - When a vtype is pushed on the stack, a new temporary is created, an 
14183     instruction computing its address (LDADDR) is emitted and pushed on
14184     the stack. Need to optimize cases when the vtype is used immediately as in
14185     argument passing, stloc etc.
14186 - Instead of the to_end stuff in the old JIT, simply call the function handling
14187   the values on the stack before emitting the last instruction of the bb.
14188 */
14189
14190 #endif /* !DISABLE_JIT */