Interp sdb (#4911)
[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 static MonoInst*
4878 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4879 {
4880         MonoInst *ins = NULL;
4881         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
4882
4883         if (cmethod->klass == mono_defaults.string_class) {
4884                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
4885                         int dreg = alloc_ireg (cfg);
4886                         int index_reg = alloc_preg (cfg);
4887                         int add_reg = alloc_preg (cfg);
4888
4889 #if SIZEOF_REGISTER == 8
4890                         if (COMPILE_LLVM (cfg)) {
4891                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
4892                         } else {
4893                                 /* The array reg is 64 bits but the index reg is only 32 */
4894                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
4895                         }
4896 #else
4897                         index_reg = args [1]->dreg;
4898 #endif  
4899                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
4900
4901 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4902                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
4903                         add_reg = ins->dreg;
4904                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4905                                                                    add_reg, 0);
4906 #else
4907                         int mult_reg = alloc_preg (cfg);
4908                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
4909                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
4910                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4911                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
4912 #endif
4913                         type_from_op (cfg, ins, NULL, NULL);
4914                         return ins;
4915                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
4916                         int dreg = alloc_ireg (cfg);
4917                         /* Decompose later to allow more optimizations */
4918                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
4919                         ins->type = STACK_I4;
4920                         ins->flags |= MONO_INST_FAULT;
4921                         cfg->cbb->has_array_access = TRUE;
4922                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
4923
4924                         return ins;
4925                 } else 
4926                         return NULL;
4927         } else if (cmethod->klass == mono_defaults.object_class) {
4928                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
4929                         int dreg = alloc_ireg_ref (cfg);
4930                         int vt_reg = alloc_preg (cfg);
4931                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4932                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
4933                         type_from_op (cfg, ins, NULL, NULL);
4934
4935                         return ins;
4936                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
4937                         int dreg = alloc_ireg (cfg);
4938                         int t1 = alloc_ireg (cfg);
4939         
4940                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
4941                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
4942                         ins->type = STACK_I4;
4943
4944                         return ins;
4945                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
4946                         MONO_INST_NEW (cfg, ins, OP_NOP);
4947                         MONO_ADD_INS (cfg->cbb, ins);
4948                         return ins;
4949                 } else
4950                         return NULL;
4951         } else if (cmethod->klass == mono_defaults.array_class) {
4952                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4953                         return emit_array_generic_access (cfg, fsig, args, FALSE);
4954                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4955                         return emit_array_generic_access (cfg, fsig, args, TRUE);
4956
4957 #ifndef MONO_BIG_ARRAYS
4958                 /*
4959                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
4960                  * Array methods.
4961                  */
4962                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
4963                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
4964                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
4965                         int dreg = alloc_ireg (cfg);
4966                         int bounds_reg = alloc_ireg_mp (cfg);
4967                         MonoBasicBlock *end_bb, *szarray_bb;
4968                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
4969
4970                         NEW_BBLOCK (cfg, end_bb);
4971                         NEW_BBLOCK (cfg, szarray_bb);
4972
4973                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
4974                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4975                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
4976                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
4977                         /* Non-szarray case */
4978                         if (get_length)
4979                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4980                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4981                         else
4982                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4983                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4984                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4985                         MONO_START_BB (cfg, szarray_bb);
4986                         /* Szarray case */
4987                         if (get_length)
4988                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4989                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
4990                         else
4991                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4992                         MONO_START_BB (cfg, end_bb);
4993
4994                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
4995                         ins->type = STACK_I4;
4996                         
4997                         return ins;
4998                 }
4999 #endif
5000
5001                 if (cmethod->name [0] != 'g')
5002                         return NULL;
5003
5004                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5005                         int dreg = alloc_ireg (cfg);
5006                         int vtable_reg = alloc_preg (cfg);
5007                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5008                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5009                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5010                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5011                         type_from_op (cfg, ins, NULL, NULL);
5012
5013                         return ins;
5014                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5015                         int dreg = alloc_ireg (cfg);
5016
5017                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5018                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5019                         type_from_op (cfg, ins, NULL, NULL);
5020
5021                         return ins;
5022                 } else
5023                         return NULL;
5024         } else if (cmethod->klass == runtime_helpers_class) {
5025                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5026                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5027                         return ins;
5028                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5029                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5030                         g_assert (ctx);
5031                         g_assert (ctx->method_inst);
5032                         g_assert (ctx->method_inst->type_argc == 1);
5033                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5034                         MonoClass *klass = mono_class_from_mono_type (t);
5035
5036                         ins = NULL;
5037
5038                         mono_class_init (klass);
5039                         if (MONO_TYPE_IS_REFERENCE (t))
5040                                 EMIT_NEW_ICONST (cfg, ins, 1);
5041                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5042                                 EMIT_NEW_ICONST (cfg, ins, 0);
5043                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5044                                 EMIT_NEW_ICONST (cfg, ins, 1);
5045                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5046                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5047                         else {
5048                                 g_assert (cfg->gshared);
5049
5050                                 int context_used = mini_class_check_context_used (cfg, klass);
5051
5052                                 /* This returns 1 or 2 */
5053                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5054                                 int dreg = alloc_ireg (cfg);
5055                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5056                         }
5057
5058                         return ins;
5059                 } else
5060                         return NULL;
5061         } else if (cmethod->klass == mono_defaults.monitor_class) {
5062                 gboolean is_enter = FALSE;
5063                 gboolean is_v4 = FALSE;
5064
5065                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5066                         is_enter = TRUE;
5067                         is_v4 = TRUE;
5068                 }
5069                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5070                         is_enter = TRUE;
5071
5072                 if (is_enter) {
5073                         /*
5074                          * To make async stack traces work, icalls which can block should have a wrapper.
5075                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5076                          */
5077                         MonoBasicBlock *end_bb;
5078
5079                         NEW_BBLOCK (cfg, end_bb);
5080
5081                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5082                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5083                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5084                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5085                         MONO_START_BB (cfg, end_bb);
5086                         return ins;
5087                 }
5088         } else if (cmethod->klass == mono_defaults.thread_class) {
5089                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5090                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5091                         MONO_ADD_INS (cfg->cbb, ins);
5092                         return ins;
5093                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5094                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5095                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5096                         guint32 opcode = 0;
5097                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5098
5099                         if (fsig->params [0]->type == MONO_TYPE_I1)
5100                                 opcode = OP_LOADI1_MEMBASE;
5101                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5102                                 opcode = OP_LOADU1_MEMBASE;
5103                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5104                                 opcode = OP_LOADI2_MEMBASE;
5105                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5106                                 opcode = OP_LOADU2_MEMBASE;
5107                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5108                                 opcode = OP_LOADI4_MEMBASE;
5109                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5110                                 opcode = OP_LOADU4_MEMBASE;
5111                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5112                                 opcode = OP_LOADI8_MEMBASE;
5113                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5114                                 opcode = OP_LOADR4_MEMBASE;
5115                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5116                                 opcode = OP_LOADR8_MEMBASE;
5117                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5118                                 opcode = OP_LOAD_MEMBASE;
5119
5120                         if (opcode) {
5121                                 MONO_INST_NEW (cfg, ins, opcode);
5122                                 ins->inst_basereg = args [0]->dreg;
5123                                 ins->inst_offset = 0;
5124                                 MONO_ADD_INS (cfg->cbb, ins);
5125
5126                                 switch (fsig->params [0]->type) {
5127                                 case MONO_TYPE_I1:
5128                                 case MONO_TYPE_U1:
5129                                 case MONO_TYPE_I2:
5130                                 case MONO_TYPE_U2:
5131                                 case MONO_TYPE_I4:
5132                                 case MONO_TYPE_U4:
5133                                         ins->dreg = mono_alloc_ireg (cfg);
5134                                         ins->type = STACK_I4;
5135                                         break;
5136                                 case MONO_TYPE_I8:
5137                                 case MONO_TYPE_U8:
5138                                         ins->dreg = mono_alloc_lreg (cfg);
5139                                         ins->type = STACK_I8;
5140                                         break;
5141                                 case MONO_TYPE_I:
5142                                 case MONO_TYPE_U:
5143                                         ins->dreg = mono_alloc_ireg (cfg);
5144 #if SIZEOF_REGISTER == 8
5145                                         ins->type = STACK_I8;
5146 #else
5147                                         ins->type = STACK_I4;
5148 #endif
5149                                         break;
5150                                 case MONO_TYPE_R4:
5151                                 case MONO_TYPE_R8:
5152                                         ins->dreg = mono_alloc_freg (cfg);
5153                                         ins->type = STACK_R8;
5154                                         break;
5155                                 default:
5156                                         g_assert (mini_type_is_reference (fsig->params [0]));
5157                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5158                                         ins->type = STACK_OBJ;
5159                                         break;
5160                                 }
5161
5162                                 if (opcode == OP_LOADI8_MEMBASE)
5163                                         ins = mono_decompose_opcode (cfg, ins);
5164
5165                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5166
5167                                 return ins;
5168                         }
5169                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5170                         guint32 opcode = 0;
5171                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5172
5173                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5174                                 opcode = OP_STOREI1_MEMBASE_REG;
5175                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5176                                 opcode = OP_STOREI2_MEMBASE_REG;
5177                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5178                                 opcode = OP_STOREI4_MEMBASE_REG;
5179                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5180                                 opcode = OP_STOREI8_MEMBASE_REG;
5181                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5182                                 opcode = OP_STORER4_MEMBASE_REG;
5183                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5184                                 opcode = OP_STORER8_MEMBASE_REG;
5185                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5186                                 opcode = OP_STORE_MEMBASE_REG;
5187
5188                         if (opcode) {
5189                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5190
5191                                 MONO_INST_NEW (cfg, ins, opcode);
5192                                 ins->sreg1 = args [1]->dreg;
5193                                 ins->inst_destbasereg = args [0]->dreg;
5194                                 ins->inst_offset = 0;
5195                                 MONO_ADD_INS (cfg->cbb, ins);
5196
5197                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5198                                         ins = mono_decompose_opcode (cfg, ins);
5199
5200                                 return ins;
5201                         }
5202                 }
5203         } else if (cmethod->klass->image == mono_defaults.corlib &&
5204                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5205                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5206                 ins = NULL;
5207
5208 #if SIZEOF_REGISTER == 8
5209                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5210                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5211                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5212                                 ins->dreg = mono_alloc_preg (cfg);
5213                                 ins->sreg1 = args [0]->dreg;
5214                                 ins->type = STACK_I8;
5215                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5216                                 MONO_ADD_INS (cfg->cbb, ins);
5217                         } else {
5218                                 MonoInst *load_ins;
5219
5220                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5221
5222                                 /* 64 bit reads are already atomic */
5223                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5224                                 load_ins->dreg = mono_alloc_preg (cfg);
5225                                 load_ins->inst_basereg = args [0]->dreg;
5226                                 load_ins->inst_offset = 0;
5227                                 load_ins->type = STACK_I8;
5228                                 MONO_ADD_INS (cfg->cbb, load_ins);
5229
5230                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5231
5232                                 ins = load_ins;
5233                         }
5234                 }
5235 #endif
5236
5237                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5238                         MonoInst *ins_iconst;
5239                         guint32 opcode = 0;
5240
5241                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5242                                 opcode = OP_ATOMIC_ADD_I4;
5243                                 cfg->has_atomic_add_i4 = TRUE;
5244                         }
5245 #if SIZEOF_REGISTER == 8
5246                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5247                                 opcode = OP_ATOMIC_ADD_I8;
5248 #endif
5249                         if (opcode) {
5250                                 if (!mono_arch_opcode_supported (opcode))
5251                                         return NULL;
5252                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5253                                 ins_iconst->inst_c0 = 1;
5254                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5255                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5256
5257                                 MONO_INST_NEW (cfg, ins, opcode);
5258                                 ins->dreg = mono_alloc_ireg (cfg);
5259                                 ins->inst_basereg = args [0]->dreg;
5260                                 ins->inst_offset = 0;
5261                                 ins->sreg2 = ins_iconst->dreg;
5262                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5263                                 MONO_ADD_INS (cfg->cbb, ins);
5264                         }
5265                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5266                         MonoInst *ins_iconst;
5267                         guint32 opcode = 0;
5268
5269                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5270                                 opcode = OP_ATOMIC_ADD_I4;
5271                                 cfg->has_atomic_add_i4 = TRUE;
5272                         }
5273 #if SIZEOF_REGISTER == 8
5274                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5275                                 opcode = OP_ATOMIC_ADD_I8;
5276 #endif
5277                         if (opcode) {
5278                                 if (!mono_arch_opcode_supported (opcode))
5279                                         return NULL;
5280                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5281                                 ins_iconst->inst_c0 = -1;
5282                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5283                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5284
5285                                 MONO_INST_NEW (cfg, ins, opcode);
5286                                 ins->dreg = mono_alloc_ireg (cfg);
5287                                 ins->inst_basereg = args [0]->dreg;
5288                                 ins->inst_offset = 0;
5289                                 ins->sreg2 = ins_iconst->dreg;
5290                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5291                                 MONO_ADD_INS (cfg->cbb, ins);
5292                         }
5293                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5294                         guint32 opcode = 0;
5295
5296                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5297                                 opcode = OP_ATOMIC_ADD_I4;
5298                                 cfg->has_atomic_add_i4 = TRUE;
5299                         }
5300 #if SIZEOF_REGISTER == 8
5301                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5302                                 opcode = OP_ATOMIC_ADD_I8;
5303 #endif
5304                         if (opcode) {
5305                                 if (!mono_arch_opcode_supported (opcode))
5306                                         return NULL;
5307                                 MONO_INST_NEW (cfg, ins, opcode);
5308                                 ins->dreg = mono_alloc_ireg (cfg);
5309                                 ins->inst_basereg = args [0]->dreg;
5310                                 ins->inst_offset = 0;
5311                                 ins->sreg2 = args [1]->dreg;
5312                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5313                                 MONO_ADD_INS (cfg->cbb, ins);
5314                         }
5315                 }
5316                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5317                         MonoInst *f2i = NULL, *i2f;
5318                         guint32 opcode, f2i_opcode, i2f_opcode;
5319                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5320                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5321
5322                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5323                             fsig->params [0]->type == MONO_TYPE_R4) {
5324                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5325                                 f2i_opcode = OP_MOVE_F_TO_I4;
5326                                 i2f_opcode = OP_MOVE_I4_TO_F;
5327                                 cfg->has_atomic_exchange_i4 = TRUE;
5328                         }
5329 #if SIZEOF_REGISTER == 8
5330                         else if (is_ref ||
5331                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5332                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5333                                  fsig->params [0]->type == MONO_TYPE_I) {
5334                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5335                                 f2i_opcode = OP_MOVE_F_TO_I8;
5336                                 i2f_opcode = OP_MOVE_I8_TO_F;
5337                         }
5338 #else
5339                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5340                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5341                                 cfg->has_atomic_exchange_i4 = TRUE;
5342                         }
5343 #endif
5344                         else
5345                                 return NULL;
5346
5347                         if (!mono_arch_opcode_supported (opcode))
5348                                 return NULL;
5349
5350                         if (is_float) {
5351                                 /* TODO: Decompose these opcodes instead of bailing here. */
5352                                 if (COMPILE_SOFT_FLOAT (cfg))
5353                                         return NULL;
5354
5355                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5356                                 f2i->dreg = mono_alloc_ireg (cfg);
5357                                 f2i->sreg1 = args [1]->dreg;
5358                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5359                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5360                                 MONO_ADD_INS (cfg->cbb, f2i);
5361                         }
5362
5363                         MONO_INST_NEW (cfg, ins, opcode);
5364                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5365                         ins->inst_basereg = args [0]->dreg;
5366                         ins->inst_offset = 0;
5367                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5368                         MONO_ADD_INS (cfg->cbb, ins);
5369
5370                         switch (fsig->params [0]->type) {
5371                         case MONO_TYPE_I4:
5372                                 ins->type = STACK_I4;
5373                                 break;
5374                         case MONO_TYPE_I8:
5375                                 ins->type = STACK_I8;
5376                                 break;
5377                         case MONO_TYPE_I:
5378 #if SIZEOF_REGISTER == 8
5379                                 ins->type = STACK_I8;
5380 #else
5381                                 ins->type = STACK_I4;
5382 #endif
5383                                 break;
5384                         case MONO_TYPE_R4:
5385                         case MONO_TYPE_R8:
5386                                 ins->type = STACK_R8;
5387                                 break;
5388                         default:
5389                                 g_assert (mini_type_is_reference (fsig->params [0]));
5390                                 ins->type = STACK_OBJ;
5391                                 break;
5392                         }
5393
5394                         if (is_float) {
5395                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5396                                 i2f->dreg = mono_alloc_freg (cfg);
5397                                 i2f->sreg1 = ins->dreg;
5398                                 i2f->type = STACK_R8;
5399                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5400                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5401                                 MONO_ADD_INS (cfg->cbb, i2f);
5402
5403                                 ins = i2f;
5404                         }
5405
5406                         if (cfg->gen_write_barriers && is_ref)
5407                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5408                 }
5409                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5410                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5411                         guint32 opcode, f2i_opcode, i2f_opcode;
5412                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5413                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5414
5415                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5416                             fsig->params [1]->type == MONO_TYPE_R4) {
5417                                 opcode = OP_ATOMIC_CAS_I4;
5418                                 f2i_opcode = OP_MOVE_F_TO_I4;
5419                                 i2f_opcode = OP_MOVE_I4_TO_F;
5420                                 cfg->has_atomic_cas_i4 = TRUE;
5421                         }
5422 #if SIZEOF_REGISTER == 8
5423                         else if (is_ref ||
5424                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5425                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5426                                  fsig->params [1]->type == MONO_TYPE_I) {
5427                                 opcode = OP_ATOMIC_CAS_I8;
5428                                 f2i_opcode = OP_MOVE_F_TO_I8;
5429                                 i2f_opcode = OP_MOVE_I8_TO_F;
5430                         }
5431 #else
5432                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5433                                 opcode = OP_ATOMIC_CAS_I4;
5434                                 cfg->has_atomic_cas_i4 = TRUE;
5435                         }
5436 #endif
5437                         else
5438                                 return NULL;
5439
5440                         if (!mono_arch_opcode_supported (opcode))
5441                                 return NULL;
5442
5443                         if (is_float) {
5444                                 /* TODO: Decompose these opcodes instead of bailing here. */
5445                                 if (COMPILE_SOFT_FLOAT (cfg))
5446                                         return NULL;
5447
5448                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5449                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5450                                 f2i_new->sreg1 = args [1]->dreg;
5451                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5452                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5453                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5454
5455                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5456                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5457                                 f2i_cmp->sreg1 = args [2]->dreg;
5458                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5459                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5460                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5461                         }
5462
5463                         MONO_INST_NEW (cfg, ins, opcode);
5464                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5465                         ins->sreg1 = args [0]->dreg;
5466                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5467                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5468                         MONO_ADD_INS (cfg->cbb, ins);
5469
5470                         switch (fsig->params [1]->type) {
5471                         case MONO_TYPE_I4:
5472                                 ins->type = STACK_I4;
5473                                 break;
5474                         case MONO_TYPE_I8:
5475                                 ins->type = STACK_I8;
5476                                 break;
5477                         case MONO_TYPE_I:
5478 #if SIZEOF_REGISTER == 8
5479                                 ins->type = STACK_I8;
5480 #else
5481                                 ins->type = STACK_I4;
5482 #endif
5483                                 break;
5484                         case MONO_TYPE_R4:
5485                                 ins->type = cfg->r4_stack_type;
5486                                 break;
5487                         case MONO_TYPE_R8:
5488                                 ins->type = STACK_R8;
5489                                 break;
5490                         default:
5491                                 g_assert (mini_type_is_reference (fsig->params [1]));
5492                                 ins->type = STACK_OBJ;
5493                                 break;
5494                         }
5495
5496                         if (is_float) {
5497                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5498                                 i2f->dreg = mono_alloc_freg (cfg);
5499                                 i2f->sreg1 = ins->dreg;
5500                                 i2f->type = STACK_R8;
5501                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5502                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5503                                 MONO_ADD_INS (cfg->cbb, i2f);
5504
5505                                 ins = i2f;
5506                         }
5507
5508                         if (cfg->gen_write_barriers && is_ref)
5509                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5510                 }
5511                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5512                          fsig->params [1]->type == MONO_TYPE_I4) {
5513                         MonoInst *cmp, *ceq;
5514
5515                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5516                                 return NULL;
5517
5518                         /* int32 r = CAS (location, value, comparand); */
5519                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5520                         ins->dreg = alloc_ireg (cfg);
5521                         ins->sreg1 = args [0]->dreg;
5522                         ins->sreg2 = args [1]->dreg;
5523                         ins->sreg3 = args [2]->dreg;
5524                         ins->type = STACK_I4;
5525                         MONO_ADD_INS (cfg->cbb, ins);
5526
5527                         /* bool result = r == comparand; */
5528                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5529                         cmp->sreg1 = ins->dreg;
5530                         cmp->sreg2 = args [2]->dreg;
5531                         cmp->type = STACK_I4;
5532                         MONO_ADD_INS (cfg->cbb, cmp);
5533
5534                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5535                         ceq->dreg = alloc_ireg (cfg);
5536                         ceq->type = STACK_I4;
5537                         MONO_ADD_INS (cfg->cbb, ceq);
5538
5539                         /* *success = result; */
5540                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5541
5542                         cfg->has_atomic_cas_i4 = TRUE;
5543                 }
5544                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5545                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5546
5547                 if (ins)
5548                         return ins;
5549         } else if (cmethod->klass->image == mono_defaults.corlib &&
5550                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5551                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5552                 ins = NULL;
5553
5554                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5555                         guint32 opcode = 0;
5556                         MonoType *t = fsig->params [0];
5557                         gboolean is_ref;
5558                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5559
5560                         g_assert (t->byref);
5561                         /* t is a byref type, so the reference check is more complicated */
5562                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5563                         if (t->type == MONO_TYPE_I1)
5564                                 opcode = OP_ATOMIC_LOAD_I1;
5565                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5566                                 opcode = OP_ATOMIC_LOAD_U1;
5567                         else if (t->type == MONO_TYPE_I2)
5568                                 opcode = OP_ATOMIC_LOAD_I2;
5569                         else if (t->type == MONO_TYPE_U2)
5570                                 opcode = OP_ATOMIC_LOAD_U2;
5571                         else if (t->type == MONO_TYPE_I4)
5572                                 opcode = OP_ATOMIC_LOAD_I4;
5573                         else if (t->type == MONO_TYPE_U4)
5574                                 opcode = OP_ATOMIC_LOAD_U4;
5575                         else if (t->type == MONO_TYPE_R4)
5576                                 opcode = OP_ATOMIC_LOAD_R4;
5577                         else if (t->type == MONO_TYPE_R8)
5578                                 opcode = OP_ATOMIC_LOAD_R8;
5579 #if SIZEOF_REGISTER == 8
5580                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5581                                 opcode = OP_ATOMIC_LOAD_I8;
5582                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5583                                 opcode = OP_ATOMIC_LOAD_U8;
5584 #else
5585                         else if (t->type == MONO_TYPE_I)
5586                                 opcode = OP_ATOMIC_LOAD_I4;
5587                         else if (is_ref || t->type == MONO_TYPE_U)
5588                                 opcode = OP_ATOMIC_LOAD_U4;
5589 #endif
5590
5591                         if (opcode) {
5592                                 if (!mono_arch_opcode_supported (opcode))
5593                                         return NULL;
5594
5595                                 MONO_INST_NEW (cfg, ins, opcode);
5596                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5597                                 ins->sreg1 = args [0]->dreg;
5598                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5599                                 MONO_ADD_INS (cfg->cbb, ins);
5600
5601                                 switch (t->type) {
5602                                 case MONO_TYPE_BOOLEAN:
5603                                 case MONO_TYPE_I1:
5604                                 case MONO_TYPE_U1:
5605                                 case MONO_TYPE_I2:
5606                                 case MONO_TYPE_U2:
5607                                 case MONO_TYPE_I4:
5608                                 case MONO_TYPE_U4:
5609                                         ins->type = STACK_I4;
5610                                         break;
5611                                 case MONO_TYPE_I8:
5612                                 case MONO_TYPE_U8:
5613                                         ins->type = STACK_I8;
5614                                         break;
5615                                 case MONO_TYPE_I:
5616                                 case MONO_TYPE_U:
5617 #if SIZEOF_REGISTER == 8
5618                                         ins->type = STACK_I8;
5619 #else
5620                                         ins->type = STACK_I4;
5621 #endif
5622                                         break;
5623                                 case MONO_TYPE_R4:
5624                                         ins->type = cfg->r4_stack_type;
5625                                         break;
5626                                 case MONO_TYPE_R8:
5627                                         ins->type = STACK_R8;
5628                                         break;
5629                                 default:
5630                                         g_assert (is_ref);
5631                                         ins->type = STACK_OBJ;
5632                                         break;
5633                                 }
5634                         }
5635                 }
5636
5637                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5638                         guint32 opcode = 0;
5639                         MonoType *t = fsig->params [0];
5640                         gboolean is_ref;
5641
5642                         g_assert (t->byref);
5643                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5644                         if (t->type == MONO_TYPE_I1)
5645                                 opcode = OP_ATOMIC_STORE_I1;
5646                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5647                                 opcode = OP_ATOMIC_STORE_U1;
5648                         else if (t->type == MONO_TYPE_I2)
5649                                 opcode = OP_ATOMIC_STORE_I2;
5650                         else if (t->type == MONO_TYPE_U2)
5651                                 opcode = OP_ATOMIC_STORE_U2;
5652                         else if (t->type == MONO_TYPE_I4)
5653                                 opcode = OP_ATOMIC_STORE_I4;
5654                         else if (t->type == MONO_TYPE_U4)
5655                                 opcode = OP_ATOMIC_STORE_U4;
5656                         else if (t->type == MONO_TYPE_R4)
5657                                 opcode = OP_ATOMIC_STORE_R4;
5658                         else if (t->type == MONO_TYPE_R8)
5659                                 opcode = OP_ATOMIC_STORE_R8;
5660 #if SIZEOF_REGISTER == 8
5661                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5662                                 opcode = OP_ATOMIC_STORE_I8;
5663                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5664                                 opcode = OP_ATOMIC_STORE_U8;
5665 #else
5666                         else if (t->type == MONO_TYPE_I)
5667                                 opcode = OP_ATOMIC_STORE_I4;
5668                         else if (is_ref || t->type == MONO_TYPE_U)
5669                                 opcode = OP_ATOMIC_STORE_U4;
5670 #endif
5671
5672                         if (opcode) {
5673                                 if (!mono_arch_opcode_supported (opcode))
5674                                         return NULL;
5675
5676                                 MONO_INST_NEW (cfg, ins, opcode);
5677                                 ins->dreg = args [0]->dreg;
5678                                 ins->sreg1 = args [1]->dreg;
5679                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5680                                 MONO_ADD_INS (cfg->cbb, ins);
5681
5682                                 if (cfg->gen_write_barriers && is_ref)
5683                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5684                         }
5685                 }
5686
5687                 if (ins)
5688                         return ins;
5689         } else if (cmethod->klass->image == mono_defaults.corlib &&
5690                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5691                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5692                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5693                         if (mini_should_insert_breakpoint (cfg->method)) {
5694                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5695                         } else {
5696                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5697                                 MONO_ADD_INS (cfg->cbb, ins);
5698                         }
5699                         return ins;
5700                 }
5701         } else if (cmethod->klass->image == mono_defaults.corlib &&
5702                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5703                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5704                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5705 #ifdef TARGET_WIN32
5706                         EMIT_NEW_ICONST (cfg, ins, 1);
5707 #else
5708                         EMIT_NEW_ICONST (cfg, ins, 0);
5709 #endif
5710                 }
5711         } else if (cmethod->klass->image == mono_defaults.corlib &&
5712                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5713                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5714                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5715                         /* No stack walks are currently available, so implement this as an intrinsic */
5716                         MonoInst *assembly_ins;
5717
5718                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5719                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5720                         return ins;
5721                 }
5722         } else if (cmethod->klass->image == mono_defaults.corlib &&
5723                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5724                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5725                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5726                         /* No stack walks are currently available, so implement this as an intrinsic */
5727                         MonoInst *method_ins;
5728                         MonoMethod *declaring = cfg->method;
5729
5730                         /* This returns the declaring generic method */
5731                         if (declaring->is_inflated)
5732                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5733                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5734                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
5735                         cfg->no_inline = TRUE;
5736                         if (cfg->method != cfg->current_method)
5737                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
5738                         return ins;
5739                 }
5740         } else if (cmethod->klass == mono_defaults.math_class) {
5741                 /* 
5742                  * There is general branchless code for Min/Max, but it does not work for 
5743                  * all inputs:
5744                  * http://everything2.com/?node_id=1051618
5745                  */
5746         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
5747                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
5748                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
5749                 ins->dreg = alloc_preg (cfg);
5750                 ins->type = STACK_I4;
5751                 MONO_ADD_INS (cfg->cbb, ins);
5752                 return ins;
5753         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
5754                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
5755                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
5756                                 !strcmp (cmethod->klass->name, "Selector")) ||
5757                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
5758                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
5759                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
5760                                 !strcmp (cmethod->klass->name, "Selector"))
5761                            ) {
5762                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
5763                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
5764                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
5765                     cfg->compile_aot) {
5766                         MonoInst *pi;
5767                         MonoJumpInfoToken *ji;
5768                         char *s;
5769
5770                         if (args [0]->opcode == OP_GOT_ENTRY) {
5771                                 pi = (MonoInst *)args [0]->inst_p1;
5772                                 g_assert (pi->opcode == OP_PATCH_INFO);
5773                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
5774                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
5775                         } else {
5776                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
5777                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
5778                         }
5779
5780                         NULLIFY_INS (args [0]);
5781
5782                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
5783                         return_val_if_nok (&cfg->error, NULL);
5784
5785                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
5786                         ins->dreg = mono_alloc_ireg (cfg);
5787                         // FIXME: Leaks
5788                         ins->inst_p0 = s;
5789                         MONO_ADD_INS (cfg->cbb, ins);
5790                         return ins;
5791                 }
5792         }
5793
5794 #ifdef MONO_ARCH_SIMD_INTRINSICS
5795         if (cfg->opt & MONO_OPT_SIMD) {
5796                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5797                 if (ins)
5798                         return ins;
5799         }
5800 #endif
5801
5802         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5803         if (ins)
5804                 return ins;
5805
5806         if (COMPILE_LLVM (cfg)) {
5807                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
5808                 if (ins)
5809                         return ins;
5810         }
5811
5812         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
5813 }
5814
5815 /*
5816  * This entry point could be used later for arbitrary method
5817  * redirection.
5818  */
5819 inline static MonoInst*
5820 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
5821                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
5822 {
5823         if (method->klass == mono_defaults.string_class) {
5824                 /* managed string allocation support */
5825                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
5826                         MonoInst *iargs [2];
5827                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
5828                         MonoMethod *managed_alloc = NULL;
5829
5830                         g_assert (vtable); /*Should not fail since it System.String*/
5831 #ifndef MONO_CROSS_COMPILE
5832                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
5833 #endif
5834                         if (!managed_alloc)
5835                                 return NULL;
5836                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
5837                         iargs [1] = args [0];
5838                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
5839                 }
5840         }
5841         return NULL;
5842 }
5843
5844 static void
5845 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
5846 {
5847         MonoInst *store, *temp;
5848         int i;
5849
5850         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5851                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
5852
5853                 /*
5854                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
5855                  * would be different than the MonoInst's used to represent arguments, and
5856                  * the ldelema implementation can't deal with that.
5857                  * Solution: When ldelema is used on an inline argument, create a var for 
5858                  * it, emit ldelema on that var, and emit the saving code below in
5859                  * inline_method () if needed.
5860                  */
5861                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
5862                 cfg->args [i] = temp;
5863                 /* This uses cfg->args [i] which is set by the preceeding line */
5864                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
5865                 store->cil_code = sp [0]->cil_code;
5866                 sp++;
5867         }
5868 }
5869
5870 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
5871 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
5872
5873 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
5874 static gboolean
5875 check_inline_called_method_name_limit (MonoMethod *called_method)
5876 {
5877         int strncmp_result;
5878         static const char *limit = NULL;
5879         
5880         if (limit == NULL) {
5881                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
5882
5883                 if (limit_string != NULL)
5884                         limit = limit_string;
5885                 else
5886                         limit = "";
5887         }
5888
5889         if (limit [0] != '\0') {
5890                 char *called_method_name = mono_method_full_name (called_method, TRUE);
5891
5892                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
5893                 g_free (called_method_name);
5894         
5895                 //return (strncmp_result <= 0);
5896                 return (strncmp_result == 0);
5897         } else {
5898                 return TRUE;
5899         }
5900 }
5901 #endif
5902
5903 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
5904 static gboolean
5905 check_inline_caller_method_name_limit (MonoMethod *caller_method)
5906 {
5907         int strncmp_result;
5908         static const char *limit = NULL;
5909         
5910         if (limit == NULL) {
5911                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
5912                 if (limit_string != NULL) {
5913                         limit = limit_string;
5914                 } else {
5915                         limit = "";
5916                 }
5917         }
5918
5919         if (limit [0] != '\0') {
5920                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
5921
5922                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
5923                 g_free (caller_method_name);
5924         
5925                 //return (strncmp_result <= 0);
5926                 return (strncmp_result == 0);
5927         } else {
5928                 return TRUE;
5929         }
5930 }
5931 #endif
5932
5933 static void
5934 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5935 {
5936         static double r8_0 = 0.0;
5937         static float r4_0 = 0.0;
5938         MonoInst *ins;
5939         int t;
5940
5941         rtype = mini_get_underlying_type (rtype);
5942         t = rtype->type;
5943
5944         if (rtype->byref) {
5945                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5946         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5947                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5948         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5949                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
5950         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
5951                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
5952                 ins->type = STACK_R4;
5953                 ins->inst_p0 = (void*)&r4_0;
5954                 ins->dreg = dreg;
5955                 MONO_ADD_INS (cfg->cbb, ins);
5956         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5957                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5958                 ins->type = STACK_R8;
5959                 ins->inst_p0 = (void*)&r8_0;
5960                 ins->dreg = dreg;
5961                 MONO_ADD_INS (cfg->cbb, ins);
5962         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
5963                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
5964                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
5965         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
5966                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
5967         } else {
5968                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5969         }
5970 }
5971
5972 static void
5973 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5974 {
5975         int t;
5976
5977         rtype = mini_get_underlying_type (rtype);
5978         t = rtype->type;
5979
5980         if (rtype->byref) {
5981                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
5982         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5983                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
5984         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5985                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
5986         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
5987                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
5988         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5989                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
5990         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
5991                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
5992                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
5993         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
5994                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
5995         } else {
5996                 emit_init_rvar (cfg, dreg, rtype);
5997         }
5998 }
5999
6000 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6001 static void
6002 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6003 {
6004         MonoInst *var = cfg->locals [local];
6005         if (COMPILE_SOFT_FLOAT (cfg)) {
6006                 MonoInst *store;
6007                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6008                 emit_init_rvar (cfg, reg, type);
6009                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6010         } else {
6011                 if (init)
6012                         emit_init_rvar (cfg, var->dreg, type);
6013                 else
6014                         emit_dummy_init_rvar (cfg, var->dreg, type);
6015         }
6016 }
6017
6018 int
6019 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6020 {
6021         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6022 }
6023
6024 /*
6025  * inline_method:
6026  *
6027  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6028  */
6029 static int
6030 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6031                guchar *ip, guint real_offset, gboolean inline_always)
6032 {
6033         MonoError error;
6034         MonoInst *ins, *rvar = NULL;
6035         MonoMethodHeader *cheader;
6036         MonoBasicBlock *ebblock, *sbblock;
6037         int i, costs;
6038         MonoMethod *prev_inlined_method;
6039         MonoInst **prev_locals, **prev_args;
6040         MonoType **prev_arg_types;
6041         guint prev_real_offset;
6042         GHashTable *prev_cbb_hash;
6043         MonoBasicBlock **prev_cil_offset_to_bb;
6044         MonoBasicBlock *prev_cbb;
6045         const unsigned char *prev_ip;
6046         unsigned char *prev_cil_start;
6047         guint32 prev_cil_offset_to_bb_len;
6048         MonoMethod *prev_current_method;
6049         MonoGenericContext *prev_generic_context;
6050         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6051
6052         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6053
6054 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6055         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6056                 return 0;
6057 #endif
6058 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6059         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6060                 return 0;
6061 #endif
6062
6063         if (!fsig)
6064                 fsig = mono_method_signature (cmethod);
6065
6066         if (cfg->verbose_level > 2)
6067                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6068
6069         if (!cmethod->inline_info) {
6070                 cfg->stat_inlineable_methods++;
6071                 cmethod->inline_info = 1;
6072         }
6073
6074         /* allocate local variables */
6075         cheader = mono_method_get_header_checked (cmethod, &error);
6076         if (!cheader) {
6077                 if (inline_always) {
6078                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6079                         mono_error_move (&cfg->error, &error);
6080                 } else {
6081                         mono_error_cleanup (&error);
6082                 }
6083                 return 0;
6084         }
6085
6086         /*Must verify before creating locals as it can cause the JIT to assert.*/
6087         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6088                 mono_metadata_free_mh (cheader);
6089                 return 0;
6090         }
6091
6092         /* allocate space to store the return value */
6093         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6094                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6095         }
6096
6097         prev_locals = cfg->locals;
6098         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6099         for (i = 0; i < cheader->num_locals; ++i)
6100                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6101
6102         /* allocate start and end blocks */
6103         /* This is needed so if the inline is aborted, we can clean up */
6104         NEW_BBLOCK (cfg, sbblock);
6105         sbblock->real_offset = real_offset;
6106
6107         NEW_BBLOCK (cfg, ebblock);
6108         ebblock->block_num = cfg->num_bblocks++;
6109         ebblock->real_offset = real_offset;
6110
6111         prev_args = cfg->args;
6112         prev_arg_types = cfg->arg_types;
6113         prev_inlined_method = cfg->inlined_method;
6114         cfg->inlined_method = cmethod;
6115         cfg->ret_var_set = FALSE;
6116         cfg->inline_depth ++;
6117         prev_real_offset = cfg->real_offset;
6118         prev_cbb_hash = cfg->cbb_hash;
6119         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6120         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6121         prev_cil_start = cfg->cil_start;
6122         prev_ip = cfg->ip;
6123         prev_cbb = cfg->cbb;
6124         prev_current_method = cfg->current_method;
6125         prev_generic_context = cfg->generic_context;
6126         prev_ret_var_set = cfg->ret_var_set;
6127         prev_disable_inline = cfg->disable_inline;
6128
6129         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6130                 virtual_ = TRUE;
6131
6132         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6133
6134         ret_var_set = cfg->ret_var_set;
6135
6136         cfg->inlined_method = prev_inlined_method;
6137         cfg->real_offset = prev_real_offset;
6138         cfg->cbb_hash = prev_cbb_hash;
6139         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6140         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6141         cfg->cil_start = prev_cil_start;
6142         cfg->ip = prev_ip;
6143         cfg->locals = prev_locals;
6144         cfg->args = prev_args;
6145         cfg->arg_types = prev_arg_types;
6146         cfg->current_method = prev_current_method;
6147         cfg->generic_context = prev_generic_context;
6148         cfg->ret_var_set = prev_ret_var_set;
6149         cfg->disable_inline = prev_disable_inline;
6150         cfg->inline_depth --;
6151
6152         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6153                 if (cfg->verbose_level > 2)
6154                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6155
6156                 cfg->stat_inlined_methods++;
6157
6158                 /* always add some code to avoid block split failures */
6159                 MONO_INST_NEW (cfg, ins, OP_NOP);
6160                 MONO_ADD_INS (prev_cbb, ins);
6161
6162                 prev_cbb->next_bb = sbblock;
6163                 link_bblock (cfg, prev_cbb, sbblock);
6164
6165                 /* 
6166                  * Get rid of the begin and end bblocks if possible to aid local
6167                  * optimizations.
6168                  */
6169                 if (prev_cbb->out_count == 1)
6170                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6171
6172                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6173                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6174
6175                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6176                         MonoBasicBlock *prev = ebblock->in_bb [0];
6177
6178                         if (prev->next_bb == ebblock) {
6179                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6180                                 cfg->cbb = prev;
6181                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6182                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6183                                         cfg->cbb = prev_cbb;
6184                                 }
6185                         } else {
6186                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6187                                 cfg->cbb = ebblock;
6188                         }
6189                 } else {
6190                         /* 
6191                          * Its possible that the rvar is set in some prev bblock, but not in others.
6192                          * (#1835).
6193                          */
6194                         if (rvar) {
6195                                 MonoBasicBlock *bb;
6196
6197                                 for (i = 0; i < ebblock->in_count; ++i) {
6198                                         bb = ebblock->in_bb [i];
6199
6200                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6201                                                 cfg->cbb = bb;
6202
6203                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6204                                         }
6205                                 }
6206                         }
6207
6208                         cfg->cbb = ebblock;
6209                 }
6210
6211                 if (rvar) {
6212                         /*
6213                          * If the inlined method contains only a throw, then the ret var is not 
6214                          * set, so set it to a dummy value.
6215                          */
6216                         if (!ret_var_set)
6217                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6218
6219                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6220                         *sp++ = ins;
6221                 }
6222                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6223                 return costs + 1;
6224         } else {
6225                 if (cfg->verbose_level > 2)
6226                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6227                 cfg->exception_type = MONO_EXCEPTION_NONE;
6228
6229                 /* This gets rid of the newly added bblocks */
6230                 cfg->cbb = prev_cbb;
6231         }
6232         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6233         return 0;
6234 }
6235
6236 /*
6237  * Some of these comments may well be out-of-date.
6238  * Design decisions: we do a single pass over the IL code (and we do bblock 
6239  * splitting/merging in the few cases when it's required: a back jump to an IL
6240  * address that was not already seen as bblock starting point).
6241  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6242  * Complex operations are decomposed in simpler ones right away. We need to let the 
6243  * arch-specific code peek and poke inside this process somehow (except when the 
6244  * optimizations can take advantage of the full semantic info of coarse opcodes).
6245  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6246  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6247  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6248  * opcode with value bigger than OP_LAST.
6249  * At this point the IR can be handed over to an interpreter, a dumb code generator
6250  * or to the optimizing code generator that will translate it to SSA form.
6251  *
6252  * Profiling directed optimizations.
6253  * We may compile by default with few or no optimizations and instrument the code
6254  * or the user may indicate what methods to optimize the most either in a config file
6255  * or through repeated runs where the compiler applies offline the optimizations to 
6256  * each method and then decides if it was worth it.
6257  */
6258
6259 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6260 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6261 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6262 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6263 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6264 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6265 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6266 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6267
6268 /* offset from br.s -> br like opcodes */
6269 #define BIG_BRANCH_OFFSET 13
6270
6271 static gboolean
6272 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6273 {
6274         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6275
6276         return b == NULL || b == bb;
6277 }
6278
6279 static int
6280 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6281 {
6282         unsigned char *ip = start;
6283         unsigned char *target;
6284         int i;
6285         guint cli_addr;
6286         MonoBasicBlock *bblock;
6287         const MonoOpcode *opcode;
6288
6289         while (ip < end) {
6290                 cli_addr = ip - start;
6291                 i = mono_opcode_value ((const guint8 **)&ip, end);
6292                 if (i < 0)
6293                         UNVERIFIED;
6294                 opcode = &mono_opcodes [i];
6295                 switch (opcode->argument) {
6296                 case MonoInlineNone:
6297                         ip++; 
6298                         break;
6299                 case MonoInlineString:
6300                 case MonoInlineType:
6301                 case MonoInlineField:
6302                 case MonoInlineMethod:
6303                 case MonoInlineTok:
6304                 case MonoInlineSig:
6305                 case MonoShortInlineR:
6306                 case MonoInlineI:
6307                         ip += 5;
6308                         break;
6309                 case MonoInlineVar:
6310                         ip += 3;
6311                         break;
6312                 case MonoShortInlineVar:
6313                 case MonoShortInlineI:
6314                         ip += 2;
6315                         break;
6316                 case MonoShortInlineBrTarget:
6317                         target = start + cli_addr + 2 + (signed char)ip [1];
6318                         GET_BBLOCK (cfg, bblock, target);
6319                         ip += 2;
6320                         if (ip < end)
6321                                 GET_BBLOCK (cfg, bblock, ip);
6322                         break;
6323                 case MonoInlineBrTarget:
6324                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6325                         GET_BBLOCK (cfg, bblock, target);
6326                         ip += 5;
6327                         if (ip < end)
6328                                 GET_BBLOCK (cfg, bblock, ip);
6329                         break;
6330                 case MonoInlineSwitch: {
6331                         guint32 n = read32 (ip + 1);
6332                         guint32 j;
6333                         ip += 5;
6334                         cli_addr += 5 + 4 * n;
6335                         target = start + cli_addr;
6336                         GET_BBLOCK (cfg, bblock, target);
6337                         
6338                         for (j = 0; j < n; ++j) {
6339                                 target = start + cli_addr + (gint32)read32 (ip);
6340                                 GET_BBLOCK (cfg, bblock, target);
6341                                 ip += 4;
6342                         }
6343                         break;
6344                 }
6345                 case MonoInlineR:
6346                 case MonoInlineI8:
6347                         ip += 9;
6348                         break;
6349                 default:
6350                         g_assert_not_reached ();
6351                 }
6352
6353                 if (i == CEE_THROW) {
6354                         unsigned char *bb_start = ip - 1;
6355                         
6356                         /* Find the start of the bblock containing the throw */
6357                         bblock = NULL;
6358                         while ((bb_start >= start) && !bblock) {
6359                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6360                                 bb_start --;
6361                         }
6362                         if (bblock)
6363                                 bblock->out_of_line = 1;
6364                 }
6365         }
6366         return 0;
6367 unverified:
6368 exception_exit:
6369         *pos = ip;
6370         return 1;
6371 }
6372
6373 static inline MonoMethod *
6374 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6375 {
6376         MonoMethod *method;
6377
6378         error_init (error);
6379
6380         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6381                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6382                 if (context) {
6383                         method = mono_class_inflate_generic_method_checked (method, context, error);
6384                 }
6385         } else {
6386                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6387         }
6388
6389         return method;
6390 }
6391
6392 static inline MonoMethod *
6393 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6394 {
6395         MonoError error;
6396         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6397
6398         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6399                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6400                 method = NULL;
6401         }
6402
6403         if (!method && !cfg)
6404                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6405
6406         return method;
6407 }
6408
6409 MonoClass*
6410 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6411 {
6412         MonoError error;
6413         MonoClass *klass;
6414
6415         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6416                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6417                 if (context) {
6418                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6419                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6420                 }
6421         } else {
6422                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6423                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6424         }
6425         if (klass)
6426                 mono_class_init (klass);
6427         return klass;
6428 }
6429
6430 static inline MonoMethodSignature*
6431 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6432 {
6433         MonoMethodSignature *fsig;
6434
6435         error_init (error);
6436         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6437                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6438         } else {
6439                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6440                 return_val_if_nok (error, NULL);
6441         }
6442         if (context) {
6443                 fsig = mono_inflate_generic_signature(fsig, context, error);
6444         }
6445         return fsig;
6446 }
6447
6448 static MonoMethod*
6449 throw_exception (void)
6450 {
6451         static MonoMethod *method = NULL;
6452
6453         if (!method) {
6454                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6455                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6456         }
6457         g_assert (method);
6458         return method;
6459 }
6460
6461 static void
6462 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6463 {
6464         MonoMethod *thrower = throw_exception ();
6465         MonoInst *args [1];
6466
6467         EMIT_NEW_PCONST (cfg, args [0], ex);
6468         mono_emit_method_call (cfg, thrower, args, NULL);
6469 }
6470
6471 /*
6472  * Return the original method is a wrapper is specified. We can only access 
6473  * the custom attributes from the original method.
6474  */
6475 static MonoMethod*
6476 get_original_method (MonoMethod *method)
6477 {
6478         if (method->wrapper_type == MONO_WRAPPER_NONE)
6479                 return method;
6480
6481         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6482         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6483                 return NULL;
6484
6485         /* in other cases we need to find the original method */
6486         return mono_marshal_method_from_wrapper (method);
6487 }
6488
6489 static void
6490 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6491 {
6492         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6493         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6494         if (ex)
6495                 emit_throw_exception (cfg, ex);
6496 }
6497
6498 static void
6499 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6500 {
6501         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6502         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6503         if (ex)
6504                 emit_throw_exception (cfg, ex);
6505 }
6506
6507 /*
6508  * Check that the IL instructions at ip are the array initialization
6509  * sequence and return the pointer to the data and the size.
6510  */
6511 static const char*
6512 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6513 {
6514         /*
6515          * newarr[System.Int32]
6516          * dup
6517          * ldtoken field valuetype ...
6518          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6519          */
6520         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6521                 MonoError error;
6522                 guint32 token = read32 (ip + 7);
6523                 guint32 field_token = read32 (ip + 2);
6524                 guint32 field_index = field_token & 0xffffff;
6525                 guint32 rva;
6526                 const char *data_ptr;
6527                 int size = 0;
6528                 MonoMethod *cmethod;
6529                 MonoClass *dummy_class;
6530                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6531                 int dummy_align;
6532
6533                 if (!field) {
6534                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6535                         return NULL;
6536                 }
6537
6538                 *out_field_token = field_token;
6539
6540                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6541                 if (!cmethod)
6542                         return NULL;
6543                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6544                         return NULL;
6545                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6546                 case MONO_TYPE_I1:
6547                 case MONO_TYPE_U1:
6548                         size = 1; break;
6549                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6550 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6551                 case MONO_TYPE_I2:
6552                 case MONO_TYPE_U2:
6553                         size = 2; break;
6554                 case MONO_TYPE_I4:
6555                 case MONO_TYPE_U4:
6556                 case MONO_TYPE_R4:
6557                         size = 4; break;
6558                 case MONO_TYPE_R8:
6559                 case MONO_TYPE_I8:
6560                 case MONO_TYPE_U8:
6561                         size = 8; break;
6562 #endif
6563                 default:
6564                         return NULL;
6565                 }
6566                 size *= len;
6567                 if (size > mono_type_size (field->type, &dummy_align))
6568                     return NULL;
6569                 *out_size = size;
6570                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6571                 if (!image_is_dynamic (method->klass->image)) {
6572                         field_index = read32 (ip + 2) & 0xffffff;
6573                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6574                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6575                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6576                         /* for aot code we do the lookup on load */
6577                         if (aot && data_ptr)
6578                                 return (const char *)GUINT_TO_POINTER (rva);
6579                 } else {
6580                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6581                         g_assert (!aot);
6582                         data_ptr = mono_field_get_data (field);
6583                 }
6584                 return data_ptr;
6585         }
6586         return NULL;
6587 }
6588
6589 static void
6590 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6591 {
6592         MonoError error;
6593         char *method_fname = mono_method_full_name (method, TRUE);
6594         char *method_code;
6595         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6596
6597         if (!header) {
6598                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6599                 mono_error_cleanup (&error);
6600         } else if (header->code_size == 0)
6601                 method_code = g_strdup ("method body is empty.");
6602         else
6603                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6604         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6605         g_free (method_fname);
6606         g_free (method_code);
6607         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6608 }
6609
6610 static void
6611 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6612 {
6613         MonoInst *ins;
6614         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6615         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6616                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6617                 /* Optimize reg-reg moves away */
6618                 /* 
6619                  * Can't optimize other opcodes, since sp[0] might point to
6620                  * the last ins of a decomposed opcode.
6621                  */
6622                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6623         } else {
6624                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6625         }
6626 }
6627
6628 /*
6629  * ldloca inhibits many optimizations so try to get rid of it in common
6630  * cases.
6631  */
6632 static inline unsigned char *
6633 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6634 {
6635         int local, token;
6636         MonoClass *klass;
6637         MonoType *type;
6638
6639         if (size == 1) {
6640                 local = ip [1];
6641                 ip += 2;
6642         } else {
6643                 local = read16 (ip + 2);
6644                 ip += 4;
6645         }
6646         
6647         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6648                 /* From the INITOBJ case */
6649                 token = read32 (ip + 2);
6650                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6651                 CHECK_TYPELOAD (klass);
6652                 type = mini_get_underlying_type (&klass->byval_arg);
6653                 emit_init_local (cfg, local, type, TRUE);
6654                 return ip + 6;
6655         }
6656  exception_exit:
6657         return NULL;
6658 }
6659
6660 static MonoInst*
6661 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6662 {
6663         MonoInst *icall_args [16];
6664         MonoInst *call_target, *ins, *vtable_ins;
6665         int arg_reg, this_reg, vtable_reg;
6666         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6667         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6668         gboolean variant_iface = FALSE;
6669         guint32 slot;
6670         int offset;
6671         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6672
6673         /*
6674          * In llvm-only mode, vtables contain function descriptors instead of
6675          * method addresses/trampolines.
6676          */
6677         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6678
6679         if (is_iface)
6680                 slot = mono_method_get_imt_slot (cmethod);
6681         else
6682                 slot = mono_method_get_vtable_index (cmethod);
6683
6684         this_reg = sp [0]->dreg;
6685
6686         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6687                 variant_iface = TRUE;
6688
6689         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6690                 /*
6691                  * The simplest case, a normal virtual call.
6692                  */
6693                 int slot_reg = alloc_preg (cfg);
6694                 int addr_reg = alloc_preg (cfg);
6695                 int arg_reg = alloc_preg (cfg);
6696                 MonoBasicBlock *non_null_bb;
6697
6698                 vtable_reg = alloc_preg (cfg);
6699                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6700                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6701
6702                 /* Load the vtable slot, which contains a function descriptor. */
6703                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6704
6705                 NEW_BBLOCK (cfg, non_null_bb);
6706
6707                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6708                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6709                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6710
6711                 /* Slow path */
6712                 // FIXME: Make the wrapper use the preserveall cconv
6713                 // FIXME: Use one icall per slot for small slot numbers ?
6714                 icall_args [0] = vtable_ins;
6715                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6716                 /* Make the icall return the vtable slot value to save some code space */
6717                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6718                 ins->dreg = slot_reg;
6719                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6720
6721                 /* Fastpath */
6722                 MONO_START_BB (cfg, non_null_bb);
6723                 /* Load the address + arg from the vtable slot */
6724                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6725                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
6726
6727                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6728         }
6729
6730         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
6731                 /*
6732                  * A simple interface call
6733                  *
6734                  * We make a call through an imt slot to obtain the function descriptor we need to call.
6735                  * The imt slot contains a function descriptor for a runtime function + arg.
6736                  */
6737                 int slot_reg = alloc_preg (cfg);
6738                 int addr_reg = alloc_preg (cfg);
6739                 int arg_reg = alloc_preg (cfg);
6740                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6741
6742                 vtable_reg = alloc_preg (cfg);
6743                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6744                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6745
6746                 /*
6747                  * The slot is already initialized when the vtable is created so there is no need
6748                  * to check it here.
6749                  */
6750
6751                 /* Load the imt slot, which contains a function descriptor. */
6752                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6753
6754                 /* Load the address + arg of the imt thunk from the imt slot */
6755                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6756                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6757                 /*
6758                  * IMT thunks in llvm-only mode are C functions which take an info argument
6759                  * plus the imt method and return the ftndesc to call.
6760                  */
6761                 icall_args [0] = thunk_arg_ins;
6762                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6763                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6764                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6765
6766                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6767         }
6768
6769         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
6770                 /*
6771                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
6772                  * dynamically extended as more instantiations are discovered.
6773                  * This handles generic virtual methods both on classes and interfaces.
6774                  */
6775                 int slot_reg = alloc_preg (cfg);
6776                 int addr_reg = alloc_preg (cfg);
6777                 int arg_reg = alloc_preg (cfg);
6778                 int ftndesc_reg = alloc_preg (cfg);
6779                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6780                 MonoBasicBlock *slowpath_bb, *end_bb;
6781
6782                 NEW_BBLOCK (cfg, slowpath_bb);
6783                 NEW_BBLOCK (cfg, end_bb);
6784
6785                 vtable_reg = alloc_preg (cfg);
6786                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6787                 if (is_iface)
6788                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6789                 else
6790                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6791
6792                 /* Load the slot, which contains a function descriptor. */
6793                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6794
6795                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
6796                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
6797                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6798                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6799
6800                 /* Fastpath */
6801                 /* Same as with iface calls */
6802                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6803                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6804                 icall_args [0] = thunk_arg_ins;
6805                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6806                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6807                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6808                 ftndesc_ins->dreg = ftndesc_reg;
6809                 /*
6810                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
6811                  * they don't know about yet. Fall back to the slowpath in that case.
6812                  */
6813                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
6814                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6815
6816                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6817
6818                 /* Slowpath */
6819                 MONO_START_BB (cfg, slowpath_bb);
6820                 icall_args [0] = vtable_ins;
6821                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6822                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6823                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6824                 if (is_iface)
6825                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
6826                 else
6827                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
6828                 ftndesc_ins->dreg = ftndesc_reg;
6829                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6830
6831                 /* Common case */
6832                 MONO_START_BB (cfg, end_bb);
6833                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6834         }
6835
6836         /*
6837          * Non-optimized cases
6838          */
6839         icall_args [0] = sp [0];
6840         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6841
6842         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6843                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
6844
6845         arg_reg = alloc_preg (cfg);
6846         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
6847         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
6848
6849         g_assert (is_gsharedvt);
6850         if (is_iface)
6851                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
6852         else
6853                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
6854
6855         /*
6856          * Pass the extra argument even if the callee doesn't receive it, most
6857          * calling conventions allow this.
6858          */
6859         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6860 }
6861
6862 static gboolean
6863 is_exception_class (MonoClass *klass)
6864 {
6865         while (klass) {
6866                 if (klass == mono_defaults.exception_class)
6867                         return TRUE;
6868                 klass = klass->parent;
6869         }
6870         return FALSE;
6871 }
6872
6873 /*
6874  * is_jit_optimizer_disabled:
6875  *
6876  *   Determine whenever M's assembly has a DebuggableAttribute with the
6877  * IsJITOptimizerDisabled flag set.
6878  */
6879 static gboolean
6880 is_jit_optimizer_disabled (MonoMethod *m)
6881 {
6882         MonoError error;
6883         MonoAssembly *ass = m->klass->image->assembly;
6884         MonoCustomAttrInfo* attrs;
6885         MonoClass *klass;
6886         int i;
6887         gboolean val = FALSE;
6888
6889         g_assert (ass);
6890         if (ass->jit_optimizer_disabled_inited)
6891                 return ass->jit_optimizer_disabled;
6892
6893         klass = mono_class_try_get_debuggable_attribute_class ();
6894
6895         if (!klass) {
6896                 /* Linked away */
6897                 ass->jit_optimizer_disabled = FALSE;
6898                 mono_memory_barrier ();
6899                 ass->jit_optimizer_disabled_inited = TRUE;
6900                 return FALSE;
6901         }
6902
6903         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
6904         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6905         if (attrs) {
6906                 for (i = 0; i < attrs->num_attrs; ++i) {
6907                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
6908                         const gchar *p;
6909                         MonoMethodSignature *sig;
6910
6911                         if (!attr->ctor || attr->ctor->klass != klass)
6912                                 continue;
6913                         /* Decode the attribute. See reflection.c */
6914                         p = (const char*)attr->data;
6915                         g_assert (read16 (p) == 0x0001);
6916                         p += 2;
6917
6918                         // FIXME: Support named parameters
6919                         sig = mono_method_signature (attr->ctor);
6920                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
6921                                 continue;
6922                         /* Two boolean arguments */
6923                         p ++;
6924                         val = *p;
6925                 }
6926                 mono_custom_attrs_free (attrs);
6927         }
6928
6929         ass->jit_optimizer_disabled = val;
6930         mono_memory_barrier ();
6931         ass->jit_optimizer_disabled_inited = TRUE;
6932
6933         return val;
6934 }
6935
6936 static gboolean
6937 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
6938 {
6939         gboolean supported_tail_call;
6940         int i;
6941
6942         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
6943
6944         for (i = 0; i < fsig->param_count; ++i) {
6945                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
6946                         /* These can point to the current method's stack */
6947                         supported_tail_call = FALSE;
6948         }
6949         if (fsig->hasthis && cmethod->klass->valuetype)
6950                 /* this might point to the current method's stack */
6951                 supported_tail_call = FALSE;
6952         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
6953                 supported_tail_call = FALSE;
6954         if (cfg->method->save_lmf)
6955                 supported_tail_call = FALSE;
6956         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
6957                 supported_tail_call = FALSE;
6958         if (call_opcode != CEE_CALL)
6959                 supported_tail_call = FALSE;
6960
6961         /* Debugging support */
6962 #if 0
6963         if (supported_tail_call) {
6964                 if (!mono_debug_count ())
6965                         supported_tail_call = FALSE;
6966         }
6967 #endif
6968
6969         return supported_tail_call;
6970 }
6971
6972 /*
6973  * handle_ctor_call:
6974  *
6975  *   Handle calls made to ctors from NEWOBJ opcodes.
6976  */
6977 static void
6978 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
6979                                   MonoInst **sp, guint8 *ip, int *inline_costs)
6980 {
6981         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
6982
6983         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
6984                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
6985                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
6986                         mono_class_vtable (cfg->domain, cmethod->klass);
6987                         CHECK_TYPELOAD (cmethod->klass);
6988
6989                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
6990                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
6991                 } else {
6992                         if (context_used) {
6993                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
6994                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
6995                         } else {
6996                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6997
6998                                 CHECK_TYPELOAD (cmethod->klass);
6999                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7000                         }
7001                 }
7002         }
7003
7004         /* Avoid virtual calls to ctors if possible */
7005         if (mono_class_is_marshalbyref (cmethod->klass))
7006                 callvirt_this_arg = sp [0];
7007
7008         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7009                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7010                 CHECK_CFG_EXCEPTION;
7011         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7012                            mono_method_check_inlining (cfg, cmethod) &&
7013                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7014                 int costs;
7015
7016                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7017                         cfg->real_offset += 5;
7018
7019                         *inline_costs += costs - 5;
7020                 } else {
7021                         INLINE_FAILURE ("inline failure");
7022                         // FIXME-VT: Clean this up
7023                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7024                                 GSHAREDVT_FAILURE(*ip);
7025                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7026                 }
7027         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7028                 MonoInst *addr;
7029
7030                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7031
7032                 if (cfg->llvm_only) {
7033                         // FIXME: Avoid initializing vtable_arg
7034                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7035                 } else {
7036                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7037                 }
7038         } else if (context_used &&
7039                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7040                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7041                 MonoInst *cmethod_addr;
7042
7043                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7044
7045                 if (cfg->llvm_only) {
7046                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7047                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7048                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7049                 } else {
7050                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7051                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7052
7053                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7054                 }
7055         } else {
7056                 INLINE_FAILURE ("ctor call");
7057                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7058                                                                                   callvirt_this_arg, NULL, vtable_arg);
7059         }
7060  exception_exit:
7061         return;
7062 }
7063
7064 static void
7065 emit_setret (MonoCompile *cfg, MonoInst *val)
7066 {
7067         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7068         MonoInst *ins;
7069
7070         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7071                 MonoInst *ret_addr;
7072
7073                 if (!cfg->vret_addr) {
7074                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7075                 } else {
7076                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7077
7078                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7079                         ins->klass = mono_class_from_mono_type (ret_type);
7080                 }
7081         } else {
7082 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7083                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7084                         MonoInst *iargs [1];
7085                         MonoInst *conv;
7086
7087                         iargs [0] = val;
7088                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7089                         mono_arch_emit_setret (cfg, cfg->method, conv);
7090                 } else {
7091                         mono_arch_emit_setret (cfg, cfg->method, val);
7092                 }
7093 #else
7094                 mono_arch_emit_setret (cfg, cfg->method, val);
7095 #endif
7096         }
7097 }
7098
7099 /*
7100  * mono_method_to_ir:
7101  *
7102  * Translate the .net IL into linear IR.
7103  *
7104  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7105  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7106  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7107  * @inline_args: if not NULL, contains the arguments to the inline call
7108  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7109  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7110  *
7111  * This method is used to turn ECMA IL into Mono's internal Linear IR
7112  * reprensetation.  It is used both for entire methods, as well as
7113  * inlining existing methods.  In the former case, the @start_bblock,
7114  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7115  * inline_offset is set to zero.
7116  * 
7117  * Returns: the inline cost, or -1 if there was an error processing this method.
7118  */
7119 int
7120 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7121                    MonoInst *return_var, MonoInst **inline_args, 
7122                    guint inline_offset, gboolean is_virtual_call)
7123 {
7124         MonoError error;
7125         MonoInst *ins, **sp, **stack_start;
7126         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7127         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7128         MonoMethod *cmethod, *method_definition;
7129         MonoInst **arg_array;
7130         MonoMethodHeader *header;
7131         MonoImage *image;
7132         guint32 token, ins_flag;
7133         MonoClass *klass;
7134         MonoClass *constrained_class = NULL;
7135         unsigned char *ip, *end, *target, *err_pos;
7136         MonoMethodSignature *sig;
7137         MonoGenericContext *generic_context = NULL;
7138         MonoGenericContainer *generic_container = NULL;
7139         MonoType **param_types;
7140         int i, n, start_new_bblock, dreg;
7141         int num_calls = 0, inline_costs = 0;
7142         int breakpoint_id = 0;
7143         guint num_args;
7144         GSList *class_inits = NULL;
7145         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7146         int context_used;
7147         gboolean init_locals, seq_points, skip_dead_blocks;
7148         gboolean sym_seq_points = FALSE;
7149         MonoDebugMethodInfo *minfo;
7150         MonoBitSet *seq_point_locs = NULL;
7151         MonoBitSet *seq_point_set_locs = NULL;
7152
7153         cfg->disable_inline = is_jit_optimizer_disabled (method);
7154
7155         /* serialization and xdomain stuff may need access to private fields and methods */
7156         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7157         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7158         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7159         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7160         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7161         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7162
7163         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7164         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7165         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7166         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7167         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7168
7169         image = method->klass->image;
7170         header = mono_method_get_header_checked (method, &cfg->error);
7171         if (!header) {
7172                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7173                 goto exception_exit;
7174         } else {
7175                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7176         }
7177
7178         generic_container = mono_method_get_generic_container (method);
7179         sig = mono_method_signature (method);
7180         num_args = sig->hasthis + sig->param_count;
7181         ip = (unsigned char*)header->code;
7182         cfg->cil_start = ip;
7183         end = ip + header->code_size;
7184         cfg->stat_cil_code_size += header->code_size;
7185
7186         seq_points = cfg->gen_seq_points && cfg->method == method;
7187
7188         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7189                 /* We could hit a seq point before attaching to the JIT (#8338) */
7190                 seq_points = FALSE;
7191         }
7192
7193         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7194                 minfo = mono_debug_lookup_method (method);
7195                 if (minfo) {
7196                         MonoSymSeqPoint *sps;
7197                         int i, n_il_offsets;
7198
7199                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7200                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7201                         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);
7202                         sym_seq_points = TRUE;
7203                         for (i = 0; i < n_il_offsets; ++i) {
7204                                 if (sps [i].il_offset < header->code_size)
7205                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7206                         }
7207                         g_free (sps);
7208
7209                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7210                         if (asyncMethod) {
7211                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7212                                 {
7213                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7214                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7215                                 }
7216                                 mono_debug_free_method_async_debug_info (asyncMethod);
7217                         }
7218                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7219                         /* Methods without line number info like auto-generated property accessors */
7220                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7221                         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);
7222                         sym_seq_points = TRUE;
7223                 }
7224         }
7225
7226         /* 
7227          * Methods without init_locals set could cause asserts in various passes
7228          * (#497220). To work around this, we emit dummy initialization opcodes
7229          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7230          * on some platforms.
7231          */
7232         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7233                 init_locals = header->init_locals;
7234         else
7235                 init_locals = TRUE;
7236
7237         method_definition = method;
7238         while (method_definition->is_inflated) {
7239                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7240                 method_definition = imethod->declaring;
7241         }
7242
7243         /* SkipVerification is not allowed if core-clr is enabled */
7244         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7245                 dont_verify = TRUE;
7246                 dont_verify_stloc = TRUE;
7247         }
7248
7249         if (sig->is_inflated)
7250                 generic_context = mono_method_get_context (method);
7251         else if (generic_container)
7252                 generic_context = &generic_container->context;
7253         cfg->generic_context = generic_context;
7254
7255         if (!cfg->gshared)
7256                 g_assert (!sig->has_type_parameters);
7257
7258         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7259                 g_assert (method->is_inflated);
7260                 g_assert (mono_method_get_context (method)->method_inst);
7261         }
7262         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7263                 g_assert (sig->generic_param_count);
7264
7265         if (cfg->method == method) {
7266                 cfg->real_offset = 0;
7267         } else {
7268                 cfg->real_offset = inline_offset;
7269         }
7270
7271         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7272         cfg->cil_offset_to_bb_len = header->code_size;
7273
7274         cfg->current_method = method;
7275
7276         if (cfg->verbose_level > 2)
7277                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7278
7279         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7280         if (sig->hasthis)
7281                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7282         for (n = 0; n < sig->param_count; ++n)
7283                 param_types [n + sig->hasthis] = sig->params [n];
7284         cfg->arg_types = param_types;
7285
7286         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7287         if (cfg->method == method) {
7288
7289                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7290                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7291
7292                 /* ENTRY BLOCK */
7293                 NEW_BBLOCK (cfg, start_bblock);
7294                 cfg->bb_entry = start_bblock;
7295                 start_bblock->cil_code = NULL;
7296                 start_bblock->cil_length = 0;
7297
7298                 /* EXIT BLOCK */
7299                 NEW_BBLOCK (cfg, end_bblock);
7300                 cfg->bb_exit = end_bblock;
7301                 end_bblock->cil_code = NULL;
7302                 end_bblock->cil_length = 0;
7303                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7304                 g_assert (cfg->num_bblocks == 2);
7305
7306                 arg_array = cfg->args;
7307
7308                 if (header->num_clauses) {
7309                         cfg->spvars = g_hash_table_new (NULL, NULL);
7310                         cfg->exvars = g_hash_table_new (NULL, NULL);
7311                 }
7312                 /* handle exception clauses */
7313                 for (i = 0; i < header->num_clauses; ++i) {
7314                         MonoBasicBlock *try_bb;
7315                         MonoExceptionClause *clause = &header->clauses [i];
7316                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7317
7318                         try_bb->real_offset = clause->try_offset;
7319                         try_bb->try_start = TRUE;
7320                         try_bb->region = ((i + 1) << 8) | clause->flags;
7321                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7322                         tblock->real_offset = clause->handler_offset;
7323                         tblock->flags |= BB_EXCEPTION_HANDLER;
7324
7325                         /*
7326                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7327                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7328                          */
7329                         if (COMPILE_LLVM (cfg))
7330                                 link_bblock (cfg, try_bb, tblock);
7331
7332                         if (*(ip + clause->handler_offset) == CEE_POP)
7333                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7334
7335                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7336                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7337                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7338                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7339                                 MONO_ADD_INS (tblock, ins);
7340
7341                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7342                                         /* finally clauses already have a seq point */
7343                                         /* seq points for filter clauses are emitted below */
7344                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7345                                         MONO_ADD_INS (tblock, ins);
7346                                 }
7347
7348                                 /* todo: is a fault block unsafe to optimize? */
7349                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7350                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7351                         }
7352
7353                         /*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);
7354                           while (p < end) {
7355                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7356                           }*/
7357                         /* catch and filter blocks get the exception object on the stack */
7358                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7359                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7360
7361                                 /* mostly like handle_stack_args (), but just sets the input args */
7362                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7363                                 tblock->in_scount = 1;
7364                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7365                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7366
7367                                 cfg->cbb = tblock;
7368
7369 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7370                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7371                                 if (!cfg->compile_llvm) {
7372                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7373                                         ins->dreg = tblock->in_stack [0]->dreg;
7374                                         MONO_ADD_INS (tblock, ins);
7375                                 }
7376 #else
7377                                 MonoInst *dummy_use;
7378
7379                                 /* 
7380                                  * Add a dummy use for the exvar so its liveness info will be
7381                                  * correct.
7382                                  */
7383                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7384 #endif
7385
7386                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7387                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7388                                         MONO_ADD_INS (tblock, ins);
7389                                 }
7390                                 
7391                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7392                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7393                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7394                                         tblock->real_offset = clause->data.filter_offset;
7395                                         tblock->in_scount = 1;
7396                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7397                                         /* The filter block shares the exvar with the handler block */
7398                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7399                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7400                                         MONO_ADD_INS (tblock, ins);
7401                                 }
7402                         }
7403
7404                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7405                                         clause->data.catch_class &&
7406                                         cfg->gshared &&
7407                                         mono_class_check_context_used (clause->data.catch_class)) {
7408                                 /*
7409                                  * In shared generic code with catch
7410                                  * clauses containing type variables
7411                                  * the exception handling code has to
7412                                  * be able to get to the rgctx.
7413                                  * Therefore we have to make sure that
7414                                  * the vtable/mrgctx argument (for
7415                                  * static or generic methods) or the
7416                                  * "this" argument (for non-static
7417                                  * methods) are live.
7418                                  */
7419                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7420                                                 mini_method_get_context (method)->method_inst ||
7421                                                 method->klass->valuetype) {
7422                                         mono_get_vtable_var (cfg);
7423                                 } else {
7424                                         MonoInst *dummy_use;
7425
7426                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7427                                 }
7428                         }
7429                 }
7430         } else {
7431                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7432                 cfg->cbb = start_bblock;
7433                 cfg->args = arg_array;
7434                 mono_save_args (cfg, sig, inline_args);
7435         }
7436
7437         /* FIRST CODE BLOCK */
7438         NEW_BBLOCK (cfg, tblock);
7439         tblock->cil_code = ip;
7440         cfg->cbb = tblock;
7441         cfg->ip = ip;
7442
7443         ADD_BBLOCK (cfg, tblock);
7444
7445         if (cfg->method == method) {
7446                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7447                 if (breakpoint_id) {
7448                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7449                         MONO_ADD_INS (cfg->cbb, ins);
7450                 }
7451         }
7452
7453         /* we use a separate basic block for the initialization code */
7454         NEW_BBLOCK (cfg, init_localsbb);
7455         if (cfg->method == method)
7456                 cfg->bb_init = init_localsbb;
7457         init_localsbb->real_offset = cfg->real_offset;
7458         start_bblock->next_bb = init_localsbb;
7459         init_localsbb->next_bb = cfg->cbb;
7460         link_bblock (cfg, start_bblock, init_localsbb);
7461         link_bblock (cfg, init_localsbb, cfg->cbb);
7462                 
7463         cfg->cbb = init_localsbb;
7464
7465         if (cfg->gsharedvt && cfg->method == method) {
7466                 MonoGSharedVtMethodInfo *info;
7467                 MonoInst *var, *locals_var;
7468                 int dreg;
7469
7470                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7471                 info->method = cfg->method;
7472                 info->count_entries = 16;
7473                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7474                 cfg->gsharedvt_info = info;
7475
7476                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7477                 /* prevent it from being register allocated */
7478                 //var->flags |= MONO_INST_VOLATILE;
7479                 cfg->gsharedvt_info_var = var;
7480
7481                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7482                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7483
7484                 /* Allocate locals */
7485                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7486                 /* prevent it from being register allocated */
7487                 //locals_var->flags |= MONO_INST_VOLATILE;
7488                 cfg->gsharedvt_locals_var = locals_var;
7489
7490                 dreg = alloc_ireg (cfg);
7491                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7492
7493                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7494                 ins->dreg = locals_var->dreg;
7495                 ins->sreg1 = dreg;
7496                 MONO_ADD_INS (cfg->cbb, ins);
7497                 cfg->gsharedvt_locals_var_ins = ins;
7498                 
7499                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7500                 /*
7501                 if (init_locals)
7502                         ins->flags |= MONO_INST_INIT;
7503                 */
7504         }
7505
7506         if (mono_security_core_clr_enabled ()) {
7507                 /* check if this is native code, e.g. an icall or a p/invoke */
7508                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7509                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7510                         if (wrapped) {
7511                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7512                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7513
7514                                 /* if this ia a native call then it can only be JITted from platform code */
7515                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7516                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7517                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7518                                                         mono_get_exception_method_access ();
7519                                                 emit_throw_exception (cfg, ex);
7520                                         }
7521                                 }
7522                         }
7523                 }
7524         }
7525
7526         CHECK_CFG_EXCEPTION;
7527
7528         if (header->code_size == 0)
7529                 UNVERIFIED;
7530
7531         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7532                 ip = err_pos;
7533                 UNVERIFIED;
7534         }
7535
7536         if (cfg->method == method)
7537                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7538
7539         for (n = 0; n < header->num_locals; ++n) {
7540                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7541                         UNVERIFIED;
7542         }
7543         class_inits = NULL;
7544
7545         /* We force the vtable variable here for all shared methods
7546            for the possibility that they might show up in a stack
7547            trace where their exact instantiation is needed. */
7548         if (cfg->gshared && method == cfg->method) {
7549                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7550                                 mini_method_get_context (method)->method_inst ||
7551                                 method->klass->valuetype) {
7552                         mono_get_vtable_var (cfg);
7553                 } else {
7554                         /* FIXME: Is there a better way to do this?
7555                            We need the variable live for the duration
7556                            of the whole method. */
7557                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7558                 }
7559         }
7560
7561         /* add a check for this != NULL to inlined methods */
7562         if (is_virtual_call) {
7563                 MonoInst *arg_ins;
7564
7565                 NEW_ARGLOAD (cfg, arg_ins, 0);
7566                 MONO_ADD_INS (cfg->cbb, arg_ins);
7567                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7568         }
7569
7570         skip_dead_blocks = !dont_verify;
7571         if (skip_dead_blocks) {
7572                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7573                 CHECK_CFG_ERROR;
7574                 g_assert (bb);
7575         }
7576
7577         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7578         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7579
7580         ins_flag = 0;
7581         start_new_bblock = 0;
7582         while (ip < end) {
7583                 if (cfg->method == method)
7584                         cfg->real_offset = ip - header->code;
7585                 else
7586                         cfg->real_offset = inline_offset;
7587                 cfg->ip = ip;
7588
7589                 context_used = 0;
7590
7591                 if (start_new_bblock) {
7592                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7593                         if (start_new_bblock == 2) {
7594                                 g_assert (ip == tblock->cil_code);
7595                         } else {
7596                                 GET_BBLOCK (cfg, tblock, ip);
7597                         }
7598                         cfg->cbb->next_bb = tblock;
7599                         cfg->cbb = tblock;
7600                         start_new_bblock = 0;
7601                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7602                                 if (cfg->verbose_level > 3)
7603                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7604                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7605                                 *sp++ = ins;
7606                         }
7607                         if (class_inits)
7608                                 g_slist_free (class_inits);
7609                         class_inits = NULL;
7610                 } else {
7611                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7612                                 link_bblock (cfg, cfg->cbb, tblock);
7613                                 if (sp != stack_start) {
7614                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7615                                         sp = stack_start;
7616                                         CHECK_UNVERIFIABLE (cfg);
7617                                 }
7618                                 cfg->cbb->next_bb = tblock;
7619                                 cfg->cbb = tblock;
7620                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7621                                         if (cfg->verbose_level > 3)
7622                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7623                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7624                                         *sp++ = ins;
7625                                 }
7626                                 g_slist_free (class_inits);
7627                                 class_inits = NULL;
7628                         }
7629                 }
7630
7631                 if (skip_dead_blocks) {
7632                         int ip_offset = ip - header->code;
7633
7634                         if (ip_offset == bb->end)
7635                                 bb = bb->next;
7636
7637                         if (bb->dead) {
7638                                 int op_size = mono_opcode_size (ip, end);
7639                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7640
7641                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7642
7643                                 if (ip_offset + op_size == bb->end) {
7644                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7645                                         MONO_ADD_INS (cfg->cbb, ins);
7646                                         start_new_bblock = 1;
7647                                 }
7648
7649                                 ip += op_size;
7650                                 continue;
7651                         }
7652                 }
7653                 /*
7654                  * Sequence points are points where the debugger can place a breakpoint.
7655                  * Currently, we generate these automatically at points where the IL
7656                  * stack is empty.
7657                  */
7658                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7659                         /*
7660                          * Make methods interruptable at the beginning, and at the targets of
7661                          * backward branches.
7662                          * Also, do this at the start of every bblock in methods with clauses too,
7663                          * to be able to handle instructions with inprecise control flow like
7664                          * throw/endfinally.
7665                          * Backward branches are handled at the end of method-to-ir ().
7666                          */
7667                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7668                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7669
7670                         /* Avoid sequence points on empty IL like .volatile */
7671                         // FIXME: Enable this
7672                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7673                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7674                         if ((sp != stack_start) && !sym_seq_point)
7675                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7676                         MONO_ADD_INS (cfg->cbb, ins);
7677
7678                         if (sym_seq_points)
7679                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7680                 }
7681
7682                 cfg->cbb->real_offset = cfg->real_offset;
7683
7684                 if ((cfg->method == method) && cfg->coverage_info) {
7685                         guint32 cil_offset = ip - header->code;
7686                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7687
7688                         /* TODO: Use an increment here */
7689 #if defined(TARGET_X86)
7690                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
7691                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
7692                         ins->inst_imm = 1;
7693                         MONO_ADD_INS (cfg->cbb, ins);
7694 #else
7695                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
7696                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7697 #endif
7698                 }
7699
7700                 if (cfg->verbose_level > 3)
7701                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7702
7703                 switch (*ip) {
7704                 case CEE_NOP:
7705                         if (seq_points && !sym_seq_points && sp != stack_start) {
7706                                 /*
7707                                  * The C# compiler uses these nops to notify the JIT that it should
7708                                  * insert seq points.
7709                                  */
7710                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7711                                 MONO_ADD_INS (cfg->cbb, ins);
7712                         }
7713                         if (cfg->keep_cil_nops)
7714                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7715                         else
7716                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7717                         ip++;
7718                         MONO_ADD_INS (cfg->cbb, ins);
7719                         break;
7720                 case CEE_BREAK:
7721                         if (mini_should_insert_breakpoint (cfg->method)) {
7722                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
7723                         } else {
7724                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7725                         }
7726                         ip++;
7727                         MONO_ADD_INS (cfg->cbb, ins);
7728                         break;
7729                 case CEE_LDARG_0:
7730                 case CEE_LDARG_1:
7731                 case CEE_LDARG_2:
7732                 case CEE_LDARG_3:
7733                         CHECK_STACK_OVF (1);
7734                         n = (*ip)-CEE_LDARG_0;
7735                         CHECK_ARG (n);
7736                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7737                         ip++;
7738                         *sp++ = ins;
7739                         break;
7740                 case CEE_LDLOC_0:
7741                 case CEE_LDLOC_1:
7742                 case CEE_LDLOC_2:
7743                 case CEE_LDLOC_3:
7744                         CHECK_STACK_OVF (1);
7745                         n = (*ip)-CEE_LDLOC_0;
7746                         CHECK_LOCAL (n);
7747                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7748                         ip++;
7749                         *sp++ = ins;
7750                         break;
7751                 case CEE_STLOC_0:
7752                 case CEE_STLOC_1:
7753                 case CEE_STLOC_2:
7754                 case CEE_STLOC_3: {
7755                         CHECK_STACK (1);
7756                         n = (*ip)-CEE_STLOC_0;
7757                         CHECK_LOCAL (n);
7758                         --sp;
7759                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
7760                                 UNVERIFIED;
7761                         emit_stloc_ir (cfg, sp, header, n);
7762                         ++ip;
7763                         inline_costs += 1;
7764                         break;
7765                         }
7766                 case CEE_LDARG_S:
7767                         CHECK_OPSIZE (2);
7768                         CHECK_STACK_OVF (1);
7769                         n = ip [1];
7770                         CHECK_ARG (n);
7771                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7772                         *sp++ = ins;
7773                         ip += 2;
7774                         break;
7775                 case CEE_LDARGA_S:
7776                         CHECK_OPSIZE (2);
7777                         CHECK_STACK_OVF (1);
7778                         n = ip [1];
7779                         CHECK_ARG (n);
7780                         NEW_ARGLOADA (cfg, ins, n);
7781                         MONO_ADD_INS (cfg->cbb, ins);
7782                         *sp++ = ins;
7783                         ip += 2;
7784                         break;
7785                 case CEE_STARG_S:
7786                         CHECK_OPSIZE (2);
7787                         CHECK_STACK (1);
7788                         --sp;
7789                         n = ip [1];
7790                         CHECK_ARG (n);
7791                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
7792                                 UNVERIFIED;
7793                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
7794                         ip += 2;
7795                         break;
7796                 case CEE_LDLOC_S:
7797                         CHECK_OPSIZE (2);
7798                         CHECK_STACK_OVF (1);
7799                         n = ip [1];
7800                         CHECK_LOCAL (n);
7801                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7802                         *sp++ = ins;
7803                         ip += 2;
7804                         break;
7805                 case CEE_LDLOCA_S: {
7806                         unsigned char *tmp_ip;
7807                         CHECK_OPSIZE (2);
7808                         CHECK_STACK_OVF (1);
7809                         CHECK_LOCAL (ip [1]);
7810
7811                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
7812                                 ip = tmp_ip;
7813                                 inline_costs += 1;
7814                                 break;
7815                         }
7816
7817                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
7818                         *sp++ = ins;
7819                         ip += 2;
7820                         break;
7821                 }
7822                 case CEE_STLOC_S:
7823                         CHECK_OPSIZE (2);
7824                         CHECK_STACK (1);
7825                         --sp;
7826                         CHECK_LOCAL (ip [1]);
7827                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
7828                                 UNVERIFIED;
7829                         emit_stloc_ir (cfg, sp, header, ip [1]);
7830                         ip += 2;
7831                         inline_costs += 1;
7832                         break;
7833                 case CEE_LDNULL:
7834                         CHECK_STACK_OVF (1);
7835                         EMIT_NEW_PCONST (cfg, ins, NULL);
7836                         ins->type = STACK_OBJ;
7837                         ++ip;
7838                         *sp++ = ins;
7839                         break;
7840                 case CEE_LDC_I4_M1:
7841                         CHECK_STACK_OVF (1);
7842                         EMIT_NEW_ICONST (cfg, ins, -1);
7843                         ++ip;
7844                         *sp++ = ins;
7845                         break;
7846                 case CEE_LDC_I4_0:
7847                 case CEE_LDC_I4_1:
7848                 case CEE_LDC_I4_2:
7849                 case CEE_LDC_I4_3:
7850                 case CEE_LDC_I4_4:
7851                 case CEE_LDC_I4_5:
7852                 case CEE_LDC_I4_6:
7853                 case CEE_LDC_I4_7:
7854                 case CEE_LDC_I4_8:
7855                         CHECK_STACK_OVF (1);
7856                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
7857                         ++ip;
7858                         *sp++ = ins;
7859                         break;
7860                 case CEE_LDC_I4_S:
7861                         CHECK_OPSIZE (2);
7862                         CHECK_STACK_OVF (1);
7863                         ++ip;
7864                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
7865                         ++ip;
7866                         *sp++ = ins;
7867                         break;
7868                 case CEE_LDC_I4:
7869                         CHECK_OPSIZE (5);
7870                         CHECK_STACK_OVF (1);
7871                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
7872                         ip += 5;
7873                         *sp++ = ins;
7874                         break;
7875                 case CEE_LDC_I8:
7876                         CHECK_OPSIZE (9);
7877                         CHECK_STACK_OVF (1);
7878                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
7879                         ins->type = STACK_I8;
7880                         ins->dreg = alloc_dreg (cfg, STACK_I8);
7881                         ++ip;
7882                         ins->inst_l = (gint64)read64 (ip);
7883                         MONO_ADD_INS (cfg->cbb, ins);
7884                         ip += 8;
7885                         *sp++ = ins;
7886                         break;
7887                 case CEE_LDC_R4: {
7888                         float *f;
7889                         gboolean use_aotconst = FALSE;
7890
7891 #ifdef TARGET_POWERPC
7892                         /* FIXME: Clean this up */
7893                         if (cfg->compile_aot)
7894                                 use_aotconst = TRUE;
7895 #endif
7896
7897                         /* FIXME: we should really allocate this only late in the compilation process */
7898                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
7899                         CHECK_OPSIZE (5);
7900                         CHECK_STACK_OVF (1);
7901
7902                         if (use_aotconst) {
7903                                 MonoInst *cons;
7904                                 int dreg;
7905
7906                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
7907
7908                                 dreg = alloc_freg (cfg);
7909                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
7910                                 ins->type = cfg->r4_stack_type;
7911                         } else {
7912                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
7913                                 ins->type = cfg->r4_stack_type;
7914                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
7915                                 ins->inst_p0 = f;
7916                                 MONO_ADD_INS (cfg->cbb, ins);
7917                         }
7918                         ++ip;
7919                         readr4 (ip, f);
7920                         ip += 4;
7921                         *sp++ = ins;                    
7922                         break;
7923                 }
7924                 case CEE_LDC_R8: {
7925                         double *d;
7926                         gboolean use_aotconst = FALSE;
7927
7928 #ifdef TARGET_POWERPC
7929                         /* FIXME: Clean this up */
7930                         if (cfg->compile_aot)
7931                                 use_aotconst = TRUE;
7932 #endif
7933
7934                         /* FIXME: we should really allocate this only late in the compilation process */
7935                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
7936                         CHECK_OPSIZE (9);
7937                         CHECK_STACK_OVF (1);
7938
7939                         if (use_aotconst) {
7940                                 MonoInst *cons;
7941                                 int dreg;
7942
7943                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
7944
7945                                 dreg = alloc_freg (cfg);
7946                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
7947                                 ins->type = STACK_R8;
7948                         } else {
7949                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7950                                 ins->type = STACK_R8;
7951                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
7952                                 ins->inst_p0 = d;
7953                                 MONO_ADD_INS (cfg->cbb, ins);
7954                         }
7955                         ++ip;
7956                         readr8 (ip, d);
7957                         ip += 8;
7958                         *sp++ = ins;
7959                         break;
7960                 }
7961                 case CEE_DUP: {
7962                         MonoInst *temp, *store;
7963                         CHECK_STACK (1);
7964                         CHECK_STACK_OVF (1);
7965                         sp--;
7966                         ins = *sp;
7967
7968                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7969                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7970
7971                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
7972                         *sp++ = ins;
7973
7974                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
7975                         *sp++ = ins;
7976
7977                         ++ip;
7978                         inline_costs += 2;
7979                         break;
7980                 }
7981                 case CEE_POP:
7982                         CHECK_STACK (1);
7983                         ip++;
7984                         --sp;
7985
7986 #ifdef TARGET_X86
7987                         if (sp [0]->type == STACK_R8)
7988                                 /* we need to pop the value from the x86 FP stack */
7989                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
7990 #endif
7991                         break;
7992                 case CEE_JMP: {
7993                         MonoCallInst *call;
7994                         MonoMethodSignature *fsig;
7995                         int i, n;
7996
7997                         INLINE_FAILURE ("jmp");
7998                         GSHAREDVT_FAILURE (*ip);
7999
8000                         CHECK_OPSIZE (5);
8001                         if (stack_start != sp)
8002                                 UNVERIFIED;
8003                         token = read32 (ip + 1);
8004                         /* FIXME: check the signature matches */
8005                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8006                         CHECK_CFG_ERROR;
8007  
8008                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8009                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8010
8011                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8012
8013                         fsig = mono_method_signature (cmethod);
8014                         n = fsig->param_count + fsig->hasthis;
8015                         if (cfg->llvm_only) {
8016                                 MonoInst **args;
8017
8018                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8019                                 for (i = 0; i < n; ++i)
8020                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8021                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8022                                 /*
8023                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8024                                  * have to emit a normal return since llvm expects it.
8025                                  */
8026                                 if (cfg->ret)
8027                                         emit_setret (cfg, ins);
8028                                 MONO_INST_NEW (cfg, ins, OP_BR);
8029                                 ins->inst_target_bb = end_bblock;
8030                                 MONO_ADD_INS (cfg->cbb, ins);
8031                                 link_bblock (cfg, cfg->cbb, end_bblock);
8032                                 ip += 5;
8033                                 break;
8034                         } else if (cfg->backend->have_op_tail_call) {
8035                                 /* Handle tail calls similarly to calls */
8036                                 DISABLE_AOT (cfg);
8037
8038                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8039                                 call->method = cmethod;
8040                                 call->tail_call = TRUE;
8041                                 call->signature = mono_method_signature (cmethod);
8042                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8043                                 call->inst.inst_p0 = cmethod;
8044                                 for (i = 0; i < n; ++i)
8045                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8046
8047                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8048                                         call->vret_var = cfg->vret_addr;
8049
8050                                 mono_arch_emit_call (cfg, call);
8051                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8052                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8053                         } else {
8054                                 for (i = 0; i < num_args; ++i)
8055                                         /* Prevent arguments from being optimized away */
8056                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8057
8058                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8059                                 ins = (MonoInst*)call;
8060                                 ins->inst_p0 = cmethod;
8061                                 MONO_ADD_INS (cfg->cbb, ins);
8062                         }
8063
8064                         ip += 5;
8065                         start_new_bblock = 1;
8066                         break;
8067                 }
8068                 case CEE_CALLI: {
8069                         MonoInst *addr;
8070                         MonoMethodSignature *fsig;
8071
8072                         CHECK_OPSIZE (5);
8073                         token = read32 (ip + 1);
8074
8075                         ins = NULL;
8076
8077                         //GSHAREDVT_FAILURE (*ip);
8078                         cmethod = NULL;
8079                         CHECK_STACK (1);
8080                         --sp;
8081                         addr = *sp;
8082                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8083                         CHECK_CFG_ERROR;
8084
8085                         if (method->dynamic && fsig->pinvoke) {
8086                                 MonoInst *args [3];
8087
8088                                 /*
8089                                  * This is a call through a function pointer using a pinvoke
8090                                  * signature. Have to create a wrapper and call that instead.
8091                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8092                                  * instead based on the signature.
8093                                  */
8094                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8095                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8096                                 args [2] = addr;
8097                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8098                         }
8099
8100                         n = fsig->param_count + fsig->hasthis;
8101
8102                         CHECK_STACK (n);
8103
8104                         //g_assert (!virtual_ || fsig->hasthis);
8105
8106                         sp -= n;
8107
8108                         inline_costs += 10 * num_calls++;
8109
8110                         /*
8111                          * Making generic calls out of gsharedvt methods.
8112                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8113                          * patching gshared method addresses into a gsharedvt method.
8114                          */
8115                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8116                                 /*
8117                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8118                                  */
8119                                 MonoInst *callee = addr;
8120
8121                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8122                                         /* Not tested */
8123                                         GSHAREDVT_FAILURE (*ip);
8124
8125                                 if (cfg->llvm_only)
8126                                         // FIXME:
8127                                         GSHAREDVT_FAILURE (*ip);
8128
8129                                 addr = emit_get_rgctx_sig (cfg, context_used,
8130                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8131                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8132                                 goto calli_end;
8133                         }
8134
8135                         /* Prevent inlining of methods with indirect calls */
8136                         INLINE_FAILURE ("indirect call");
8137
8138                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8139                                 MonoJumpInfoType info_type;
8140                                 gpointer info_data;
8141
8142                                 /*
8143                                  * Instead of emitting an indirect call, emit a direct call
8144                                  * with the contents of the aotconst as the patch info.
8145                                  */
8146                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8147                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8148                                         info_data = addr->inst_p0;
8149                                 } else {
8150                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8151                                         info_data = addr->inst_right->inst_left;
8152                                 }
8153
8154                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8155                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8156                                         NULLIFY_INS (addr);
8157                                         goto calli_end;
8158                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8159                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8160                                         NULLIFY_INS (addr);
8161                                         goto calli_end;
8162                                 }
8163                         }
8164                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8165
8166                         calli_end:
8167
8168                         /* End of call, INS should contain the result of the call, if any */
8169
8170                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8171                                 g_assert (ins);
8172                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8173                         }
8174
8175                         CHECK_CFG_EXCEPTION;
8176
8177                         ip += 5;
8178                         ins_flag = 0;
8179                         constrained_class = NULL;
8180                         break;
8181                 }
8182                 case CEE_CALL:
8183                 case CEE_CALLVIRT: {
8184                         MonoInst *addr = NULL;
8185                         MonoMethodSignature *fsig = NULL;
8186                         int array_rank = 0;
8187                         int virtual_ = *ip == CEE_CALLVIRT;
8188                         gboolean pass_imt_from_rgctx = FALSE;
8189                         MonoInst *imt_arg = NULL;
8190                         MonoInst *keep_this_alive = NULL;
8191                         gboolean pass_vtable = FALSE;
8192                         gboolean pass_mrgctx = FALSE;
8193                         MonoInst *vtable_arg = NULL;
8194                         gboolean check_this = FALSE;
8195                         gboolean supported_tail_call = FALSE;
8196                         gboolean tail_call = FALSE;
8197                         gboolean need_seq_point = FALSE;
8198                         guint32 call_opcode = *ip;
8199                         gboolean emit_widen = TRUE;
8200                         gboolean push_res = TRUE;
8201                         gboolean skip_ret = FALSE;
8202                         gboolean delegate_invoke = FALSE;
8203                         gboolean direct_icall = FALSE;
8204                         gboolean constrained_partial_call = FALSE;
8205                         MonoMethod *cil_method;
8206
8207                         CHECK_OPSIZE (5);
8208                         token = read32 (ip + 1);
8209
8210                         ins = NULL;
8211
8212                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8213                         CHECK_CFG_ERROR;
8214
8215                         cil_method = cmethod;
8216                                 
8217                         if (constrained_class) {
8218                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8219                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8220                                                 g_assert (!cmethod->klass->valuetype);
8221                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8222                                                         constrained_partial_call = TRUE;
8223                                         }
8224                                 }
8225
8226                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8227                                         if (cfg->verbose_level > 2)
8228                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8229                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8230                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8231                                                   cfg->gshared)) {
8232                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8233                                                 CHECK_CFG_ERROR;
8234                                         }
8235                                 } else {
8236                                         if (cfg->verbose_level > 2)
8237                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8238
8239                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8240                                                 /* 
8241                                                  * This is needed since get_method_constrained can't find 
8242                                                  * the method in klass representing a type var.
8243                                                  * The type var is guaranteed to be a reference type in this
8244                                                  * case.
8245                                                  */
8246                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8247                                                         g_assert (!cmethod->klass->valuetype);
8248                                         } else {
8249                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8250                                                 CHECK_CFG_ERROR;
8251                                         }
8252                                 }
8253
8254                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8255                                         /* Use the corresponding method from the base type to avoid boxing */
8256                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8257                                         g_assert (base_type);
8258                                         constrained_class = mono_class_from_mono_type (base_type);
8259                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8260                                         g_assert (cmethod);
8261                                 }
8262                         }
8263                                         
8264                         if (!dont_verify && !cfg->skip_visibility) {
8265                                 MonoMethod *target_method = cil_method;
8266                                 if (method->is_inflated) {
8267                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8268                                         CHECK_CFG_ERROR;
8269                                 }
8270                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8271                                         !mono_method_can_access_method (method, cil_method))
8272                                         emit_method_access_failure (cfg, method, cil_method);
8273                         }
8274
8275                         if (mono_security_core_clr_enabled ())
8276                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8277
8278                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8279                                 /* MS.NET seems to silently convert this to a callvirt */
8280                                 virtual_ = 1;
8281
8282                         {
8283                                 /*
8284                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8285                                  * converts to a callvirt.
8286                                  *
8287                                  * tests/bug-515884.il is an example of this behavior
8288                                  */
8289                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8290                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8291                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8292                                         virtual_ = 1;
8293                         }
8294
8295                         if (!cmethod->klass->inited)
8296                                 if (!mono_class_init (cmethod->klass))
8297                                         TYPE_LOAD_ERROR (cmethod->klass);
8298
8299                         fsig = mono_method_signature (cmethod);
8300                         if (!fsig)
8301                                 LOAD_ERROR;
8302                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8303                                 mini_class_is_system_array (cmethod->klass)) {
8304                                 array_rank = cmethod->klass->rank;
8305                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8306                                 direct_icall = TRUE;
8307                         } else if (fsig->pinvoke) {
8308                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8309                                 fsig = mono_method_signature (wrapper);
8310                         } else if (constrained_class) {
8311                         } else {
8312                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8313                                 CHECK_CFG_ERROR;
8314                         }
8315
8316                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8317                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8318
8319                         /* See code below */
8320                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8321                                 MonoBasicBlock *tbb;
8322
8323                                 GET_BBLOCK (cfg, tbb, ip + 5);
8324                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8325                                         /*
8326                                          * We want to extend the try block to cover the call, but we can't do it if the
8327                                          * call is made directly since its followed by an exception check.
8328                                          */
8329                                         direct_icall = FALSE;
8330                                 }
8331                         }
8332
8333                         mono_save_token_info (cfg, image, token, cil_method);
8334
8335                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8336                                 need_seq_point = TRUE;
8337
8338                         /* Don't support calls made using type arguments for now */
8339                         /*
8340                           if (cfg->gsharedvt) {
8341                           if (mini_is_gsharedvt_signature (fsig))
8342                           GSHAREDVT_FAILURE (*ip);
8343                           }
8344                         */
8345
8346                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8347                                 g_assert_not_reached ();
8348
8349                         n = fsig->param_count + fsig->hasthis;
8350
8351                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8352                                 UNVERIFIED;
8353
8354                         if (!cfg->gshared)
8355                                 g_assert (!mono_method_check_context_used (cmethod));
8356
8357                         CHECK_STACK (n);
8358
8359                         //g_assert (!virtual_ || fsig->hasthis);
8360
8361                         sp -= n;
8362
8363                         if (cmethod && cmethod->klass->image == mono_defaults.corlib && !strcmp (cmethod->klass->name, "ThrowHelper"))
8364                                 cfg->cbb->out_of_line = TRUE;
8365
8366                         /*
8367                          * We have the `constrained.' prefix opcode.
8368                          */
8369                         if (constrained_class) {
8370                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8371                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8372                                                 /* The 'Own method' case below */
8373                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8374                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8375                                         } else {
8376                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8377                                                 CHECK_CFG_EXCEPTION;
8378                                                 g_assert (ins);
8379                                                 goto call_end;
8380                                         }
8381                                 }
8382
8383                                 if (constrained_partial_call) {
8384                                         gboolean need_box = TRUE;
8385
8386                                         /*
8387                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8388                                          * called method is not known at compile time either. The called method could end up being
8389                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8390                                          * to box the receiver.
8391                                          * A simple solution would be to box always and make a normal virtual call, but that would
8392                                          * be bad performance wise.
8393                                          */
8394                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8395                                                 /*
8396                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8397                                                  */
8398                                                 need_box = FALSE;
8399                                         }
8400
8401                                         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)) {
8402                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8403                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8404                                                 ins->klass = constrained_class;
8405                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8406                                                 CHECK_CFG_EXCEPTION;
8407                                         } else if (need_box) {
8408                                                 MonoInst *box_type;
8409                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8410                                                 MonoInst *nonbox_call;
8411
8412                                                 /*
8413                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8414                                                  * if needed.
8415                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8416                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8417                                                  */
8418                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8419
8420                                                 NEW_BBLOCK (cfg, is_ref_bb);
8421                                                 NEW_BBLOCK (cfg, end_bb);
8422
8423                                                 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);
8424                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8425                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8426
8427                                                 /* Non-ref case */
8428                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8429
8430                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8431
8432                                                 /* Ref case */
8433                                                 MONO_START_BB (cfg, is_ref_bb);
8434                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8435                                                 ins->klass = constrained_class;
8436                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8437                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8438
8439                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8440
8441                                                 MONO_START_BB (cfg, end_bb);
8442                                                 cfg->cbb = end_bb;
8443
8444                                                 nonbox_call->dreg = ins->dreg;
8445                                                 goto call_end;
8446                                         } else {
8447                                                 g_assert (mono_class_is_interface (cmethod->klass));
8448                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8449                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8450                                                 goto call_end;
8451                                         }
8452                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8453                                         /*
8454                                          * The type parameter is instantiated as a valuetype,
8455                                          * but that type doesn't override the method we're
8456                                          * calling, so we need to box `this'.
8457                                          */
8458                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8459                                         ins->klass = constrained_class;
8460                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8461                                         CHECK_CFG_EXCEPTION;
8462                                 } else if (!constrained_class->valuetype) {
8463                                         int dreg = alloc_ireg_ref (cfg);
8464
8465                                         /*
8466                                          * The type parameter is instantiated as a reference
8467                                          * type.  We have a managed pointer on the stack, so
8468                                          * we need to dereference it here.
8469                                          */
8470                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8471                                         ins->type = STACK_OBJ;
8472                                         sp [0] = ins;
8473                                 } else {
8474                                         if (cmethod->klass->valuetype) {
8475                                                 /* Own method */
8476                                         } else {
8477                                                 /* Interface method */
8478                                                 int ioffset, slot;
8479
8480                                                 mono_class_setup_vtable (constrained_class);
8481                                                 CHECK_TYPELOAD (constrained_class);
8482                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8483                                                 if (ioffset == -1)
8484                                                         TYPE_LOAD_ERROR (constrained_class);
8485                                                 slot = mono_method_get_vtable_slot (cmethod);
8486                                                 if (slot == -1)
8487                                                         TYPE_LOAD_ERROR (cmethod->klass);
8488                                                 cmethod = constrained_class->vtable [ioffset + slot];
8489
8490                                                 if (cmethod->klass == mono_defaults.enum_class) {
8491                                                         /* Enum implements some interfaces, so treat this as the first case */
8492                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8493                                                         ins->klass = constrained_class;
8494                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8495                                                         CHECK_CFG_EXCEPTION;
8496                                                 }
8497                                         }
8498                                         virtual_ = 0;
8499                                 }
8500                                 constrained_class = NULL;
8501                         }
8502
8503                         if (check_call_signature (cfg, fsig, sp))
8504                                 UNVERIFIED;
8505
8506                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8507                                 delegate_invoke = TRUE;
8508
8509                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8510                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8511                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8512                                         emit_widen = FALSE;
8513                                 }
8514
8515                                 goto call_end;
8516                         }
8517
8518                         /* 
8519                          * If the callee is a shared method, then its static cctor
8520                          * might not get called after the call was patched.
8521                          */
8522                         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)) {
8523                                 emit_class_init (cfg, cmethod->klass);
8524                                 CHECK_TYPELOAD (cmethod->klass);
8525                         }
8526
8527                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8528
8529                         if (cfg->gshared) {
8530                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8531
8532                                 context_used = mini_method_check_context_used (cfg, cmethod);
8533
8534                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8535                                         /* Generic method interface
8536                                            calls are resolved via a
8537                                            helper function and don't
8538                                            need an imt. */
8539                                         if (!cmethod_context || !cmethod_context->method_inst)
8540                                                 pass_imt_from_rgctx = TRUE;
8541                                 }
8542
8543                                 /*
8544                                  * If a shared method calls another
8545                                  * shared method then the caller must
8546                                  * have a generic sharing context
8547                                  * because the magic trampoline
8548                                  * requires it.  FIXME: We shouldn't
8549                                  * have to force the vtable/mrgctx
8550                                  * variable here.  Instead there
8551                                  * should be a flag in the cfg to
8552                                  * request a generic sharing context.
8553                                  */
8554                                 if (context_used &&
8555                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8556                                         mono_get_vtable_var (cfg);
8557                         }
8558
8559                         if (pass_vtable) {
8560                                 if (context_used) {
8561                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8562                                 } else {
8563                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8564
8565                                         CHECK_TYPELOAD (cmethod->klass);
8566                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8567                                 }
8568                         }
8569
8570                         if (pass_mrgctx) {
8571                                 g_assert (!vtable_arg);
8572
8573                                 if (!cfg->compile_aot) {
8574                                         /* 
8575                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8576                                          * for type load errors before.
8577                                          */
8578                                         mono_class_setup_vtable (cmethod->klass);
8579                                         CHECK_TYPELOAD (cmethod->klass);
8580                                 }
8581
8582                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8583
8584                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8585                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8586                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8587                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8588                                         if (virtual_)
8589                                                 check_this = TRUE;
8590                                         virtual_ = 0;
8591                                 }
8592                         }
8593
8594                         if (pass_imt_from_rgctx) {
8595                                 g_assert (!pass_vtable);
8596
8597                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8598                                         cmethod, MONO_RGCTX_INFO_METHOD);
8599                         }
8600
8601                         if (check_this)
8602                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8603
8604                         /* Calling virtual generic methods */
8605                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8606                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8607                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8608                             fsig->generic_param_count && 
8609                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8610                                 !cfg->llvm_only) {
8611                                 MonoInst *this_temp, *this_arg_temp, *store;
8612                                 MonoInst *iargs [4];
8613
8614                                 g_assert (fsig->is_inflated);
8615
8616                                 /* Prevent inlining of methods that contain indirect calls */
8617                                 INLINE_FAILURE ("virtual generic call");
8618
8619                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8620                                         GSHAREDVT_FAILURE (*ip);
8621
8622                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8623                                         g_assert (!imt_arg);
8624                                         if (!context_used)
8625                                                 g_assert (cmethod->is_inflated);
8626                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8627                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8628                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8629                                 } else {
8630                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8631                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8632                                         MONO_ADD_INS (cfg->cbb, store);
8633
8634                                         /* FIXME: This should be a managed pointer */
8635                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8636
8637                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8638                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8639                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8640                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8641                                         addr = mono_emit_jit_icall (cfg,
8642                                                                                                 mono_helper_compile_generic_method, iargs);
8643
8644                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8645
8646                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8647                                 }
8648
8649                                 goto call_end;
8650                         }
8651
8652                         /*
8653                          * Implement a workaround for the inherent races involved in locking:
8654                          * Monitor.Enter ()
8655                          * try {
8656                          * } finally {
8657                          *    Monitor.Exit ()
8658                          * }
8659                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8660                          * try block, the Exit () won't be executed, see:
8661                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8662                          * To work around this, we extend such try blocks to include the last x bytes
8663                          * of the Monitor.Enter () call.
8664                          */
8665                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8666                                 MonoBasicBlock *tbb;
8667
8668                                 GET_BBLOCK (cfg, tbb, ip + 5);
8669                                 /* 
8670                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8671                                  * from Monitor.Enter like ArgumentNullException.
8672                                  */
8673                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8674                                         /* Mark this bblock as needing to be extended */
8675                                         tbb->extend_try_block = TRUE;
8676                                 }
8677                         }
8678
8679                         /* Conversion to a JIT intrinsic */
8680                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8681                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8682                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8683                                         emit_widen = FALSE;
8684                                 }
8685                                 goto call_end;
8686                         }
8687                         CHECK_CFG_ERROR;
8688                         
8689                         /* Inlining */
8690                         if ((cfg->opt & MONO_OPT_INLINE) &&
8691                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8692                             mono_method_check_inlining (cfg, cmethod)) {
8693                                 int costs;
8694                                 gboolean always = FALSE;
8695
8696                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8697                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8698                                         /* Prevent inlining of methods that call wrappers */
8699                                         INLINE_FAILURE ("wrapper call");
8700                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8701                                         always = TRUE;
8702                                 }
8703
8704                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8705                                 if (costs) {
8706                                         cfg->real_offset += 5;
8707
8708                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8709                                                 /* *sp is already set by inline_method */
8710                                                 sp++;
8711                                                 push_res = FALSE;
8712                                         }
8713
8714                                         inline_costs += costs;
8715
8716                                         goto call_end;
8717                                 }
8718                         }
8719
8720                         /* Tail recursion elimination */
8721                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
8722                                 gboolean has_vtargs = FALSE;
8723                                 int i;
8724
8725                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8726                                 INLINE_FAILURE ("tail call");
8727
8728                                 /* keep it simple */
8729                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
8730                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
8731                                                 has_vtargs = TRUE;
8732                                 }
8733
8734                                 if (!has_vtargs) {
8735                                         if (need_seq_point) {
8736                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
8737                                                 need_seq_point = FALSE;
8738                                         }
8739                                         for (i = 0; i < n; ++i)
8740                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8741                                         MONO_INST_NEW (cfg, ins, OP_BR);
8742                                         MONO_ADD_INS (cfg->cbb, ins);
8743                                         tblock = start_bblock->out_bb [0];
8744                                         link_bblock (cfg, cfg->cbb, tblock);
8745                                         ins->inst_target_bb = tblock;
8746                                         start_new_bblock = 1;
8747
8748                                         /* skip the CEE_RET, too */
8749                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
8750                                                 skip_ret = TRUE;
8751                                         push_res = FALSE;
8752                                         goto call_end;
8753                                 }
8754                         }
8755
8756                         inline_costs += 10 * num_calls++;
8757
8758                         /*
8759                          * Synchronized wrappers.
8760                          * Its hard to determine where to replace a method with its synchronized
8761                          * wrapper without causing an infinite recursion. The current solution is
8762                          * to add the synchronized wrapper in the trampolines, and to
8763                          * change the called method to a dummy wrapper, and resolve that wrapper
8764                          * to the real method in mono_jit_compile_method ().
8765                          */
8766                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
8767                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
8768                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
8769                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
8770                         }
8771
8772                         /*
8773                          * Making generic calls out of gsharedvt methods.
8774                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8775                          * patching gshared method addresses into a gsharedvt method.
8776                          */
8777                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
8778                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
8779                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
8780                                 MonoRgctxInfoType info_type;
8781
8782                                 if (virtual_) {
8783                                         //if (mono_class_is_interface (cmethod->klass))
8784                                                 //GSHAREDVT_FAILURE (*ip);
8785                                         // disable for possible remoting calls
8786                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
8787                                                 GSHAREDVT_FAILURE (*ip);
8788                                         if (fsig->generic_param_count) {
8789                                                 /* virtual generic call */
8790                                                 g_assert (!imt_arg);
8791                                                 /* Same as the virtual generic case above */
8792                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8793                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8794                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
8795                                                 vtable_arg = NULL;
8796                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
8797                                                 /* This can happen when we call a fully instantiated iface method */
8798                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8799                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8800                                                 vtable_arg = NULL;
8801                                         }
8802                                 }
8803
8804                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
8805                                         keep_this_alive = sp [0];
8806
8807                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
8808                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
8809                                 else
8810                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
8811                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
8812
8813                                 if (cfg->llvm_only) {
8814                                         // FIXME: Avoid initializing vtable_arg
8815                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8816                                 } else {
8817                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8818                                 }
8819                                 goto call_end;
8820                         }
8821
8822                         /* Generic sharing */
8823
8824                         /*
8825                          * Use this if the callee is gsharedvt sharable too, since
8826                          * at runtime we might find an instantiation so the call cannot
8827                          * be patched (the 'no_patch' code path in mini-trampolines.c).
8828                          */
8829                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
8830                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8831                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
8832                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
8833                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
8834                                 INLINE_FAILURE ("gshared");
8835
8836                                 g_assert (cfg->gshared && cmethod);
8837                                 g_assert (!addr);
8838
8839                                 /*
8840                                  * We are compiling a call to a
8841                                  * generic method from shared code,
8842                                  * which means that we have to look up
8843                                  * the method in the rgctx and do an
8844                                  * indirect call.
8845                                  */
8846                                 if (fsig->hasthis)
8847                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8848
8849                                 if (cfg->llvm_only) {
8850                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
8851                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
8852                                         else
8853                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8854                                         // FIXME: Avoid initializing imt_arg/vtable_arg
8855                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8856                                 } else {
8857                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8858                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8859                                 }
8860                                 goto call_end;
8861                         }
8862
8863                         /* Direct calls to icalls */
8864                         if (direct_icall) {
8865                                 MonoMethod *wrapper;
8866                                 int costs;
8867
8868                                 /* Inline the wrapper */
8869                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8870
8871                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
8872                                 g_assert (costs > 0);
8873                                 cfg->real_offset += 5;
8874
8875                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8876                                         /* *sp is already set by inline_method */
8877                                         sp++;
8878                                         push_res = FALSE;
8879                                 }
8880
8881                                 inline_costs += costs;
8882
8883                                 goto call_end;
8884                         }
8885                                         
8886                         /* Array methods */
8887                         if (array_rank) {
8888                                 MonoInst *addr;
8889
8890                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
8891                                         MonoInst *val = sp [fsig->param_count];
8892
8893                                         if (val->type == STACK_OBJ) {
8894                                                 MonoInst *iargs [2];
8895
8896                                                 iargs [0] = sp [0];
8897                                                 iargs [1] = val;
8898                                                 
8899                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
8900                                         }
8901                                         
8902                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
8903                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
8904                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
8905                                                 mini_emit_write_barrier (cfg, addr, val);
8906                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
8907                                                 GSHAREDVT_FAILURE (*ip);
8908                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
8909                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8910
8911                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
8912                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
8913                                         if (!cmethod->klass->element_class->valuetype && !readonly)
8914                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
8915                                         CHECK_TYPELOAD (cmethod->klass);
8916                                         
8917                                         readonly = FALSE;
8918                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8919                                         ins = addr;
8920                                 } else {
8921                                         g_assert_not_reached ();
8922                                 }
8923
8924                                 emit_widen = FALSE;
8925                                 goto call_end;
8926                         }
8927
8928                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
8929                         if (ins)
8930                                 goto call_end;
8931
8932                         /* Tail prefix / tail call optimization */
8933
8934                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
8935                         /* FIXME: runtime generic context pointer for jumps? */
8936                         /* FIXME: handle this for generic sharing eventually */
8937                         if ((ins_flag & MONO_INST_TAILCALL) &&
8938                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
8939                                 supported_tail_call = TRUE;
8940
8941                         if (supported_tail_call) {
8942                                 MonoCallInst *call;
8943
8944                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8945                                 INLINE_FAILURE ("tail call");
8946
8947                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
8948
8949                                 if (cfg->backend->have_op_tail_call) {
8950                                         /* Handle tail calls similarly to normal calls */
8951                                         tail_call = TRUE;
8952                                 } else {
8953                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8954
8955                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8956                                         call->tail_call = TRUE;
8957                                         call->method = cmethod;
8958                                         call->signature = mono_method_signature (cmethod);
8959
8960                                         /*
8961                                          * We implement tail calls by storing the actual arguments into the 
8962                                          * argument variables, then emitting a CEE_JMP.
8963                                          */
8964                                         for (i = 0; i < n; ++i) {
8965                                                 /* Prevent argument from being register allocated */
8966                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
8967                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8968                                         }
8969                                         ins = (MonoInst*)call;
8970                                         ins->inst_p0 = cmethod;
8971                                         ins->inst_p1 = arg_array [0];
8972                                         MONO_ADD_INS (cfg->cbb, ins);
8973                                         link_bblock (cfg, cfg->cbb, end_bblock);
8974                                         start_new_bblock = 1;
8975
8976                                         // FIXME: Eliminate unreachable epilogs
8977
8978                                         /*
8979                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
8980                                          * only reachable from this call.
8981                                          */
8982                                         GET_BBLOCK (cfg, tblock, ip + 5);
8983                                         if (tblock == cfg->cbb || tblock->in_count == 0)
8984                                                 skip_ret = TRUE;
8985                                         push_res = FALSE;
8986
8987                                         goto call_end;
8988                                 }
8989                         }
8990
8991                         /*
8992                          * Virtual calls in llvm-only mode.
8993                          */
8994                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
8995                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
8996                                 goto call_end;
8997                         }
8998
8999                         /* Common call */
9000                         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) && !(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9001                                 INLINE_FAILURE ("call");
9002                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9003                                                                                           imt_arg, vtable_arg);
9004
9005                         if (tail_call && !cfg->llvm_only) {
9006                                 link_bblock (cfg, cfg->cbb, end_bblock);
9007                                 start_new_bblock = 1;
9008
9009                                 // FIXME: Eliminate unreachable epilogs
9010
9011                                 /*
9012                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9013                                  * only reachable from this call.
9014                                  */
9015                                 GET_BBLOCK (cfg, tblock, ip + 5);
9016                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9017                                         skip_ret = TRUE;
9018                                 push_res = FALSE;
9019                         }
9020
9021                         call_end:
9022
9023                         /* End of call, INS should contain the result of the call, if any */
9024
9025                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9026                                 g_assert (ins);
9027                                 if (emit_widen)
9028                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9029                                 else
9030                                         *sp++ = ins;
9031                         }
9032
9033                         if (keep_this_alive) {
9034                                 MonoInst *dummy_use;
9035
9036                                 /* See mono_emit_method_call_full () */
9037                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9038                         }
9039
9040                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9041                                 /*
9042                                  * Clang can convert these calls to tail calls which screw up the stack
9043                                  * walk. This happens even when the -fno-optimize-sibling-calls
9044                                  * option is passed to clang.
9045                                  * Work around this by emitting a dummy call.
9046                                  */
9047                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9048                         }
9049
9050                         CHECK_CFG_EXCEPTION;
9051
9052                         ip += 5;
9053                         if (skip_ret) {
9054                                 g_assert (*ip == CEE_RET);
9055                                 ip += 1;
9056                         }
9057                         ins_flag = 0;
9058                         constrained_class = NULL;
9059                         if (need_seq_point)
9060                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9061                         break;
9062                 }
9063                 case CEE_RET:
9064                         if (cfg->method != method) {
9065                                 /* return from inlined method */
9066                                 /* 
9067                                  * If in_count == 0, that means the ret is unreachable due to
9068                                  * being preceeded by a throw. In that case, inline_method () will
9069                                  * handle setting the return value 
9070                                  * (test case: test_0_inline_throw ()).
9071                                  */
9072                                 if (return_var && cfg->cbb->in_count) {
9073                                         MonoType *ret_type = mono_method_signature (method)->ret;
9074
9075                                         MonoInst *store;
9076                                         CHECK_STACK (1);
9077                                         --sp;
9078
9079                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9080                                                 UNVERIFIED;
9081
9082                                         //g_assert (returnvar != -1);
9083                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9084                                         cfg->ret_var_set = TRUE;
9085                                 } 
9086                         } else {
9087                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9088
9089                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9090                                         emit_pop_lmf (cfg);
9091
9092                                 if (cfg->ret) {
9093                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9094
9095                                         if (seq_points && !sym_seq_points) {
9096                                                 /* 
9097                                                  * Place a seq point here too even through the IL stack is not
9098                                                  * empty, so a step over on
9099                                                  * call <FOO>
9100                                                  * ret
9101                                                  * will work correctly.
9102                                                  */
9103                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9104                                                 MONO_ADD_INS (cfg->cbb, ins);
9105                                         }
9106
9107                                         g_assert (!return_var);
9108                                         CHECK_STACK (1);
9109                                         --sp;
9110
9111                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9112                                                 UNVERIFIED;
9113
9114                                         emit_setret (cfg, *sp);
9115                                 }
9116                         }
9117                         if (sp != stack_start)
9118                                 UNVERIFIED;
9119                         MONO_INST_NEW (cfg, ins, OP_BR);
9120                         ip++;
9121                         ins->inst_target_bb = end_bblock;
9122                         MONO_ADD_INS (cfg->cbb, ins);
9123                         link_bblock (cfg, cfg->cbb, end_bblock);
9124                         start_new_bblock = 1;
9125                         break;
9126                 case CEE_BR_S:
9127                         CHECK_OPSIZE (2);
9128                         MONO_INST_NEW (cfg, ins, OP_BR);
9129                         ip++;
9130                         target = ip + 1 + (signed char)(*ip);
9131                         ++ip;
9132                         GET_BBLOCK (cfg, tblock, target);
9133                         link_bblock (cfg, cfg->cbb, tblock);
9134                         ins->inst_target_bb = tblock;
9135                         if (sp != stack_start) {
9136                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9137                                 sp = stack_start;
9138                                 CHECK_UNVERIFIABLE (cfg);
9139                         }
9140                         MONO_ADD_INS (cfg->cbb, ins);
9141                         start_new_bblock = 1;
9142                         inline_costs += BRANCH_COST;
9143                         break;
9144                 case CEE_BEQ_S:
9145                 case CEE_BGE_S:
9146                 case CEE_BGT_S:
9147                 case CEE_BLE_S:
9148                 case CEE_BLT_S:
9149                 case CEE_BNE_UN_S:
9150                 case CEE_BGE_UN_S:
9151                 case CEE_BGT_UN_S:
9152                 case CEE_BLE_UN_S:
9153                 case CEE_BLT_UN_S:
9154                         CHECK_OPSIZE (2);
9155                         CHECK_STACK (2);
9156                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9157                         ip++;
9158                         target = ip + 1 + *(signed char*)ip;
9159                         ip++;
9160
9161                         ADD_BINCOND (NULL);
9162
9163                         sp = stack_start;
9164                         inline_costs += BRANCH_COST;
9165                         break;
9166                 case CEE_BR:
9167                         CHECK_OPSIZE (5);
9168                         MONO_INST_NEW (cfg, ins, OP_BR);
9169                         ip++;
9170
9171                         target = ip + 4 + (gint32)read32(ip);
9172                         ip += 4;
9173                         GET_BBLOCK (cfg, tblock, target);
9174                         link_bblock (cfg, cfg->cbb, tblock);
9175                         ins->inst_target_bb = tblock;
9176                         if (sp != stack_start) {
9177                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9178                                 sp = stack_start;
9179                                 CHECK_UNVERIFIABLE (cfg);
9180                         }
9181
9182                         MONO_ADD_INS (cfg->cbb, ins);
9183
9184                         start_new_bblock = 1;
9185                         inline_costs += BRANCH_COST;
9186                         break;
9187                 case CEE_BRFALSE_S:
9188                 case CEE_BRTRUE_S:
9189                 case CEE_BRFALSE:
9190                 case CEE_BRTRUE: {
9191                         MonoInst *cmp;
9192                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9193                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9194                         guint32 opsize = is_short ? 1 : 4;
9195
9196                         CHECK_OPSIZE (opsize);
9197                         CHECK_STACK (1);
9198                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9199                                 UNVERIFIED;
9200                         ip ++;
9201                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9202                         ip += opsize;
9203
9204                         sp--;
9205
9206                         GET_BBLOCK (cfg, tblock, target);
9207                         link_bblock (cfg, cfg->cbb, tblock);
9208                         GET_BBLOCK (cfg, tblock, ip);
9209                         link_bblock (cfg, cfg->cbb, tblock);
9210
9211                         if (sp != stack_start) {
9212                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9213                                 CHECK_UNVERIFIABLE (cfg);
9214                         }
9215
9216                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9217                         cmp->sreg1 = sp [0]->dreg;
9218                         type_from_op (cfg, cmp, sp [0], NULL);
9219                         CHECK_TYPE (cmp);
9220
9221 #if SIZEOF_REGISTER == 4
9222                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9223                                 /* Convert it to OP_LCOMPARE */
9224                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9225                                 ins->type = STACK_I8;
9226                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9227                                 ins->inst_l = 0;
9228                                 MONO_ADD_INS (cfg->cbb, ins);
9229                                 cmp->opcode = OP_LCOMPARE;
9230                                 cmp->sreg2 = ins->dreg;
9231                         }
9232 #endif
9233                         MONO_ADD_INS (cfg->cbb, cmp);
9234
9235                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9236                         type_from_op (cfg, ins, sp [0], NULL);
9237                         MONO_ADD_INS (cfg->cbb, ins);
9238                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9239                         GET_BBLOCK (cfg, tblock, target);
9240                         ins->inst_true_bb = tblock;
9241                         GET_BBLOCK (cfg, tblock, ip);
9242                         ins->inst_false_bb = tblock;
9243                         start_new_bblock = 2;
9244
9245                         sp = stack_start;
9246                         inline_costs += BRANCH_COST;
9247                         break;
9248                 }
9249                 case CEE_BEQ:
9250                 case CEE_BGE:
9251                 case CEE_BGT:
9252                 case CEE_BLE:
9253                 case CEE_BLT:
9254                 case CEE_BNE_UN:
9255                 case CEE_BGE_UN:
9256                 case CEE_BGT_UN:
9257                 case CEE_BLE_UN:
9258                 case CEE_BLT_UN:
9259                         CHECK_OPSIZE (5);
9260                         CHECK_STACK (2);
9261                         MONO_INST_NEW (cfg, ins, *ip);
9262                         ip++;
9263                         target = ip + 4 + (gint32)read32(ip);
9264                         ip += 4;
9265
9266                         ADD_BINCOND (NULL);
9267
9268                         sp = stack_start;
9269                         inline_costs += BRANCH_COST;
9270                         break;
9271                 case CEE_SWITCH: {
9272                         MonoInst *src1;
9273                         MonoBasicBlock **targets;
9274                         MonoBasicBlock *default_bblock;
9275                         MonoJumpInfoBBTable *table;
9276                         int offset_reg = alloc_preg (cfg);
9277                         int target_reg = alloc_preg (cfg);
9278                         int table_reg = alloc_preg (cfg);
9279                         int sum_reg = alloc_preg (cfg);
9280                         gboolean use_op_switch;
9281
9282                         CHECK_OPSIZE (5);
9283                         CHECK_STACK (1);
9284                         n = read32 (ip + 1);
9285                         --sp;
9286                         src1 = sp [0];
9287                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9288                                 UNVERIFIED;
9289
9290                         ip += 5;
9291                         CHECK_OPSIZE (n * sizeof (guint32));
9292                         target = ip + n * sizeof (guint32);
9293
9294                         GET_BBLOCK (cfg, default_bblock, target);
9295                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9296
9297                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9298                         for (i = 0; i < n; ++i) {
9299                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9300                                 targets [i] = tblock;
9301                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9302                                 ip += 4;
9303                         }
9304
9305                         if (sp != stack_start) {
9306                                 /* 
9307                                  * Link the current bb with the targets as well, so handle_stack_args
9308                                  * will set their in_stack correctly.
9309                                  */
9310                                 link_bblock (cfg, cfg->cbb, default_bblock);
9311                                 for (i = 0; i < n; ++i)
9312                                         link_bblock (cfg, cfg->cbb, targets [i]);
9313
9314                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9315                                 sp = stack_start;
9316                                 CHECK_UNVERIFIABLE (cfg);
9317
9318                                 /* Undo the links */
9319                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9320                                 for (i = 0; i < n; ++i)
9321                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9322                         }
9323
9324                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9325                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9326
9327                         for (i = 0; i < n; ++i)
9328                                 link_bblock (cfg, cfg->cbb, targets [i]);
9329
9330                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9331                         table->table = targets;
9332                         table->table_size = n;
9333
9334                         use_op_switch = FALSE;
9335 #ifdef TARGET_ARM
9336                         /* ARM implements SWITCH statements differently */
9337                         /* FIXME: Make it use the generic implementation */
9338                         if (!cfg->compile_aot)
9339                                 use_op_switch = TRUE;
9340 #endif
9341
9342                         if (COMPILE_LLVM (cfg))
9343                                 use_op_switch = TRUE;
9344
9345                         cfg->cbb->has_jump_table = 1;
9346
9347                         if (use_op_switch) {
9348                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9349                                 ins->sreg1 = src1->dreg;
9350                                 ins->inst_p0 = table;
9351                                 ins->inst_many_bb = targets;
9352                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9353                                 MONO_ADD_INS (cfg->cbb, ins);
9354                         } else {
9355                                 if (sizeof (gpointer) == 8)
9356                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9357                                 else
9358                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9359
9360 #if SIZEOF_REGISTER == 8
9361                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9362                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9363 #endif
9364
9365                                 if (cfg->compile_aot) {
9366                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9367                                 } else {
9368                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9369                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9370                                         ins->inst_p0 = table;
9371                                         ins->dreg = table_reg;
9372                                         MONO_ADD_INS (cfg->cbb, ins);
9373                                 }
9374
9375                                 /* FIXME: Use load_memindex */
9376                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9377                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9378                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9379                         }
9380                         start_new_bblock = 1;
9381                         inline_costs += (BRANCH_COST * 2);
9382                         break;
9383                 }
9384                 case CEE_LDIND_I1:
9385                 case CEE_LDIND_U1:
9386                 case CEE_LDIND_I2:
9387                 case CEE_LDIND_U2:
9388                 case CEE_LDIND_I4:
9389                 case CEE_LDIND_U4:
9390                 case CEE_LDIND_I8:
9391                 case CEE_LDIND_I:
9392                 case CEE_LDIND_R4:
9393                 case CEE_LDIND_R8:
9394                 case CEE_LDIND_REF:
9395                         CHECK_STACK (1);
9396                         --sp;
9397
9398                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9399                         *sp++ = ins;
9400                         ins_flag = 0;
9401                         ++ip;
9402                         break;
9403                 case CEE_STIND_REF:
9404                 case CEE_STIND_I1:
9405                 case CEE_STIND_I2:
9406                 case CEE_STIND_I4:
9407                 case CEE_STIND_I8:
9408                 case CEE_STIND_R4:
9409                 case CEE_STIND_R8:
9410                 case CEE_STIND_I:
9411                         CHECK_STACK (2);
9412                         sp -= 2;
9413
9414                         if (ins_flag & MONO_INST_VOLATILE) {
9415                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9416                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9417                         }
9418
9419                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9420                         ins->flags |= ins_flag;
9421                         ins_flag = 0;
9422
9423                         MONO_ADD_INS (cfg->cbb, ins);
9424
9425                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9426                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9427
9428                         inline_costs += 1;
9429                         ++ip;
9430                         break;
9431
9432                 case CEE_MUL:
9433                         CHECK_STACK (2);
9434
9435                         MONO_INST_NEW (cfg, ins, (*ip));
9436                         sp -= 2;
9437                         ins->sreg1 = sp [0]->dreg;
9438                         ins->sreg2 = sp [1]->dreg;
9439                         type_from_op (cfg, ins, sp [0], sp [1]);
9440                         CHECK_TYPE (ins);
9441                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9442
9443                         /* Use the immediate opcodes if possible */
9444                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9445                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9446                                 if (imm_opcode != -1) {
9447                                         ins->opcode = imm_opcode;
9448                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9449                                         ins->sreg2 = -1;
9450
9451                                         NULLIFY_INS (sp [1]);
9452                                 }
9453                         }
9454
9455                         MONO_ADD_INS ((cfg)->cbb, (ins));
9456
9457                         *sp++ = mono_decompose_opcode (cfg, ins);
9458                         ip++;
9459                         break;
9460                 case CEE_ADD:
9461                 case CEE_SUB:
9462                 case CEE_DIV:
9463                 case CEE_DIV_UN:
9464                 case CEE_REM:
9465                 case CEE_REM_UN:
9466                 case CEE_AND:
9467                 case CEE_OR:
9468                 case CEE_XOR:
9469                 case CEE_SHL:
9470                 case CEE_SHR:
9471                 case CEE_SHR_UN:
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                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9481                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9482
9483                         /* FIXME: Pass opcode to is_inst_imm */
9484
9485                         /* Use the immediate opcodes if possible */
9486                         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)) {
9487                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9488                                 if (imm_opcode != -1) {
9489                                         ins->opcode = imm_opcode;
9490                                         if (sp [1]->opcode == OP_I8CONST) {
9491 #if SIZEOF_REGISTER == 8
9492                                                 ins->inst_imm = sp [1]->inst_l;
9493 #else
9494                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9495                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9496 #endif
9497                                         }
9498                                         else
9499                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9500                                         ins->sreg2 = -1;
9501
9502                                         /* Might be followed by an instruction added by add_widen_op */
9503                                         if (sp [1]->next == NULL)
9504                                                 NULLIFY_INS (sp [1]);
9505                                 }
9506                         }
9507                         MONO_ADD_INS ((cfg)->cbb, (ins));
9508
9509                         *sp++ = mono_decompose_opcode (cfg, ins);
9510                         ip++;
9511                         break;
9512                 case CEE_NEG:
9513                 case CEE_NOT:
9514                 case CEE_CONV_I1:
9515                 case CEE_CONV_I2:
9516                 case CEE_CONV_I4:
9517                 case CEE_CONV_R4:
9518                 case CEE_CONV_R8:
9519                 case CEE_CONV_U4:
9520                 case CEE_CONV_I8:
9521                 case CEE_CONV_U8:
9522                 case CEE_CONV_OVF_I8:
9523                 case CEE_CONV_OVF_U8:
9524                 case CEE_CONV_R_UN:
9525                         CHECK_STACK (1);
9526
9527                         /* Special case this earlier so we have long constants in the IR */
9528                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9529                                 int data = sp [-1]->inst_c0;
9530                                 sp [-1]->opcode = OP_I8CONST;
9531                                 sp [-1]->type = STACK_I8;
9532 #if SIZEOF_REGISTER == 8
9533                                 if ((*ip) == CEE_CONV_U8)
9534                                         sp [-1]->inst_c0 = (guint32)data;
9535                                 else
9536                                         sp [-1]->inst_c0 = data;
9537 #else
9538                                 sp [-1]->inst_ls_word = data;
9539                                 if ((*ip) == CEE_CONV_U8)
9540                                         sp [-1]->inst_ms_word = 0;
9541                                 else
9542                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9543 #endif
9544                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9545                         }
9546                         else {
9547                                 ADD_UNOP (*ip);
9548                         }
9549                         ip++;
9550                         break;
9551                 case CEE_CONV_OVF_I4:
9552                 case CEE_CONV_OVF_I1:
9553                 case CEE_CONV_OVF_I2:
9554                 case CEE_CONV_OVF_I:
9555                 case CEE_CONV_OVF_U:
9556                         CHECK_STACK (1);
9557
9558                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9559                                 ADD_UNOP (CEE_CONV_OVF_I8);
9560                                 ADD_UNOP (*ip);
9561                         } else {
9562                                 ADD_UNOP (*ip);
9563                         }
9564                         ip++;
9565                         break;
9566                 case CEE_CONV_OVF_U1:
9567                 case CEE_CONV_OVF_U2:
9568                 case CEE_CONV_OVF_U4:
9569                         CHECK_STACK (1);
9570
9571                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9572                                 ADD_UNOP (CEE_CONV_OVF_U8);
9573                                 ADD_UNOP (*ip);
9574                         } else {
9575                                 ADD_UNOP (*ip);
9576                         }
9577                         ip++;
9578                         break;
9579                 case CEE_CONV_OVF_I1_UN:
9580                 case CEE_CONV_OVF_I2_UN:
9581                 case CEE_CONV_OVF_I4_UN:
9582                 case CEE_CONV_OVF_I8_UN:
9583                 case CEE_CONV_OVF_U1_UN:
9584                 case CEE_CONV_OVF_U2_UN:
9585                 case CEE_CONV_OVF_U4_UN:
9586                 case CEE_CONV_OVF_U8_UN:
9587                 case CEE_CONV_OVF_I_UN:
9588                 case CEE_CONV_OVF_U_UN:
9589                 case CEE_CONV_U2:
9590                 case CEE_CONV_U1:
9591                 case CEE_CONV_I:
9592                 case CEE_CONV_U:
9593                         CHECK_STACK (1);
9594                         ADD_UNOP (*ip);
9595                         CHECK_CFG_EXCEPTION;
9596                         ip++;
9597                         break;
9598                 case CEE_ADD_OVF:
9599                 case CEE_ADD_OVF_UN:
9600                 case CEE_MUL_OVF:
9601                 case CEE_MUL_OVF_UN:
9602                 case CEE_SUB_OVF:
9603                 case CEE_SUB_OVF_UN:
9604                         CHECK_STACK (2);
9605                         ADD_BINOP (*ip);
9606                         ip++;
9607                         break;
9608                 case CEE_CPOBJ:
9609                         GSHAREDVT_FAILURE (*ip);
9610                         CHECK_OPSIZE (5);
9611                         CHECK_STACK (2);
9612                         token = read32 (ip + 1);
9613                         klass = mini_get_class (method, token, generic_context);
9614                         CHECK_TYPELOAD (klass);
9615                         sp -= 2;
9616                         mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9617                         ins_flag = 0;
9618                         ip += 5;
9619                         break;
9620                 case CEE_LDOBJ: {
9621                         int loc_index = -1;
9622                         int stloc_len = 0;
9623
9624                         CHECK_OPSIZE (5);
9625                         CHECK_STACK (1);
9626                         --sp;
9627                         token = read32 (ip + 1);
9628                         klass = mini_get_class (method, token, generic_context);
9629                         CHECK_TYPELOAD (klass);
9630
9631                         /* Optimize the common ldobj+stloc combination */
9632                         switch (ip [5]) {
9633                         case CEE_STLOC_S:
9634                                 loc_index = ip [6];
9635                                 stloc_len = 2;
9636                                 break;
9637                         case CEE_STLOC_0:
9638                         case CEE_STLOC_1:
9639                         case CEE_STLOC_2:
9640                         case CEE_STLOC_3:
9641                                 loc_index = ip [5] - CEE_STLOC_0;
9642                                 stloc_len = 1;
9643                                 break;
9644                         default:
9645                                 break;
9646                         }
9647
9648                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9649                                 CHECK_LOCAL (loc_index);
9650
9651                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9652                                 ins->dreg = cfg->locals [loc_index]->dreg;
9653                                 ins->flags |= ins_flag;
9654                                 ip += 5;
9655                                 ip += stloc_len;
9656                                 if (ins_flag & MONO_INST_VOLATILE) {
9657                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9658                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9659                                 }
9660                                 ins_flag = 0;
9661                                 break;
9662                         }
9663
9664                         /* Optimize the ldobj+stobj combination */
9665                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token)) {
9666                                 CHECK_STACK (1);
9667
9668                                 sp --;
9669
9670                                 mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9671
9672                                 ip += 5 + 5;
9673                                 ins_flag = 0;
9674                                 break;
9675                         }
9676
9677                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9678                         *sp++ = ins;
9679
9680                         ip += 5;
9681                         ins_flag = 0;
9682                         inline_costs += 1;
9683                         break;
9684                 }
9685                 case CEE_LDSTR:
9686                         CHECK_STACK_OVF (1);
9687                         CHECK_OPSIZE (5);
9688                         n = read32 (ip + 1);
9689
9690                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9691                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9692                                 ins->type = STACK_OBJ;
9693                                 *sp = ins;
9694                         }
9695                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9696                                 MonoInst *iargs [1];
9697                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9698
9699                                 if (cfg->compile_aot)
9700                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9701                                 else
9702                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
9703                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
9704                         } else {
9705                                 if (cfg->opt & MONO_OPT_SHARED) {
9706                                         MonoInst *iargs [3];
9707
9708                                         if (cfg->compile_aot) {
9709                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
9710                                         }
9711                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
9712                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
9713                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
9714                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
9715                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9716                                         CHECK_CFG_ERROR;
9717                                 } else {
9718                                         if (cfg->cbb->out_of_line) {
9719                                                 MonoInst *iargs [2];
9720
9721                                                 if (image == mono_defaults.corlib) {
9722                                                         /* 
9723                                                          * Avoid relocations in AOT and save some space by using a 
9724                                                          * version of helper_ldstr specialized to mscorlib.
9725                                                          */
9726                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
9727                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
9728                                                 } else {
9729                                                         /* Avoid creating the string object */
9730                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
9731                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
9732                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
9733                                                 }
9734                                         } 
9735                                         else
9736                                         if (cfg->compile_aot) {
9737                                                 NEW_LDSTRCONST (cfg, ins, image, n);
9738                                                 *sp = ins;
9739                                                 MONO_ADD_INS (cfg->cbb, ins);
9740                                         } 
9741                                         else {
9742                                                 NEW_PCONST (cfg, ins, NULL);
9743                                                 ins->type = STACK_OBJ;
9744                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9745                                                 CHECK_CFG_ERROR;
9746                                                 
9747                                                 if (!ins->inst_p0)
9748                                                         OUT_OF_MEMORY_FAILURE;
9749
9750                                                 *sp = ins;
9751                                                 MONO_ADD_INS (cfg->cbb, ins);
9752                                         }
9753                                 }
9754                         }
9755
9756                         sp++;
9757                         ip += 5;
9758                         break;
9759                 case CEE_NEWOBJ: {
9760                         MonoInst *iargs [2];
9761                         MonoMethodSignature *fsig;
9762                         MonoInst this_ins;
9763                         MonoInst *alloc;
9764                         MonoInst *vtable_arg = NULL;
9765
9766                         CHECK_OPSIZE (5);
9767                         token = read32 (ip + 1);
9768                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9769                         CHECK_CFG_ERROR;
9770
9771                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9772                         CHECK_CFG_ERROR;
9773
9774                         mono_save_token_info (cfg, image, token, cmethod);
9775
9776                         if (!mono_class_init (cmethod->klass))
9777                                 TYPE_LOAD_ERROR (cmethod->klass);
9778
9779                         context_used = mini_method_check_context_used (cfg, cmethod);
9780                                         
9781                         if (!dont_verify && !cfg->skip_visibility) {
9782                                 MonoMethod *cil_method = cmethod;
9783                                 MonoMethod *target_method = cil_method;
9784
9785                                 if (method->is_inflated) {
9786                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
9787                                         CHECK_CFG_ERROR;
9788                                 }
9789                                 
9790                                 if (!mono_method_can_access_method (method_definition, target_method) &&
9791                                         !mono_method_can_access_method (method, cil_method))
9792                                         emit_method_access_failure (cfg, method, cil_method);
9793                         }
9794
9795                         if (mono_security_core_clr_enabled ())
9796                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
9797
9798                         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)) {
9799                                 emit_class_init (cfg, cmethod->klass);
9800                                 CHECK_TYPELOAD (cmethod->klass);
9801                         }
9802
9803                         /*
9804                         if (cfg->gsharedvt) {
9805                                 if (mini_is_gsharedvt_variable_signature (sig))
9806                                         GSHAREDVT_FAILURE (*ip);
9807                         }
9808                         */
9809
9810                         n = fsig->param_count;
9811                         CHECK_STACK (n);
9812
9813                         /* 
9814                          * Generate smaller code for the common newobj <exception> instruction in
9815                          * argument checking code.
9816                          */
9817                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
9818                                 is_exception_class (cmethod->klass) && n <= 2 &&
9819                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
9820                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
9821                                 MonoInst *iargs [3];
9822
9823                                 sp -= n;
9824
9825                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
9826                                 switch (n) {
9827                                 case 0:
9828                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
9829                                         break;
9830                                 case 1:
9831                                         iargs [1] = sp [0];
9832                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
9833                                         break;
9834                                 case 2:
9835                                         iargs [1] = sp [0];
9836                                         iargs [2] = sp [1];
9837                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
9838                                         break;
9839                                 default:
9840                                         g_assert_not_reached ();
9841                                 }
9842
9843                                 ip += 5;
9844                                 inline_costs += 5;
9845                                 break;
9846                         }
9847
9848                         /* move the args to allow room for 'this' in the first position */
9849                         while (n--) {
9850                                 --sp;
9851                                 sp [1] = sp [0];
9852                         }
9853
9854                         /* check_call_signature () requires sp[0] to be set */
9855                         this_ins.type = STACK_OBJ;
9856                         sp [0] = &this_ins;
9857                         if (check_call_signature (cfg, fsig, sp))
9858                                 UNVERIFIED;
9859
9860                         iargs [0] = NULL;
9861
9862                         if (mini_class_is_system_array (cmethod->klass)) {
9863                                 *sp = emit_get_rgctx_method (cfg, context_used,
9864                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9865
9866                                 /* Avoid varargs in the common case */
9867                                 if (fsig->param_count == 1)
9868                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
9869                                 else if (fsig->param_count == 2)
9870                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
9871                                 else if (fsig->param_count == 3)
9872                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
9873                                 else if (fsig->param_count == 4)
9874                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
9875                                 else
9876                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
9877                         } else if (cmethod->string_ctor) {
9878                                 g_assert (!context_used);
9879                                 g_assert (!vtable_arg);
9880                                 /* we simply pass a null pointer */
9881                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
9882                                 /* now call the string ctor */
9883                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
9884                         } else {
9885                                 if (cmethod->klass->valuetype) {
9886                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
9887                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
9888                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
9889
9890                                         alloc = NULL;
9891
9892                                         /* 
9893                                          * The code generated by mini_emit_virtual_call () expects
9894                                          * iargs [0] to be a boxed instance, but luckily the vcall
9895                                          * will be transformed into a normal call there.
9896                                          */
9897                                 } else if (context_used) {
9898                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
9899                                         *sp = alloc;
9900                                 } else {
9901                                         MonoVTable *vtable = NULL;
9902
9903                                         if (!cfg->compile_aot)
9904                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
9905                                         CHECK_TYPELOAD (cmethod->klass);
9906
9907                                         /*
9908                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
9909                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
9910                                          * As a workaround, we call class cctors before allocating objects.
9911                                          */
9912                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
9913                                                 emit_class_init (cfg, cmethod->klass);
9914                                                 if (cfg->verbose_level > 2)
9915                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
9916                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
9917                                         }
9918
9919                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
9920                                         *sp = alloc;
9921                                 }
9922                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
9923
9924                                 if (alloc)
9925                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
9926
9927                                 /* Now call the actual ctor */
9928                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
9929                                 CHECK_CFG_EXCEPTION;
9930                         }
9931
9932                         if (alloc == NULL) {
9933                                 /* Valuetype */
9934                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
9935                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
9936                                 *sp++= ins;
9937                         } else {
9938                                 *sp++ = alloc;
9939                         }
9940                         
9941                         ip += 5;
9942                         inline_costs += 5;
9943                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
9944                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9945                         break;
9946                 }
9947                 case CEE_CASTCLASS:
9948                 case CEE_ISINST: {
9949                         CHECK_STACK (1);
9950                         --sp;
9951                         CHECK_OPSIZE (5);
9952                         token = read32 (ip + 1);
9953                         klass = mini_get_class (method, token, generic_context);
9954                         CHECK_TYPELOAD (klass);
9955                         if (sp [0]->type != STACK_OBJ)
9956                                 UNVERIFIED;
9957
9958                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
9959                         ins->dreg = alloc_preg (cfg);
9960                         ins->sreg1 = (*sp)->dreg;
9961                         ins->klass = klass;
9962                         ins->type = STACK_OBJ;
9963                         MONO_ADD_INS (cfg->cbb, ins);
9964
9965                         CHECK_CFG_EXCEPTION;
9966                         *sp++ = ins;
9967                         ip += 5;
9968
9969                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
9970                         break;
9971                 }
9972                 case CEE_UNBOX_ANY: {
9973                         MonoInst *res, *addr;
9974
9975                         CHECK_STACK (1);
9976                         --sp;
9977                         CHECK_OPSIZE (5);
9978                         token = read32 (ip + 1);
9979                         klass = mini_get_class (method, token, generic_context);
9980                         CHECK_TYPELOAD (klass);
9981
9982                         mono_save_token_info (cfg, image, token, klass);
9983
9984                         context_used = mini_class_check_context_used (cfg, klass);
9985
9986                         if (mini_is_gsharedvt_klass (klass)) {
9987                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
9988                                 inline_costs += 2;
9989                         } else if (generic_class_is_reference_type (cfg, klass)) {
9990                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
9991                                         EMIT_NEW_PCONST (cfg, res, NULL);
9992                                         res->type = STACK_OBJ;
9993                                 } else {
9994                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
9995                                         res->dreg = alloc_preg (cfg);
9996                                         res->sreg1 = (*sp)->dreg;
9997                                         res->klass = klass;
9998                                         res->type = STACK_OBJ;
9999                                         MONO_ADD_INS (cfg->cbb, res);
10000                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10001                                 }
10002                         } else if (mono_class_is_nullable (klass)) {
10003                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10004                         } else {
10005                                 addr = handle_unbox (cfg, klass, sp, context_used);
10006                                 /* LDOBJ */
10007                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10008                                 res = ins;
10009                                 inline_costs += 2;
10010                         }
10011
10012                         *sp ++ = res;
10013                         ip += 5;
10014                         break;
10015                 }
10016                 case CEE_BOX: {
10017                         MonoInst *val;
10018                         MonoClass *enum_class;
10019                         MonoMethod *has_flag;
10020
10021                         CHECK_STACK (1);
10022                         --sp;
10023                         val = *sp;
10024                         CHECK_OPSIZE (5);
10025                         token = read32 (ip + 1);
10026                         klass = mini_get_class (method, token, generic_context);
10027                         CHECK_TYPELOAD (klass);
10028
10029                         mono_save_token_info (cfg, image, token, klass);
10030
10031                         context_used = mini_class_check_context_used (cfg, klass);
10032
10033                         if (generic_class_is_reference_type (cfg, klass)) {
10034                                 *sp++ = val;
10035                                 ip += 5;
10036                                 break;
10037                         }
10038
10039                         if (klass == mono_defaults.void_class)
10040                                 UNVERIFIED;
10041                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10042                                 UNVERIFIED;
10043                         /* frequent check in generic code: box (struct), brtrue */
10044
10045                         /*
10046                          * Look for:
10047                          *
10048                          *   <push int/long ptr>
10049                          *   <push int/long>
10050                          *   box MyFlags
10051                          *   constrained. MyFlags
10052                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10053                          *
10054                          * If we find this sequence and the operand types on box and constrained
10055                          * are equal, we can emit a specialized instruction sequence instead of
10056                          * the very slow HasFlag () call.
10057                          */
10058                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10059                             /* Cheap checks first. */
10060                             ip + 5 + 6 + 5 < end &&
10061                             ip [5] == CEE_PREFIX1 &&
10062                             ip [6] == CEE_CONSTRAINED_ &&
10063                             ip [11] == CEE_CALLVIRT &&
10064                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10065                             mono_class_is_enum (klass) &&
10066                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10067                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10068                             has_flag->klass == mono_defaults.enum_class &&
10069                             !strcmp (has_flag->name, "HasFlag") &&
10070                             has_flag->signature->hasthis &&
10071                             has_flag->signature->param_count == 1) {
10072                                 CHECK_TYPELOAD (enum_class);
10073
10074                                 if (enum_class == klass) {
10075                                         MonoInst *enum_this, *enum_flag;
10076
10077                                         ip += 5 + 6 + 5;
10078                                         --sp;
10079
10080                                         enum_this = sp [0];
10081                                         enum_flag = sp [1];
10082
10083                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10084                                         break;
10085                                 }
10086                         }
10087
10088                         // FIXME: LLVM can't handle the inconsistent bb linking
10089                         if (!mono_class_is_nullable (klass) &&
10090                                 !mini_is_gsharedvt_klass (klass) &&
10091                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10092                                 (ip [5] == CEE_BRTRUE || 
10093                                  ip [5] == CEE_BRTRUE_S ||
10094                                  ip [5] == CEE_BRFALSE ||
10095                                  ip [5] == CEE_BRFALSE_S)) {
10096                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10097                                 int dreg;
10098                                 MonoBasicBlock *true_bb, *false_bb;
10099
10100                                 ip += 5;
10101
10102                                 if (cfg->verbose_level > 3) {
10103                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10104                                         printf ("<box+brtrue opt>\n");
10105                                 }
10106
10107                                 switch (*ip) {
10108                                 case CEE_BRTRUE_S:
10109                                 case CEE_BRFALSE_S:
10110                                         CHECK_OPSIZE (2);
10111                                         ip++;
10112                                         target = ip + 1 + (signed char)(*ip);
10113                                         ip++;
10114                                         break;
10115                                 case CEE_BRTRUE:
10116                                 case CEE_BRFALSE:
10117                                         CHECK_OPSIZE (5);
10118                                         ip++;
10119                                         target = ip + 4 + (gint)(read32 (ip));
10120                                         ip += 4;
10121                                         break;
10122                                 default:
10123                                         g_assert_not_reached ();
10124                                 }
10125
10126                                 /* 
10127                                  * We need to link both bblocks, since it is needed for handling stack
10128                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10129                                  * Branching to only one of them would lead to inconsistencies, so
10130                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10131                                  */
10132                                 GET_BBLOCK (cfg, true_bb, target);
10133                                 GET_BBLOCK (cfg, false_bb, ip);
10134
10135                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10136                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10137
10138                                 if (sp != stack_start) {
10139                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10140                                         sp = stack_start;
10141                                         CHECK_UNVERIFIABLE (cfg);
10142                                 }
10143
10144                                 if (COMPILE_LLVM (cfg)) {
10145                                         dreg = alloc_ireg (cfg);
10146                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10147                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10148
10149                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10150                                 } else {
10151                                         /* The JIT can't eliminate the iconst+compare */
10152                                         MONO_INST_NEW (cfg, ins, OP_BR);
10153                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10154                                         MONO_ADD_INS (cfg->cbb, ins);
10155                                 }
10156
10157                                 start_new_bblock = 1;
10158                                 break;
10159                         }
10160
10161                         *sp++ = handle_box (cfg, val, klass, context_used);
10162
10163                         CHECK_CFG_EXCEPTION;
10164                         ip += 5;
10165                         inline_costs += 1;
10166                         break;
10167                 }
10168                 case CEE_UNBOX: {
10169                         CHECK_STACK (1);
10170                         --sp;
10171                         CHECK_OPSIZE (5);
10172                         token = read32 (ip + 1);
10173                         klass = mini_get_class (method, token, generic_context);
10174                         CHECK_TYPELOAD (klass);
10175
10176                         mono_save_token_info (cfg, image, token, klass);
10177
10178                         context_used = mini_class_check_context_used (cfg, klass);
10179
10180                         if (mono_class_is_nullable (klass)) {
10181                                 MonoInst *val;
10182
10183                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10184                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10185
10186                                 *sp++= ins;
10187                         } else {
10188                                 ins = handle_unbox (cfg, klass, sp, context_used);
10189                                 *sp++ = ins;
10190                         }
10191                         ip += 5;
10192                         inline_costs += 2;
10193                         break;
10194                 }
10195                 case CEE_LDFLD:
10196                 case CEE_LDFLDA:
10197                 case CEE_STFLD:
10198                 case CEE_LDSFLD:
10199                 case CEE_LDSFLDA:
10200                 case CEE_STSFLD: {
10201                         MonoClassField *field;
10202 #ifndef DISABLE_REMOTING
10203                         int costs;
10204 #endif
10205                         guint foffset;
10206                         gboolean is_instance;
10207                         int op;
10208                         gpointer addr = NULL;
10209                         gboolean is_special_static;
10210                         MonoType *ftype;
10211                         MonoInst *store_val = NULL;
10212                         MonoInst *thread_ins;
10213
10214                         op = *ip;
10215                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10216                         if (is_instance) {
10217                                 if (op == CEE_STFLD) {
10218                                         CHECK_STACK (2);
10219                                         sp -= 2;
10220                                         store_val = sp [1];
10221                                 } else {
10222                                         CHECK_STACK (1);
10223                                         --sp;
10224                                 }
10225                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10226                                         UNVERIFIED;
10227                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10228                                         UNVERIFIED;
10229                         } else {
10230                                 if (op == CEE_STSFLD) {
10231                                         CHECK_STACK (1);
10232                                         sp--;
10233                                         store_val = sp [0];
10234                                 }
10235                         }
10236
10237                         CHECK_OPSIZE (5);
10238                         token = read32 (ip + 1);
10239                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10240                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10241                                 klass = field->parent;
10242                         }
10243                         else {
10244                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10245                                 CHECK_CFG_ERROR;
10246                         }
10247                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10248                                 FIELD_ACCESS_FAILURE (method, field);
10249                         mono_class_init (klass);
10250
10251                         /* if the class is Critical then transparent code cannot access it's fields */
10252                         if (!is_instance && mono_security_core_clr_enabled ())
10253                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10254
10255                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10256                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10257                         if (mono_security_core_clr_enabled ())
10258                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10259                         */
10260
10261                         ftype = mono_field_get_type (field);
10262
10263                         /*
10264                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10265                          * the static case.
10266                          */
10267                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10268                                 switch (op) {
10269                                 case CEE_LDFLD:
10270                                         op = CEE_LDSFLD;
10271                                         break;
10272                                 case CEE_STFLD:
10273                                         op = CEE_STSFLD;
10274                                         break;
10275                                 case CEE_LDFLDA:
10276                                         op = CEE_LDSFLDA;
10277                                         break;
10278                                 default:
10279                                         g_assert_not_reached ();
10280                                 }
10281                                 is_instance = FALSE;
10282                         }
10283
10284                         context_used = mini_class_check_context_used (cfg, klass);
10285
10286                         /* INSTANCE CASE */
10287
10288                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10289                         if (op == CEE_STFLD) {
10290                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10291                                         UNVERIFIED;
10292 #ifndef DISABLE_REMOTING
10293                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10294                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10295                                         MonoInst *iargs [5];
10296
10297                                         GSHAREDVT_FAILURE (op);
10298
10299                                         iargs [0] = sp [0];
10300                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10301                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10302                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10303                                                     field->offset);
10304                                         iargs [4] = sp [1];
10305
10306                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10307                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10308                                                                                            iargs, ip, cfg->real_offset, TRUE);
10309                                                 CHECK_CFG_EXCEPTION;
10310                                                 g_assert (costs > 0);
10311                                                       
10312                                                 cfg->real_offset += 5;
10313
10314                                                 inline_costs += costs;
10315                                         } else {
10316                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10317                                         }
10318                                 } else
10319 #endif
10320                                 {
10321                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10322
10323                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10324
10325                                         if (ins_flag & MONO_INST_VOLATILE) {
10326                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10327                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10328                                         }
10329
10330                                         if (mini_is_gsharedvt_klass (klass)) {
10331                                                 MonoInst *offset_ins;
10332
10333                                                 context_used = mini_class_check_context_used (cfg, klass);
10334
10335                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10336                                                 /* The value is offset by 1 */
10337                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10338                                                 dreg = alloc_ireg_mp (cfg);
10339                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10340                                                 wbarrier_ptr_ins = ins;
10341                                                 /* The decomposition will call mini_emit_memory_copy () which will emit a wbarrier if needed */
10342                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10343                                         } else {
10344                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10345                                         }
10346                                         if (sp [0]->opcode != OP_LDADDR)
10347                                                 store->flags |= MONO_INST_FAULT;
10348
10349                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10350                                                 if (mini_is_gsharedvt_klass (klass)) {
10351                                                         g_assert (wbarrier_ptr_ins);
10352                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10353                                                 } else {
10354                                                         /* insert call to write barrier */
10355                                                         MonoInst *ptr;
10356                                                         int dreg;
10357
10358                                                         dreg = alloc_ireg_mp (cfg);
10359                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10360                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10361                                                 }
10362                                         }
10363
10364                                         store->flags |= ins_flag;
10365                                 }
10366                                 ins_flag = 0;
10367                                 ip += 5;
10368                                 break;
10369                         }
10370
10371 #ifndef DISABLE_REMOTING
10372                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10373                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10374                                 MonoInst *iargs [4];
10375
10376                                 GSHAREDVT_FAILURE (op);
10377
10378                                 iargs [0] = sp [0];
10379                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10380                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10381                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10382                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10383                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10384                                                                                    iargs, ip, cfg->real_offset, TRUE);
10385                                         CHECK_CFG_EXCEPTION;
10386                                         g_assert (costs > 0);
10387                                                       
10388                                         cfg->real_offset += 5;
10389
10390                                         *sp++ = iargs [0];
10391
10392                                         inline_costs += costs;
10393                                 } else {
10394                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10395                                         *sp++ = ins;
10396                                 }
10397                         } else 
10398 #endif
10399                         if (is_instance) {
10400                                 if (sp [0]->type == STACK_VTYPE) {
10401                                         MonoInst *var;
10402
10403                                         /* Have to compute the address of the variable */
10404
10405                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10406                                         if (!var)
10407                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10408                                         else
10409                                                 g_assert (var->klass == klass);
10410                                         
10411                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10412                                         sp [0] = ins;
10413                                 }
10414
10415                                 if (op == CEE_LDFLDA) {
10416                                         if (sp [0]->type == STACK_OBJ) {
10417                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10418                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10419                                         }
10420
10421                                         dreg = alloc_ireg_mp (cfg);
10422
10423                                         if (mini_is_gsharedvt_klass (klass)) {
10424                                                 MonoInst *offset_ins;
10425
10426                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10427                                                 /* The value is offset by 1 */
10428                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10429                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10430                                         } else {
10431                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10432                                         }
10433                                         ins->klass = mono_class_from_mono_type (field->type);
10434                                         ins->type = STACK_MP;
10435                                         *sp++ = ins;
10436                                 } else {
10437                                         MonoInst *load;
10438
10439                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10440
10441                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10442                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10443                                                 if (ins) {
10444                                                         *sp++ = ins;
10445                                                         ins_flag = 0;
10446                                                         ip += 5;
10447                                                         break;
10448                                                 }
10449                                         }
10450
10451                                         MonoInst *field_add_inst = sp [0];
10452                                         if (mini_is_gsharedvt_klass (klass)) {
10453                                                 MonoInst *offset_ins;
10454
10455                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10456                                                 /* The value is offset by 1 */
10457                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10458                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10459                                                 foffset = 0;
10460                                         }
10461
10462                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10463
10464                                         if (sp [0]->opcode != OP_LDADDR)
10465                                                 load->flags |= MONO_INST_FAULT;
10466                                         *sp++ = load;
10467                                 }
10468                         }
10469
10470                         if (is_instance) {
10471                                 ins_flag = 0;
10472                                 ip += 5;
10473                                 break;
10474                         }
10475
10476                         /* STATIC CASE */
10477                         context_used = mini_class_check_context_used (cfg, klass);
10478
10479                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10480                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10481                                 CHECK_CFG_ERROR;
10482                         }
10483
10484                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10485                          * to be called here.
10486                          */
10487                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10488                                 mono_class_vtable (cfg->domain, klass);
10489                                 CHECK_TYPELOAD (klass);
10490                         }
10491                         mono_domain_lock (cfg->domain);
10492                         if (cfg->domain->special_static_fields)
10493                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10494                         mono_domain_unlock (cfg->domain);
10495
10496                         is_special_static = mono_class_field_is_special_static (field);
10497
10498                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10499                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10500                         else
10501                                 thread_ins = NULL;
10502
10503                         /* Generate IR to compute the field address */
10504                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10505                                 /*
10506                                  * Fast access to TLS data
10507                                  * Inline version of get_thread_static_data () in
10508                                  * threads.c.
10509                                  */
10510                                 guint32 offset;
10511                                 int idx, static_data_reg, array_reg, dreg;
10512
10513                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10514                                         GSHAREDVT_FAILURE (op);
10515
10516                                 static_data_reg = alloc_ireg (cfg);
10517                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10518
10519                                 if (cfg->compile_aot) {
10520                                         int offset_reg, offset2_reg, idx_reg;
10521
10522                                         /* For TLS variables, this will return the TLS offset */
10523                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10524                                         offset_reg = ins->dreg;
10525                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10526                                         idx_reg = alloc_ireg (cfg);
10527                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10528                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10529                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10530                                         array_reg = alloc_ireg (cfg);
10531                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10532                                         offset2_reg = alloc_ireg (cfg);
10533                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10534                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10535                                         dreg = alloc_ireg (cfg);
10536                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10537                                 } else {
10538                                         offset = (gsize)addr & 0x7fffffff;
10539                                         idx = offset & 0x3f;
10540
10541                                         array_reg = alloc_ireg (cfg);
10542                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10543                                         dreg = alloc_ireg (cfg);
10544                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10545                                 }
10546                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10547                                         (cfg->compile_aot && is_special_static) ||
10548                                         (context_used && is_special_static)) {
10549                                 MonoInst *iargs [2];
10550
10551                                 g_assert (field->parent);
10552                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10553                                 if (context_used) {
10554                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10555                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10556                                 } else {
10557                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10558                                 }
10559                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10560                         } else if (context_used) {
10561                                 MonoInst *static_data;
10562
10563                                 /*
10564                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10565                                         method->klass->name_space, method->klass->name, method->name,
10566                                         depth, field->offset);
10567                                 */
10568
10569                                 if (mono_class_needs_cctor_run (klass, method))
10570                                         emit_class_init (cfg, klass);
10571
10572                                 /*
10573                                  * The pointer we're computing here is
10574                                  *
10575                                  *   super_info.static_data + field->offset
10576                                  */
10577                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10578                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10579
10580                                 if (mini_is_gsharedvt_klass (klass)) {
10581                                         MonoInst *offset_ins;
10582
10583                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10584                                         /* The value is offset by 1 */
10585                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10586                                         dreg = alloc_ireg_mp (cfg);
10587                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10588                                 } else if (field->offset == 0) {
10589                                         ins = static_data;
10590                                 } else {
10591                                         int addr_reg = mono_alloc_preg (cfg);
10592                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10593                                 }
10594                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10595                                 MonoInst *iargs [2];
10596
10597                                 g_assert (field->parent);
10598                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10599                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10600                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10601                         } else {
10602                                 MonoVTable *vtable = NULL;
10603
10604                                 if (!cfg->compile_aot)
10605                                         vtable = mono_class_vtable (cfg->domain, klass);
10606                                 CHECK_TYPELOAD (klass);
10607
10608                                 if (!addr) {
10609                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10610                                                 if (!(g_slist_find (class_inits, klass))) {
10611                                                         emit_class_init (cfg, klass);
10612                                                         if (cfg->verbose_level > 2)
10613                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10614                                                         class_inits = g_slist_prepend (class_inits, klass);
10615                                                 }
10616                                         } else {
10617                                                 if (cfg->run_cctors) {
10618                                                         /* This makes so that inline cannot trigger */
10619                                                         /* .cctors: too many apps depend on them */
10620                                                         /* running with a specific order... */
10621                                                         g_assert (vtable);
10622                                                         if (! vtable->initialized)
10623                                                                 INLINE_FAILURE ("class init");
10624                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10625                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10626                                                                 goto exception_exit;
10627                                                         }
10628                                                 }
10629                                         }
10630                                         if (cfg->compile_aot)
10631                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10632                                         else {
10633                                                 g_assert (vtable);
10634                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10635                                                 g_assert (addr);
10636                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10637                                         }
10638                                 } else {
10639                                         MonoInst *iargs [1];
10640                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10641                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10642                                 }
10643                         }
10644
10645                         /* Generate IR to do the actual load/store operation */
10646
10647                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10648                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10649                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10650                         }
10651
10652                         if (op == CEE_LDSFLDA) {
10653                                 ins->klass = mono_class_from_mono_type (ftype);
10654                                 ins->type = STACK_PTR;
10655                                 *sp++ = ins;
10656                         } else if (op == CEE_STSFLD) {
10657                                 MonoInst *store;
10658
10659                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10660                                 store->flags |= ins_flag;
10661                         } else {
10662                                 gboolean is_const = FALSE;
10663                                 MonoVTable *vtable = NULL;
10664                                 gpointer addr = NULL;
10665
10666                                 if (!context_used) {
10667                                         vtable = mono_class_vtable (cfg->domain, klass);
10668                                         CHECK_TYPELOAD (klass);
10669                                 }
10670                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10671                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10672                                         int ro_type = ftype->type;
10673                                         if (!addr)
10674                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10675                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10676                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10677                                         }
10678
10679                                         GSHAREDVT_FAILURE (op);
10680
10681                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10682                                         is_const = TRUE;
10683                                         switch (ro_type) {
10684                                         case MONO_TYPE_BOOLEAN:
10685                                         case MONO_TYPE_U1:
10686                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10687                                                 sp++;
10688                                                 break;
10689                                         case MONO_TYPE_I1:
10690                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10691                                                 sp++;
10692                                                 break;                                          
10693                                         case MONO_TYPE_CHAR:
10694                                         case MONO_TYPE_U2:
10695                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10696                                                 sp++;
10697                                                 break;
10698                                         case MONO_TYPE_I2:
10699                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10700                                                 sp++;
10701                                                 break;
10702                                                 break;
10703                                         case MONO_TYPE_I4:
10704                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
10705                                                 sp++;
10706                                                 break;                                          
10707                                         case MONO_TYPE_U4:
10708                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
10709                                                 sp++;
10710                                                 break;
10711                                         case MONO_TYPE_I:
10712                                         case MONO_TYPE_U:
10713                                         case MONO_TYPE_PTR:
10714                                         case MONO_TYPE_FNPTR:
10715                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10716                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
10717                                                 sp++;
10718                                                 break;
10719                                         case MONO_TYPE_STRING:
10720                                         case MONO_TYPE_OBJECT:
10721                                         case MONO_TYPE_CLASS:
10722                                         case MONO_TYPE_SZARRAY:
10723                                         case MONO_TYPE_ARRAY:
10724                                                 if (!mono_gc_is_moving ()) {
10725                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10726                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
10727                                                         sp++;
10728                                                 } else {
10729                                                         is_const = FALSE;
10730                                                 }
10731                                                 break;
10732                                         case MONO_TYPE_I8:
10733                                         case MONO_TYPE_U8:
10734                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
10735                                                 sp++;
10736                                                 break;
10737                                         case MONO_TYPE_R4:
10738                                         case MONO_TYPE_R8:
10739                                         case MONO_TYPE_VALUETYPE:
10740                                         default:
10741                                                 is_const = FALSE;
10742                                                 break;
10743                                         }
10744                                 }
10745
10746                                 if (!is_const) {
10747                                         MonoInst *load;
10748
10749                                         CHECK_STACK_OVF (1);
10750
10751                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
10752                                         load->flags |= ins_flag;
10753                                         ins_flag = 0;
10754                                         *sp++ = load;
10755                                 }
10756                         }
10757
10758                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10759                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10760                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10761                         }
10762
10763                         ins_flag = 0;
10764                         ip += 5;
10765                         break;
10766                 }
10767                 case CEE_STOBJ:
10768                         CHECK_STACK (2);
10769                         sp -= 2;
10770                         CHECK_OPSIZE (5);
10771                         token = read32 (ip + 1);
10772                         klass = mini_get_class (method, token, generic_context);
10773                         CHECK_TYPELOAD (klass);
10774
10775                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
10776                         mini_emit_memory_store (cfg, &klass->byval_arg, sp [0], sp [1], ins_flag);
10777                         ins_flag = 0;
10778                         ip += 5;
10779                         inline_costs += 1;
10780                         break;
10781
10782                         /*
10783                          * Array opcodes
10784                          */
10785                 case CEE_NEWARR: {
10786                         MonoInst *len_ins;
10787                         const char *data_ptr;
10788                         int data_size = 0;
10789                         guint32 field_token;
10790
10791                         CHECK_STACK (1);
10792                         --sp;
10793
10794                         CHECK_OPSIZE (5);
10795                         token = read32 (ip + 1);
10796
10797                         klass = mini_get_class (method, token, generic_context);
10798                         CHECK_TYPELOAD (klass);
10799                         if (klass->byval_arg.type == MONO_TYPE_VOID)
10800                                 UNVERIFIED;
10801
10802                         context_used = mini_class_check_context_used (cfg, klass);
10803
10804                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
10805                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
10806                                 ins->sreg1 = sp [0]->dreg;
10807                                 ins->type = STACK_I4;
10808                                 ins->dreg = alloc_ireg (cfg);
10809                                 MONO_ADD_INS (cfg->cbb, ins);
10810                                 *sp = mono_decompose_opcode (cfg, ins);
10811                         }
10812
10813                         if (context_used) {
10814                                 MonoInst *args [3];
10815                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10816                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
10817
10818                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
10819
10820                                 /* vtable */
10821                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
10822                                         array_class, MONO_RGCTX_INFO_VTABLE);
10823                                 /* array len */
10824                                 args [1] = sp [0];
10825
10826                                 if (managed_alloc)
10827                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
10828                                 else
10829                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
10830                         } else {
10831                                 if (cfg->opt & MONO_OPT_SHARED) {
10832                                         /* Decompose now to avoid problems with references to the domainvar */
10833                                         MonoInst *iargs [3];
10834
10835                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10836                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10837                                         iargs [2] = sp [0];
10838
10839                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
10840                                 } else {
10841                                         /* Decompose later since it is needed by abcrem */
10842                                         MonoClass *array_type = mono_array_class_get (klass, 1);
10843                                         mono_class_vtable (cfg->domain, array_type);
10844                                         CHECK_TYPELOAD (array_type);
10845
10846                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
10847                                         ins->dreg = alloc_ireg_ref (cfg);
10848                                         ins->sreg1 = sp [0]->dreg;
10849                                         ins->inst_newa_class = klass;
10850                                         ins->type = STACK_OBJ;
10851                                         ins->klass = array_type;
10852                                         MONO_ADD_INS (cfg->cbb, ins);
10853                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10854                                         cfg->cbb->has_array_access = TRUE;
10855
10856                                         /* Needed so mono_emit_load_get_addr () gets called */
10857                                         mono_get_got_var (cfg);
10858                                 }
10859                         }
10860
10861                         len_ins = sp [0];
10862                         ip += 5;
10863                         *sp++ = ins;
10864                         inline_costs += 1;
10865
10866                         /* 
10867                          * we inline/optimize the initialization sequence if possible.
10868                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
10869                          * for small sizes open code the memcpy
10870                          * ensure the rva field is big enough
10871                          */
10872                         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))) {
10873                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
10874                                 MonoInst *iargs [3];
10875                                 int add_reg = alloc_ireg_mp (cfg);
10876
10877                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
10878                                 if (cfg->compile_aot) {
10879                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
10880                                 } else {
10881                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
10882                                 }
10883                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
10884                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
10885                                 ip += 11;
10886                         }
10887
10888                         break;
10889                 }
10890                 case CEE_LDLEN:
10891                         CHECK_STACK (1);
10892                         --sp;
10893                         if (sp [0]->type != STACK_OBJ)
10894                                 UNVERIFIED;
10895
10896                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
10897                         ins->dreg = alloc_preg (cfg);
10898                         ins->sreg1 = sp [0]->dreg;
10899                         ins->type = STACK_I4;
10900                         /* This flag will be inherited by the decomposition */
10901                         ins->flags |= MONO_INST_FAULT;
10902                         MONO_ADD_INS (cfg->cbb, ins);
10903                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10904                         cfg->cbb->has_array_access = TRUE;
10905                         ip ++;
10906                         *sp++ = ins;
10907                         break;
10908                 case CEE_LDELEMA:
10909                         CHECK_STACK (2);
10910                         sp -= 2;
10911                         CHECK_OPSIZE (5);
10912                         if (sp [0]->type != STACK_OBJ)
10913                                 UNVERIFIED;
10914
10915                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
10916
10917                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
10918                         CHECK_TYPELOAD (klass);
10919                         /* we need to make sure that this array is exactly the type it needs
10920                          * to be for correctness. the wrappers are lax with their usage
10921                          * so we need to ignore them here
10922                          */
10923                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
10924                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10925                                 mini_emit_check_array_type (cfg, sp [0], array_class);
10926                                 CHECK_TYPELOAD (array_class);
10927                         }
10928
10929                         readonly = FALSE;
10930                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
10931                         *sp++ = ins;
10932                         ip += 5;
10933                         break;
10934                 case CEE_LDELEM:
10935                 case CEE_LDELEM_I1:
10936                 case CEE_LDELEM_U1:
10937                 case CEE_LDELEM_I2:
10938                 case CEE_LDELEM_U2:
10939                 case CEE_LDELEM_I4:
10940                 case CEE_LDELEM_U4:
10941                 case CEE_LDELEM_I8:
10942                 case CEE_LDELEM_I:
10943                 case CEE_LDELEM_R4:
10944                 case CEE_LDELEM_R8:
10945                 case CEE_LDELEM_REF: {
10946                         MonoInst *addr;
10947
10948                         CHECK_STACK (2);
10949                         sp -= 2;
10950
10951                         if (*ip == CEE_LDELEM) {
10952                                 CHECK_OPSIZE (5);
10953                                 token = read32 (ip + 1);
10954                                 klass = mini_get_class (method, token, generic_context);
10955                                 CHECK_TYPELOAD (klass);
10956                                 mono_class_init (klass);
10957                         }
10958                         else
10959                                 klass = array_access_to_klass (*ip);
10960
10961                         if (sp [0]->type != STACK_OBJ)
10962                                 UNVERIFIED;
10963
10964                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
10965
10966                         if (mini_is_gsharedvt_variable_klass (klass)) {
10967                                 // FIXME-VT: OP_ICONST optimization
10968                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
10969                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10970                                 ins->opcode = OP_LOADV_MEMBASE;
10971                         } else if (sp [1]->opcode == OP_ICONST) {
10972                                 int array_reg = sp [0]->dreg;
10973                                 int index_reg = sp [1]->dreg;
10974                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
10975
10976                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
10977                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
10978
10979                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
10980                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
10981                         } else {
10982                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
10983                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10984                         }
10985                         *sp++ = ins;
10986                         if (*ip == CEE_LDELEM)
10987                                 ip += 5;
10988                         else
10989                                 ++ip;
10990                         break;
10991                 }
10992                 case CEE_STELEM_I:
10993                 case CEE_STELEM_I1:
10994                 case CEE_STELEM_I2:
10995                 case CEE_STELEM_I4:
10996                 case CEE_STELEM_I8:
10997                 case CEE_STELEM_R4:
10998                 case CEE_STELEM_R8:
10999                 case CEE_STELEM_REF:
11000                 case CEE_STELEM: {
11001                         CHECK_STACK (3);
11002                         sp -= 3;
11003
11004                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11005
11006                         if (*ip == CEE_STELEM) {
11007                                 CHECK_OPSIZE (5);
11008                                 token = read32 (ip + 1);
11009                                 klass = mini_get_class (method, token, generic_context);
11010                                 CHECK_TYPELOAD (klass);
11011                                 mono_class_init (klass);
11012                         }
11013                         else
11014                                 klass = array_access_to_klass (*ip);
11015
11016                         if (sp [0]->type != STACK_OBJ)
11017                                 UNVERIFIED;
11018
11019                         emit_array_store (cfg, klass, sp, TRUE);
11020
11021                         if (*ip == CEE_STELEM)
11022                                 ip += 5;
11023                         else
11024                                 ++ip;
11025                         inline_costs += 1;
11026                         break;
11027                 }
11028                 case CEE_CKFINITE: {
11029                         CHECK_STACK (1);
11030                         --sp;
11031
11032                         if (cfg->llvm_only) {
11033                                 MonoInst *iargs [1];
11034
11035                                 iargs [0] = sp [0];
11036                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11037                         } else  {
11038                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11039                                 ins->sreg1 = sp [0]->dreg;
11040                                 ins->dreg = alloc_freg (cfg);
11041                                 ins->type = STACK_R8;
11042                                 MONO_ADD_INS (cfg->cbb, ins);
11043
11044                                 *sp++ = mono_decompose_opcode (cfg, ins);
11045                         }
11046
11047                         ++ip;
11048                         break;
11049                 }
11050                 case CEE_REFANYVAL: {
11051                         MonoInst *src_var, *src;
11052
11053                         int klass_reg = alloc_preg (cfg);
11054                         int dreg = alloc_preg (cfg);
11055
11056                         GSHAREDVT_FAILURE (*ip);
11057
11058                         CHECK_STACK (1);
11059                         MONO_INST_NEW (cfg, ins, *ip);
11060                         --sp;
11061                         CHECK_OPSIZE (5);
11062                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11063                         CHECK_TYPELOAD (klass);
11064
11065                         context_used = mini_class_check_context_used (cfg, klass);
11066
11067                         // FIXME:
11068                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11069                         if (!src_var)
11070                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11071                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11072                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11073
11074                         if (context_used) {
11075                                 MonoInst *klass_ins;
11076
11077                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11078                                                 klass, MONO_RGCTX_INFO_KLASS);
11079
11080                                 // FIXME:
11081                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11082                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11083                         } else {
11084                                 mini_emit_class_check (cfg, klass_reg, klass);
11085                         }
11086                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11087                         ins->type = STACK_MP;
11088                         ins->klass = klass;
11089                         *sp++ = ins;
11090                         ip += 5;
11091                         break;
11092                 }
11093                 case CEE_MKREFANY: {
11094                         MonoInst *loc, *addr;
11095
11096                         GSHAREDVT_FAILURE (*ip);
11097
11098                         CHECK_STACK (1);
11099                         MONO_INST_NEW (cfg, ins, *ip);
11100                         --sp;
11101                         CHECK_OPSIZE (5);
11102                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11103                         CHECK_TYPELOAD (klass);
11104
11105                         context_used = mini_class_check_context_used (cfg, klass);
11106
11107                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11108                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11109
11110                         if (context_used) {
11111                                 MonoInst *const_ins;
11112                                 int type_reg = alloc_preg (cfg);
11113
11114                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11115                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11116                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11117                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11118                         } else {
11119                                 int const_reg = alloc_preg (cfg);
11120                                 int type_reg = alloc_preg (cfg);
11121
11122                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11123                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11124                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11125                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11126                         }
11127                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11128
11129                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11130                         ins->type = STACK_VTYPE;
11131                         ins->klass = mono_defaults.typed_reference_class;
11132                         *sp++ = ins;
11133                         ip += 5;
11134                         break;
11135                 }
11136                 case CEE_LDTOKEN: {
11137                         gpointer handle;
11138                         MonoClass *handle_class;
11139
11140                         CHECK_STACK_OVF (1);
11141
11142                         CHECK_OPSIZE (5);
11143                         n = read32 (ip + 1);
11144
11145                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11146                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11147                                 handle = mono_method_get_wrapper_data (method, n);
11148                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11149                                 if (handle_class == mono_defaults.typehandle_class)
11150                                         handle = &((MonoClass*)handle)->byval_arg;
11151                         }
11152                         else {
11153                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11154                                 CHECK_CFG_ERROR;
11155                         }
11156                         if (!handle)
11157                                 LOAD_ERROR;
11158                         mono_class_init (handle_class);
11159                         if (cfg->gshared) {
11160                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11161                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11162                                         /* This case handles ldtoken
11163                                            of an open type, like for
11164                                            typeof(Gen<>). */
11165                                         context_used = 0;
11166                                 } else if (handle_class == mono_defaults.typehandle_class) {
11167                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11168                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11169                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11170                                 else if (handle_class == mono_defaults.methodhandle_class)
11171                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11172                                 else
11173                                         g_assert_not_reached ();
11174                         }
11175
11176                         if ((cfg->opt & MONO_OPT_SHARED) &&
11177                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11178                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11179                                 MonoInst *addr, *vtvar, *iargs [3];
11180                                 int method_context_used;
11181
11182                                 method_context_used = mini_method_check_context_used (cfg, method);
11183
11184                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11185
11186                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11187                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11188                                 if (method_context_used) {
11189                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11190                                                 method, MONO_RGCTX_INFO_METHOD);
11191                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11192                                 } else {
11193                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11194                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11195                                 }
11196                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11197
11198                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11199
11200                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11201                         } else {
11202                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11203                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11204                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11205                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11206                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11207                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11208
11209                                         mono_class_init (tclass);
11210                                         if (context_used) {
11211                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11212                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11213                                         } else if (cfg->compile_aot) {
11214                                                 if (method->wrapper_type) {
11215                                                         error_init (&error); //got to do it since there are multiple conditionals below
11216                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11217                                                                 /* Special case for static synchronized wrappers */
11218                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11219                                                         } else {
11220                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11221                                                                 /* FIXME: n is not a normal token */
11222                                                                 DISABLE_AOT (cfg);
11223                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11224                                                         }
11225                                                 } else {
11226                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11227                                                 }
11228                                         } else {
11229                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11230                                                 CHECK_CFG_ERROR;
11231                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11232                                         }
11233                                         ins->type = STACK_OBJ;
11234                                         ins->klass = cmethod->klass;
11235                                         ip += 5;
11236                                 } else {
11237                                         MonoInst *addr, *vtvar;
11238
11239                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11240
11241                                         if (context_used) {
11242                                                 if (handle_class == mono_defaults.typehandle_class) {
11243                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11244                                                                         mono_class_from_mono_type ((MonoType *)handle),
11245                                                                         MONO_RGCTX_INFO_TYPE);
11246                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11247                                                         ins = emit_get_rgctx_method (cfg, context_used,
11248                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11249                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11250                                                         ins = emit_get_rgctx_field (cfg, context_used,
11251                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11252                                                 } else {
11253                                                         g_assert_not_reached ();
11254                                                 }
11255                                         } else if (cfg->compile_aot) {
11256                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11257                                         } else {
11258                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11259                                         }
11260                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11261                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11262                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11263                                 }
11264                         }
11265
11266                         *sp++ = ins;
11267                         ip += 5;
11268                         break;
11269                 }
11270                 case CEE_THROW:
11271                         CHECK_STACK (1);
11272                         if (sp [-1]->type != STACK_OBJ)
11273                                 UNVERIFIED;
11274
11275                         MONO_INST_NEW (cfg, ins, OP_THROW);
11276                         --sp;
11277                         ins->sreg1 = sp [0]->dreg;
11278                         ip++;
11279                         cfg->cbb->out_of_line = TRUE;
11280                         MONO_ADD_INS (cfg->cbb, ins);
11281                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11282                         MONO_ADD_INS (cfg->cbb, ins);
11283                         sp = stack_start;
11284                         
11285                         link_bblock (cfg, cfg->cbb, end_bblock);
11286                         start_new_bblock = 1;
11287                         /* This can complicate code generation for llvm since the return value might not be defined */
11288                         if (COMPILE_LLVM (cfg))
11289                                 INLINE_FAILURE ("throw");
11290                         break;
11291                 case CEE_ENDFINALLY:
11292                         if (!ip_in_finally_clause (cfg, ip - header->code))
11293                                 UNVERIFIED;
11294                         /* mono_save_seq_point_info () depends on this */
11295                         if (sp != stack_start)
11296                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11297                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11298                         MONO_ADD_INS (cfg->cbb, ins);
11299                         ip++;
11300                         start_new_bblock = 1;
11301
11302                         /*
11303                          * Control will leave the method so empty the stack, otherwise
11304                          * the next basic block will start with a nonempty stack.
11305                          */
11306                         while (sp != stack_start) {
11307                                 sp--;
11308                         }
11309                         break;
11310                 case CEE_LEAVE:
11311                 case CEE_LEAVE_S: {
11312                         GList *handlers;
11313
11314                         if (*ip == CEE_LEAVE) {
11315                                 CHECK_OPSIZE (5);
11316                                 target = ip + 5 + (gint32)read32(ip + 1);
11317                         } else {
11318                                 CHECK_OPSIZE (2);
11319                                 target = ip + 2 + (signed char)(ip [1]);
11320                         }
11321
11322                         /* empty the stack */
11323                         while (sp != stack_start) {
11324                                 sp--;
11325                         }
11326
11327                         /* 
11328                          * If this leave statement is in a catch block, check for a
11329                          * pending exception, and rethrow it if necessary.
11330                          * We avoid doing this in runtime invoke wrappers, since those are called
11331                          * by native code which excepts the wrapper to catch all exceptions.
11332                          */
11333                         for (i = 0; i < header->num_clauses; ++i) {
11334                                 MonoExceptionClause *clause = &header->clauses [i];
11335
11336                                 /* 
11337                                  * Use <= in the final comparison to handle clauses with multiple
11338                                  * leave statements, like in bug #78024.
11339                                  * The ordering of the exception clauses guarantees that we find the
11340                                  * innermost clause.
11341                                  */
11342                                 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) {
11343                                         MonoInst *exc_ins;
11344                                         MonoBasicBlock *dont_throw;
11345
11346                                         /*
11347                                           MonoInst *load;
11348
11349                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11350                                         */
11351
11352                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11353
11354                                         NEW_BBLOCK (cfg, dont_throw);
11355
11356                                         /*
11357                                          * Currently, we always rethrow the abort exception, despite the 
11358                                          * fact that this is not correct. See thread6.cs for an example. 
11359                                          * But propagating the abort exception is more important than 
11360                                          * getting the sematics right.
11361                                          */
11362                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11363                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11364                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11365
11366                                         MONO_START_BB (cfg, dont_throw);
11367                                 }
11368                         }
11369
11370 #ifdef ENABLE_LLVM
11371                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11372 #endif
11373
11374                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11375                                 GList *tmp;
11376                                 MonoExceptionClause *clause;
11377
11378                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11379                                         clause = (MonoExceptionClause *)tmp->data;
11380                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11381                                         g_assert (tblock);
11382                                         link_bblock (cfg, cfg->cbb, tblock);
11383                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11384                                         ins->inst_target_bb = tblock;
11385                                         ins->inst_eh_block = clause;
11386                                         MONO_ADD_INS (cfg->cbb, ins);
11387                                         cfg->cbb->has_call_handler = 1;
11388                                         if (COMPILE_LLVM (cfg)) {
11389                                                 MonoBasicBlock *target_bb;
11390
11391                                                 /* 
11392                                                  * Link the finally bblock with the target, since it will
11393                                                  * conceptually branch there.
11394                                                  */
11395                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11396                                                 GET_BBLOCK (cfg, target_bb, target);
11397                                                 link_bblock (cfg, tblock, target_bb);
11398                                         }
11399                                 }
11400                                 g_list_free (handlers);
11401                         } 
11402
11403                         MONO_INST_NEW (cfg, ins, OP_BR);
11404                         MONO_ADD_INS (cfg->cbb, ins);
11405                         GET_BBLOCK (cfg, tblock, target);
11406                         link_bblock (cfg, cfg->cbb, tblock);
11407                         ins->inst_target_bb = tblock;
11408
11409                         start_new_bblock = 1;
11410
11411                         if (*ip == CEE_LEAVE)
11412                                 ip += 5;
11413                         else
11414                                 ip += 2;
11415
11416                         break;
11417                 }
11418
11419                         /*
11420                          * Mono specific opcodes
11421                          */
11422                 case MONO_CUSTOM_PREFIX: {
11423
11424                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11425
11426                         CHECK_OPSIZE (2);
11427                         switch (ip [1]) {
11428                         case CEE_MONO_ICALL: {
11429                                 gpointer func;
11430                                 MonoJitICallInfo *info;
11431
11432                                 token = read32 (ip + 2);
11433                                 func = mono_method_get_wrapper_data (method, token);
11434                                 info = mono_find_jit_icall_by_addr (func);
11435                                 if (!info)
11436                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11437                                 g_assert (info);
11438
11439                                 CHECK_STACK (info->sig->param_count);
11440                                 sp -= info->sig->param_count;
11441
11442                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11443                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11444                                         *sp++ = ins;
11445
11446                                 ip += 6;
11447                                 inline_costs += 10 * num_calls++;
11448
11449                                 break;
11450                         }
11451                         case CEE_MONO_LDPTR_CARD_TABLE:
11452                         case CEE_MONO_LDPTR_NURSERY_START:
11453                         case CEE_MONO_LDPTR_NURSERY_BITS:
11454                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11455                                 CHECK_STACK_OVF (1);
11456
11457                                 switch (ip [1]) {
11458                                         case CEE_MONO_LDPTR_CARD_TABLE:
11459                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11460                                                 break;
11461                                         case CEE_MONO_LDPTR_NURSERY_START:
11462                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11463                                                 break;
11464                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11465                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11466                                                 break;
11467                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11468                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11469                                                 break;
11470                                 }
11471
11472                                 *sp++ = ins;
11473                                 ip += 2;
11474                                 inline_costs += 10 * num_calls++;
11475                                 break;
11476                         }
11477                         case CEE_MONO_LDPTR: {
11478                                 gpointer ptr;
11479
11480                                 CHECK_STACK_OVF (1);
11481                                 CHECK_OPSIZE (6);
11482                                 token = read32 (ip + 2);
11483
11484                                 ptr = mono_method_get_wrapper_data (method, token);
11485                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11486                                 *sp++ = ins;
11487                                 ip += 6;
11488                                 inline_costs += 10 * num_calls++;
11489                                 /* Can't embed random pointers into AOT code */
11490                                 DISABLE_AOT (cfg);
11491                                 break;
11492                         }
11493                         case CEE_MONO_JIT_ICALL_ADDR: {
11494                                 MonoJitICallInfo *callinfo;
11495                                 gpointer ptr;
11496
11497                                 CHECK_STACK_OVF (1);
11498                                 CHECK_OPSIZE (6);
11499                                 token = read32 (ip + 2);
11500
11501                                 ptr = mono_method_get_wrapper_data (method, token);
11502                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11503                                 g_assert (callinfo);
11504                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11505                                 *sp++ = ins;
11506                                 ip += 6;
11507                                 inline_costs += 10 * num_calls++;
11508                                 break;
11509                         }
11510                         case CEE_MONO_ICALL_ADDR: {
11511                                 MonoMethod *cmethod;
11512                                 gpointer ptr;
11513
11514                                 CHECK_STACK_OVF (1);
11515                                 CHECK_OPSIZE (6);
11516                                 token = read32 (ip + 2);
11517
11518                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11519
11520                                 if (cfg->compile_aot) {
11521                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11522                                                 /*
11523                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11524                                                  * before the call, its not needed when using direct pinvoke.
11525                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11526                                                  * on platforms which don't support dlopen ().
11527                                                  */
11528                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11529                                         } else {
11530                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11531                                         }
11532                                 } else {
11533                                         ptr = mono_lookup_internal_call (cmethod);
11534                                         g_assert (ptr);
11535                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11536                                 }
11537                                 *sp++ = ins;
11538                                 ip += 6;
11539                                 break;
11540                         }
11541                         case CEE_MONO_VTADDR: {
11542                                 MonoInst *src_var, *src;
11543
11544                                 CHECK_STACK (1);
11545                                 --sp;
11546
11547                                 // FIXME:
11548                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11549                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11550                                 *sp++ = src;
11551                                 ip += 2;
11552                                 break;
11553                         }
11554                         case CEE_MONO_NEWOBJ: {
11555                                 MonoInst *iargs [2];
11556
11557                                 CHECK_STACK_OVF (1);
11558                                 CHECK_OPSIZE (6);
11559                                 token = read32 (ip + 2);
11560                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11561                                 mono_class_init (klass);
11562                                 NEW_DOMAINCONST (cfg, iargs [0]);
11563                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11564                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11565                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11566                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11567                                 ip += 6;
11568                                 inline_costs += 10 * num_calls++;
11569                                 break;
11570                         }
11571                         case CEE_MONO_OBJADDR:
11572                                 CHECK_STACK (1);
11573                                 --sp;
11574                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11575                                 ins->dreg = alloc_ireg_mp (cfg);
11576                                 ins->sreg1 = sp [0]->dreg;
11577                                 ins->type = STACK_MP;
11578                                 MONO_ADD_INS (cfg->cbb, ins);
11579                                 *sp++ = ins;
11580                                 ip += 2;
11581                                 break;
11582                         case CEE_MONO_LDNATIVEOBJ:
11583                                 /*
11584                                  * Similar to LDOBJ, but instead load the unmanaged 
11585                                  * representation of the vtype to the stack.
11586                                  */
11587                                 CHECK_STACK (1);
11588                                 CHECK_OPSIZE (6);
11589                                 --sp;
11590                                 token = read32 (ip + 2);
11591                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11592                                 g_assert (klass->valuetype);
11593                                 mono_class_init (klass);
11594
11595                                 {
11596                                         MonoInst *src, *dest, *temp;
11597
11598                                         src = sp [0];
11599                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11600                                         temp->backend.is_pinvoke = 1;
11601                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11602                                         mini_emit_memory_copy (cfg, dest, src, klass, TRUE, 0);
11603
11604                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11605                                         dest->type = STACK_VTYPE;
11606                                         dest->klass = klass;
11607
11608                                         *sp ++ = dest;
11609                                         ip += 6;
11610                                 }
11611                                 break;
11612                         case CEE_MONO_RETOBJ: {
11613                                 /*
11614                                  * Same as RET, but return the native representation of a vtype
11615                                  * to the caller.
11616                                  */
11617                                 g_assert (cfg->ret);
11618                                 g_assert (mono_method_signature (method)->pinvoke); 
11619                                 CHECK_STACK (1);
11620                                 --sp;
11621                                 
11622                                 CHECK_OPSIZE (6);
11623                                 token = read32 (ip + 2);    
11624                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11625
11626                                 if (!cfg->vret_addr) {
11627                                         g_assert (cfg->ret_var_is_local);
11628
11629                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11630                                 } else {
11631                                         EMIT_NEW_RETLOADA (cfg, ins);
11632                                 }
11633                                 mini_emit_memory_copy (cfg, ins, sp [0], klass, TRUE, 0);
11634                                 
11635                                 if (sp != stack_start)
11636                                         UNVERIFIED;
11637                                 
11638                                 MONO_INST_NEW (cfg, ins, OP_BR);
11639                                 ins->inst_target_bb = end_bblock;
11640                                 MONO_ADD_INS (cfg->cbb, ins);
11641                                 link_bblock (cfg, cfg->cbb, end_bblock);
11642                                 start_new_bblock = 1;
11643                                 ip += 6;
11644                                 break;
11645                         }
11646                         case CEE_MONO_SAVE_LMF:
11647                         case CEE_MONO_RESTORE_LMF:
11648                                 ip += 2;
11649                                 break;
11650                         case CEE_MONO_CLASSCONST:
11651                                 CHECK_STACK_OVF (1);
11652                                 CHECK_OPSIZE (6);
11653                                 token = read32 (ip + 2);
11654                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11655                                 *sp++ = ins;
11656                                 ip += 6;
11657                                 inline_costs += 10 * num_calls++;
11658                                 break;
11659                         case CEE_MONO_NOT_TAKEN:
11660                                 cfg->cbb->out_of_line = TRUE;
11661                                 ip += 2;
11662                                 break;
11663                         case CEE_MONO_TLS: {
11664                                 MonoTlsKey key;
11665
11666                                 CHECK_STACK_OVF (1);
11667                                 CHECK_OPSIZE (6);
11668                                 key = (MonoTlsKey)read32 (ip + 2);
11669                                 g_assert (key < TLS_KEY_NUM);
11670
11671                                 ins = mono_create_tls_get (cfg, key);
11672                                 g_assert (ins);
11673                                 ins->type = STACK_PTR;
11674                                 *sp++ = ins;
11675                                 ip += 6;
11676                                 break;
11677                         }
11678                         case CEE_MONO_DYN_CALL: {
11679                                 MonoCallInst *call;
11680
11681                                 /* It would be easier to call a trampoline, but that would put an
11682                                  * extra frame on the stack, confusing exception handling. So
11683                                  * implement it inline using an opcode for now.
11684                                  */
11685
11686                                 if (!cfg->dyn_call_var) {
11687                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11688                                         /* prevent it from being register allocated */
11689                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11690                                 }
11691
11692                                 /* Has to use a call inst since it local regalloc expects it */
11693                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11694                                 ins = (MonoInst*)call;
11695                                 sp -= 2;
11696                                 ins->sreg1 = sp [0]->dreg;
11697                                 ins->sreg2 = sp [1]->dreg;
11698                                 MONO_ADD_INS (cfg->cbb, ins);
11699
11700                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11701
11702                                 ip += 2;
11703                                 inline_costs += 10 * num_calls++;
11704
11705                                 break;
11706                         }
11707                         case CEE_MONO_MEMORY_BARRIER: {
11708                                 CHECK_OPSIZE (6);
11709                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
11710                                 ip += 6;
11711                                 break;
11712                         }
11713                         case CEE_MONO_ATOMIC_STORE_I4: {
11714                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
11715
11716                                 CHECK_OPSIZE (6);
11717                                 CHECK_STACK (2);
11718                                 sp -= 2;
11719
11720                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
11721                                 ins->dreg = sp [0]->dreg;
11722                                 ins->sreg1 = sp [1]->dreg;
11723                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
11724                                 MONO_ADD_INS (cfg->cbb, ins);
11725
11726                                 ip += 6;
11727                                 break;
11728                         }
11729                         case CEE_MONO_JIT_ATTACH: {
11730                                 MonoInst *args [16], *domain_ins;
11731                                 MonoInst *ad_ins, *jit_tls_ins;
11732                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
11733
11734                                 g_assert (!mono_threads_is_coop_enabled ());
11735
11736                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11737
11738                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11739                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11740
11741                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
11742                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
11743
11744                                 if (ad_ins && jit_tls_ins) {
11745                                         NEW_BBLOCK (cfg, next_bb);
11746                                         NEW_BBLOCK (cfg, call_bb);
11747
11748                                         if (cfg->compile_aot) {
11749                                                 /* AOT code is only used in the root domain */
11750                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
11751                                         } else {
11752                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
11753                                         }
11754                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
11755                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
11756
11757                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
11758                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
11759
11760                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
11761                                         MONO_START_BB (cfg, call_bb);
11762                                 }
11763
11764                                 /* AOT code is only used in the root domain */
11765                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
11766                                 if (cfg->compile_aot) {
11767                                         MonoInst *addr;
11768
11769                                         /*
11770                                          * This is called on unattached threads, so it cannot go through the trampoline
11771                                          * infrastructure. Use an indirect call through a got slot initialized at load time
11772                                          * instead.
11773                                          */
11774                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
11775                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
11776                                 } else {
11777                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
11778                                 }
11779                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11780
11781                                 if (next_bb)
11782                                         MONO_START_BB (cfg, next_bb);
11783
11784                                 ip += 2;
11785                                 break;
11786                         }
11787                         case CEE_MONO_JIT_DETACH: {
11788                                 MonoInst *args [16];
11789
11790                                 /* Restore the original domain */
11791                                 dreg = alloc_ireg (cfg);
11792                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
11793                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
11794                                 ip += 2;
11795                                 break;
11796                         }
11797                         case CEE_MONO_CALLI_EXTRA_ARG: {
11798                                 MonoInst *addr;
11799                                 MonoMethodSignature *fsig;
11800                                 MonoInst *arg;
11801
11802                                 /*
11803                                  * This is the same as CEE_CALLI, but passes an additional argument
11804                                  * to the called method in llvmonly mode.
11805                                  * This is only used by delegate invoke wrappers to call the
11806                                  * actual delegate method.
11807                                  */
11808                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
11809
11810                                 CHECK_OPSIZE (6);
11811                                 token = read32 (ip + 2);
11812
11813                                 ins = NULL;
11814
11815                                 cmethod = NULL;
11816                                 CHECK_STACK (1);
11817                                 --sp;
11818                                 addr = *sp;
11819                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
11820                                 CHECK_CFG_ERROR;
11821
11822                                 if (cfg->llvm_only)
11823                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
11824
11825                                 n = fsig->param_count + fsig->hasthis + 1;
11826
11827                                 CHECK_STACK (n);
11828
11829                                 sp -= n;
11830                                 arg = sp [n - 1];
11831
11832                                 if (cfg->llvm_only) {
11833                                         /*
11834                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
11835                                          * cconv. This is set by mono_init_delegate ().
11836                                          */
11837                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
11838                                                 MonoInst *callee = addr;
11839                                                 MonoInst *call, *localloc_ins;
11840                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11841                                                 int low_bit_reg = alloc_preg (cfg);
11842
11843                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11844                                                 NEW_BBLOCK (cfg, end_bb);
11845
11846                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11847                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11848                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11849
11850                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
11851                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11852                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11853                                                 /*
11854                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
11855                                                  */
11856                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11857                                                 ins->dreg = alloc_preg (cfg);
11858                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11859                                                 MONO_ADD_INS (cfg->cbb, ins);
11860                                                 localloc_ins = ins;
11861                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11862                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11863                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11864
11865                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11866                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11867
11868                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
11869                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11870                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11871                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11872                                                 ins->dreg = call->dreg;
11873
11874                                                 MONO_START_BB (cfg, end_bb);
11875                                         } else {
11876                                                 /* Caller uses a normal calling conv */
11877
11878                                                 MonoInst *callee = addr;
11879                                                 MonoInst *call, *localloc_ins;
11880                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11881                                                 int low_bit_reg = alloc_preg (cfg);
11882
11883                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11884                                                 NEW_BBLOCK (cfg, end_bb);
11885
11886                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11887                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11888                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11889
11890                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
11891                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11892                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11893                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
11894                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11895                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11896                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
11897                                                 MONO_ADD_INS (cfg->cbb, addr);
11898                                                 /*
11899                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
11900                                                  */
11901                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11902                                                 ins->dreg = alloc_preg (cfg);
11903                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11904                                                 MONO_ADD_INS (cfg->cbb, ins);
11905                                                 localloc_ins = ins;
11906                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11907                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11908                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11909
11910                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11911                                                 ins->dreg = call->dreg;
11912                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11913
11914                                                 MONO_START_BB (cfg, end_bb);
11915                                         }
11916                                 } else {
11917                                         /* Same as CEE_CALLI */
11918                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
11919                                                 /*
11920                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
11921                                                  */
11922                                                 MonoInst *callee = addr;
11923
11924                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11925                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11926                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
11927                                         } else {
11928                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
11929                                         }
11930                                 }
11931
11932                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
11933                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
11934
11935                                 CHECK_CFG_EXCEPTION;
11936
11937                                 ip += 6;
11938                                 ins_flag = 0;
11939                                 constrained_class = NULL;
11940                                 break;
11941                         }
11942                         case CEE_MONO_LDDOMAIN:
11943                                 CHECK_STACK_OVF (1);
11944                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
11945                                 ip += 2;
11946                                 *sp++ = ins;
11947                                 break;
11948                         case CEE_MONO_GET_LAST_ERROR:
11949                                 CHECK_OPSIZE (2);
11950                                 CHECK_STACK_OVF (1);
11951
11952                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
11953                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
11954                                 ins->type = STACK_I4;
11955                                 MONO_ADD_INS (cfg->cbb, ins);
11956
11957                                 ip += 2;
11958                                 *sp++ = ins;
11959                                 break;
11960                         case CEE_MONO_GET_RGCTX_ARG:
11961                                 CHECK_OPSIZE (2);
11962                                 CHECK_STACK_OVF (1);
11963
11964                                 mono_create_rgctx_var (cfg);
11965
11966                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11967                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
11968                                 ins->sreg1 = cfg->rgctx_var->dreg;
11969                                 ins->type = STACK_PTR;
11970                                 MONO_ADD_INS (cfg->cbb, ins);
11971
11972                                 ip += 2;
11973                                 *sp++ = ins;
11974                                 break;
11975                         default:
11976                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
11977                                 break;
11978                         }
11979                         break;
11980                 }
11981
11982                 case CEE_PREFIX1: {
11983                         CHECK_OPSIZE (2);
11984                         switch (ip [1]) {
11985                         case CEE_ARGLIST: {
11986                                 /* somewhat similar to LDTOKEN */
11987                                 MonoInst *addr, *vtvar;
11988                                 CHECK_STACK_OVF (1);
11989                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
11990
11991                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11992                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
11993
11994                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11995                                 ins->type = STACK_VTYPE;
11996                                 ins->klass = mono_defaults.argumenthandle_class;
11997                                 *sp++ = ins;
11998                                 ip += 2;
11999                                 break;
12000                         }
12001                         case CEE_CEQ:
12002                         case CEE_CGT:
12003                         case CEE_CGT_UN:
12004                         case CEE_CLT:
12005                         case CEE_CLT_UN: {
12006                                 MonoInst *cmp, *arg1, *arg2;
12007
12008                                 CHECK_STACK (2);
12009                                 sp -= 2;
12010                                 arg1 = sp [0];
12011                                 arg2 = sp [1];
12012
12013                                 /*
12014                                  * The following transforms:
12015                                  *    CEE_CEQ    into OP_CEQ
12016                                  *    CEE_CGT    into OP_CGT
12017                                  *    CEE_CGT_UN into OP_CGT_UN
12018                                  *    CEE_CLT    into OP_CLT
12019                                  *    CEE_CLT_UN into OP_CLT_UN
12020                                  */
12021                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12022
12023                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12024                                 cmp->sreg1 = arg1->dreg;
12025                                 cmp->sreg2 = arg2->dreg;
12026                                 type_from_op (cfg, cmp, arg1, arg2);
12027                                 CHECK_TYPE (cmp);
12028                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12029                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12030                                         cmp->opcode = OP_LCOMPARE;
12031                                 else if (arg1->type == STACK_R4)
12032                                         cmp->opcode = OP_RCOMPARE;
12033                                 else if (arg1->type == STACK_R8)
12034                                         cmp->opcode = OP_FCOMPARE;
12035                                 else
12036                                         cmp->opcode = OP_ICOMPARE;
12037                                 MONO_ADD_INS (cfg->cbb, cmp);
12038                                 ins->type = STACK_I4;
12039                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12040                                 type_from_op (cfg, ins, arg1, arg2);
12041
12042                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12043                                         /*
12044                                          * The backends expect the fceq opcodes to do the
12045                                          * comparison too.
12046                                          */
12047                                         ins->sreg1 = cmp->sreg1;
12048                                         ins->sreg2 = cmp->sreg2;
12049                                         NULLIFY_INS (cmp);
12050                                 }
12051                                 MONO_ADD_INS (cfg->cbb, ins);
12052                                 *sp++ = ins;
12053                                 ip += 2;
12054                                 break;
12055                         }
12056                         case CEE_LDFTN: {
12057                                 MonoInst *argconst;
12058                                 MonoMethod *cil_method;
12059
12060                                 CHECK_STACK_OVF (1);
12061                                 CHECK_OPSIZE (6);
12062                                 n = read32 (ip + 2);
12063                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12064                                 CHECK_CFG_ERROR;
12065
12066                                 mono_class_init (cmethod->klass);
12067
12068                                 mono_save_token_info (cfg, image, n, cmethod);
12069
12070                                 context_used = mini_method_check_context_used (cfg, cmethod);
12071
12072                                 cil_method = cmethod;
12073                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12074                                         emit_method_access_failure (cfg, method, cil_method);
12075
12076                                 if (mono_security_core_clr_enabled ())
12077                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12078
12079                                 /* 
12080                                  * Optimize the common case of ldftn+delegate creation
12081                                  */
12082                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12083                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12084                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12085                                                 MonoInst *target_ins, *handle_ins;
12086                                                 MonoMethod *invoke;
12087                                                 int invoke_context_used;
12088
12089                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12090                                                 if (!invoke || !mono_method_signature (invoke))
12091                                                         LOAD_ERROR;
12092
12093                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12094
12095                                                 target_ins = sp [-1];
12096
12097                                                 if (mono_security_core_clr_enabled ())
12098                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12099
12100                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12101                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12102                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12103                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12104                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12105                                                         }
12106                                                 }
12107
12108                                                 /* FIXME: SGEN support */
12109                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12110                                                         ip += 6;
12111                                                         if (cfg->verbose_level > 3)
12112                                                                 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));
12113                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12114                                                                 sp --;
12115                                                                 *sp = handle_ins;
12116                                                                 CHECK_CFG_EXCEPTION;
12117                                                                 ip += 5;
12118                                                                 sp ++;
12119                                                                 break;
12120                                                         }
12121                                                         ip -= 6;
12122                                                 }
12123                                         }
12124                                 }
12125
12126                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12127                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12128                                 *sp++ = ins;
12129                                 
12130                                 ip += 6;
12131                                 inline_costs += 10 * num_calls++;
12132                                 break;
12133                         }
12134                         case CEE_LDVIRTFTN: {
12135                                 MonoInst *args [2];
12136
12137                                 CHECK_STACK (1);
12138                                 CHECK_OPSIZE (6);
12139                                 n = read32 (ip + 2);
12140                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12141                                 CHECK_CFG_ERROR;
12142
12143                                 mono_class_init (cmethod->klass);
12144  
12145                                 context_used = mini_method_check_context_used (cfg, cmethod);
12146
12147                                 if (mono_security_core_clr_enabled ())
12148                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12149
12150                                 /*
12151                                  * Optimize the common case of ldvirtftn+delegate creation
12152                                  */
12153                                 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)) {
12154                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12155                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12156                                                 MonoInst *target_ins, *handle_ins;
12157                                                 MonoMethod *invoke;
12158                                                 int invoke_context_used;
12159                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12160
12161                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12162                                                 if (!invoke || !mono_method_signature (invoke))
12163                                                         LOAD_ERROR;
12164
12165                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12166
12167                                                 target_ins = sp [-1];
12168
12169                                                 if (mono_security_core_clr_enabled ())
12170                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12171
12172                                                 /* FIXME: SGEN support */
12173                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12174                                                         ip += 6;
12175                                                         if (cfg->verbose_level > 3)
12176                                                                 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));
12177                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12178                                                                 sp -= 2;
12179                                                                 *sp = handle_ins;
12180                                                                 CHECK_CFG_EXCEPTION;
12181                                                                 ip += 5;
12182                                                                 sp ++;
12183                                                                 break;
12184                                                         }
12185                                                         ip -= 6;
12186                                                 }
12187                                         }
12188                                 }
12189
12190                                 --sp;
12191                                 args [0] = *sp;
12192
12193                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12194                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12195
12196                                 if (context_used)
12197                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12198                                 else
12199                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12200
12201                                 ip += 6;
12202                                 inline_costs += 10 * num_calls++;
12203                                 break;
12204                         }
12205                         case CEE_LDARG:
12206                                 CHECK_STACK_OVF (1);
12207                                 CHECK_OPSIZE (4);
12208                                 n = read16 (ip + 2);
12209                                 CHECK_ARG (n);
12210                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12211                                 *sp++ = ins;
12212                                 ip += 4;
12213                                 break;
12214                         case CEE_LDARGA:
12215                                 CHECK_STACK_OVF (1);
12216                                 CHECK_OPSIZE (4);
12217                                 n = read16 (ip + 2);
12218                                 CHECK_ARG (n);
12219                                 NEW_ARGLOADA (cfg, ins, n);
12220                                 MONO_ADD_INS (cfg->cbb, ins);
12221                                 *sp++ = ins;
12222                                 ip += 4;
12223                                 break;
12224                         case CEE_STARG:
12225                                 CHECK_STACK (1);
12226                                 --sp;
12227                                 CHECK_OPSIZE (4);
12228                                 n = read16 (ip + 2);
12229                                 CHECK_ARG (n);
12230                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12231                                         UNVERIFIED;
12232                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12233                                 ip += 4;
12234                                 break;
12235                         case CEE_LDLOC:
12236                                 CHECK_STACK_OVF (1);
12237                                 CHECK_OPSIZE (4);
12238                                 n = read16 (ip + 2);
12239                                 CHECK_LOCAL (n);
12240                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12241                                 *sp++ = ins;
12242                                 ip += 4;
12243                                 break;
12244                         case CEE_LDLOCA: {
12245                                 unsigned char *tmp_ip;
12246                                 CHECK_STACK_OVF (1);
12247                                 CHECK_OPSIZE (4);
12248                                 n = read16 (ip + 2);
12249                                 CHECK_LOCAL (n);
12250
12251                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12252                                         ip = tmp_ip;
12253                                         inline_costs += 1;
12254                                         break;
12255                                 }                       
12256                                 
12257                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12258                                 *sp++ = ins;
12259                                 ip += 4;
12260                                 break;
12261                         }
12262                         case CEE_STLOC:
12263                                 CHECK_STACK (1);
12264                                 --sp;
12265                                 CHECK_OPSIZE (4);
12266                                 n = read16 (ip + 2);
12267                                 CHECK_LOCAL (n);
12268                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12269                                         UNVERIFIED;
12270                                 emit_stloc_ir (cfg, sp, header, n);
12271                                 ip += 4;
12272                                 inline_costs += 1;
12273                                 break;
12274                         case CEE_LOCALLOC: {
12275                                 CHECK_STACK (1);
12276                                 MonoBasicBlock *non_zero_bb, *end_bb;
12277                                 int alloc_ptr = alloc_preg (cfg);
12278                                 --sp;
12279                                 if (sp != stack_start) 
12280                                         UNVERIFIED;
12281                                 if (cfg->method != method) 
12282                                         /* 
12283                                          * Inlining this into a loop in a parent could lead to 
12284                                          * stack overflows which is different behavior than the
12285                                          * non-inlined case, thus disable inlining in this case.
12286                                          */
12287                                         INLINE_FAILURE("localloc");
12288
12289                                 NEW_BBLOCK (cfg, non_zero_bb);
12290                                 NEW_BBLOCK (cfg, end_bb);
12291
12292                                 /* if size != zero */
12293                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12294                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12295
12296                                 //size is zero, so result is NULL
12297                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12298                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12299
12300                                 MONO_START_BB (cfg, non_zero_bb);
12301                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12302                                 ins->dreg = alloc_ptr;
12303                                 ins->sreg1 = sp [0]->dreg;
12304                                 ins->type = STACK_PTR;
12305                                 MONO_ADD_INS (cfg->cbb, ins);
12306
12307                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12308                                 if (init_locals)
12309                                         ins->flags |= MONO_INST_INIT;
12310
12311                                 MONO_START_BB (cfg, end_bb);
12312                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12313                                 ins->type = STACK_PTR;
12314
12315                                 *sp++ = ins;
12316                                 ip += 2;
12317                                 break;
12318                         }
12319                         case CEE_ENDFILTER: {
12320                                 MonoExceptionClause *clause, *nearest;
12321                                 int cc;
12322
12323                                 CHECK_STACK (1);
12324                                 --sp;
12325                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12326                                         UNVERIFIED;
12327                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12328                                 ins->sreg1 = (*sp)->dreg;
12329                                 MONO_ADD_INS (cfg->cbb, ins);
12330                                 start_new_bblock = 1;
12331                                 ip += 2;
12332
12333                                 nearest = NULL;
12334                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12335                                         clause = &header->clauses [cc];
12336                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12337                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12338                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12339                                                 nearest = clause;
12340                                 }
12341                                 g_assert (nearest);
12342                                 if ((ip - header->code) != nearest->handler_offset)
12343                                         UNVERIFIED;
12344
12345                                 break;
12346                         }
12347                         case CEE_UNALIGNED_:
12348                                 ins_flag |= MONO_INST_UNALIGNED;
12349                                 /* FIXME: record alignment? we can assume 1 for now */
12350                                 CHECK_OPSIZE (3);
12351                                 ip += 3;
12352                                 break;
12353                         case CEE_VOLATILE_:
12354                                 ins_flag |= MONO_INST_VOLATILE;
12355                                 ip += 2;
12356                                 break;
12357                         case CEE_TAIL_:
12358                                 ins_flag   |= MONO_INST_TAILCALL;
12359                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12360                                 /* Can't inline tail calls at this time */
12361                                 inline_costs += 100000;
12362                                 ip += 2;
12363                                 break;
12364                         case CEE_INITOBJ:
12365                                 CHECK_STACK (1);
12366                                 --sp;
12367                                 CHECK_OPSIZE (6);
12368                                 token = read32 (ip + 2);
12369                                 klass = mini_get_class (method, token, generic_context);
12370                                 CHECK_TYPELOAD (klass);
12371                                 if (generic_class_is_reference_type (cfg, klass))
12372                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12373                                 else
12374                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12375                                 ip += 6;
12376                                 inline_costs += 1;
12377                                 break;
12378                         case CEE_CONSTRAINED_:
12379                                 CHECK_OPSIZE (6);
12380                                 token = read32 (ip + 2);
12381                                 constrained_class = mini_get_class (method, token, generic_context);
12382                                 CHECK_TYPELOAD (constrained_class);
12383                                 ip += 6;
12384                                 break;
12385                         case CEE_CPBLK:
12386                                 CHECK_STACK (3);
12387                                 sp -= 3;
12388                                 mini_emit_memory_copy_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12389                                 ip += 2;
12390                                 ins_flag = 0;
12391                                 inline_costs += 1;
12392                                 break;
12393                         case CEE_INITBLK:
12394                                 CHECK_STACK (3);
12395                                 sp -= 3;
12396                                 mini_emit_memory_init_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12397                                 ip += 2;
12398                                 ins_flag = 0;
12399                                 inline_costs += 1;
12400                                 break;
12401                         case CEE_NO_:
12402                                 CHECK_OPSIZE (3);
12403                                 if (ip [2] & 0x1)
12404                                         ins_flag |= MONO_INST_NOTYPECHECK;
12405                                 if (ip [2] & 0x2)
12406                                         ins_flag |= MONO_INST_NORANGECHECK;
12407                                 /* we ignore the no-nullcheck for now since we
12408                                  * really do it explicitly only when doing callvirt->call
12409                                  */
12410                                 ip += 3;
12411                                 break;
12412                         case CEE_RETHROW: {
12413                                 MonoInst *load;
12414                                 int handler_offset = -1;
12415
12416                                 for (i = 0; i < header->num_clauses; ++i) {
12417                                         MonoExceptionClause *clause = &header->clauses [i];
12418                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12419                                                 handler_offset = clause->handler_offset;
12420                                                 break;
12421                                         }
12422                                 }
12423
12424                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12425
12426                                 if (handler_offset == -1)
12427                                         UNVERIFIED;
12428
12429                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12430                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12431                                 ins->sreg1 = load->dreg;
12432                                 MONO_ADD_INS (cfg->cbb, ins);
12433
12434                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12435                                 MONO_ADD_INS (cfg->cbb, ins);
12436
12437                                 sp = stack_start;
12438                                 link_bblock (cfg, cfg->cbb, end_bblock);
12439                                 start_new_bblock = 1;
12440                                 ip += 2;
12441                                 break;
12442                         }
12443                         case CEE_SIZEOF: {
12444                                 guint32 val;
12445                                 int ialign;
12446
12447                                 CHECK_STACK_OVF (1);
12448                                 CHECK_OPSIZE (6);
12449                                 token = read32 (ip + 2);
12450                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12451                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12452                                         CHECK_CFG_ERROR;
12453
12454                                         val = mono_type_size (type, &ialign);
12455                                 } else {
12456                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12457                                         CHECK_TYPELOAD (klass);
12458
12459                                         val = mono_type_size (&klass->byval_arg, &ialign);
12460
12461                                         if (mini_is_gsharedvt_klass (klass))
12462                                                 GSHAREDVT_FAILURE (*ip);
12463                                 }
12464                                 EMIT_NEW_ICONST (cfg, ins, val);
12465                                 *sp++= ins;
12466                                 ip += 6;
12467                                 break;
12468                         }
12469                         case CEE_REFANYTYPE: {
12470                                 MonoInst *src_var, *src;
12471
12472                                 GSHAREDVT_FAILURE (*ip);
12473
12474                                 CHECK_STACK (1);
12475                                 --sp;
12476
12477                                 // FIXME:
12478                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12479                                 if (!src_var)
12480                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12481                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12482                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12483                                 *sp++ = ins;
12484                                 ip += 2;
12485                                 break;
12486                         }
12487                         case CEE_READONLY_:
12488                                 readonly = TRUE;
12489                                 ip += 2;
12490                                 break;
12491
12492                         case CEE_UNUSED56:
12493                         case CEE_UNUSED57:
12494                         case CEE_UNUSED70:
12495                         case CEE_UNUSED:
12496                         case CEE_UNUSED99:
12497                                 UNVERIFIED;
12498                                 
12499                         default:
12500                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12501                                 UNVERIFIED;
12502                         }
12503                         break;
12504                 }
12505                 case CEE_UNUSED58:
12506                 case CEE_UNUSED1:
12507                         UNVERIFIED;
12508
12509                 default:
12510                         g_warning ("opcode 0x%02x not handled", *ip);
12511                         UNVERIFIED;
12512                 }
12513         }
12514         if (start_new_bblock != 1)
12515                 UNVERIFIED;
12516
12517         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12518         if (cfg->cbb->next_bb) {
12519                 /* This could already be set because of inlining, #693905 */
12520                 MonoBasicBlock *bb = cfg->cbb;
12521
12522                 while (bb->next_bb)
12523                         bb = bb->next_bb;
12524                 bb->next_bb = end_bblock;
12525         } else {
12526                 cfg->cbb->next_bb = end_bblock;
12527         }
12528
12529         if (cfg->method == method && cfg->domainvar) {
12530                 MonoInst *store;
12531                 MonoInst *get_domain;
12532
12533                 cfg->cbb = init_localsbb;
12534
12535                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12536                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12537                 MONO_ADD_INS (cfg->cbb, store);
12538         }
12539
12540 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12541         if (cfg->compile_aot)
12542                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12543                 mono_get_got_var (cfg);
12544 #endif
12545
12546         if (cfg->method == method && cfg->got_var)
12547                 mono_emit_load_got_addr (cfg);
12548
12549         if (init_localsbb) {
12550                 cfg->cbb = init_localsbb;
12551                 cfg->ip = NULL;
12552                 for (i = 0; i < header->num_locals; ++i) {
12553                         emit_init_local (cfg, i, header->locals [i], init_locals);
12554                 }
12555         }
12556
12557         if (cfg->init_ref_vars && cfg->method == method) {
12558                 /* Emit initialization for ref vars */
12559                 // FIXME: Avoid duplication initialization for IL locals.
12560                 for (i = 0; i < cfg->num_varinfo; ++i) {
12561                         MonoInst *ins = cfg->varinfo [i];
12562
12563                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12564                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12565                 }
12566         }
12567
12568         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12569                 cfg->cbb = init_localsbb;
12570                 emit_push_lmf (cfg);
12571         }
12572
12573         cfg->cbb = init_localsbb;
12574         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12575
12576         if (seq_points) {
12577                 MonoBasicBlock *bb;
12578
12579                 /*
12580                  * Make seq points at backward branch targets interruptable.
12581                  */
12582                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12583                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12584                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12585         }
12586
12587         /* Add a sequence point for method entry/exit events */
12588         if (seq_points && cfg->gen_sdb_seq_points) {
12589                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12590                 MONO_ADD_INS (init_localsbb, ins);
12591                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12592                 MONO_ADD_INS (cfg->bb_exit, ins);
12593         }
12594
12595         /*
12596          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12597          * the code they refer to was dead (#11880).
12598          */
12599         if (sym_seq_points) {
12600                 for (i = 0; i < header->code_size; ++i) {
12601                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12602                                 MonoInst *ins;
12603
12604                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12605                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12606                         }
12607                 }
12608         }
12609
12610         cfg->ip = NULL;
12611
12612         if (cfg->method == method) {
12613                 MonoBasicBlock *bb;
12614                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12615                         if (bb == cfg->bb_init)
12616                                 bb->region = -1;
12617                         else
12618                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12619                         if (cfg->spvars)
12620                                 mono_create_spvar_for_region (cfg, bb->region);
12621                         if (cfg->verbose_level > 2)
12622                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12623                 }
12624         } else {
12625                 MonoBasicBlock *bb;
12626                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12627                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12628                         bb->real_offset = inline_offset;
12629                 }
12630         }
12631
12632         if (inline_costs < 0) {
12633                 char *mname;
12634
12635                 /* Method is too large */
12636                 mname = mono_method_full_name (method, TRUE);
12637                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12638                 g_free (mname);
12639         }
12640
12641         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12642                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12643
12644         goto cleanup;
12645
12646 mono_error_exit:
12647         g_assert (!mono_error_ok (&cfg->error));
12648         goto cleanup;
12649  
12650  exception_exit:
12651         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12652         goto cleanup;
12653
12654  unverified:
12655         set_exception_type_from_invalid_il (cfg, method, ip);
12656         goto cleanup;
12657
12658  cleanup:
12659         g_slist_free (class_inits);
12660         mono_basic_block_free (original_bb);
12661         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12662         if (cfg->exception_type)
12663                 return -1;
12664         else
12665                 return inline_costs;
12666 }
12667
12668 static int
12669 store_membase_reg_to_store_membase_imm (int opcode)
12670 {
12671         switch (opcode) {
12672         case OP_STORE_MEMBASE_REG:
12673                 return OP_STORE_MEMBASE_IMM;
12674         case OP_STOREI1_MEMBASE_REG:
12675                 return OP_STOREI1_MEMBASE_IMM;
12676         case OP_STOREI2_MEMBASE_REG:
12677                 return OP_STOREI2_MEMBASE_IMM;
12678         case OP_STOREI4_MEMBASE_REG:
12679                 return OP_STOREI4_MEMBASE_IMM;
12680         case OP_STOREI8_MEMBASE_REG:
12681                 return OP_STOREI8_MEMBASE_IMM;
12682         default:
12683                 g_assert_not_reached ();
12684         }
12685
12686         return -1;
12687 }               
12688
12689 int
12690 mono_op_to_op_imm (int opcode)
12691 {
12692         switch (opcode) {
12693         case OP_IADD:
12694                 return OP_IADD_IMM;
12695         case OP_ISUB:
12696                 return OP_ISUB_IMM;
12697         case OP_IDIV:
12698                 return OP_IDIV_IMM;
12699         case OP_IDIV_UN:
12700                 return OP_IDIV_UN_IMM;
12701         case OP_IREM:
12702                 return OP_IREM_IMM;
12703         case OP_IREM_UN:
12704                 return OP_IREM_UN_IMM;
12705         case OP_IMUL:
12706                 return OP_IMUL_IMM;
12707         case OP_IAND:
12708                 return OP_IAND_IMM;
12709         case OP_IOR:
12710                 return OP_IOR_IMM;
12711         case OP_IXOR:
12712                 return OP_IXOR_IMM;
12713         case OP_ISHL:
12714                 return OP_ISHL_IMM;
12715         case OP_ISHR:
12716                 return OP_ISHR_IMM;
12717         case OP_ISHR_UN:
12718                 return OP_ISHR_UN_IMM;
12719
12720         case OP_LADD:
12721                 return OP_LADD_IMM;
12722         case OP_LSUB:
12723                 return OP_LSUB_IMM;
12724         case OP_LAND:
12725                 return OP_LAND_IMM;
12726         case OP_LOR:
12727                 return OP_LOR_IMM;
12728         case OP_LXOR:
12729                 return OP_LXOR_IMM;
12730         case OP_LSHL:
12731                 return OP_LSHL_IMM;
12732         case OP_LSHR:
12733                 return OP_LSHR_IMM;
12734         case OP_LSHR_UN:
12735                 return OP_LSHR_UN_IMM;
12736 #if SIZEOF_REGISTER == 8
12737         case OP_LREM:
12738                 return OP_LREM_IMM;
12739 #endif
12740
12741         case OP_COMPARE:
12742                 return OP_COMPARE_IMM;
12743         case OP_ICOMPARE:
12744                 return OP_ICOMPARE_IMM;
12745         case OP_LCOMPARE:
12746                 return OP_LCOMPARE_IMM;
12747
12748         case OP_STORE_MEMBASE_REG:
12749                 return OP_STORE_MEMBASE_IMM;
12750         case OP_STOREI1_MEMBASE_REG:
12751                 return OP_STOREI1_MEMBASE_IMM;
12752         case OP_STOREI2_MEMBASE_REG:
12753                 return OP_STOREI2_MEMBASE_IMM;
12754         case OP_STOREI4_MEMBASE_REG:
12755                 return OP_STOREI4_MEMBASE_IMM;
12756
12757 #if defined(TARGET_X86) || defined (TARGET_AMD64)
12758         case OP_X86_PUSH:
12759                 return OP_X86_PUSH_IMM;
12760         case OP_X86_COMPARE_MEMBASE_REG:
12761                 return OP_X86_COMPARE_MEMBASE_IMM;
12762 #endif
12763 #if defined(TARGET_AMD64)
12764         case OP_AMD64_ICOMPARE_MEMBASE_REG:
12765                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
12766 #endif
12767         case OP_VOIDCALL_REG:
12768                 return OP_VOIDCALL;
12769         case OP_CALL_REG:
12770                 return OP_CALL;
12771         case OP_LCALL_REG:
12772                 return OP_LCALL;
12773         case OP_FCALL_REG:
12774                 return OP_FCALL;
12775         case OP_LOCALLOC:
12776                 return OP_LOCALLOC_IMM;
12777         }
12778
12779         return -1;
12780 }
12781
12782 static int
12783 ldind_to_load_membase (int opcode)
12784 {
12785         switch (opcode) {
12786         case CEE_LDIND_I1:
12787                 return OP_LOADI1_MEMBASE;
12788         case CEE_LDIND_U1:
12789                 return OP_LOADU1_MEMBASE;
12790         case CEE_LDIND_I2:
12791                 return OP_LOADI2_MEMBASE;
12792         case CEE_LDIND_U2:
12793                 return OP_LOADU2_MEMBASE;
12794         case CEE_LDIND_I4:
12795                 return OP_LOADI4_MEMBASE;
12796         case CEE_LDIND_U4:
12797                 return OP_LOADU4_MEMBASE;
12798         case CEE_LDIND_I:
12799                 return OP_LOAD_MEMBASE;
12800         case CEE_LDIND_REF:
12801                 return OP_LOAD_MEMBASE;
12802         case CEE_LDIND_I8:
12803                 return OP_LOADI8_MEMBASE;
12804         case CEE_LDIND_R4:
12805                 return OP_LOADR4_MEMBASE;
12806         case CEE_LDIND_R8:
12807                 return OP_LOADR8_MEMBASE;
12808         default:
12809                 g_assert_not_reached ();
12810         }
12811
12812         return -1;
12813 }
12814
12815 static int
12816 stind_to_store_membase (int opcode)
12817 {
12818         switch (opcode) {
12819         case CEE_STIND_I1:
12820                 return OP_STOREI1_MEMBASE_REG;
12821         case CEE_STIND_I2:
12822                 return OP_STOREI2_MEMBASE_REG;
12823         case CEE_STIND_I4:
12824                 return OP_STOREI4_MEMBASE_REG;
12825         case CEE_STIND_I:
12826         case CEE_STIND_REF:
12827                 return OP_STORE_MEMBASE_REG;
12828         case CEE_STIND_I8:
12829                 return OP_STOREI8_MEMBASE_REG;
12830         case CEE_STIND_R4:
12831                 return OP_STORER4_MEMBASE_REG;
12832         case CEE_STIND_R8:
12833                 return OP_STORER8_MEMBASE_REG;
12834         default:
12835                 g_assert_not_reached ();
12836         }
12837
12838         return -1;
12839 }
12840
12841 int
12842 mono_load_membase_to_load_mem (int opcode)
12843 {
12844         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
12845 #if defined(TARGET_X86) || defined(TARGET_AMD64)
12846         switch (opcode) {
12847         case OP_LOAD_MEMBASE:
12848                 return OP_LOAD_MEM;
12849         case OP_LOADU1_MEMBASE:
12850                 return OP_LOADU1_MEM;
12851         case OP_LOADU2_MEMBASE:
12852                 return OP_LOADU2_MEM;
12853         case OP_LOADI4_MEMBASE:
12854                 return OP_LOADI4_MEM;
12855         case OP_LOADU4_MEMBASE:
12856                 return OP_LOADU4_MEM;
12857 #if SIZEOF_REGISTER == 8
12858         case OP_LOADI8_MEMBASE:
12859                 return OP_LOADI8_MEM;
12860 #endif
12861         }
12862 #endif
12863
12864         return -1;
12865 }
12866
12867 static inline int
12868 op_to_op_dest_membase (int store_opcode, int opcode)
12869 {
12870 #if defined(TARGET_X86)
12871         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
12872                 return -1;
12873
12874         switch (opcode) {
12875         case OP_IADD:
12876                 return OP_X86_ADD_MEMBASE_REG;
12877         case OP_ISUB:
12878                 return OP_X86_SUB_MEMBASE_REG;
12879         case OP_IAND:
12880                 return OP_X86_AND_MEMBASE_REG;
12881         case OP_IOR:
12882                 return OP_X86_OR_MEMBASE_REG;
12883         case OP_IXOR:
12884                 return OP_X86_XOR_MEMBASE_REG;
12885         case OP_ADD_IMM:
12886         case OP_IADD_IMM:
12887                 return OP_X86_ADD_MEMBASE_IMM;
12888         case OP_SUB_IMM:
12889         case OP_ISUB_IMM:
12890                 return OP_X86_SUB_MEMBASE_IMM;
12891         case OP_AND_IMM:
12892         case OP_IAND_IMM:
12893                 return OP_X86_AND_MEMBASE_IMM;
12894         case OP_OR_IMM:
12895         case OP_IOR_IMM:
12896                 return OP_X86_OR_MEMBASE_IMM;
12897         case OP_XOR_IMM:
12898         case OP_IXOR_IMM:
12899                 return OP_X86_XOR_MEMBASE_IMM;
12900         case OP_MOVE:
12901                 return OP_NOP;
12902         }
12903 #endif
12904
12905 #if defined(TARGET_AMD64)
12906         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
12907                 return -1;
12908
12909         switch (opcode) {
12910         case OP_IADD:
12911                 return OP_X86_ADD_MEMBASE_REG;
12912         case OP_ISUB:
12913                 return OP_X86_SUB_MEMBASE_REG;
12914         case OP_IAND:
12915                 return OP_X86_AND_MEMBASE_REG;
12916         case OP_IOR:
12917                 return OP_X86_OR_MEMBASE_REG;
12918         case OP_IXOR:
12919                 return OP_X86_XOR_MEMBASE_REG;
12920         case OP_IADD_IMM:
12921                 return OP_X86_ADD_MEMBASE_IMM;
12922         case OP_ISUB_IMM:
12923                 return OP_X86_SUB_MEMBASE_IMM;
12924         case OP_IAND_IMM:
12925                 return OP_X86_AND_MEMBASE_IMM;
12926         case OP_IOR_IMM:
12927                 return OP_X86_OR_MEMBASE_IMM;
12928         case OP_IXOR_IMM:
12929                 return OP_X86_XOR_MEMBASE_IMM;
12930         case OP_LADD:
12931                 return OP_AMD64_ADD_MEMBASE_REG;
12932         case OP_LSUB:
12933                 return OP_AMD64_SUB_MEMBASE_REG;
12934         case OP_LAND:
12935                 return OP_AMD64_AND_MEMBASE_REG;
12936         case OP_LOR:
12937                 return OP_AMD64_OR_MEMBASE_REG;
12938         case OP_LXOR:
12939                 return OP_AMD64_XOR_MEMBASE_REG;
12940         case OP_ADD_IMM:
12941         case OP_LADD_IMM:
12942                 return OP_AMD64_ADD_MEMBASE_IMM;
12943         case OP_SUB_IMM:
12944         case OP_LSUB_IMM:
12945                 return OP_AMD64_SUB_MEMBASE_IMM;
12946         case OP_AND_IMM:
12947         case OP_LAND_IMM:
12948                 return OP_AMD64_AND_MEMBASE_IMM;
12949         case OP_OR_IMM:
12950         case OP_LOR_IMM:
12951                 return OP_AMD64_OR_MEMBASE_IMM;
12952         case OP_XOR_IMM:
12953         case OP_LXOR_IMM:
12954                 return OP_AMD64_XOR_MEMBASE_IMM;
12955         case OP_MOVE:
12956                 return OP_NOP;
12957         }
12958 #endif
12959
12960         return -1;
12961 }
12962
12963 static inline int
12964 op_to_op_store_membase (int store_opcode, int opcode)
12965 {
12966 #if defined(TARGET_X86) || defined(TARGET_AMD64)
12967         switch (opcode) {
12968         case OP_ICEQ:
12969                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
12970                         return OP_X86_SETEQ_MEMBASE;
12971         case OP_CNE:
12972                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
12973                         return OP_X86_SETNE_MEMBASE;
12974         }
12975 #endif
12976
12977         return -1;
12978 }
12979
12980 static inline int
12981 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
12982 {
12983 #ifdef TARGET_X86
12984         /* FIXME: This has sign extension issues */
12985         /*
12986         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
12987                 return OP_X86_COMPARE_MEMBASE8_IMM;
12988         */
12989
12990         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
12991                 return -1;
12992
12993         switch (opcode) {
12994         case OP_X86_PUSH:
12995                 return OP_X86_PUSH_MEMBASE;
12996         case OP_COMPARE_IMM:
12997         case OP_ICOMPARE_IMM:
12998                 return OP_X86_COMPARE_MEMBASE_IMM;
12999         case OP_COMPARE:
13000         case OP_ICOMPARE:
13001                 return OP_X86_COMPARE_MEMBASE_REG;
13002         }
13003 #endif
13004
13005 #ifdef TARGET_AMD64
13006         /* FIXME: This has sign extension issues */
13007         /*
13008         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13009                 return OP_X86_COMPARE_MEMBASE8_IMM;
13010         */
13011
13012         switch (opcode) {
13013         case OP_X86_PUSH:
13014                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13015                         return OP_X86_PUSH_MEMBASE;
13016                 break;
13017                 /* FIXME: This only works for 32 bit immediates
13018         case OP_COMPARE_IMM:
13019         case OP_LCOMPARE_IMM:
13020                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13021                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13022                 */
13023         case OP_ICOMPARE_IMM:
13024                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13025                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13026                 break;
13027         case OP_COMPARE:
13028         case OP_LCOMPARE:
13029                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13030                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13031                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13032                         return OP_AMD64_COMPARE_MEMBASE_REG;
13033                 break;
13034         case OP_ICOMPARE:
13035                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13036                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13037                 break;
13038         }
13039 #endif
13040
13041         return -1;
13042 }
13043
13044 static inline int
13045 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13046 {
13047 #ifdef TARGET_X86
13048         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13049                 return -1;
13050         
13051         switch (opcode) {
13052         case OP_COMPARE:
13053         case OP_ICOMPARE:
13054                 return OP_X86_COMPARE_REG_MEMBASE;
13055         case OP_IADD:
13056                 return OP_X86_ADD_REG_MEMBASE;
13057         case OP_ISUB:
13058                 return OP_X86_SUB_REG_MEMBASE;
13059         case OP_IAND:
13060                 return OP_X86_AND_REG_MEMBASE;
13061         case OP_IOR:
13062                 return OP_X86_OR_REG_MEMBASE;
13063         case OP_IXOR:
13064                 return OP_X86_XOR_REG_MEMBASE;
13065         }
13066 #endif
13067
13068 #ifdef TARGET_AMD64
13069         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13070                 switch (opcode) {
13071                 case OP_ICOMPARE:
13072                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13073                 case OP_IADD:
13074                         return OP_X86_ADD_REG_MEMBASE;
13075                 case OP_ISUB:
13076                         return OP_X86_SUB_REG_MEMBASE;
13077                 case OP_IAND:
13078                         return OP_X86_AND_REG_MEMBASE;
13079                 case OP_IOR:
13080                         return OP_X86_OR_REG_MEMBASE;
13081                 case OP_IXOR:
13082                         return OP_X86_XOR_REG_MEMBASE;
13083                 }
13084         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13085                 switch (opcode) {
13086                 case OP_COMPARE:
13087                 case OP_LCOMPARE:
13088                         return OP_AMD64_COMPARE_REG_MEMBASE;
13089                 case OP_LADD:
13090                         return OP_AMD64_ADD_REG_MEMBASE;
13091                 case OP_LSUB:
13092                         return OP_AMD64_SUB_REG_MEMBASE;
13093                 case OP_LAND:
13094                         return OP_AMD64_AND_REG_MEMBASE;
13095                 case OP_LOR:
13096                         return OP_AMD64_OR_REG_MEMBASE;
13097                 case OP_LXOR:
13098                         return OP_AMD64_XOR_REG_MEMBASE;
13099                 }
13100         }
13101 #endif
13102
13103         return -1;
13104 }
13105
13106 int
13107 mono_op_to_op_imm_noemul (int opcode)
13108 {
13109         switch (opcode) {
13110 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13111         case OP_LSHR:
13112         case OP_LSHL:
13113         case OP_LSHR_UN:
13114                 return -1;
13115 #endif
13116 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13117         case OP_IDIV:
13118         case OP_IDIV_UN:
13119         case OP_IREM:
13120         case OP_IREM_UN:
13121                 return -1;
13122 #endif
13123 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13124         case OP_IMUL:
13125                 return -1;
13126 #endif
13127         default:
13128                 return mono_op_to_op_imm (opcode);
13129         }
13130 }
13131
13132 /**
13133  * mono_handle_global_vregs:
13134  *
13135  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13136  * for them.
13137  */
13138 void
13139 mono_handle_global_vregs (MonoCompile *cfg)
13140 {
13141         gint32 *vreg_to_bb;
13142         MonoBasicBlock *bb;
13143         int i, pos;
13144
13145         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13146
13147 #ifdef MONO_ARCH_SIMD_INTRINSICS
13148         if (cfg->uses_simd_intrinsics)
13149                 mono_simd_simplify_indirection (cfg);
13150 #endif
13151
13152         /* Find local vregs used in more than one bb */
13153         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13154                 MonoInst *ins = bb->code;       
13155                 int block_num = bb->block_num;
13156
13157                 if (cfg->verbose_level > 2)
13158                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13159
13160                 cfg->cbb = bb;
13161                 for (; ins; ins = ins->next) {
13162                         const char *spec = INS_INFO (ins->opcode);
13163                         int regtype = 0, regindex;
13164                         gint32 prev_bb;
13165
13166                         if (G_UNLIKELY (cfg->verbose_level > 2))
13167                                 mono_print_ins (ins);
13168
13169                         g_assert (ins->opcode >= MONO_CEE_LAST);
13170
13171                         for (regindex = 0; regindex < 4; regindex ++) {
13172                                 int vreg = 0;
13173
13174                                 if (regindex == 0) {
13175                                         regtype = spec [MONO_INST_DEST];
13176                                         if (regtype == ' ')
13177                                                 continue;
13178                                         vreg = ins->dreg;
13179                                 } else if (regindex == 1) {
13180                                         regtype = spec [MONO_INST_SRC1];
13181                                         if (regtype == ' ')
13182                                                 continue;
13183                                         vreg = ins->sreg1;
13184                                 } else if (regindex == 2) {
13185                                         regtype = spec [MONO_INST_SRC2];
13186                                         if (regtype == ' ')
13187                                                 continue;
13188                                         vreg = ins->sreg2;
13189                                 } else if (regindex == 3) {
13190                                         regtype = spec [MONO_INST_SRC3];
13191                                         if (regtype == ' ')
13192                                                 continue;
13193                                         vreg = ins->sreg3;
13194                                 }
13195
13196 #if SIZEOF_REGISTER == 4
13197                                 /* In the LLVM case, the long opcodes are not decomposed */
13198                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13199                                         /*
13200                                          * Since some instructions reference the original long vreg,
13201                                          * and some reference the two component vregs, it is quite hard
13202                                          * to determine when it needs to be global. So be conservative.
13203                                          */
13204                                         if (!get_vreg_to_inst (cfg, vreg)) {
13205                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13206
13207                                                 if (cfg->verbose_level > 2)
13208                                                         printf ("LONG VREG R%d made global.\n", vreg);
13209                                         }
13210
13211                                         /*
13212                                          * Make the component vregs volatile since the optimizations can
13213                                          * get confused otherwise.
13214                                          */
13215                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13216                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13217                                 }
13218 #endif
13219
13220                                 g_assert (vreg != -1);
13221
13222                                 prev_bb = vreg_to_bb [vreg];
13223                                 if (prev_bb == 0) {
13224                                         /* 0 is a valid block num */
13225                                         vreg_to_bb [vreg] = block_num + 1;
13226                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13227                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13228                                                 continue;
13229
13230                                         if (!get_vreg_to_inst (cfg, vreg)) {
13231                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13232                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13233
13234                                                 switch (regtype) {
13235                                                 case 'i':
13236                                                         if (vreg_is_ref (cfg, vreg))
13237                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13238                                                         else
13239                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13240                                                         break;
13241                                                 case 'l':
13242                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13243                                                         break;
13244                                                 case 'f':
13245                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13246                                                         break;
13247                                                 case 'v':
13248                                                 case 'x':
13249                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13250                                                         break;
13251                                                 default:
13252                                                         g_assert_not_reached ();
13253                                                 }
13254                                         }
13255
13256                                         /* Flag as having been used in more than one bb */
13257                                         vreg_to_bb [vreg] = -1;
13258                                 }
13259                         }
13260                 }
13261         }
13262
13263         /* If a variable is used in only one bblock, convert it into a local vreg */
13264         for (i = 0; i < cfg->num_varinfo; i++) {
13265                 MonoInst *var = cfg->varinfo [i];
13266                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13267
13268                 switch (var->type) {
13269                 case STACK_I4:
13270                 case STACK_OBJ:
13271                 case STACK_PTR:
13272                 case STACK_MP:
13273                 case STACK_VTYPE:
13274 #if SIZEOF_REGISTER == 8
13275                 case STACK_I8:
13276 #endif
13277 #if !defined(TARGET_X86)
13278                 /* Enabling this screws up the fp stack on x86 */
13279                 case STACK_R8:
13280 #endif
13281                         if (mono_arch_is_soft_float ())
13282                                 break;
13283
13284                         /*
13285                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13286                                 break;
13287                         */
13288
13289                         /* Arguments are implicitly global */
13290                         /* Putting R4 vars into registers doesn't work currently */
13291                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13292                         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) {
13293                                 /* 
13294                                  * Make that the variable's liveness interval doesn't contain a call, since
13295                                  * that would cause the lvreg to be spilled, making the whole optimization
13296                                  * useless.
13297                                  */
13298                                 /* This is too slow for JIT compilation */
13299 #if 0
13300                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13301                                         MonoInst *ins;
13302                                         int def_index, call_index, ins_index;
13303                                         gboolean spilled = FALSE;
13304
13305                                         def_index = -1;
13306                                         call_index = -1;
13307                                         ins_index = 0;
13308                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13309                                                 const char *spec = INS_INFO (ins->opcode);
13310
13311                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13312                                                         def_index = ins_index;
13313
13314                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13315                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13316                                                         if (call_index > def_index) {
13317                                                                 spilled = TRUE;
13318                                                                 break;
13319                                                         }
13320                                                 }
13321
13322                                                 if (MONO_IS_CALL (ins))
13323                                                         call_index = ins_index;
13324
13325                                                 ins_index ++;
13326                                         }
13327
13328                                         if (spilled)
13329                                                 break;
13330                                 }
13331 #endif
13332
13333                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13334                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13335                                 var->flags |= MONO_INST_IS_DEAD;
13336                                 cfg->vreg_to_inst [var->dreg] = NULL;
13337                         }
13338                         break;
13339                 }
13340         }
13341
13342         /* 
13343          * Compress the varinfo and vars tables so the liveness computation is faster and
13344          * takes up less space.
13345          */
13346         pos = 0;
13347         for (i = 0; i < cfg->num_varinfo; ++i) {
13348                 MonoInst *var = cfg->varinfo [i];
13349                 if (pos < i && cfg->locals_start == i)
13350                         cfg->locals_start = pos;
13351                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13352                         if (pos < i) {
13353                                 cfg->varinfo [pos] = cfg->varinfo [i];
13354                                 cfg->varinfo [pos]->inst_c0 = pos;
13355                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13356                                 cfg->vars [pos].idx = pos;
13357 #if SIZEOF_REGISTER == 4
13358                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13359                                         /* Modify the two component vars too */
13360                                         MonoInst *var1;
13361
13362                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13363                                         var1->inst_c0 = pos;
13364                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13365                                         var1->inst_c0 = pos;
13366                                 }
13367 #endif
13368                         }
13369                         pos ++;
13370                 }
13371         }
13372         cfg->num_varinfo = pos;
13373         if (cfg->locals_start > cfg->num_varinfo)
13374                 cfg->locals_start = cfg->num_varinfo;
13375 }
13376
13377 /*
13378  * mono_allocate_gsharedvt_vars:
13379  *
13380  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13381  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13382  */
13383 void
13384 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13385 {
13386         int i;
13387
13388         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13389
13390         for (i = 0; i < cfg->num_varinfo; ++i) {
13391                 MonoInst *ins = cfg->varinfo [i];
13392                 int idx;
13393
13394                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13395                         if (i >= cfg->locals_start) {
13396                                 /* Local */
13397                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13398                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13399                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13400                                 ins->inst_imm = idx;
13401                         } else {
13402                                 /* Arg */
13403                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13404                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13405                         }
13406                 }
13407         }
13408 }
13409
13410 /**
13411  * mono_spill_global_vars:
13412  *
13413  *   Generate spill code for variables which are not allocated to registers, 
13414  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13415  * code is generated which could be optimized by the local optimization passes.
13416  */
13417 void
13418 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13419 {
13420         MonoBasicBlock *bb;
13421         char spec2 [16];
13422         int orig_next_vreg;
13423         guint32 *vreg_to_lvreg;
13424         guint32 *lvregs;
13425         guint32 i, lvregs_len, lvregs_size;
13426         gboolean dest_has_lvreg = FALSE;
13427         MonoStackType stacktypes [128];
13428         MonoInst **live_range_start, **live_range_end;
13429         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13430
13431         *need_local_opts = FALSE;
13432
13433         memset (spec2, 0, sizeof (spec2));
13434
13435         /* FIXME: Move this function to mini.c */
13436         stacktypes ['i'] = STACK_PTR;
13437         stacktypes ['l'] = STACK_I8;
13438         stacktypes ['f'] = STACK_R8;
13439 #ifdef MONO_ARCH_SIMD_INTRINSICS
13440         stacktypes ['x'] = STACK_VTYPE;
13441 #endif
13442
13443 #if SIZEOF_REGISTER == 4
13444         /* Create MonoInsts for longs */
13445         for (i = 0; i < cfg->num_varinfo; i++) {
13446                 MonoInst *ins = cfg->varinfo [i];
13447
13448                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13449                         switch (ins->type) {
13450                         case STACK_R8:
13451                         case STACK_I8: {
13452                                 MonoInst *tree;
13453
13454                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13455                                         break;
13456
13457                                 g_assert (ins->opcode == OP_REGOFFSET);
13458
13459                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13460                                 g_assert (tree);
13461                                 tree->opcode = OP_REGOFFSET;
13462                                 tree->inst_basereg = ins->inst_basereg;
13463                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13464
13465                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13466                                 g_assert (tree);
13467                                 tree->opcode = OP_REGOFFSET;
13468                                 tree->inst_basereg = ins->inst_basereg;
13469                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13470                                 break;
13471                         }
13472                         default:
13473                                 break;
13474                         }
13475                 }
13476         }
13477 #endif
13478
13479         if (cfg->compute_gc_maps) {
13480                 /* registers need liveness info even for !non refs */
13481                 for (i = 0; i < cfg->num_varinfo; i++) {
13482                         MonoInst *ins = cfg->varinfo [i];
13483
13484                         if (ins->opcode == OP_REGVAR)
13485                                 ins->flags |= MONO_INST_GC_TRACK;
13486                 }
13487         }
13488                 
13489         /* FIXME: widening and truncation */
13490
13491         /*
13492          * As an optimization, when a variable allocated to the stack is first loaded into 
13493          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13494          * the variable again.
13495          */
13496         orig_next_vreg = cfg->next_vreg;
13497         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13498         lvregs_size = 1024;
13499         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13500         lvregs_len = 0;
13501
13502         /* 
13503          * These arrays contain the first and last instructions accessing a given
13504          * variable.
13505          * Since we emit bblocks in the same order we process them here, and we
13506          * don't split live ranges, these will precisely describe the live range of
13507          * the variable, i.e. the instruction range where a valid value can be found
13508          * in the variables location.
13509          * The live range is computed using the liveness info computed by the liveness pass.
13510          * We can't use vmv->range, since that is an abstract live range, and we need
13511          * one which is instruction precise.
13512          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13513          */
13514         /* FIXME: Only do this if debugging info is requested */
13515         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13516         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13517         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13518         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13519         
13520         /* Add spill loads/stores */
13521         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13522                 MonoInst *ins;
13523
13524                 if (cfg->verbose_level > 2)
13525                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13526
13527                 /* Clear vreg_to_lvreg array */
13528                 for (i = 0; i < lvregs_len; i++)
13529                         vreg_to_lvreg [lvregs [i]] = 0;
13530                 lvregs_len = 0;
13531
13532                 cfg->cbb = bb;
13533                 MONO_BB_FOR_EACH_INS (bb, ins) {
13534                         const char *spec = INS_INFO (ins->opcode);
13535                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13536                         gboolean store, no_lvreg;
13537                         int sregs [MONO_MAX_SRC_REGS];
13538
13539                         if (G_UNLIKELY (cfg->verbose_level > 2))
13540                                 mono_print_ins (ins);
13541
13542                         if (ins->opcode == OP_NOP)
13543                                 continue;
13544
13545                         /* 
13546                          * We handle LDADDR here as well, since it can only be decomposed
13547                          * when variable addresses are known.
13548                          */
13549                         if (ins->opcode == OP_LDADDR) {
13550                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13551
13552                                 if (var->opcode == OP_VTARG_ADDR) {
13553                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13554                                         MonoInst *vtaddr = var->inst_left;
13555                                         if (vtaddr->opcode == OP_REGVAR) {
13556                                                 ins->opcode = OP_MOVE;
13557                                                 ins->sreg1 = vtaddr->dreg;
13558                                         }
13559                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13560                                                 ins->opcode = OP_LOAD_MEMBASE;
13561                                                 ins->inst_basereg = vtaddr->inst_basereg;
13562                                                 ins->inst_offset = vtaddr->inst_offset;
13563                                         } else
13564                                                 NOT_IMPLEMENTED;
13565                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13566                                         /* gsharedvt arg passed by ref */
13567                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13568
13569                                         ins->opcode = OP_LOAD_MEMBASE;
13570                                         ins->inst_basereg = var->inst_basereg;
13571                                         ins->inst_offset = var->inst_offset;
13572                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13573                                         MonoInst *load, *load2, *load3;
13574                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13575                                         int reg1, reg2, reg3;
13576                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13577                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13578
13579                                         /*
13580                                          * gsharedvt local.
13581                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13582                                          */
13583
13584                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13585
13586                                         g_assert (info_var);
13587                                         g_assert (locals_var);
13588
13589                                         /* Mark the instruction used to compute the locals var as used */
13590                                         cfg->gsharedvt_locals_var_ins = NULL;
13591
13592                                         /* Load the offset */
13593                                         if (info_var->opcode == OP_REGOFFSET) {
13594                                                 reg1 = alloc_ireg (cfg);
13595                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13596                                         } else if (info_var->opcode == OP_REGVAR) {
13597                                                 load = NULL;
13598                                                 reg1 = info_var->dreg;
13599                                         } else {
13600                                                 g_assert_not_reached ();
13601                                         }
13602                                         reg2 = alloc_ireg (cfg);
13603                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13604                                         /* Load the locals area address */
13605                                         reg3 = alloc_ireg (cfg);
13606                                         if (locals_var->opcode == OP_REGOFFSET) {
13607                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13608                                         } else if (locals_var->opcode == OP_REGVAR) {
13609                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13610                                         } else {
13611                                                 g_assert_not_reached ();
13612                                         }
13613                                         /* Compute the address */
13614                                         ins->opcode = OP_PADD;
13615                                         ins->sreg1 = reg3;
13616                                         ins->sreg2 = reg2;
13617
13618                                         mono_bblock_insert_before_ins (bb, ins, load3);
13619                                         mono_bblock_insert_before_ins (bb, load3, load2);
13620                                         if (load)
13621                                                 mono_bblock_insert_before_ins (bb, load2, load);
13622                                 } else {
13623                                         g_assert (var->opcode == OP_REGOFFSET);
13624
13625                                         ins->opcode = OP_ADD_IMM;
13626                                         ins->sreg1 = var->inst_basereg;
13627                                         ins->inst_imm = var->inst_offset;
13628                                 }
13629
13630                                 *need_local_opts = TRUE;
13631                                 spec = INS_INFO (ins->opcode);
13632                         }
13633
13634                         if (ins->opcode < MONO_CEE_LAST) {
13635                                 mono_print_ins (ins);
13636                                 g_assert_not_reached ();
13637                         }
13638
13639                         /*
13640                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13641                          * src register.
13642                          * FIXME:
13643                          */
13644                         if (MONO_IS_STORE_MEMBASE (ins)) {
13645                                 tmp_reg = ins->dreg;
13646                                 ins->dreg = ins->sreg2;
13647                                 ins->sreg2 = tmp_reg;
13648                                 store = TRUE;
13649
13650                                 spec2 [MONO_INST_DEST] = ' ';
13651                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13652                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13653                                 spec2 [MONO_INST_SRC3] = ' ';
13654                                 spec = spec2;
13655                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13656                                 g_assert_not_reached ();
13657                         else
13658                                 store = FALSE;
13659                         no_lvreg = FALSE;
13660
13661                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13662                                 printf ("\t %.3s %d", spec, ins->dreg);
13663                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13664                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13665                                         printf (" %d", sregs [srcindex]);
13666                                 printf ("\n");
13667                         }
13668
13669                         /***************/
13670                         /*    DREG     */
13671                         /***************/
13672                         regtype = spec [MONO_INST_DEST];
13673                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13674                         prev_dreg = -1;
13675
13676                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13677                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13678                                 MonoInst *store_ins;
13679                                 int store_opcode;
13680                                 MonoInst *def_ins = ins;
13681                                 int dreg = ins->dreg; /* The original vreg */
13682
13683                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13684
13685                                 if (var->opcode == OP_REGVAR) {
13686                                         ins->dreg = var->dreg;
13687                                 } 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)) {
13688                                         /* 
13689                                          * Instead of emitting a load+store, use a _membase opcode.
13690                                          */
13691                                         g_assert (var->opcode == OP_REGOFFSET);
13692                                         if (ins->opcode == OP_MOVE) {
13693                                                 NULLIFY_INS (ins);
13694                                                 def_ins = NULL;
13695                                         } else {
13696                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13697                                                 ins->inst_basereg = var->inst_basereg;
13698                                                 ins->inst_offset = var->inst_offset;
13699                                                 ins->dreg = -1;
13700                                         }
13701                                         spec = INS_INFO (ins->opcode);
13702                                 } else {
13703                                         guint32 lvreg;
13704
13705                                         g_assert (var->opcode == OP_REGOFFSET);
13706
13707                                         prev_dreg = ins->dreg;
13708
13709                                         /* Invalidate any previous lvreg for this vreg */
13710                                         vreg_to_lvreg [ins->dreg] = 0;
13711
13712                                         lvreg = 0;
13713
13714                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
13715                                                 regtype = 'l';
13716                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
13717                                         }
13718
13719                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
13720
13721 #if SIZEOF_REGISTER != 8
13722                                         if (regtype == 'l') {
13723                                                 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));
13724                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13725                                                 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));
13726                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13727                                                 def_ins = store_ins;
13728                                         }
13729                                         else
13730 #endif
13731                                         {
13732                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
13733
13734                                                 /* Try to fuse the store into the instruction itself */
13735                                                 /* FIXME: Add more instructions */
13736                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
13737                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
13738                                                         ins->inst_imm = ins->inst_c0;
13739                                                         ins->inst_destbasereg = var->inst_basereg;
13740                                                         ins->inst_offset = var->inst_offset;
13741                                                         spec = INS_INFO (ins->opcode);
13742                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
13743                                                         ins->opcode = store_opcode;
13744                                                         ins->inst_destbasereg = var->inst_basereg;
13745                                                         ins->inst_offset = var->inst_offset;
13746
13747                                                         no_lvreg = TRUE;
13748
13749                                                         tmp_reg = ins->dreg;
13750                                                         ins->dreg = ins->sreg2;
13751                                                         ins->sreg2 = tmp_reg;
13752                                                         store = TRUE;
13753
13754                                                         spec2 [MONO_INST_DEST] = ' ';
13755                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13756                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13757                                                         spec2 [MONO_INST_SRC3] = ' ';
13758                                                         spec = spec2;
13759                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
13760                                                         // FIXME: The backends expect the base reg to be in inst_basereg
13761                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
13762                                                         ins->dreg = -1;
13763                                                         ins->inst_basereg = var->inst_basereg;
13764                                                         ins->inst_offset = var->inst_offset;
13765                                                         spec = INS_INFO (ins->opcode);
13766                                                 } else {
13767                                                         /* printf ("INS: "); mono_print_ins (ins); */
13768                                                         /* Create a store instruction */
13769                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
13770
13771                                                         /* Insert it after the instruction */
13772                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
13773
13774                                                         def_ins = store_ins;
13775
13776                                                         /* 
13777                                                          * We can't assign ins->dreg to var->dreg here, since the
13778                                                          * sregs could use it. So set a flag, and do it after
13779                                                          * the sregs.
13780                                                          */
13781                                                         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)))
13782                                                                 dest_has_lvreg = TRUE;
13783                                                 }
13784                                         }
13785                                 }
13786
13787                                 if (def_ins && !live_range_start [dreg]) {
13788                                         live_range_start [dreg] = def_ins;
13789                                         live_range_start_bb [dreg] = bb;
13790                                 }
13791
13792                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
13793                                         MonoInst *tmp;
13794
13795                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
13796                                         tmp->inst_c1 = dreg;
13797                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
13798                                 }
13799                         }
13800
13801                         /************/
13802                         /*  SREGS   */
13803                         /************/
13804                         num_sregs = mono_inst_get_src_registers (ins, sregs);
13805                         for (srcindex = 0; srcindex < 3; ++srcindex) {
13806                                 regtype = spec [MONO_INST_SRC1 + srcindex];
13807                                 sreg = sregs [srcindex];
13808
13809                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
13810                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
13811                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
13812                                         MonoInst *use_ins = ins;
13813                                         MonoInst *load_ins;
13814                                         guint32 load_opcode;
13815
13816                                         if (var->opcode == OP_REGVAR) {
13817                                                 sregs [srcindex] = var->dreg;
13818                                                 //mono_inst_set_src_registers (ins, sregs);
13819                                                 live_range_end [sreg] = use_ins;
13820                                                 live_range_end_bb [sreg] = bb;
13821
13822                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13823                                                         MonoInst *tmp;
13824
13825                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13826                                                         /* var->dreg is a hreg */
13827                                                         tmp->inst_c1 = sreg;
13828                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
13829                                                 }
13830
13831                                                 continue;
13832                                         }
13833
13834                                         g_assert (var->opcode == OP_REGOFFSET);
13835                                                 
13836                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
13837
13838                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
13839
13840                                         if (vreg_to_lvreg [sreg]) {
13841                                                 g_assert (vreg_to_lvreg [sreg] != -1);
13842
13843                                                 /* The variable is already loaded to an lvreg */
13844                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13845                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
13846                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
13847                                                 //mono_inst_set_src_registers (ins, sregs);
13848                                                 continue;
13849                                         }
13850
13851                                         /* Try to fuse the load into the instruction */
13852                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
13853                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
13854                                                 sregs [0] = var->inst_basereg;
13855                                                 //mono_inst_set_src_registers (ins, sregs);
13856                                                 ins->inst_offset = var->inst_offset;
13857                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
13858                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
13859                                                 sregs [1] = var->inst_basereg;
13860                                                 //mono_inst_set_src_registers (ins, sregs);
13861                                                 ins->inst_offset = var->inst_offset;
13862                                         } else {
13863                                                 if (MONO_IS_REAL_MOVE (ins)) {
13864                                                         ins->opcode = OP_NOP;
13865                                                         sreg = ins->dreg;
13866                                                 } else {
13867                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
13868
13869                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
13870
13871                                                         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) {
13872                                                                 if (var->dreg == prev_dreg) {
13873                                                                         /*
13874                                                                          * sreg refers to the value loaded by the load
13875                                                                          * emitted below, but we need to use ins->dreg
13876                                                                          * since it refers to the store emitted earlier.
13877                                                                          */
13878                                                                         sreg = ins->dreg;
13879                                                                 }
13880                                                                 g_assert (sreg != -1);
13881                                                                 vreg_to_lvreg [var->dreg] = sreg;
13882                                                                 if (lvregs_len >= lvregs_size) {
13883                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13884                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13885                                                                         lvregs = new_lvregs;
13886                                                                         lvregs_size *= 2;
13887                                                                 }
13888                                                                 lvregs [lvregs_len ++] = var->dreg;
13889                                                         }
13890                                                 }
13891
13892                                                 sregs [srcindex] = sreg;
13893                                                 //mono_inst_set_src_registers (ins, sregs);
13894
13895 #if SIZEOF_REGISTER != 8
13896                                                 if (regtype == 'l') {
13897                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
13898                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13899                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
13900                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13901                                                         use_ins = load_ins;
13902                                                 }
13903                                                 else
13904 #endif
13905                                                 {
13906 #if SIZEOF_REGISTER == 4
13907                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
13908 #endif
13909                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
13910                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13911                                                         use_ins = load_ins;
13912                                                 }
13913                                         }
13914
13915                                         if (var->dreg < orig_next_vreg) {
13916                                                 live_range_end [var->dreg] = use_ins;
13917                                                 live_range_end_bb [var->dreg] = bb;
13918                                         }
13919
13920                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13921                                                 MonoInst *tmp;
13922
13923                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13924                                                 tmp->inst_c1 = var->dreg;
13925                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
13926                                         }
13927                                 }
13928                         }
13929                         mono_inst_set_src_registers (ins, sregs);
13930
13931                         if (dest_has_lvreg) {
13932                                 g_assert (ins->dreg != -1);
13933                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
13934                                 if (lvregs_len >= lvregs_size) {
13935                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13936                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13937                                         lvregs = new_lvregs;
13938                                         lvregs_size *= 2;
13939                                 }
13940                                 lvregs [lvregs_len ++] = prev_dreg;
13941                                 dest_has_lvreg = FALSE;
13942                         }
13943
13944                         if (store) {
13945                                 tmp_reg = ins->dreg;
13946                                 ins->dreg = ins->sreg2;
13947                                 ins->sreg2 = tmp_reg;
13948                         }
13949
13950                         if (MONO_IS_CALL (ins)) {
13951                                 /* Clear vreg_to_lvreg array */
13952                                 for (i = 0; i < lvregs_len; i++)
13953                                         vreg_to_lvreg [lvregs [i]] = 0;
13954                                 lvregs_len = 0;
13955                         } else if (ins->opcode == OP_NOP) {
13956                                 ins->dreg = -1;
13957                                 MONO_INST_NULLIFY_SREGS (ins);
13958                         }
13959
13960                         if (cfg->verbose_level > 2)
13961                                 mono_print_ins_index (1, ins);
13962                 }
13963
13964                 /* Extend the live range based on the liveness info */
13965                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
13966                         for (i = 0; i < cfg->num_varinfo; i ++) {
13967                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
13968
13969                                 if (vreg_is_volatile (cfg, vi->vreg))
13970                                         /* The liveness info is incomplete */
13971                                         continue;
13972
13973                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
13974                                         /* Live from at least the first ins of this bb */
13975                                         live_range_start [vi->vreg] = bb->code;
13976                                         live_range_start_bb [vi->vreg] = bb;
13977                                 }
13978
13979                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
13980                                         /* Live at least until the last ins of this bb */
13981                                         live_range_end [vi->vreg] = bb->last_ins;
13982                                         live_range_end_bb [vi->vreg] = bb;
13983                                 }
13984                         }
13985                 }
13986         }
13987         
13988         /*
13989          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
13990          * by storing the current native offset into MonoMethodVar->live_range_start/end.
13991          */
13992         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
13993                 for (i = 0; i < cfg->num_varinfo; ++i) {
13994                         int vreg = MONO_VARINFO (cfg, i)->vreg;
13995                         MonoInst *ins;
13996
13997                         if (live_range_start [vreg]) {
13998                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
13999                                 ins->inst_c0 = i;
14000                                 ins->inst_c1 = vreg;
14001                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14002                         }
14003                         if (live_range_end [vreg]) {
14004                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14005                                 ins->inst_c0 = i;
14006                                 ins->inst_c1 = vreg;
14007                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14008                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14009                                 else
14010                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14011                         }
14012                 }
14013         }
14014
14015         if (cfg->gsharedvt_locals_var_ins) {
14016                 /* Nullify if unused */
14017                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14018                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14019         }
14020
14021         g_free (live_range_start);
14022         g_free (live_range_end);
14023         g_free (live_range_start_bb);
14024         g_free (live_range_end_bb);
14025 }
14026
14027
14028 /**
14029  * FIXME:
14030  * - use 'iadd' instead of 'int_add'
14031  * - handling ovf opcodes: decompose in method_to_ir.
14032  * - unify iregs/fregs
14033  *   -> partly done, the missing parts are:
14034  *   - a more complete unification would involve unifying the hregs as well, so
14035  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14036  *     would no longer map to the machine hregs, so the code generators would need to
14037  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14038  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14039  *     fp/non-fp branches speeds it up by about 15%.
14040  * - use sext/zext opcodes instead of shifts
14041  * - add OP_ICALL
14042  * - get rid of TEMPLOADs if possible and use vregs instead
14043  * - clean up usage of OP_P/OP_ opcodes
14044  * - cleanup usage of DUMMY_USE
14045  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14046  *   stack
14047  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14048  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14049  * - make sure handle_stack_args () is called before the branch is emitted
14050  * - when the new IR is done, get rid of all unused stuff
14051  * - COMPARE/BEQ as separate instructions or unify them ?
14052  *   - keeping them separate allows specialized compare instructions like
14053  *     compare_imm, compare_membase
14054  *   - most back ends unify fp compare+branch, fp compare+ceq
14055  * - integrate mono_save_args into inline_method
14056  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14057  * - handle long shift opts on 32 bit platforms somehow: they require 
14058  *   3 sregs (2 for arg1 and 1 for arg2)
14059  * - make byref a 'normal' type.
14060  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14061  *   variable if needed.
14062  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14063  *   like inline_method.
14064  * - remove inlining restrictions
14065  * - fix LNEG and enable cfold of INEG
14066  * - generalize x86 optimizations like ldelema as a peephole optimization
14067  * - add store_mem_imm for amd64
14068  * - optimize the loading of the interruption flag in the managed->native wrappers
14069  * - avoid special handling of OP_NOP in passes
14070  * - move code inserting instructions into one function/macro.
14071  * - try a coalescing phase after liveness analysis
14072  * - add float -> vreg conversion + local optimizations on !x86
14073  * - figure out how to handle decomposed branches during optimizations, ie.
14074  *   compare+branch, op_jump_table+op_br etc.
14075  * - promote RuntimeXHandles to vregs
14076  * - vtype cleanups:
14077  *   - add a NEW_VARLOADA_VREG macro
14078  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14079  *   accessing vtype fields.
14080  * - get rid of I8CONST on 64 bit platforms
14081  * - dealing with the increase in code size due to branches created during opcode
14082  *   decomposition:
14083  *   - use extended basic blocks
14084  *     - all parts of the JIT
14085  *     - handle_global_vregs () && local regalloc
14086  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14087  * - sources of increase in code size:
14088  *   - vtypes
14089  *   - long compares
14090  *   - isinst and castclass
14091  *   - lvregs not allocated to global registers even if used multiple times
14092  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14093  *   meaningful.
14094  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14095  * - add all micro optimizations from the old JIT
14096  * - put tree optimizations into the deadce pass
14097  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14098  *   specific function.
14099  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14100  *   fcompare + branchCC.
14101  * - create a helper function for allocating a stack slot, taking into account 
14102  *   MONO_CFG_HAS_SPILLUP.
14103  * - merge r68207.
14104  * - optimize mono_regstate2_alloc_int/float.
14105  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14106  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14107  *   parts of the tree could be separated by other instructions, killing the tree
14108  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14109  *   instructions if the result of the load is used multiple times ?
14110  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14111  * - LAST MERGE: 108395.
14112  * - when returning vtypes in registers, generate IR and append it to the end of the
14113  *   last bb instead of doing it in the epilog.
14114  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14115  */
14116
14117 /*
14118
14119 NOTES
14120 -----
14121
14122 - When to decompose opcodes:
14123   - earlier: this makes some optimizations hard to implement, since the low level IR
14124   no longer contains the neccessary information. But it is easier to do.
14125   - later: harder to implement, enables more optimizations.
14126 - Branches inside bblocks:
14127   - created when decomposing complex opcodes. 
14128     - branches to another bblock: harmless, but not tracked by the branch 
14129       optimizations, so need to branch to a label at the start of the bblock.
14130     - branches to inside the same bblock: very problematic, trips up the local
14131       reg allocator. Can be fixed by spitting the current bblock, but that is a
14132       complex operation, since some local vregs can become global vregs etc.
14133 - Local/global vregs:
14134   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14135     local register allocator.
14136   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14137     structure, created by mono_create_var (). Assigned to hregs or the stack by
14138     the global register allocator.
14139 - When to do optimizations like alu->alu_imm:
14140   - earlier -> saves work later on since the IR will be smaller/simpler
14141   - later -> can work on more instructions
14142 - Handling of valuetypes:
14143   - When a vtype is pushed on the stack, a new temporary is created, an 
14144     instruction computing its address (LDADDR) is emitted and pushed on
14145     the stack. Need to optimize cases when the vtype is used immediately as in
14146     argument passing, stloc etc.
14147 - Instead of the to_end stuff in the old JIT, simply call the function handling
14148   the values on the stack before emitting the last instruction of the bb.
14149 */
14150
14151 #endif /* !DISABLE_JIT */