Merge pull request #3040 from xmcclure/debugger-step-recursive
[mono.git] / mono / mini / method-to-ir.c
1 /*
2  * method-to-ir.c: Convert CIL to the JIT internal representation
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #include <config.h>
15
16 #ifndef DISABLE_JIT
17
18 #include <signal.h>
19
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include <math.h>
25 #include <string.h>
26 #include <ctype.h>
27
28 #ifdef HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #endif
31
32 #ifdef HAVE_ALLOCA_H
33 #include <alloca.h>
34 #endif
35
36 #include <mono/utils/memcheck.h>
37 #include "mini.h"
38 #include <mono/metadata/abi-details.h>
39 #include <mono/metadata/assembly.h>
40 #include <mono/metadata/attrdefs.h>
41 #include <mono/metadata/loader.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/exception.h>
46 #include <mono/metadata/opcodes.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/tokentype.h>
49 #include <mono/metadata/tabledefs.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/mono-debug.h>
53 #include <mono/metadata/mono-debug-debugger.h>
54 #include <mono/metadata/gc-internals.h>
55 #include <mono/metadata/security-manager.h>
56 #include <mono/metadata/threads-types.h>
57 #include <mono/metadata/security-core-clr.h>
58 #include <mono/metadata/profiler-private.h>
59 #include <mono/metadata/profiler.h>
60 #include <mono/metadata/monitor.h>
61 #include <mono/metadata/debug-mono-symfile.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-memory-model.h>
64 #include <mono/utils/mono-error-internals.h>
65 #include <mono/metadata/mono-basic-block.h>
66 #include <mono/metadata/reflection-internals.h>
67 #include <mono/utils/mono-threads-coop.h>
68
69 #include "trace.h"
70
71 #include "ir-emit.h"
72
73 #include "jit-icalls.h"
74 #include "jit.h"
75 #include "debugger-agent.h"
76 #include "seq-points.h"
77 #include "aot-compiler.h"
78 #include "mini-llvm.h"
79
80 #define BRANCH_COST 10
81 #define INLINE_LENGTH_LIMIT 20
82
83 /* These have 'cfg' as an implicit argument */
84 #define INLINE_FAILURE(msg) do {                                                                        \
85         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
86                 inline_failure (cfg, msg);                                                                              \
87                 goto exception_exit;                                                                                    \
88         } \
89         } while (0)
90 #define CHECK_CFG_EXCEPTION do {\
91                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
92                         goto exception_exit;                                            \
93         } while (0)
94 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
95                 field_access_failure ((cfg), (method), (field));                        \
96                 goto exception_exit;    \
97         } while (0)
98 #define GENERIC_SHARING_FAILURE(opcode) do {            \
99                 if (cfg->gshared) {                                                                     \
100                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
101                         goto exception_exit;    \
102                 }                       \
103         } while (0)
104 #define GSHAREDVT_FAILURE(opcode) do {          \
105         if (cfg->gsharedvt) {                                                                                           \
106                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
107                 goto exception_exit;                                                                                    \
108         }                                                                                                                                       \
109         } while (0)
110 #define OUT_OF_MEMORY_FAILURE do {      \
111                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
112                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
113                 goto exception_exit;    \
114         } while (0)
115 #define DISABLE_AOT(cfg) do { \
116                 if ((cfg)->verbose_level >= 2)                                            \
117                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
118                 (cfg)->disable_aot = TRUE;                                                        \
119         } while (0)
120 #define LOAD_ERROR do { \
121                 break_on_unverified ();                                                         \
122                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
123                 goto exception_exit;                                                                    \
124         } while (0)
125
126 #define TYPE_LOAD_ERROR(klass) do { \
127                 cfg->exception_ptr = klass; \
128                 LOAD_ERROR;                                     \
129         } while (0)
130
131 #define CHECK_CFG_ERROR do {\
132                 if (!mono_error_ok (&cfg->error)) { \
133                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
134                         goto mono_error_exit; \
135                 } \
136         } while (0)
137
138 /* Determine whenever 'ins' represents a load of the 'this' argument */
139 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
140
141 static int ldind_to_load_membase (int opcode);
142 static int stind_to_store_membase (int opcode);
143
144 int mono_op_to_op_imm (int opcode);
145 int mono_op_to_op_imm_noemul (int opcode);
146
147 MONO_API MonoInst* mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig, MonoInst **args);
148
149 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
150                                                   guchar *ip, guint real_offset, gboolean inline_always);
151 static MonoInst*
152 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
153
154 /* helper methods signatures */
155 static MonoMethodSignature *helper_sig_domain_get;
156 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
157 static MonoMethodSignature *helper_sig_llvmonly_imt_thunk;
158
159
160 /* type loading helpers */
161 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, System.Runtime.CompilerServices, RuntimeHelpers)
162 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, System.Diagnostics, DebuggableAttribute)
163
164 /*
165  * Instruction metadata
166  */
167 #ifdef MINI_OP
168 #undef MINI_OP
169 #endif
170 #ifdef MINI_OP3
171 #undef MINI_OP3
172 #endif
173 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
174 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
175 #define NONE ' '
176 #define IREG 'i'
177 #define FREG 'f'
178 #define VREG 'v'
179 #define XREG 'x'
180 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
181 #define LREG IREG
182 #else
183 #define LREG 'l'
184 #endif
185 /* keep in sync with the enum in mini.h */
186 const char
187 ins_info[] = {
188 #include "mini-ops.h"
189 };
190 #undef MINI_OP
191 #undef MINI_OP3
192
193 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
194 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
195 /* 
196  * This should contain the index of the last sreg + 1. This is not the same
197  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
198  */
199 const gint8 ins_sreg_counts[] = {
200 #include "mini-ops.h"
201 };
202 #undef MINI_OP
203 #undef MINI_OP3
204
205 #define MONO_INIT_VARINFO(vi,id) do { \
206         (vi)->range.first_use.pos.bid = 0xffff; \
207         (vi)->reg = -1; \
208         (vi)->idx = (id); \
209 } while (0)
210
211 guint32
212 mono_alloc_ireg (MonoCompile *cfg)
213 {
214         return alloc_ireg (cfg);
215 }
216
217 guint32
218 mono_alloc_lreg (MonoCompile *cfg)
219 {
220         return alloc_lreg (cfg);
221 }
222
223 guint32
224 mono_alloc_freg (MonoCompile *cfg)
225 {
226         return alloc_freg (cfg);
227 }
228
229 guint32
230 mono_alloc_preg (MonoCompile *cfg)
231 {
232         return alloc_preg (cfg);
233 }
234
235 guint32
236 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
237 {
238         return alloc_dreg (cfg, stack_type);
239 }
240
241 /*
242  * mono_alloc_ireg_ref:
243  *
244  *   Allocate an IREG, and mark it as holding a GC ref.
245  */
246 guint32
247 mono_alloc_ireg_ref (MonoCompile *cfg)
248 {
249         return alloc_ireg_ref (cfg);
250 }
251
252 /*
253  * mono_alloc_ireg_mp:
254  *
255  *   Allocate an IREG, and mark it as holding a managed pointer.
256  */
257 guint32
258 mono_alloc_ireg_mp (MonoCompile *cfg)
259 {
260         return alloc_ireg_mp (cfg);
261 }
262
263 /*
264  * mono_alloc_ireg_copy:
265  *
266  *   Allocate an IREG with the same GC type as VREG.
267  */
268 guint32
269 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
270 {
271         if (vreg_is_ref (cfg, vreg))
272                 return alloc_ireg_ref (cfg);
273         else if (vreg_is_mp (cfg, vreg))
274                 return alloc_ireg_mp (cfg);
275         else
276                 return alloc_ireg (cfg);
277 }
278
279 guint
280 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
281 {
282         if (type->byref)
283                 return OP_MOVE;
284
285         type = mini_get_underlying_type (type);
286 handle_enum:
287         switch (type->type) {
288         case MONO_TYPE_I1:
289         case MONO_TYPE_U1:
290                 return OP_MOVE;
291         case MONO_TYPE_I2:
292         case MONO_TYPE_U2:
293                 return OP_MOVE;
294         case MONO_TYPE_I4:
295         case MONO_TYPE_U4:
296                 return OP_MOVE;
297         case MONO_TYPE_I:
298         case MONO_TYPE_U:
299         case MONO_TYPE_PTR:
300         case MONO_TYPE_FNPTR:
301                 return OP_MOVE;
302         case MONO_TYPE_CLASS:
303         case MONO_TYPE_STRING:
304         case MONO_TYPE_OBJECT:
305         case MONO_TYPE_SZARRAY:
306         case MONO_TYPE_ARRAY:    
307                 return OP_MOVE;
308         case MONO_TYPE_I8:
309         case MONO_TYPE_U8:
310 #if SIZEOF_REGISTER == 8
311                 return OP_MOVE;
312 #else
313                 return OP_LMOVE;
314 #endif
315         case MONO_TYPE_R4:
316                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
317         case MONO_TYPE_R8:
318                 return OP_FMOVE;
319         case MONO_TYPE_VALUETYPE:
320                 if (type->data.klass->enumtype) {
321                         type = mono_class_enum_basetype (type->data.klass);
322                         goto handle_enum;
323                 }
324                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
325                         return OP_XMOVE;
326                 return OP_VMOVE;
327         case MONO_TYPE_TYPEDBYREF:
328                 return OP_VMOVE;
329         case MONO_TYPE_GENERICINST:
330                 type = &type->data.generic_class->container_class->byval_arg;
331                 goto handle_enum;
332         case MONO_TYPE_VAR:
333         case MONO_TYPE_MVAR:
334                 g_assert (cfg->gshared);
335                 if (mini_type_var_is_vt (type))
336                         return OP_VMOVE;
337                 else
338                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
339         default:
340                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
341         }
342         return -1;
343 }
344
345 void
346 mono_print_bb (MonoBasicBlock *bb, const char *msg)
347 {
348         int i;
349         MonoInst *tree;
350
351         printf ("\n%s %d: [IN: ", msg, bb->block_num);
352         for (i = 0; i < bb->in_count; ++i)
353                 printf (" BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
354         printf (", OUT: ");
355         for (i = 0; i < bb->out_count; ++i)
356                 printf (" BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
357         printf (" ]\n");
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_thunk = mono_create_icall_signature ("ptr ptr ptr");
368 }
369
370 static MONO_NEVER_INLINE void
371 break_on_unverified (void)
372 {
373         if (mini_get_debug_options ()->break_on_unverified)
374                 G_BREAKPOINT ();
375 }
376
377 static MONO_NEVER_INLINE void
378 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
379 {
380         char *method_fname = mono_method_full_name (method, TRUE);
381         char *field_fname = mono_field_full_name (field);
382         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
383         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
384         g_free (method_fname);
385         g_free (field_fname);
386 }
387
388 static MONO_NEVER_INLINE void
389 inline_failure (MonoCompile *cfg, const char *msg)
390 {
391         if (cfg->verbose_level >= 2)
392                 printf ("inline failed: %s\n", msg);
393         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
394 }
395
396 static MONO_NEVER_INLINE void
397 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
398 {
399         if (cfg->verbose_level > 2)                                                                                     \
400                 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);
401         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
402 }
403
404 static MONO_NEVER_INLINE void
405 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
406 {
407         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);
408         if (cfg->verbose_level >= 2)
409                 printf ("%s\n", cfg->exception_message);
410         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
411 }
412
413 /*
414  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
415  * foo<T> (int i) { ldarg.0; box T; }
416  */
417 #define UNVERIFIED do { \
418         if (cfg->gsharedvt) { \
419                 if (cfg->verbose_level > 2)                                                                     \
420                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
421                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
422                 goto exception_exit;                                                                                    \
423         }                                                                                                                                       \
424         break_on_unverified ();                                                                                         \
425         goto unverified;                                                                                                        \
426 } while (0)
427
428 #define GET_BBLOCK(cfg,tblock,ip) do {  \
429                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
430                 if (!(tblock)) {        \
431                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
432             NEW_BBLOCK (cfg, (tblock)); \
433                         (tblock)->cil_code = (ip);      \
434                         ADD_BBLOCK (cfg, (tblock));     \
435                 } \
436         } while (0)
437
438 #if defined(TARGET_X86) || defined(TARGET_AMD64)
439 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
440                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
441                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
442                 (dest)->sreg1 = (sr1); \
443                 (dest)->sreg2 = (sr2); \
444                 (dest)->inst_imm = (imm); \
445                 (dest)->backend.shift_amount = (shift); \
446                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
447         } while (0)
448 #endif
449
450 /* Emit conversions so both operands of a binary opcode are of the same type */
451 static void
452 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
453 {
454         MonoInst *arg1 = *arg1_ref;
455         MonoInst *arg2 = *arg2_ref;
456
457         if (cfg->r4fp &&
458                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
459                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
460                 MonoInst *conv;
461
462                 /* Mixing r4/r8 is allowed by the spec */
463                 if (arg1->type == STACK_R4) {
464                         int dreg = alloc_freg (cfg);
465
466                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
467                         conv->type = STACK_R8;
468                         ins->sreg1 = dreg;
469                         *arg1_ref = conv;
470                 }
471                 if (arg2->type == STACK_R4) {
472                         int dreg = alloc_freg (cfg);
473
474                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
475                         conv->type = STACK_R8;
476                         ins->sreg2 = dreg;
477                         *arg2_ref = conv;
478                 }
479         }
480
481 #if SIZEOF_REGISTER == 8
482         /* FIXME: Need to add many more cases */
483         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
484                 MonoInst *widen;
485
486                 int dr = alloc_preg (cfg);
487                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
488                 (ins)->sreg2 = widen->dreg;
489         }
490 #endif
491 }
492
493 #define ADD_BINOP(op) do {      \
494                 MONO_INST_NEW (cfg, ins, (op)); \
495                 sp -= 2;        \
496                 ins->sreg1 = sp [0]->dreg;      \
497                 ins->sreg2 = sp [1]->dreg;      \
498                 type_from_op (cfg, ins, sp [0], sp [1]);        \
499                 CHECK_TYPE (ins);       \
500                 /* Have to insert a widening op */               \
501         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
502         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
503         MONO_ADD_INS ((cfg)->cbb, (ins)); \
504         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
505         } while (0)
506
507 #define ADD_UNOP(op) do {       \
508                 MONO_INST_NEW (cfg, ins, (op)); \
509                 sp--;   \
510                 ins->sreg1 = sp [0]->dreg;      \
511                 type_from_op (cfg, ins, sp [0], NULL);  \
512                 CHECK_TYPE (ins);       \
513         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
514         MONO_ADD_INS ((cfg)->cbb, (ins)); \
515                 *sp++ = mono_decompose_opcode (cfg, ins);       \
516         } while (0)
517
518 #define ADD_BINCOND(next_block) do {    \
519                 MonoInst *cmp;  \
520                 sp -= 2; \
521                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
522                 cmp->sreg1 = sp [0]->dreg;      \
523                 cmp->sreg2 = sp [1]->dreg;      \
524                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
525                 CHECK_TYPE (cmp);       \
526                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
527                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
528                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
529                 GET_BBLOCK (cfg, tblock, target);               \
530                 link_bblock (cfg, cfg->cbb, tblock);    \
531                 ins->inst_true_bb = tblock;     \
532                 if ((next_block)) {     \
533                         link_bblock (cfg, cfg->cbb, (next_block));      \
534                         ins->inst_false_bb = (next_block);      \
535                         start_new_bblock = 1;   \
536                 } else {        \
537                         GET_BBLOCK (cfg, tblock, ip);           \
538                         link_bblock (cfg, cfg->cbb, tblock);    \
539                         ins->inst_false_bb = tblock;    \
540                         start_new_bblock = 2;   \
541                 }       \
542                 if (sp != stack_start) {                                                                        \
543                     handle_stack_args (cfg, stack_start, sp - stack_start); \
544                         CHECK_UNVERIFIABLE (cfg); \
545                 } \
546         MONO_ADD_INS (cfg->cbb, cmp); \
547                 MONO_ADD_INS (cfg->cbb, ins);   \
548         } while (0)
549
550 /* *
551  * link_bblock: Links two basic blocks
552  *
553  * links two basic blocks in the control flow graph, the 'from'
554  * argument is the starting block and the 'to' argument is the block
555  * the control flow ends to after 'from'.
556  */
557 static void
558 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
559 {
560         MonoBasicBlock **newa;
561         int i, found;
562
563 #if 0
564         if (from->cil_code) {
565                 if (to->cil_code)
566                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
567                 else
568                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
569         } else {
570                 if (to->cil_code)
571                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
572                 else
573                         printf ("edge from entry to exit\n");
574         }
575 #endif
576
577         found = FALSE;
578         for (i = 0; i < from->out_count; ++i) {
579                 if (to == from->out_bb [i]) {
580                         found = TRUE;
581                         break;
582                 }
583         }
584         if (!found) {
585                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
586                 for (i = 0; i < from->out_count; ++i) {
587                         newa [i] = from->out_bb [i];
588                 }
589                 newa [i] = to;
590                 from->out_count++;
591                 from->out_bb = newa;
592         }
593
594         found = FALSE;
595         for (i = 0; i < to->in_count; ++i) {
596                 if (from == to->in_bb [i]) {
597                         found = TRUE;
598                         break;
599                 }
600         }
601         if (!found) {
602                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
603                 for (i = 0; i < to->in_count; ++i) {
604                         newa [i] = to->in_bb [i];
605                 }
606                 newa [i] = from;
607                 to->in_count++;
608                 to->in_bb = newa;
609         }
610 }
611
612 void
613 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
614 {
615         link_bblock (cfg, from, to);
616 }
617
618 /**
619  * mono_find_block_region:
620  *
621  *   We mark each basic block with a region ID. We use that to avoid BB
622  *   optimizations when blocks are in different regions.
623  *
624  * Returns:
625  *   A region token that encodes where this region is, and information
626  *   about the clause owner for this block.
627  *
628  *   The region encodes the try/catch/filter clause that owns this block
629  *   as well as the type.  -1 is a special value that represents a block
630  *   that is in none of try/catch/filter.
631  */
632 static int
633 mono_find_block_region (MonoCompile *cfg, int offset)
634 {
635         MonoMethodHeader *header = cfg->header;
636         MonoExceptionClause *clause;
637         int i;
638
639         for (i = 0; i < header->num_clauses; ++i) {
640                 clause = &header->clauses [i];
641                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
642                     (offset < (clause->handler_offset)))
643                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
644                            
645                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
646                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
647                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
648                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
649                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
650                         else
651                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
652                 }
653         }
654         for (i = 0; i < header->num_clauses; ++i) {
655                 clause = &header->clauses [i];
656
657                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
658                         return ((i + 1) << 8) | clause->flags;
659         }
660
661         return -1;
662 }
663
664 static GList*
665 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
666 {
667         MonoMethodHeader *header = cfg->header;
668         MonoExceptionClause *clause;
669         int i;
670         GList *res = NULL;
671
672         for (i = 0; i < header->num_clauses; ++i) {
673                 clause = &header->clauses [i];
674                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
675                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
676                         if (clause->flags == type)
677                                 res = g_list_append (res, clause);
678                 }
679         }
680         return res;
681 }
682
683 static void
684 mono_create_spvar_for_region (MonoCompile *cfg, int region)
685 {
686         MonoInst *var;
687
688         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
689         if (var)
690                 return;
691
692         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
693         /* prevent it from being register allocated */
694         var->flags |= MONO_INST_VOLATILE;
695
696         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
697 }
698
699 MonoInst *
700 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
701 {
702         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
703 }
704
705 static MonoInst*
706 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
707 {
708         MonoInst *var;
709
710         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
711         if (var)
712                 return var;
713
714         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
715         /* prevent it from being register allocated */
716         var->flags |= MONO_INST_VOLATILE;
717
718         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
719
720         return var;
721 }
722
723 /*
724  * Returns the type used in the eval stack when @type is loaded.
725  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
726  */
727 void
728 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
729 {
730         MonoClass *klass;
731
732         type = mini_get_underlying_type (type);
733         inst->klass = klass = mono_class_from_mono_type (type);
734         if (type->byref) {
735                 inst->type = STACK_MP;
736                 return;
737         }
738
739 handle_enum:
740         switch (type->type) {
741         case MONO_TYPE_VOID:
742                 inst->type = STACK_INV;
743                 return;
744         case MONO_TYPE_I1:
745         case MONO_TYPE_U1:
746         case MONO_TYPE_I2:
747         case MONO_TYPE_U2:
748         case MONO_TYPE_I4:
749         case MONO_TYPE_U4:
750                 inst->type = STACK_I4;
751                 return;
752         case MONO_TYPE_I:
753         case MONO_TYPE_U:
754         case MONO_TYPE_PTR:
755         case MONO_TYPE_FNPTR:
756                 inst->type = STACK_PTR;
757                 return;
758         case MONO_TYPE_CLASS:
759         case MONO_TYPE_STRING:
760         case MONO_TYPE_OBJECT:
761         case MONO_TYPE_SZARRAY:
762         case MONO_TYPE_ARRAY:    
763                 inst->type = STACK_OBJ;
764                 return;
765         case MONO_TYPE_I8:
766         case MONO_TYPE_U8:
767                 inst->type = STACK_I8;
768                 return;
769         case MONO_TYPE_R4:
770                 inst->type = cfg->r4_stack_type;
771                 break;
772         case MONO_TYPE_R8:
773                 inst->type = STACK_R8;
774                 return;
775         case MONO_TYPE_VALUETYPE:
776                 if (type->data.klass->enumtype) {
777                         type = mono_class_enum_basetype (type->data.klass);
778                         goto handle_enum;
779                 } else {
780                         inst->klass = klass;
781                         inst->type = STACK_VTYPE;
782                         return;
783                 }
784         case MONO_TYPE_TYPEDBYREF:
785                 inst->klass = mono_defaults.typed_reference_class;
786                 inst->type = STACK_VTYPE;
787                 return;
788         case MONO_TYPE_GENERICINST:
789                 type = &type->data.generic_class->container_class->byval_arg;
790                 goto handle_enum;
791         case MONO_TYPE_VAR:
792         case MONO_TYPE_MVAR:
793                 g_assert (cfg->gshared);
794                 if (mini_is_gsharedvt_type (type)) {
795                         g_assert (cfg->gsharedvt);
796                         inst->type = STACK_VTYPE;
797                 } else {
798                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
799                 }
800                 return;
801         default:
802                 g_error ("unknown type 0x%02x in eval stack type", type->type);
803         }
804 }
805
806 /*
807  * The following tables are used to quickly validate the IL code in type_from_op ().
808  */
809 static const char
810 bin_num_table [STACK_MAX] [STACK_MAX] = {
811         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
812         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
813         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
814         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
815         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
816         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
817         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
818         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
819         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
820 };
821
822 static const char 
823 neg_table [] = {
824         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
825 };
826
827 /* reduce the size of this table */
828 static const char
829 bin_int_table [STACK_MAX] [STACK_MAX] = {
830         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
831         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
832         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
834         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
835         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
836         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
837         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
838 };
839
840 static const char
841 bin_comp_table [STACK_MAX] [STACK_MAX] = {
842 /*      Inv i  L  p  F  &  O  vt r4 */
843         {0},
844         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
845         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
846         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
847         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
848         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
849         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
850         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
851         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
852 };
853
854 /* reduce the size of this table */
855 static const char
856 shift_table [STACK_MAX] [STACK_MAX] = {
857         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
859         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
860         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
861         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
862         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
863         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
864         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
865 };
866
867 /*
868  * Tables to map from the non-specific opcode to the matching
869  * type-specific opcode.
870  */
871 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
872 static const guint16
873 binops_op_map [STACK_MAX] = {
874         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
875 };
876
877 /* handles from CEE_NEG to CEE_CONV_U8 */
878 static const guint16
879 unops_op_map [STACK_MAX] = {
880         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
881 };
882
883 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
884 static const guint16
885 ovfops_op_map [STACK_MAX] = {
886         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
887 };
888
889 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
890 static const guint16
891 ovf2ops_op_map [STACK_MAX] = {
892         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
893 };
894
895 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
896 static const guint16
897 ovf3ops_op_map [STACK_MAX] = {
898         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
899 };
900
901 /* handles from CEE_BEQ to CEE_BLT_UN */
902 static const guint16
903 beqops_op_map [STACK_MAX] = {
904         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
905 };
906
907 /* handles from CEE_CEQ to CEE_CLT_UN */
908 static const guint16
909 ceqops_op_map [STACK_MAX] = {
910         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
911 };
912
913 /*
914  * Sets ins->type (the type on the eval stack) according to the
915  * type of the opcode and the arguments to it.
916  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
917  *
918  * FIXME: this function sets ins->type unconditionally in some cases, but
919  * it should set it to invalid for some types (a conv.x on an object)
920  */
921 static void
922 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
923 {
924         switch (ins->opcode) {
925         /* binops */
926         case CEE_ADD:
927         case CEE_SUB:
928         case CEE_MUL:
929         case CEE_DIV:
930         case CEE_REM:
931                 /* FIXME: check unverifiable args for STACK_MP */
932                 ins->type = bin_num_table [src1->type] [src2->type];
933                 ins->opcode += binops_op_map [ins->type];
934                 break;
935         case CEE_DIV_UN:
936         case CEE_REM_UN:
937         case CEE_AND:
938         case CEE_OR:
939         case CEE_XOR:
940                 ins->type = bin_int_table [src1->type] [src2->type];
941                 ins->opcode += binops_op_map [ins->type];
942                 break;
943         case CEE_SHL:
944         case CEE_SHR:
945         case CEE_SHR_UN:
946                 ins->type = shift_table [src1->type] [src2->type];
947                 ins->opcode += binops_op_map [ins->type];
948                 break;
949         case OP_COMPARE:
950         case OP_LCOMPARE:
951         case OP_ICOMPARE:
952                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
953                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
954                         ins->opcode = OP_LCOMPARE;
955                 else if (src1->type == STACK_R4)
956                         ins->opcode = OP_RCOMPARE;
957                 else if (src1->type == STACK_R8)
958                         ins->opcode = OP_FCOMPARE;
959                 else
960                         ins->opcode = OP_ICOMPARE;
961                 break;
962         case OP_ICOMPARE_IMM:
963                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
964                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
965                         ins->opcode = OP_LCOMPARE_IMM;          
966                 break;
967         case CEE_BEQ:
968         case CEE_BGE:
969         case CEE_BGT:
970         case CEE_BLE:
971         case CEE_BLT:
972         case CEE_BNE_UN:
973         case CEE_BGE_UN:
974         case CEE_BGT_UN:
975         case CEE_BLE_UN:
976         case CEE_BLT_UN:
977                 ins->opcode += beqops_op_map [src1->type];
978                 break;
979         case OP_CEQ:
980                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
981                 ins->opcode += ceqops_op_map [src1->type];
982                 break;
983         case OP_CGT:
984         case OP_CGT_UN:
985         case OP_CLT:
986         case OP_CLT_UN:
987                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
988                 ins->opcode += ceqops_op_map [src1->type];
989                 break;
990         /* unops */
991         case CEE_NEG:
992                 ins->type = neg_table [src1->type];
993                 ins->opcode += unops_op_map [ins->type];
994                 break;
995         case CEE_NOT:
996                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
997                         ins->type = src1->type;
998                 else
999                         ins->type = STACK_INV;
1000                 ins->opcode += unops_op_map [ins->type];
1001                 break;
1002         case CEE_CONV_I1:
1003         case CEE_CONV_I2:
1004         case CEE_CONV_I4:
1005         case CEE_CONV_U4:
1006                 ins->type = STACK_I4;
1007                 ins->opcode += unops_op_map [src1->type];
1008                 break;
1009         case CEE_CONV_R_UN:
1010                 ins->type = STACK_R8;
1011                 switch (src1->type) {
1012                 case STACK_I4:
1013                 case STACK_PTR:
1014                         ins->opcode = OP_ICONV_TO_R_UN;
1015                         break;
1016                 case STACK_I8:
1017                         ins->opcode = OP_LCONV_TO_R_UN; 
1018                         break;
1019                 }
1020                 break;
1021         case CEE_CONV_OVF_I1:
1022         case CEE_CONV_OVF_U1:
1023         case CEE_CONV_OVF_I2:
1024         case CEE_CONV_OVF_U2:
1025         case CEE_CONV_OVF_I4:
1026         case CEE_CONV_OVF_U4:
1027                 ins->type = STACK_I4;
1028                 ins->opcode += ovf3ops_op_map [src1->type];
1029                 break;
1030         case CEE_CONV_OVF_I_UN:
1031         case CEE_CONV_OVF_U_UN:
1032                 ins->type = STACK_PTR;
1033                 ins->opcode += ovf2ops_op_map [src1->type];
1034                 break;
1035         case CEE_CONV_OVF_I1_UN:
1036         case CEE_CONV_OVF_I2_UN:
1037         case CEE_CONV_OVF_I4_UN:
1038         case CEE_CONV_OVF_U1_UN:
1039         case CEE_CONV_OVF_U2_UN:
1040         case CEE_CONV_OVF_U4_UN:
1041                 ins->type = STACK_I4;
1042                 ins->opcode += ovf2ops_op_map [src1->type];
1043                 break;
1044         case CEE_CONV_U:
1045                 ins->type = STACK_PTR;
1046                 switch (src1->type) {
1047                 case STACK_I4:
1048                         ins->opcode = OP_ICONV_TO_U;
1049                         break;
1050                 case STACK_PTR:
1051                 case STACK_MP:
1052 #if SIZEOF_VOID_P == 8
1053                         ins->opcode = OP_LCONV_TO_U;
1054 #else
1055                         ins->opcode = OP_MOVE;
1056 #endif
1057                         break;
1058                 case STACK_I8:
1059                         ins->opcode = OP_LCONV_TO_U;
1060                         break;
1061                 case STACK_R8:
1062                         ins->opcode = OP_FCONV_TO_U;
1063                         break;
1064                 }
1065                 break;
1066         case CEE_CONV_I8:
1067         case CEE_CONV_U8:
1068                 ins->type = STACK_I8;
1069                 ins->opcode += unops_op_map [src1->type];
1070                 break;
1071         case CEE_CONV_OVF_I8:
1072         case CEE_CONV_OVF_U8:
1073                 ins->type = STACK_I8;
1074                 ins->opcode += ovf3ops_op_map [src1->type];
1075                 break;
1076         case CEE_CONV_OVF_U8_UN:
1077         case CEE_CONV_OVF_I8_UN:
1078                 ins->type = STACK_I8;
1079                 ins->opcode += ovf2ops_op_map [src1->type];
1080                 break;
1081         case CEE_CONV_R4:
1082                 ins->type = cfg->r4_stack_type;
1083                 ins->opcode += unops_op_map [src1->type];
1084                 break;
1085         case CEE_CONV_R8:
1086                 ins->type = STACK_R8;
1087                 ins->opcode += unops_op_map [src1->type];
1088                 break;
1089         case OP_CKFINITE:
1090                 ins->type = STACK_R8;           
1091                 break;
1092         case CEE_CONV_U2:
1093         case CEE_CONV_U1:
1094                 ins->type = STACK_I4;
1095                 ins->opcode += ovfops_op_map [src1->type];
1096                 break;
1097         case CEE_CONV_I:
1098         case CEE_CONV_OVF_I:
1099         case CEE_CONV_OVF_U:
1100                 ins->type = STACK_PTR;
1101                 ins->opcode += ovfops_op_map [src1->type];
1102                 break;
1103         case CEE_ADD_OVF:
1104         case CEE_ADD_OVF_UN:
1105         case CEE_MUL_OVF:
1106         case CEE_MUL_OVF_UN:
1107         case CEE_SUB_OVF:
1108         case CEE_SUB_OVF_UN:
1109                 ins->type = bin_num_table [src1->type] [src2->type];
1110                 ins->opcode += ovfops_op_map [src1->type];
1111                 if (ins->type == STACK_R8)
1112                         ins->type = STACK_INV;
1113                 break;
1114         case OP_LOAD_MEMBASE:
1115                 ins->type = STACK_PTR;
1116                 break;
1117         case OP_LOADI1_MEMBASE:
1118         case OP_LOADU1_MEMBASE:
1119         case OP_LOADI2_MEMBASE:
1120         case OP_LOADU2_MEMBASE:
1121         case OP_LOADI4_MEMBASE:
1122         case OP_LOADU4_MEMBASE:
1123                 ins->type = STACK_PTR;
1124                 break;
1125         case OP_LOADI8_MEMBASE:
1126                 ins->type = STACK_I8;
1127                 break;
1128         case OP_LOADR4_MEMBASE:
1129                 ins->type = cfg->r4_stack_type;
1130                 break;
1131         case OP_LOADR8_MEMBASE:
1132                 ins->type = STACK_R8;
1133                 break;
1134         default:
1135                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1136                 break;
1137         }
1138
1139         if (ins->type == STACK_MP)
1140                 ins->klass = mono_defaults.object_class;
1141 }
1142
1143 static const char 
1144 ldind_type [] = {
1145         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1146 };
1147
1148 #if 0
1149
1150 static const char
1151 param_table [STACK_MAX] [STACK_MAX] = {
1152         {0},
1153 };
1154
1155 static int
1156 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1157 {
1158         int i;
1159
1160         if (sig->hasthis) {
1161                 switch (args->type) {
1162                 case STACK_I4:
1163                 case STACK_I8:
1164                 case STACK_R8:
1165                 case STACK_VTYPE:
1166                 case STACK_INV:
1167                         return 0;
1168                 }
1169                 args++;
1170         }
1171         for (i = 0; i < sig->param_count; ++i) {
1172                 switch (args [i].type) {
1173                 case STACK_INV:
1174                         return 0;
1175                 case STACK_MP:
1176                         if (!sig->params [i]->byref)
1177                                 return 0;
1178                         continue;
1179                 case STACK_OBJ:
1180                         if (sig->params [i]->byref)
1181                                 return 0;
1182                         switch (sig->params [i]->type) {
1183                         case MONO_TYPE_CLASS:
1184                         case MONO_TYPE_STRING:
1185                         case MONO_TYPE_OBJECT:
1186                         case MONO_TYPE_SZARRAY:
1187                         case MONO_TYPE_ARRAY:
1188                                 break;
1189                         default:
1190                                 return 0;
1191                         }
1192                         continue;
1193                 case STACK_R8:
1194                         if (sig->params [i]->byref)
1195                                 return 0;
1196                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1197                                 return 0;
1198                         continue;
1199                 case STACK_PTR:
1200                 case STACK_I4:
1201                 case STACK_I8:
1202                 case STACK_VTYPE:
1203                         break;
1204                 }
1205                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1206                         return 0;*/
1207         }
1208         return 1;
1209 }
1210 #endif
1211
1212 /*
1213  * When we need a pointer to the current domain many times in a method, we
1214  * call mono_domain_get() once and we store the result in a local variable.
1215  * This function returns the variable that represents the MonoDomain*.
1216  */
1217 inline static MonoInst *
1218 mono_get_domainvar (MonoCompile *cfg)
1219 {
1220         if (!cfg->domainvar)
1221                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1222         return cfg->domainvar;
1223 }
1224
1225 /*
1226  * The got_var contains the address of the Global Offset Table when AOT 
1227  * compiling.
1228  */
1229 MonoInst *
1230 mono_get_got_var (MonoCompile *cfg)
1231 {
1232         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1233                 return NULL;
1234         if (!cfg->got_var) {
1235                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1236         }
1237         return cfg->got_var;
1238 }
1239
1240 static MonoInst *
1241 mono_get_vtable_var (MonoCompile *cfg)
1242 {
1243         g_assert (cfg->gshared);
1244
1245         if (!cfg->rgctx_var) {
1246                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1247                 /* force the var to be stack allocated */
1248                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1249         }
1250
1251         return cfg->rgctx_var;
1252 }
1253
1254 static MonoType*
1255 type_from_stack_type (MonoInst *ins) {
1256         switch (ins->type) {
1257         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1258         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1259         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1260         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1261         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1262         case STACK_MP:
1263                 return &ins->klass->this_arg;
1264         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1265         case STACK_VTYPE: return &ins->klass->byval_arg;
1266         default:
1267                 g_error ("stack type %d to monotype not handled\n", ins->type);
1268         }
1269         return NULL;
1270 }
1271
1272 static G_GNUC_UNUSED int
1273 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1274 {
1275         t = mono_type_get_underlying_type (t);
1276         switch (t->type) {
1277         case MONO_TYPE_I1:
1278         case MONO_TYPE_U1:
1279         case MONO_TYPE_I2:
1280         case MONO_TYPE_U2:
1281         case MONO_TYPE_I4:
1282         case MONO_TYPE_U4:
1283                 return STACK_I4;
1284         case MONO_TYPE_I:
1285         case MONO_TYPE_U:
1286         case MONO_TYPE_PTR:
1287         case MONO_TYPE_FNPTR:
1288                 return STACK_PTR;
1289         case MONO_TYPE_CLASS:
1290         case MONO_TYPE_STRING:
1291         case MONO_TYPE_OBJECT:
1292         case MONO_TYPE_SZARRAY:
1293         case MONO_TYPE_ARRAY:    
1294                 return STACK_OBJ;
1295         case MONO_TYPE_I8:
1296         case MONO_TYPE_U8:
1297                 return STACK_I8;
1298         case MONO_TYPE_R4:
1299                 return cfg->r4_stack_type;
1300         case MONO_TYPE_R8:
1301                 return STACK_R8;
1302         case MONO_TYPE_VALUETYPE:
1303         case MONO_TYPE_TYPEDBYREF:
1304                 return STACK_VTYPE;
1305         case MONO_TYPE_GENERICINST:
1306                 if (mono_type_generic_inst_is_valuetype (t))
1307                         return STACK_VTYPE;
1308                 else
1309                         return STACK_OBJ;
1310                 break;
1311         default:
1312                 g_assert_not_reached ();
1313         }
1314
1315         return -1;
1316 }
1317
1318 static MonoClass*
1319 array_access_to_klass (int opcode)
1320 {
1321         switch (opcode) {
1322         case CEE_LDELEM_U1:
1323                 return mono_defaults.byte_class;
1324         case CEE_LDELEM_U2:
1325                 return mono_defaults.uint16_class;
1326         case CEE_LDELEM_I:
1327         case CEE_STELEM_I:
1328                 return mono_defaults.int_class;
1329         case CEE_LDELEM_I1:
1330         case CEE_STELEM_I1:
1331                 return mono_defaults.sbyte_class;
1332         case CEE_LDELEM_I2:
1333         case CEE_STELEM_I2:
1334                 return mono_defaults.int16_class;
1335         case CEE_LDELEM_I4:
1336         case CEE_STELEM_I4:
1337                 return mono_defaults.int32_class;
1338         case CEE_LDELEM_U4:
1339                 return mono_defaults.uint32_class;
1340         case CEE_LDELEM_I8:
1341         case CEE_STELEM_I8:
1342                 return mono_defaults.int64_class;
1343         case CEE_LDELEM_R4:
1344         case CEE_STELEM_R4:
1345                 return mono_defaults.single_class;
1346         case CEE_LDELEM_R8:
1347         case CEE_STELEM_R8:
1348                 return mono_defaults.double_class;
1349         case CEE_LDELEM_REF:
1350         case CEE_STELEM_REF:
1351                 return mono_defaults.object_class;
1352         default:
1353                 g_assert_not_reached ();
1354         }
1355         return NULL;
1356 }
1357
1358 /*
1359  * We try to share variables when possible
1360  */
1361 static MonoInst *
1362 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1363 {
1364         MonoInst *res;
1365         int pos, vnum;
1366
1367         /* inlining can result in deeper stacks */ 
1368         if (slot >= cfg->header->max_stack)
1369                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1370
1371         pos = ins->type - 1 + slot * STACK_MAX;
1372
1373         switch (ins->type) {
1374         case STACK_I4:
1375         case STACK_I8:
1376         case STACK_R8:
1377         case STACK_PTR:
1378         case STACK_MP:
1379         case STACK_OBJ:
1380                 if ((vnum = cfg->intvars [pos]))
1381                         return cfg->varinfo [vnum];
1382                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1383                 cfg->intvars [pos] = res->inst_c0;
1384                 break;
1385         default:
1386                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1387         }
1388         return res;
1389 }
1390
1391 static void
1392 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1393 {
1394         /* 
1395          * Don't use this if a generic_context is set, since that means AOT can't
1396          * look up the method using just the image+token.
1397          * table == 0 means this is a reference made from a wrapper.
1398          */
1399         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1400                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1401                 jump_info_token->image = image;
1402                 jump_info_token->token = token;
1403                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1404         }
1405 }
1406
1407 /*
1408  * This function is called to handle items that are left on the evaluation stack
1409  * at basic block boundaries. What happens is that we save the values to local variables
1410  * and we reload them later when first entering the target basic block (with the
1411  * handle_loaded_temps () function).
1412  * A single joint point will use the same variables (stored in the array bb->out_stack or
1413  * bb->in_stack, if the basic block is before or after the joint point).
1414  *
1415  * This function needs to be called _before_ emitting the last instruction of
1416  * the bb (i.e. before emitting a branch).
1417  * If the stack merge fails at a join point, cfg->unverifiable is set.
1418  */
1419 static void
1420 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1421 {
1422         int i, bindex;
1423         MonoBasicBlock *bb = cfg->cbb;
1424         MonoBasicBlock *outb;
1425         MonoInst *inst, **locals;
1426         gboolean found;
1427
1428         if (!count)
1429                 return;
1430         if (cfg->verbose_level > 3)
1431                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1432         if (!bb->out_scount) {
1433                 bb->out_scount = count;
1434                 //printf ("bblock %d has out:", bb->block_num);
1435                 found = FALSE;
1436                 for (i = 0; i < bb->out_count; ++i) {
1437                         outb = bb->out_bb [i];
1438                         /* exception handlers are linked, but they should not be considered for stack args */
1439                         if (outb->flags & BB_EXCEPTION_HANDLER)
1440                                 continue;
1441                         //printf (" %d", outb->block_num);
1442                         if (outb->in_stack) {
1443                                 found = TRUE;
1444                                 bb->out_stack = outb->in_stack;
1445                                 break;
1446                         }
1447                 }
1448                 //printf ("\n");
1449                 if (!found) {
1450                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1451                         for (i = 0; i < count; ++i) {
1452                                 /* 
1453                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1454                                  * stack slot and if they are of the same type.
1455                                  * This won't cause conflicts since if 'local' is used to 
1456                                  * store one of the values in the in_stack of a bblock, then
1457                                  * the same variable will be used for the same outgoing stack 
1458                                  * slot as well. 
1459                                  * This doesn't work when inlining methods, since the bblocks
1460                                  * in the inlined methods do not inherit their in_stack from
1461                                  * the bblock they are inlined to. See bug #58863 for an
1462                                  * example.
1463                                  */
1464                                 if (cfg->inlined_method)
1465                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1466                                 else
1467                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1468                         }
1469                 }
1470         }
1471
1472         for (i = 0; i < bb->out_count; ++i) {
1473                 outb = bb->out_bb [i];
1474                 /* exception handlers are linked, but they should not be considered for stack args */
1475                 if (outb->flags & BB_EXCEPTION_HANDLER)
1476                         continue;
1477                 if (outb->in_scount) {
1478                         if (outb->in_scount != bb->out_scount) {
1479                                 cfg->unverifiable = TRUE;
1480                                 return;
1481                         }
1482                         continue; /* check they are the same locals */
1483                 }
1484                 outb->in_scount = count;
1485                 outb->in_stack = bb->out_stack;
1486         }
1487
1488         locals = bb->out_stack;
1489         cfg->cbb = bb;
1490         for (i = 0; i < count; ++i) {
1491                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1492                 inst->cil_code = sp [i]->cil_code;
1493                 sp [i] = locals [i];
1494                 if (cfg->verbose_level > 3)
1495                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1496         }
1497
1498         /*
1499          * It is possible that the out bblocks already have in_stack assigned, and
1500          * the in_stacks differ. In this case, we will store to all the different 
1501          * in_stacks.
1502          */
1503
1504         found = TRUE;
1505         bindex = 0;
1506         while (found) {
1507                 /* Find a bblock which has a different in_stack */
1508                 found = FALSE;
1509                 while (bindex < bb->out_count) {
1510                         outb = bb->out_bb [bindex];
1511                         /* exception handlers are linked, but they should not be considered for stack args */
1512                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1513                                 bindex++;
1514                                 continue;
1515                         }
1516                         if (outb->in_stack != locals) {
1517                                 for (i = 0; i < count; ++i) {
1518                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1519                                         inst->cil_code = sp [i]->cil_code;
1520                                         sp [i] = locals [i];
1521                                         if (cfg->verbose_level > 3)
1522                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1523                                 }
1524                                 locals = outb->in_stack;
1525                                 found = TRUE;
1526                                 break;
1527                         }
1528                         bindex ++;
1529                 }
1530         }
1531 }
1532
1533 static MonoInst*
1534 emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1535 {
1536         MonoInst *ins;
1537
1538         if (cfg->compile_aot) {
1539                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1540         } else {
1541                 MonoJumpInfo ji;
1542                 gpointer target;
1543                 MonoError error;
1544
1545                 ji.type = patch_type;
1546                 ji.data.target = data;
1547                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1548                 mono_error_assert_ok (&error);
1549
1550                 EMIT_NEW_PCONST (cfg, ins, target);
1551         }
1552         return ins;
1553 }
1554
1555 static void
1556 mini_emit_interface_bitmap_check (MonoCompile *cfg, int intf_bit_reg, int base_reg, int offset, MonoClass *klass)
1557 {
1558         int ibitmap_reg = alloc_preg (cfg);
1559 #ifdef COMPRESSED_INTERFACE_BITMAP
1560         MonoInst *args [2];
1561         MonoInst *res, *ins;
1562         NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, ibitmap_reg, base_reg, offset);
1563         MONO_ADD_INS (cfg->cbb, ins);
1564         args [0] = ins;
1565         args [1] = emit_runtime_constant (cfg, MONO_PATCH_INFO_IID, klass);
1566         res = mono_emit_jit_icall (cfg, mono_class_interface_match, args);
1567         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, intf_bit_reg, res->dreg);
1568 #else
1569         int ibitmap_byte_reg = alloc_preg (cfg);
1570
1571         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, ibitmap_reg, base_reg, offset);
1572
1573         if (cfg->compile_aot) {
1574                 int iid_reg = alloc_preg (cfg);
1575                 int shifted_iid_reg = alloc_preg (cfg);
1576                 int ibitmap_byte_address_reg = alloc_preg (cfg);
1577                 int masked_iid_reg = alloc_preg (cfg);
1578                 int iid_one_bit_reg = alloc_preg (cfg);
1579                 int iid_bit_reg = alloc_preg (cfg);
1580                 MONO_EMIT_NEW_AOTCONST (cfg, iid_reg, klass, MONO_PATCH_INFO_IID);
1581                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, shifted_iid_reg, iid_reg, 3);
1582                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, ibitmap_byte_address_reg, ibitmap_reg, shifted_iid_reg);
1583                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, ibitmap_byte_reg, ibitmap_byte_address_reg, 0);
1584                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, masked_iid_reg, iid_reg, 7);
1585                 MONO_EMIT_NEW_ICONST (cfg, iid_one_bit_reg, 1);
1586                 MONO_EMIT_NEW_BIALU (cfg, OP_ISHL, iid_bit_reg, iid_one_bit_reg, masked_iid_reg);
1587                 MONO_EMIT_NEW_BIALU (cfg, OP_IAND, intf_bit_reg, ibitmap_byte_reg, iid_bit_reg);
1588         } else {
1589                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, ibitmap_byte_reg, ibitmap_reg, klass->interface_id >> 3);
1590                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_AND_IMM, intf_bit_reg, ibitmap_byte_reg, 1 << (klass->interface_id & 7));
1591         }
1592 #endif
1593 }
1594
1595 /* 
1596  * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoClass
1597  * stored in "klass_reg" implements the interface "klass".
1598  */
1599 static void
1600 mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass_reg, MonoClass *klass)
1601 {
1602         mini_emit_interface_bitmap_check (cfg, intf_bit_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, interface_bitmap), klass);
1603 }
1604
1605 /* 
1606  * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoVTable
1607  * stored in "vtable_reg" implements the interface "klass".
1608  */
1609 static void
1610 mini_emit_load_intf_bit_reg_vtable (MonoCompile *cfg, int intf_bit_reg, int vtable_reg, MonoClass *klass)
1611 {
1612         mini_emit_interface_bitmap_check (cfg, intf_bit_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap), klass);
1613 }
1614
1615 /* 
1616  * Emit code which checks whenever the interface id of @klass is smaller than
1617  * than the value given by max_iid_reg.
1618 */
1619 static void
1620 mini_emit_max_iid_check (MonoCompile *cfg, int max_iid_reg, MonoClass *klass,
1621                                                  MonoBasicBlock *false_target)
1622 {
1623         if (cfg->compile_aot) {
1624                 int iid_reg = alloc_preg (cfg);
1625                 MONO_EMIT_NEW_AOTCONST (cfg, iid_reg, klass, MONO_PATCH_INFO_IID);
1626                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, max_iid_reg, iid_reg);
1627         }
1628         else
1629                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, max_iid_reg, klass->interface_id);
1630         if (false_target)
1631                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBLT_UN, false_target);
1632         else
1633                 MONO_EMIT_NEW_COND_EXC (cfg, LT_UN, "InvalidCastException");
1634 }
1635
1636 /* Same as above, but obtains max_iid from a vtable */
1637 static void
1638 mini_emit_max_iid_check_vtable (MonoCompile *cfg, int vtable_reg, MonoClass *klass,
1639                                                                  MonoBasicBlock *false_target)
1640 {
1641         int max_iid_reg = alloc_preg (cfg);
1642                 
1643         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, max_iid_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
1644         mini_emit_max_iid_check (cfg, max_iid_reg, klass, false_target);
1645 }
1646
1647 /* Same as above, but obtains max_iid from a klass */
1648 static void
1649 mini_emit_max_iid_check_class (MonoCompile *cfg, int klass_reg, MonoClass *klass,
1650                                                                  MonoBasicBlock *false_target)
1651 {
1652         int max_iid_reg = alloc_preg (cfg);
1653
1654         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, max_iid_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, max_interface_id));
1655         mini_emit_max_iid_check (cfg, max_iid_reg, klass, false_target);
1656 }
1657
1658 static void
1659 mini_emit_isninst_cast_inst (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoInst *klass_ins, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1660 {
1661         int idepth_reg = alloc_preg (cfg);
1662         int stypes_reg = alloc_preg (cfg);
1663         int stype = alloc_preg (cfg);
1664
1665         mono_class_setup_supertypes (klass);
1666
1667         if (klass->idepth > MONO_DEFAULT_SUPERTABLE_SIZE) {
1668                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, idepth_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, idepth));
1669                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, idepth_reg, klass->idepth);
1670                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBLT_UN, false_target);
1671         }
1672         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stypes_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, supertypes));
1673         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stype, stypes_reg, ((klass->idepth - 1) * SIZEOF_VOID_P));
1674         if (klass_ins) {
1675                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, stype, klass_ins->dreg);
1676         } else if (cfg->compile_aot) {
1677                 int const_reg = alloc_preg (cfg);
1678                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
1679                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, stype, const_reg);
1680         } else {
1681                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, stype, klass);
1682         }
1683         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, true_target);
1684 }
1685
1686 static void
1687 mini_emit_isninst_cast (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1688 {
1689         mini_emit_isninst_cast_inst (cfg, klass_reg, klass, NULL, false_target, true_target);
1690 }
1691
1692 static void
1693 mini_emit_iface_cast (MonoCompile *cfg, int vtable_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1694 {
1695         int intf_reg = alloc_preg (cfg);
1696
1697         mini_emit_max_iid_check_vtable (cfg, vtable_reg, klass, false_target);
1698         mini_emit_load_intf_bit_reg_vtable (cfg, intf_reg, vtable_reg, klass);
1699         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, intf_reg, 0);
1700         if (true_target)
1701                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, true_target);
1702         else
1703                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");               
1704 }
1705
1706 /*
1707  * Variant of the above that takes a register to the class, not the vtable.
1708  */
1709 static void
1710 mini_emit_iface_class_cast (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1711 {
1712         int intf_bit_reg = alloc_preg (cfg);
1713
1714         mini_emit_max_iid_check_class (cfg, klass_reg, klass, false_target);
1715         mini_emit_load_intf_bit_reg_class (cfg, intf_bit_reg, klass_reg, klass);
1716         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, intf_bit_reg, 0);
1717         if (true_target)
1718                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, true_target);
1719         else
1720                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");
1721 }
1722
1723 static inline void
1724 mini_emit_class_check_inst (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoInst *klass_inst)
1725 {
1726         if (klass_inst) {
1727                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_inst->dreg);
1728         } else {
1729                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
1730                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, ins->dreg);
1731         }
1732         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1733 }
1734
1735 static inline void
1736 mini_emit_class_check (MonoCompile *cfg, int klass_reg, MonoClass *klass)
1737 {
1738         mini_emit_class_check_inst (cfg, klass_reg, klass, NULL);
1739 }
1740
1741 static inline void
1742 mini_emit_class_check_branch (MonoCompile *cfg, int klass_reg, MonoClass *klass, int branch_op, MonoBasicBlock *target)
1743 {
1744         if (cfg->compile_aot) {
1745                 int const_reg = alloc_preg (cfg);
1746                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
1747                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, const_reg);
1748         } else {
1749                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
1750         }
1751         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, branch_op, target);
1752 }
1753
1754 static void
1755 mini_emit_castclass (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoBasicBlock *object_is_null);
1756         
1757 static void
1758 mini_emit_castclass_inst (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoInst *klass_inst, MonoBasicBlock *object_is_null)
1759 {
1760         if (klass->rank) {
1761                 int rank_reg = alloc_preg (cfg);
1762                 int eclass_reg = alloc_preg (cfg);
1763
1764                 g_assert (!klass_inst);
1765                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, rank));
1766                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, klass->rank);
1767                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1768                 //              MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
1769                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, cast_class));
1770                 if (klass->cast_class == mono_defaults.object_class) {
1771                         int parent_reg = alloc_preg (cfg);
1772                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, parent_reg, eclass_reg, MONO_STRUCT_OFFSET (MonoClass, parent));
1773                         mini_emit_class_check_branch (cfg, parent_reg, mono_defaults.enum_class->parent, OP_PBNE_UN, object_is_null);
1774                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1775                 } else if (klass->cast_class == mono_defaults.enum_class->parent) {
1776                         mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class->parent, OP_PBEQ, object_is_null);
1777                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1778                 } else if (klass->cast_class == mono_defaults.enum_class) {
1779                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1780                 } else if (klass->cast_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
1781                         mini_emit_iface_class_cast (cfg, eclass_reg, klass->cast_class, NULL, NULL);
1782                 } else {
1783                         // Pass -1 as obj_reg to skip the check below for arrays of arrays
1784                         mini_emit_castclass (cfg, -1, eclass_reg, klass->cast_class, object_is_null);
1785                 }
1786
1787                 if ((klass->rank == 1) && (klass->byval_arg.type == MONO_TYPE_SZARRAY) && (obj_reg != -1)) {
1788                         /* Check that the object is a vector too */
1789                         int bounds_reg = alloc_preg (cfg);
1790                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, obj_reg, MONO_STRUCT_OFFSET (MonoArray, bounds));
1791                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
1792                         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1793                 }
1794         } else {
1795                 int idepth_reg = alloc_preg (cfg);
1796                 int stypes_reg = alloc_preg (cfg);
1797                 int stype = alloc_preg (cfg);
1798
1799                 mono_class_setup_supertypes (klass);
1800
1801                 if (klass->idepth > MONO_DEFAULT_SUPERTABLE_SIZE) {
1802                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, idepth_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, idepth));
1803                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, idepth_reg, klass->idepth);
1804                         MONO_EMIT_NEW_COND_EXC (cfg, LT_UN, "InvalidCastException");
1805                 }
1806                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stypes_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, supertypes));
1807                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stype, stypes_reg, ((klass->idepth - 1) * SIZEOF_VOID_P));
1808                 mini_emit_class_check_inst (cfg, stype, klass, klass_inst);
1809         }
1810 }
1811
1812 static void
1813 mini_emit_castclass (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoBasicBlock *object_is_null)
1814 {
1815         mini_emit_castclass_inst (cfg, obj_reg, klass_reg, klass, NULL, object_is_null);
1816 }
1817
1818 static void 
1819 mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, int align)
1820 {
1821         int val_reg;
1822
1823         g_assert (val == 0);
1824
1825         if (align == 0)
1826                 align = 4;
1827
1828         if ((size <= SIZEOF_REGISTER) && (size <= align)) {
1829                 switch (size) {
1830                 case 1:
1831                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, destreg, offset, val);
1832                         return;
1833                 case 2:
1834                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI2_MEMBASE_IMM, destreg, offset, val);
1835                         return;
1836                 case 4:
1837                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, destreg, offset, val);
1838                         return;
1839 #if SIZEOF_REGISTER == 8
1840                 case 8:
1841                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI8_MEMBASE_IMM, destreg, offset, val);
1842                         return;
1843 #endif
1844                 }
1845         }
1846
1847         val_reg = alloc_preg (cfg);
1848
1849         if (SIZEOF_REGISTER == 8)
1850                 MONO_EMIT_NEW_I8CONST (cfg, val_reg, val);
1851         else
1852                 MONO_EMIT_NEW_ICONST (cfg, val_reg, val);
1853
1854         if (align < 4) {
1855                 /* This could be optimized further if neccesary */
1856                 while (size >= 1) {
1857                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1858                         offset += 1;
1859                         size -= 1;
1860                 }
1861                 return;
1862         }       
1863
1864         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1865                 if (offset % 8) {
1866                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1867                         offset += 4;
1868                         size -= 4;
1869                 }
1870                 while (size >= 8) {
1871                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, offset, val_reg);
1872                         offset += 8;
1873                         size -= 8;
1874                 }
1875         }       
1876
1877         while (size >= 4) {
1878                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1879                 offset += 4;
1880                 size -= 4;
1881         }
1882         while (size >= 2) {
1883                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, val_reg);
1884                 offset += 2;
1885                 size -= 2;
1886         }
1887         while (size >= 1) {
1888                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1889                 offset += 1;
1890                 size -= 1;
1891         }
1892 }
1893
1894 void 
1895 mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
1896 {
1897         int cur_reg;
1898
1899         if (align == 0)
1900                 align = 4;
1901
1902         /*FIXME arbitrary hack to avoid unbound code expansion.*/
1903         g_assert (size < 10000);
1904
1905         if (align < 4) {
1906                 /* This could be optimized further if neccesary */
1907                 while (size >= 1) {
1908                         cur_reg = alloc_preg (cfg);
1909                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1910                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1911                         doffset += 1;
1912                         soffset += 1;
1913                         size -= 1;
1914                 }
1915         }
1916
1917         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1918                 while (size >= 8) {
1919                         cur_reg = alloc_preg (cfg);
1920                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI8_MEMBASE, cur_reg, srcreg, soffset);
1921                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, doffset, cur_reg);
1922                         doffset += 8;
1923                         soffset += 8;
1924                         size -= 8;
1925                 }
1926         }       
1927
1928         while (size >= 4) {
1929                 cur_reg = alloc_preg (cfg);
1930                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, cur_reg, srcreg, soffset);
1931                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, doffset, cur_reg);
1932                 doffset += 4;
1933                 soffset += 4;
1934                 size -= 4;
1935         }
1936         while (size >= 2) {
1937                 cur_reg = alloc_preg (cfg);
1938                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, cur_reg, srcreg, soffset);
1939                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, doffset, cur_reg);
1940                 doffset += 2;
1941                 soffset += 2;
1942                 size -= 2;
1943         }
1944         while (size >= 1) {
1945                 cur_reg = alloc_preg (cfg);
1946                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1947                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1948                 doffset += 1;
1949                 soffset += 1;
1950                 size -= 1;
1951         }
1952 }
1953
1954 static void
1955 emit_tls_set (MonoCompile *cfg, int sreg1, MonoTlsKey tls_key)
1956 {
1957         MonoInst *ins, *c;
1958
1959         if (cfg->compile_aot) {
1960                 EMIT_NEW_TLS_OFFSETCONST (cfg, c, tls_key);
1961                 MONO_INST_NEW (cfg, ins, OP_TLS_SET_REG);
1962                 ins->sreg1 = sreg1;
1963                 ins->sreg2 = c->dreg;
1964                 MONO_ADD_INS (cfg->cbb, ins);
1965         } else {
1966                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1967                 ins->sreg1 = sreg1;
1968                 ins->inst_offset = mini_get_tls_offset (tls_key);
1969                 MONO_ADD_INS (cfg->cbb, ins);
1970         }
1971 }
1972
1973 /*
1974  * emit_push_lmf:
1975  *
1976  *   Emit IR to push the current LMF onto the LMF stack.
1977  */
1978 static void
1979 emit_push_lmf (MonoCompile *cfg)
1980 {
1981         /*
1982          * Emit IR to push the LMF:
1983          * lmf_addr = <lmf_addr from tls>
1984          * lmf->lmf_addr = lmf_addr
1985          * lmf->prev_lmf = *lmf_addr
1986          * *lmf_addr = lmf
1987          */
1988         int lmf_reg, prev_lmf_reg;
1989         MonoInst *ins, *lmf_ins;
1990
1991         if (!cfg->lmf_ir)
1992                 return;
1993
1994         if (cfg->lmf_ir_mono_lmf && mini_tls_get_supported (cfg, TLS_KEY_LMF)) {
1995                 /* Load current lmf */
1996                 lmf_ins = mono_get_lmf_intrinsic (cfg);
1997                 g_assert (lmf_ins);
1998                 MONO_ADD_INS (cfg->cbb, lmf_ins);
1999                 EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2000                 lmf_reg = ins->dreg;
2001                 /* Save previous_lmf */
2002                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), lmf_ins->dreg);
2003                 /* Set new LMF */
2004                 emit_tls_set (cfg, lmf_reg, TLS_KEY_LMF);
2005         } else {
2006                 /*
2007                  * Store lmf_addr in a variable, so it can be allocated to a global register.
2008                  */
2009                 if (!cfg->lmf_addr_var)
2010                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2011
2012 #ifdef HOST_WIN32
2013                 ins = mono_get_jit_tls_intrinsic (cfg);
2014                 if (ins) {
2015                         int jit_tls_dreg = ins->dreg;
2016
2017                         MONO_ADD_INS (cfg->cbb, ins);
2018                         lmf_reg = alloc_preg (cfg);
2019                         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
2020                 } else {
2021                         lmf_ins = mono_emit_jit_icall (cfg, mono_get_lmf_addr, NULL);
2022                 }
2023 #else
2024                 lmf_ins = mono_get_lmf_addr_intrinsic (cfg);
2025                 if (lmf_ins) {
2026                         MONO_ADD_INS (cfg->cbb, lmf_ins);
2027                 } else {
2028 #ifdef TARGET_IOS
2029                         MonoInst *args [16], *jit_tls_ins, *ins;
2030
2031                         /* Inline mono_get_lmf_addr () */
2032                         /* jit_tls = pthread_getspecific (mono_jit_tls_id); lmf_addr = &jit_tls->lmf; */
2033
2034                         /* Load mono_jit_tls_id */
2035                         if (cfg->compile_aot)
2036                                 EMIT_NEW_AOTCONST (cfg, args [0], MONO_PATCH_INFO_JIT_TLS_ID, NULL);
2037                         else
2038                                 EMIT_NEW_ICONST (cfg, args [0], mono_jit_tls_id);
2039                         /* call pthread_getspecific () */
2040                         jit_tls_ins = mono_emit_jit_icall (cfg, pthread_getspecific, args);
2041                         /* lmf_addr = &jit_tls->lmf */
2042                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, cfg->lmf_addr_var->dreg, jit_tls_ins->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
2043                         lmf_ins = ins;
2044 #else
2045                         lmf_ins = mono_emit_jit_icall (cfg, mono_get_lmf_addr, NULL);
2046 #endif
2047                 }
2048 #endif
2049                 lmf_ins->dreg = cfg->lmf_addr_var->dreg;
2050
2051                 EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2052                 lmf_reg = ins->dreg;
2053
2054                 prev_lmf_reg = alloc_preg (cfg);
2055                 /* Save previous_lmf */
2056                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
2057                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
2058                 /* Set new lmf */
2059                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
2060         }
2061 }
2062
2063 /*
2064  * emit_pop_lmf:
2065  *
2066  *   Emit IR to pop the current LMF from the LMF stack.
2067  */
2068 static void
2069 emit_pop_lmf (MonoCompile *cfg)
2070 {
2071         int lmf_reg, lmf_addr_reg, prev_lmf_reg;
2072         MonoInst *ins;
2073
2074         if (!cfg->lmf_ir)
2075                 return;
2076
2077         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2078         lmf_reg = ins->dreg;
2079
2080         if (cfg->lmf_ir_mono_lmf && mini_tls_get_supported (cfg, TLS_KEY_LMF)) {
2081                 /* Load previous_lmf */
2082                 prev_lmf_reg = alloc_preg (cfg);
2083                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
2084                 /* Set new LMF */
2085                 emit_tls_set (cfg, prev_lmf_reg, TLS_KEY_LMF);
2086         } else {
2087                 /*
2088                  * Emit IR to pop the LMF:
2089                  * *(lmf->lmf_addr) = lmf->prev_lmf
2090                  */
2091                 /* This could be called before emit_push_lmf () */
2092                 if (!cfg->lmf_addr_var)
2093                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2094                 lmf_addr_reg = cfg->lmf_addr_var->dreg;
2095
2096                 prev_lmf_reg = alloc_preg (cfg);
2097                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
2098                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
2099         }
2100 }
2101
2102 static void
2103 emit_instrumentation_call (MonoCompile *cfg, void *func)
2104 {
2105         MonoInst *iargs [1];
2106
2107         /*
2108          * Avoid instrumenting inlined methods since it can
2109          * distort profiling results.
2110          */
2111         if (cfg->method != cfg->current_method)
2112                 return;
2113
2114         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
2115                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
2116                 mono_emit_jit_icall (cfg, func, iargs);
2117         }
2118 }
2119
2120 static int
2121 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
2122 {
2123 handle_enum:
2124         type = mini_get_underlying_type (type);
2125         switch (type->type) {
2126         case MONO_TYPE_VOID:
2127                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
2128         case MONO_TYPE_I1:
2129         case MONO_TYPE_U1:
2130         case MONO_TYPE_I2:
2131         case MONO_TYPE_U2:
2132         case MONO_TYPE_I4:
2133         case MONO_TYPE_U4:
2134                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2135         case MONO_TYPE_I:
2136         case MONO_TYPE_U:
2137         case MONO_TYPE_PTR:
2138         case MONO_TYPE_FNPTR:
2139                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2140         case MONO_TYPE_CLASS:
2141         case MONO_TYPE_STRING:
2142         case MONO_TYPE_OBJECT:
2143         case MONO_TYPE_SZARRAY:
2144         case MONO_TYPE_ARRAY:    
2145                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2146         case MONO_TYPE_I8:
2147         case MONO_TYPE_U8:
2148                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
2149         case MONO_TYPE_R4:
2150                 if (cfg->r4fp)
2151                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
2152                 else
2153                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
2154         case MONO_TYPE_R8:
2155                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
2156         case MONO_TYPE_VALUETYPE:
2157                 if (type->data.klass->enumtype) {
2158                         type = mono_class_enum_basetype (type->data.klass);
2159                         goto handle_enum;
2160                 } else
2161                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2162         case MONO_TYPE_TYPEDBYREF:
2163                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2164         case MONO_TYPE_GENERICINST:
2165                 type = &type->data.generic_class->container_class->byval_arg;
2166                 goto handle_enum;
2167         case MONO_TYPE_VAR:
2168         case MONO_TYPE_MVAR:
2169                 /* gsharedvt */
2170                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2171         default:
2172                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2173         }
2174         return -1;
2175 }
2176
2177 //XXX this ignores if t is byref
2178 #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)))))
2179
2180 /*
2181  * target_type_is_incompatible:
2182  * @cfg: MonoCompile context
2183  *
2184  * Check that the item @arg on the evaluation stack can be stored
2185  * in the target type (can be a local, or field, etc).
2186  * The cfg arg can be used to check if we need verification or just
2187  * validity checks.
2188  *
2189  * Returns: non-0 value if arg can't be stored on a target.
2190  */
2191 static int
2192 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2193 {
2194         MonoType *simple_type;
2195         MonoClass *klass;
2196
2197         if (target->byref) {
2198                 /* FIXME: check that the pointed to types match */
2199                 if (arg->type == STACK_MP) {
2200                         if (cfg->verbose_level) printf ("ok\n");
2201                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
2202                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
2203                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
2204
2205                         /* if the target is native int& or same type */
2206                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
2207                                 return 0;
2208
2209                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
2210                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
2211                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
2212                                 return 0;
2213                         return 1;
2214                 }
2215                 if (arg->type == STACK_PTR)
2216                         return 0;
2217                 return 1;
2218         }
2219
2220         simple_type = mini_get_underlying_type (target);
2221         switch (simple_type->type) {
2222         case MONO_TYPE_VOID:
2223                 return 1;
2224         case MONO_TYPE_I1:
2225         case MONO_TYPE_U1:
2226         case MONO_TYPE_I2:
2227         case MONO_TYPE_U2:
2228         case MONO_TYPE_I4:
2229         case MONO_TYPE_U4:
2230                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2231                         return 1;
2232                 return 0;
2233         case MONO_TYPE_PTR:
2234                 /* STACK_MP is needed when setting pinned locals */
2235                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2236                         return 1;
2237                 return 0;
2238         case MONO_TYPE_I:
2239         case MONO_TYPE_U:
2240         case MONO_TYPE_FNPTR:
2241                 /* 
2242                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
2243                  * in native int. (#688008).
2244                  */
2245                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2246                         return 1;
2247                 return 0;
2248         case MONO_TYPE_CLASS:
2249         case MONO_TYPE_STRING:
2250         case MONO_TYPE_OBJECT:
2251         case MONO_TYPE_SZARRAY:
2252         case MONO_TYPE_ARRAY:    
2253                 if (arg->type != STACK_OBJ)
2254                         return 1;
2255                 /* FIXME: check type compatibility */
2256                 return 0;
2257         case MONO_TYPE_I8:
2258         case MONO_TYPE_U8:
2259                 if (arg->type != STACK_I8)
2260                         return 1;
2261                 return 0;
2262         case MONO_TYPE_R4:
2263                 if (arg->type != cfg->r4_stack_type)
2264                         return 1;
2265                 return 0;
2266         case MONO_TYPE_R8:
2267                 if (arg->type != STACK_R8)
2268                         return 1;
2269                 return 0;
2270         case MONO_TYPE_VALUETYPE:
2271                 if (arg->type != STACK_VTYPE)
2272                         return 1;
2273                 klass = mono_class_from_mono_type (simple_type);
2274                 if (klass != arg->klass)
2275                         return 1;
2276                 return 0;
2277         case MONO_TYPE_TYPEDBYREF:
2278                 if (arg->type != STACK_VTYPE)
2279                         return 1;
2280                 klass = mono_class_from_mono_type (simple_type);
2281                 if (klass != arg->klass)
2282                         return 1;
2283                 return 0;
2284         case MONO_TYPE_GENERICINST:
2285                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2286                         MonoClass *target_class;
2287                         if (arg->type != STACK_VTYPE)
2288                                 return 1;
2289                         klass = mono_class_from_mono_type (simple_type);
2290                         target_class = mono_class_from_mono_type (target);
2291                         /* The second cases is needed when doing partial sharing */
2292                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
2293                                 return 1;
2294                         return 0;
2295                 } else {
2296                         if (arg->type != STACK_OBJ)
2297                                 return 1;
2298                         /* FIXME: check type compatibility */
2299                         return 0;
2300                 }
2301         case MONO_TYPE_VAR:
2302         case MONO_TYPE_MVAR:
2303                 g_assert (cfg->gshared);
2304                 if (mini_type_var_is_vt (simple_type)) {
2305                         if (arg->type != STACK_VTYPE)
2306                                 return 1;
2307                 } else {
2308                         if (arg->type != STACK_OBJ)
2309                                 return 1;
2310                 }
2311                 return 0;
2312         default:
2313                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2314         }
2315         return 1;
2316 }
2317
2318 /*
2319  * Prepare arguments for passing to a function call.
2320  * Return a non-zero value if the arguments can't be passed to the given
2321  * signature.
2322  * The type checks are not yet complete and some conversions may need
2323  * casts on 32 or 64 bit architectures.
2324  *
2325  * FIXME: implement this using target_type_is_incompatible ()
2326  */
2327 static int
2328 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2329 {
2330         MonoType *simple_type;
2331         int i;
2332
2333         if (sig->hasthis) {
2334                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2335                         return 1;
2336                 args++;
2337         }
2338         for (i = 0; i < sig->param_count; ++i) {
2339                 if (sig->params [i]->byref) {
2340                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2341                                 return 1;
2342                         continue;
2343                 }
2344                 simple_type = mini_get_underlying_type (sig->params [i]);
2345 handle_enum:
2346                 switch (simple_type->type) {
2347                 case MONO_TYPE_VOID:
2348                         return 1;
2349                         continue;
2350                 case MONO_TYPE_I1:
2351                 case MONO_TYPE_U1:
2352                 case MONO_TYPE_I2:
2353                 case MONO_TYPE_U2:
2354                 case MONO_TYPE_I4:
2355                 case MONO_TYPE_U4:
2356                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2357                                 return 1;
2358                         continue;
2359                 case MONO_TYPE_I:
2360                 case MONO_TYPE_U:
2361                 case MONO_TYPE_PTR:
2362                 case MONO_TYPE_FNPTR:
2363                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2364                                 return 1;
2365                         continue;
2366                 case MONO_TYPE_CLASS:
2367                 case MONO_TYPE_STRING:
2368                 case MONO_TYPE_OBJECT:
2369                 case MONO_TYPE_SZARRAY:
2370                 case MONO_TYPE_ARRAY:    
2371                         if (args [i]->type != STACK_OBJ)
2372                                 return 1;
2373                         continue;
2374                 case MONO_TYPE_I8:
2375                 case MONO_TYPE_U8:
2376                         if (args [i]->type != STACK_I8)
2377                                 return 1;
2378                         continue;
2379                 case MONO_TYPE_R4:
2380                         if (args [i]->type != cfg->r4_stack_type)
2381                                 return 1;
2382                         continue;
2383                 case MONO_TYPE_R8:
2384                         if (args [i]->type != STACK_R8)
2385                                 return 1;
2386                         continue;
2387                 case MONO_TYPE_VALUETYPE:
2388                         if (simple_type->data.klass->enumtype) {
2389                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2390                                 goto handle_enum;
2391                         }
2392                         if (args [i]->type != STACK_VTYPE)
2393                                 return 1;
2394                         continue;
2395                 case MONO_TYPE_TYPEDBYREF:
2396                         if (args [i]->type != STACK_VTYPE)
2397                                 return 1;
2398                         continue;
2399                 case MONO_TYPE_GENERICINST:
2400                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2401                         goto handle_enum;
2402                 case MONO_TYPE_VAR:
2403                 case MONO_TYPE_MVAR:
2404                         /* gsharedvt */
2405                         if (args [i]->type != STACK_VTYPE)
2406                                 return 1;
2407                         continue;
2408                 default:
2409                         g_error ("unknown type 0x%02x in check_call_signature",
2410                                  simple_type->type);
2411                 }
2412         }
2413         return 0;
2414 }
2415
2416 static int
2417 callvirt_to_call (int opcode)
2418 {
2419         switch (opcode) {
2420         case OP_CALL_MEMBASE:
2421                 return OP_CALL;
2422         case OP_VOIDCALL_MEMBASE:
2423                 return OP_VOIDCALL;
2424         case OP_FCALL_MEMBASE:
2425                 return OP_FCALL;
2426         case OP_RCALL_MEMBASE:
2427                 return OP_RCALL;
2428         case OP_VCALL_MEMBASE:
2429                 return OP_VCALL;
2430         case OP_LCALL_MEMBASE:
2431                 return OP_LCALL;
2432         default:
2433                 g_assert_not_reached ();
2434         }
2435
2436         return -1;
2437 }
2438
2439 static int
2440 callvirt_to_call_reg (int opcode)
2441 {
2442         switch (opcode) {
2443         case OP_CALL_MEMBASE:
2444                 return OP_CALL_REG;
2445         case OP_VOIDCALL_MEMBASE:
2446                 return OP_VOIDCALL_REG;
2447         case OP_FCALL_MEMBASE:
2448                 return OP_FCALL_REG;
2449         case OP_RCALL_MEMBASE:
2450                 return OP_RCALL_REG;
2451         case OP_VCALL_MEMBASE:
2452                 return OP_VCALL_REG;
2453         case OP_LCALL_MEMBASE:
2454                 return OP_LCALL_REG;
2455         default:
2456                 g_assert_not_reached ();
2457         }
2458
2459         return -1;
2460 }
2461
2462 /* Either METHOD or IMT_ARG needs to be set */
2463 static void
2464 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2465 {
2466         int method_reg;
2467
2468         if (COMPILE_LLVM (cfg)) {
2469                 if (imt_arg) {
2470                         method_reg = alloc_preg (cfg);
2471                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2472                 } else {
2473                         MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2474                         method_reg = ins->dreg;
2475                 }
2476
2477 #ifdef ENABLE_LLVM
2478                 call->imt_arg_reg = method_reg;
2479 #endif
2480                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2481                 return;
2482         }
2483
2484         if (imt_arg) {
2485                 method_reg = alloc_preg (cfg);
2486                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2487         } else {
2488                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2489                 method_reg = ins->dreg;
2490         }
2491
2492         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2493 }
2494
2495 static MonoJumpInfo *
2496 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2497 {
2498         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2499
2500         ji->ip.i = ip;
2501         ji->type = type;
2502         ji->data.target = target;
2503
2504         return ji;
2505 }
2506
2507 static int
2508 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2509 {
2510         if (cfg->gshared)
2511                 return mono_class_check_context_used (klass);
2512         else
2513                 return 0;
2514 }
2515
2516 static int
2517 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2518 {
2519         if (cfg->gshared)
2520                 return mono_method_check_context_used (method);
2521         else
2522                 return 0;
2523 }
2524
2525 /*
2526  * check_method_sharing:
2527  *
2528  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2529  */
2530 static void
2531 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2532 {
2533         gboolean pass_vtable = FALSE;
2534         gboolean pass_mrgctx = FALSE;
2535
2536         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2537                 (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
2538                 gboolean sharable = FALSE;
2539
2540                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2541                         sharable = TRUE;
2542
2543                 /*
2544                  * Pass vtable iff target method might
2545                  * be shared, which means that sharing
2546                  * is enabled for its class and its
2547                  * context is sharable (and it's not a
2548                  * generic method).
2549                  */
2550                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2551                         pass_vtable = TRUE;
2552         }
2553
2554         if (mini_method_get_context (cmethod) &&
2555                 mini_method_get_context (cmethod)->method_inst) {
2556                 g_assert (!pass_vtable);
2557
2558                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2559                         pass_mrgctx = TRUE;
2560                 } else {
2561                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2562                                 pass_mrgctx = TRUE;
2563                 }
2564         }
2565
2566         if (out_pass_vtable)
2567                 *out_pass_vtable = pass_vtable;
2568         if (out_pass_mrgctx)
2569                 *out_pass_mrgctx = pass_mrgctx;
2570 }
2571
2572 inline static MonoCallInst *
2573 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2574                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2575 {
2576         MonoType *sig_ret;
2577         MonoCallInst *call;
2578 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2579         int i;
2580 #endif
2581
2582         if (cfg->llvm_only)
2583                 tail = FALSE;
2584
2585         if (tail) {
2586                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2587
2588                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2589         } else
2590                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2591
2592         call->args = args;
2593         call->signature = sig;
2594         call->rgctx_reg = rgctx;
2595         sig_ret = mini_get_underlying_type (sig->ret);
2596
2597         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2598
2599         if (tail) {
2600                 if (mini_type_is_vtype (sig_ret)) {
2601                         call->vret_var = cfg->vret_addr;
2602                         //g_assert_not_reached ();
2603                 }
2604         } else if (mini_type_is_vtype (sig_ret)) {
2605                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2606                 MonoInst *loada;
2607
2608                 temp->backend.is_pinvoke = sig->pinvoke;
2609
2610                 /*
2611                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2612                  * address of return value to increase optimization opportunities.
2613                  * Before vtype decomposition, the dreg of the call ins itself represents the
2614                  * fact the call modifies the return value. After decomposition, the call will
2615                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2616                  * will be transformed into an LDADDR.
2617                  */
2618                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2619                 loada->dreg = alloc_preg (cfg);
2620                 loada->inst_p0 = temp;
2621                 /* We reference the call too since call->dreg could change during optimization */
2622                 loada->inst_p1 = call;
2623                 MONO_ADD_INS (cfg->cbb, loada);
2624
2625                 call->inst.dreg = temp->dreg;
2626
2627                 call->vret_var = loada;
2628         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2629                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2630
2631 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2632         if (COMPILE_SOFT_FLOAT (cfg)) {
2633                 /* 
2634                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2635                  * an icall, but that cannot be done during the call sequence since it would clobber
2636                  * the call registers + the stack. So we do it before emitting the call.
2637                  */
2638                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2639                         MonoType *t;
2640                         MonoInst *in = call->args [i];
2641
2642                         if (i >= sig->hasthis)
2643                                 t = sig->params [i - sig->hasthis];
2644                         else
2645                                 t = &mono_defaults.int_class->byval_arg;
2646                         t = mono_type_get_underlying_type (t);
2647
2648                         if (!t->byref && t->type == MONO_TYPE_R4) {
2649                                 MonoInst *iargs [1];
2650                                 MonoInst *conv;
2651
2652                                 iargs [0] = in;
2653                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2654
2655                                 /* The result will be in an int vreg */
2656                                 call->args [i] = conv;
2657                         }
2658                 }
2659         }
2660 #endif
2661
2662         call->need_unbox_trampoline = unbox_trampoline;
2663
2664 #ifdef ENABLE_LLVM
2665         if (COMPILE_LLVM (cfg))
2666                 mono_llvm_emit_call (cfg, call);
2667         else
2668                 mono_arch_emit_call (cfg, call);
2669 #else
2670         mono_arch_emit_call (cfg, call);
2671 #endif
2672
2673         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2674         cfg->flags |= MONO_CFG_HAS_CALLS;
2675         
2676         return call;
2677 }
2678
2679 static void
2680 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2681 {
2682         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2683         cfg->uses_rgctx_reg = TRUE;
2684         call->rgctx_reg = TRUE;
2685 #ifdef ENABLE_LLVM
2686         call->rgctx_arg_reg = rgctx_reg;
2687 #endif
2688 }       
2689
2690 inline static MonoInst*
2691 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2692 {
2693         MonoCallInst *call;
2694         MonoInst *ins;
2695         int rgctx_reg = -1;
2696         gboolean check_sp = FALSE;
2697
2698         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2699                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2700
2701                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2702                         check_sp = TRUE;
2703         }
2704
2705         if (rgctx_arg) {
2706                 rgctx_reg = mono_alloc_preg (cfg);
2707                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2708         }
2709
2710         if (check_sp) {
2711                 if (!cfg->stack_inbalance_var)
2712                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2713
2714                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2715                 ins->dreg = cfg->stack_inbalance_var->dreg;
2716                 MONO_ADD_INS (cfg->cbb, ins);
2717         }
2718
2719         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2720
2721         call->inst.sreg1 = addr->dreg;
2722
2723         if (imt_arg)
2724                 emit_imt_argument (cfg, call, NULL, imt_arg);
2725
2726         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2727
2728         if (check_sp) {
2729                 int sp_reg;
2730
2731                 sp_reg = mono_alloc_preg (cfg);
2732
2733                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2734                 ins->dreg = sp_reg;
2735                 MONO_ADD_INS (cfg->cbb, ins);
2736
2737                 /* Restore the stack so we don't crash when throwing the exception */
2738                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2739                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2740                 MONO_ADD_INS (cfg->cbb, ins);
2741
2742                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2743                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2744         }
2745
2746         if (rgctx_arg)
2747                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2748
2749         return (MonoInst*)call;
2750 }
2751
2752 static MonoInst*
2753 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2754
2755 static MonoInst*
2756 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2757 static MonoInst*
2758 emit_get_rgctx_klass (MonoCompile *cfg, int context_used, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2759
2760 static MonoInst*
2761 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2762                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2763 {
2764 #ifndef DISABLE_REMOTING
2765         gboolean might_be_remote = FALSE;
2766 #endif
2767         gboolean virtual_ = this_ins != NULL;
2768         gboolean enable_for_aot = TRUE;
2769         int context_used;
2770         MonoCallInst *call;
2771         MonoInst *call_target = NULL;
2772         int rgctx_reg = 0;
2773         gboolean need_unbox_trampoline;
2774
2775         if (!sig)
2776                 sig = mono_method_signature (method);
2777
2778         if (cfg->llvm_only && (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE))
2779                 g_assert_not_reached ();
2780
2781         if (rgctx_arg) {
2782                 rgctx_reg = mono_alloc_preg (cfg);
2783                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2784         }
2785
2786         if (method->string_ctor) {
2787                 /* Create the real signature */
2788                 /* FIXME: Cache these */
2789                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2790                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2791
2792                 sig = ctor_sig;
2793         }
2794
2795         context_used = mini_method_check_context_used (cfg, method);
2796
2797 #ifndef DISABLE_REMOTING
2798         might_be_remote = this_ins && sig->hasthis &&
2799                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2800                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2801
2802         if (might_be_remote && context_used) {
2803                 MonoInst *addr;
2804
2805                 g_assert (cfg->gshared);
2806
2807                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2808
2809                 return mono_emit_calli (cfg, sig, args, addr, NULL, NULL);
2810         }
2811 #endif
2812
2813         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2814                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2815
2816         need_unbox_trampoline = method->klass == mono_defaults.object_class || (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE);
2817
2818         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2819
2820 #ifndef DISABLE_REMOTING
2821         if (might_be_remote)
2822                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2823         else
2824 #endif
2825                 call->method = method;
2826         call->inst.flags |= MONO_INST_HAS_METHOD;
2827         call->inst.inst_left = this_ins;
2828         call->tail_call = tail;
2829
2830         if (virtual_) {
2831                 int vtable_reg, slot_reg, this_reg;
2832                 int offset;
2833
2834                 this_reg = this_ins->dreg;
2835
2836                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2837                         MonoInst *dummy_use;
2838
2839                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2840
2841                         /* Make a call to delegate->invoke_impl */
2842                         call->inst.inst_basereg = this_reg;
2843                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2844                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2845
2846                         /* We must emit a dummy use here because the delegate trampoline will
2847                         replace the 'this' argument with the delegate target making this activation
2848                         no longer a root for the delegate.
2849                         This is an issue for delegates that target collectible code such as dynamic
2850                         methods of GC'able assemblies.
2851
2852                         For a test case look into #667921.
2853
2854                         FIXME: a dummy use is not the best way to do it as the local register allocator
2855                         will put it on a caller save register and spil it around the call. 
2856                         Ideally, we would either put it on a callee save register or only do the store part.  
2857                          */
2858                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2859
2860                         return (MonoInst*)call;
2861                 }
2862
2863                 if ((!cfg->compile_aot || enable_for_aot) && 
2864                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2865                          (MONO_METHOD_IS_FINAL (method) &&
2866                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2867                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2868                         /* 
2869                          * the method is not virtual, we just need to ensure this is not null
2870                          * and then we can call the method directly.
2871                          */
2872 #ifndef DISABLE_REMOTING
2873                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2874                                 /* 
2875                                  * The check above ensures method is not gshared, this is needed since
2876                                  * gshared methods can't have wrappers.
2877                                  */
2878                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2879                         }
2880 #endif
2881
2882                         if (!method->string_ctor)
2883                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2884
2885                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2886                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2887                         /*
2888                          * the method is virtual, but we can statically dispatch since either
2889                          * it's class or the method itself are sealed.
2890                          * But first we need to ensure it's not a null reference.
2891                          */
2892                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2893
2894                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2895                 } else if (call_target) {
2896                         vtable_reg = alloc_preg (cfg);
2897                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2898
2899                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2900                         call->inst.sreg1 = call_target->dreg;
2901                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2902                 } else {
2903                         vtable_reg = alloc_preg (cfg);
2904                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2905                         if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
2906                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2907                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2908                                 slot_reg = vtable_reg;
2909                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2910                         } else {
2911                                 slot_reg = vtable_reg;
2912                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2913                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2914                                 if (imt_arg) {
2915                                         g_assert (mono_method_signature (method)->generic_param_count);
2916                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2917                                 }
2918                         }
2919
2920                         call->inst.sreg1 = slot_reg;
2921                         call->inst.inst_offset = offset;
2922                         call->is_virtual = TRUE;
2923                 }
2924         }
2925
2926         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2927
2928         if (rgctx_arg)
2929                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2930
2931         return (MonoInst*)call;
2932 }
2933
2934 MonoInst*
2935 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2936 {
2937         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2938 }
2939
2940 MonoInst*
2941 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2942                                            MonoInst **args)
2943 {
2944         MonoCallInst *call;
2945
2946         g_assert (sig);
2947
2948         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2949         call->fptr = func;
2950
2951         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2952
2953         return (MonoInst*)call;
2954 }
2955
2956 MonoInst*
2957 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2958 {
2959         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2960
2961         g_assert (info);
2962
2963         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2964 }
2965
2966 /*
2967  * mono_emit_abs_call:
2968  *
2969  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2970  */
2971 inline static MonoInst*
2972 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2973                                         MonoMethodSignature *sig, MonoInst **args)
2974 {
2975         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2976         MonoInst *ins;
2977
2978         /* 
2979          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2980          * handle it.
2981          */
2982         if (cfg->abs_patches == NULL)
2983                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2984         g_hash_table_insert (cfg->abs_patches, ji, ji);
2985         ins = mono_emit_native_call (cfg, ji, sig, args);
2986         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2987         return ins;
2988 }
2989
2990 static MonoMethodSignature*
2991 sig_to_rgctx_sig (MonoMethodSignature *sig)
2992 {
2993         // FIXME: memory allocation
2994         MonoMethodSignature *res;
2995         int i;
2996
2997         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2998         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2999         res->param_count = sig->param_count + 1;
3000         for (i = 0; i < sig->param_count; ++i)
3001                 res->params [i] = sig->params [i];
3002         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
3003         return res;
3004 }
3005
3006 /* Make an indirect call to FSIG passing an additional argument */
3007 static MonoInst*
3008 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
3009 {
3010         MonoMethodSignature *csig;
3011         MonoInst *args_buf [16];
3012         MonoInst **args;
3013         int i, pindex, tmp_reg;
3014
3015         /* Make a call with an rgctx/extra arg */
3016         if (fsig->param_count + 2 < 16)
3017                 args = args_buf;
3018         else
3019                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
3020         pindex = 0;
3021         if (fsig->hasthis)
3022                 args [pindex ++] = orig_args [0];
3023         for (i = 0; i < fsig->param_count; ++i)
3024                 args [pindex ++] = orig_args [fsig->hasthis + i];
3025         tmp_reg = alloc_preg (cfg);
3026         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
3027         csig = sig_to_rgctx_sig (fsig);
3028         return mono_emit_calli (cfg, csig, args, call_target, NULL, NULL);
3029 }
3030
3031 /* Emit an indirect call to the function descriptor ADDR */
3032 static MonoInst*
3033 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
3034 {
3035         int addr_reg, arg_reg;
3036         MonoInst *call_target;
3037
3038         g_assert (cfg->llvm_only);
3039
3040         /*
3041          * addr points to a <addr, arg> pair, load both of them, and
3042          * make a call to addr, passing arg as an extra arg.
3043          */
3044         addr_reg = alloc_preg (cfg);
3045         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
3046         arg_reg = alloc_preg (cfg);
3047         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
3048
3049         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
3050 }
3051
3052 static gboolean
3053 direct_icalls_enabled (MonoCompile *cfg)
3054 {
3055         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
3056 #ifdef TARGET_AMD64
3057         if (cfg->compile_llvm && !cfg->llvm_only)
3058                 return FALSE;
3059 #endif
3060         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
3061                 return FALSE;
3062         return TRUE;
3063 }
3064
3065 MonoInst*
3066 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
3067 {
3068         /*
3069          * Call the jit icall without a wrapper if possible.
3070          * The wrapper is needed for the following reasons:
3071          * - to handle exceptions thrown using mono_raise_exceptions () from the
3072          *   icall function. The EH code needs the lmf frame pushed by the
3073          *   wrapper to be able to unwind back to managed code.
3074          * - to be able to do stack walks for asynchronously suspended
3075          *   threads when debugging.
3076          */
3077         if (info->no_raise && direct_icalls_enabled (cfg)) {
3078                 char *name;
3079                 int costs;
3080
3081                 if (!info->wrapper_method) {
3082                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
3083                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
3084                         g_free (name);
3085                         mono_memory_barrier ();
3086                 }
3087
3088                 /*
3089                  * Inline the wrapper method, which is basically a call to the C icall, and
3090                  * an exception check.
3091                  */
3092                 costs = inline_method (cfg, info->wrapper_method, NULL,
3093                                                            args, NULL, il_offset, TRUE);
3094                 g_assert (costs > 0);
3095                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
3096
3097                 return args [0];
3098         } else {
3099                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
3100         }
3101 }
3102  
3103 static MonoInst*
3104 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
3105 {
3106         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3107                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
3108                         int widen_op = -1;
3109
3110                         /* 
3111                          * Native code might return non register sized integers 
3112                          * without initializing the upper bits.
3113                          */
3114                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
3115                         case OP_LOADI1_MEMBASE:
3116                                 widen_op = OP_ICONV_TO_I1;
3117                                 break;
3118                         case OP_LOADU1_MEMBASE:
3119                                 widen_op = OP_ICONV_TO_U1;
3120                                 break;
3121                         case OP_LOADI2_MEMBASE:
3122                                 widen_op = OP_ICONV_TO_I2;
3123                                 break;
3124                         case OP_LOADU2_MEMBASE:
3125                                 widen_op = OP_ICONV_TO_U2;
3126                                 break;
3127                         default:
3128                                 break;
3129                         }
3130
3131                         if (widen_op != -1) {
3132                                 int dreg = alloc_preg (cfg);
3133                                 MonoInst *widen;
3134
3135                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
3136                                 widen->type = ins->type;
3137                                 ins = widen;
3138                         }
3139                 }
3140         }
3141
3142         return ins;
3143 }
3144
3145
3146 static void
3147 emit_method_access_failure (MonoCompile *cfg, MonoMethod *method, MonoMethod *cil_method)
3148 {
3149         MonoInst *args [16];
3150
3151         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (method), method, MONO_RGCTX_INFO_METHOD);
3152         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cil_method), cil_method, MONO_RGCTX_INFO_METHOD);
3153
3154         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
3155 }
3156
3157 static MonoMethod*
3158 get_memcpy_method (void)
3159 {
3160         static MonoMethod *memcpy_method = NULL;
3161         if (!memcpy_method) {
3162                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
3163                 if (!memcpy_method)
3164                         g_error ("Old corlib found. Install a new one");
3165         }
3166         return memcpy_method;
3167 }
3168
3169 static void
3170 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
3171 {
3172         MonoClassField *field;
3173         gpointer iter = NULL;
3174
3175         while ((field = mono_class_get_fields (klass, &iter))) {
3176                 int foffset;
3177
3178                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
3179                         continue;
3180                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
3181                 if (mini_type_is_reference (mono_field_get_type (field))) {
3182                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
3183                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
3184                 } else {
3185                         MonoClass *field_class = mono_class_from_mono_type (field->type);
3186                         if (field_class->has_references)
3187                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
3188                 }
3189         }
3190 }
3191
3192 static void
3193 emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
3194 {
3195         int card_table_shift_bits;
3196         gpointer card_table_mask;
3197         guint8 *card_table;
3198         MonoInst *dummy_use;
3199         int nursery_shift_bits;
3200         size_t nursery_size;
3201
3202         if (!cfg->gen_write_barriers)
3203                 return;
3204
3205         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3206
3207         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
3208
3209         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
3210                 MonoInst *wbarrier;
3211
3212                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
3213                 wbarrier->sreg1 = ptr->dreg;
3214                 wbarrier->sreg2 = value->dreg;
3215                 MONO_ADD_INS (cfg->cbb, wbarrier);
3216         } else if (card_table && !cfg->compile_aot && !mono_gc_card_table_nursery_check ()) {
3217                 int offset_reg = alloc_preg (cfg);
3218                 int card_reg;
3219                 MonoInst *ins;
3220
3221                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
3222                 if (card_table_mask)
3223                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
3224
3225                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
3226                  * IMM's larger than 32bits.
3227                  */
3228                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
3229                 card_reg = ins->dreg;
3230
3231                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
3232                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
3233         } else {
3234                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
3235                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
3236         }
3237
3238         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
3239 }
3240
3241 static gboolean
3242 mono_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
3243 {
3244         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
3245         unsigned need_wb = 0;
3246
3247         if (align == 0)
3248                 align = 4;
3249
3250         /*types with references can't have alignment smaller than sizeof(void*) */
3251         if (align < SIZEOF_VOID_P)
3252                 return FALSE;
3253
3254         /*This value cannot be bigger than 32 due to the way we calculate the required wb bitmap.*/
3255         if (size > 32 * SIZEOF_VOID_P)
3256                 return FALSE;
3257
3258         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
3259
3260         /* We don't unroll more than 5 stores to avoid code bloat. */
3261         if (size > 5 * SIZEOF_VOID_P) {
3262                 /*This is harmless and simplify mono_gc_wbarrier_value_copy_bitmap */
3263                 size += (SIZEOF_VOID_P - 1);
3264                 size &= ~(SIZEOF_VOID_P - 1);
3265
3266                 EMIT_NEW_ICONST (cfg, iargs [2], size);
3267                 EMIT_NEW_ICONST (cfg, iargs [3], need_wb);
3268                 mono_emit_jit_icall (cfg, mono_gc_wbarrier_value_copy_bitmap, iargs);
3269                 return TRUE;
3270         }
3271
3272         destreg = iargs [0]->dreg;
3273         srcreg = iargs [1]->dreg;
3274         offset = 0;
3275
3276         dest_ptr_reg = alloc_preg (cfg);
3277         tmp_reg = alloc_preg (cfg);
3278
3279         /*tmp = dreg*/
3280         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
3281
3282         while (size >= SIZEOF_VOID_P) {
3283                 MonoInst *load_inst;
3284                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
3285                 load_inst->dreg = tmp_reg;
3286                 load_inst->inst_basereg = srcreg;
3287                 load_inst->inst_offset = offset;
3288                 MONO_ADD_INS (cfg->cbb, load_inst);
3289
3290                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
3291
3292                 if (need_wb & 0x1)
3293                         emit_write_barrier (cfg, iargs [0], load_inst);
3294
3295                 offset += SIZEOF_VOID_P;
3296                 size -= SIZEOF_VOID_P;
3297                 need_wb >>= 1;
3298
3299                 /*tmp += sizeof (void*)*/
3300                 if (size >= SIZEOF_VOID_P) {
3301                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
3302                         MONO_ADD_INS (cfg->cbb, iargs [0]);
3303                 }
3304         }
3305
3306         /* Those cannot be references since size < sizeof (void*) */
3307         while (size >= 4) {
3308                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
3309                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
3310                 offset += 4;
3311                 size -= 4;
3312         }
3313
3314         while (size >= 2) {
3315                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
3316                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
3317                 offset += 2;
3318                 size -= 2;
3319         }
3320
3321         while (size >= 1) {
3322                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
3323                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
3324                 offset += 1;
3325                 size -= 1;
3326         }
3327
3328         return TRUE;
3329 }
3330
3331 /*
3332  * Emit code to copy a valuetype of type @klass whose address is stored in
3333  * @src->dreg to memory whose address is stored at @dest->dreg.
3334  */
3335 void
3336 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
3337 {
3338         MonoInst *iargs [4];
3339         int n;
3340         guint32 align = 0;
3341         MonoMethod *memcpy_method;
3342         MonoInst *size_ins = NULL;
3343         MonoInst *memcpy_ins = NULL;
3344
3345         g_assert (klass);
3346         if (cfg->gshared)
3347                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3348
3349         /*
3350          * This check breaks with spilled vars... need to handle it during verification anyway.
3351          * g_assert (klass && klass == src->klass && klass == dest->klass);
3352          */
3353
3354         if (mini_is_gsharedvt_klass (klass)) {
3355                 g_assert (!native);
3356                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3357                 memcpy_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3358         }
3359
3360         if (native)
3361                 n = mono_class_native_size (klass, &align);
3362         else
3363                 n = mono_class_value_size (klass, &align);
3364
3365         /* if native is true there should be no references in the struct */
3366         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3367                 /* Avoid barriers when storing to the stack */
3368                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3369                           (dest->opcode == OP_LDADDR))) {
3370                         int context_used;
3371
3372                         iargs [0] = dest;
3373                         iargs [1] = src;
3374
3375                         context_used = mini_class_check_context_used (cfg, klass);
3376
3377                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3378                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mono_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3379                                 return;
3380                         } else if (context_used) {
3381                                 iargs [2] = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3382                         }  else {
3383                                 iargs [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3384                                 if (!cfg->compile_aot)
3385                                         mono_class_compute_gc_descriptor (klass);
3386                         }
3387
3388                         if (size_ins)
3389                                 mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3390                         else
3391                                 mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3392                         return;
3393                 }
3394         }
3395
3396         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3397                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3398                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3399         } else {
3400                 iargs [0] = dest;
3401                 iargs [1] = src;
3402                 if (size_ins)
3403                         iargs [2] = size_ins;
3404                 else
3405                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3406                 
3407                 memcpy_method = get_memcpy_method ();
3408                 if (memcpy_ins)
3409                         mono_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3410                 else
3411                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3412         }
3413 }
3414
3415 static MonoMethod*
3416 get_memset_method (void)
3417 {
3418         static MonoMethod *memset_method = NULL;
3419         if (!memset_method) {
3420                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3421                 if (!memset_method)
3422                         g_error ("Old corlib found. Install a new one");
3423         }
3424         return memset_method;
3425 }
3426
3427 void
3428 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3429 {
3430         MonoInst *iargs [3];
3431         int n;
3432         guint32 align;
3433         MonoMethod *memset_method;
3434         MonoInst *size_ins = NULL;
3435         MonoInst *bzero_ins = NULL;
3436         static MonoMethod *bzero_method;
3437
3438         /* FIXME: Optimize this for the case when dest is an LDADDR */
3439         mono_class_init (klass);
3440         if (mini_is_gsharedvt_klass (klass)) {
3441                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3442                 bzero_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3443                 if (!bzero_method)
3444                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3445                 g_assert (bzero_method);
3446                 iargs [0] = dest;
3447                 iargs [1] = size_ins;
3448                 mono_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3449                 return;
3450         }
3451
3452         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3453
3454         n = mono_class_value_size (klass, &align);
3455
3456         if (n <= sizeof (gpointer) * 8) {
3457                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3458         }
3459         else {
3460                 memset_method = get_memset_method ();
3461                 iargs [0] = dest;
3462                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3463                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3464                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3465         }
3466 }
3467
3468 /*
3469  * emit_get_rgctx:
3470  *
3471  *   Emit IR to return either the this pointer for instance method,
3472  * or the mrgctx for static methods.
3473  */
3474 static MonoInst*
3475 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3476 {
3477         MonoInst *this_ins = NULL;
3478
3479         g_assert (cfg->gshared);
3480
3481         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3482                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3483                         !method->klass->valuetype)
3484                 EMIT_NEW_ARGLOAD (cfg, this_ins, 0);
3485
3486         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3487                 MonoInst *mrgctx_loc, *mrgctx_var;
3488
3489                 g_assert (!this_ins);
3490                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3491
3492                 mrgctx_loc = mono_get_vtable_var (cfg);
3493                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3494
3495                 return mrgctx_var;
3496         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3497                 MonoInst *vtable_loc, *vtable_var;
3498
3499                 g_assert (!this_ins);
3500
3501                 vtable_loc = mono_get_vtable_var (cfg);
3502                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3503
3504                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3505                         MonoInst *mrgctx_var = vtable_var;
3506                         int vtable_reg;
3507
3508                         vtable_reg = alloc_preg (cfg);
3509                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3510                         vtable_var->type = STACK_PTR;
3511                 }
3512
3513                 return vtable_var;
3514         } else {
3515                 MonoInst *ins;
3516                 int vtable_reg;
3517         
3518                 vtable_reg = alloc_preg (cfg);
3519                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3520                 return ins;
3521         }
3522 }
3523
3524 static MonoJumpInfoRgctxEntry *
3525 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3526 {
3527         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3528         res->method = method;
3529         res->in_mrgctx = in_mrgctx;
3530         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3531         res->data->type = patch_type;
3532         res->data->data.target = patch_data;
3533         res->info_type = info_type;
3534
3535         return res;
3536 }
3537
3538 static inline MonoInst*
3539 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3540 {
3541         MonoInst *args [16];
3542         MonoInst *call;
3543
3544         // FIXME: No fastpath since the slot is not a compile time constant
3545         args [0] = rgctx;
3546         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3547         if (entry->in_mrgctx)
3548                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3549         else
3550                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3551         return call;
3552 #if 0
3553         /*
3554          * FIXME: This can be called during decompose, which is a problem since it creates
3555          * new bblocks.
3556          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3557          */
3558         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3559         gboolean mrgctx;
3560         MonoBasicBlock *is_null_bb, *end_bb;
3561         MonoInst *res, *ins, *call;
3562         MonoInst *args[16];
3563
3564         slot = mini_get_rgctx_entry_slot (entry);
3565
3566         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3567         index = MONO_RGCTX_SLOT_INDEX (slot);
3568         if (mrgctx)
3569                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3570         for (depth = 0; ; ++depth) {
3571                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3572
3573                 if (index < size - 1)
3574                         break;
3575                 index -= size - 1;
3576         }
3577
3578         NEW_BBLOCK (cfg, end_bb);
3579         NEW_BBLOCK (cfg, is_null_bb);
3580
3581         if (mrgctx) {
3582                 rgctx_reg = rgctx->dreg;
3583         } else {
3584                 rgctx_reg = alloc_preg (cfg);
3585
3586                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3587                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3588                 NEW_BBLOCK (cfg, is_null_bb);
3589
3590                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3591                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3592         }
3593
3594         for (i = 0; i < depth; ++i) {
3595                 int array_reg = alloc_preg (cfg);
3596
3597                 /* load ptr to next array */
3598                 if (mrgctx && i == 0)
3599                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3600                 else
3601                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3602                 rgctx_reg = array_reg;
3603                 /* is the ptr null? */
3604                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3605                 /* if yes, jump to actual trampoline */
3606                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3607         }
3608
3609         /* fetch slot */
3610         val_reg = alloc_preg (cfg);
3611         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3612         /* is the slot null? */
3613         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3614         /* if yes, jump to actual trampoline */
3615         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3616
3617         /* Fastpath */
3618         res_reg = alloc_preg (cfg);
3619         MONO_INST_NEW (cfg, ins, OP_MOVE);
3620         ins->dreg = res_reg;
3621         ins->sreg1 = val_reg;
3622         MONO_ADD_INS (cfg->cbb, ins);
3623         res = ins;
3624         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3625
3626         /* Slowpath */
3627         MONO_START_BB (cfg, is_null_bb);
3628         args [0] = rgctx;
3629         EMIT_NEW_ICONST (cfg, args [1], index);
3630         if (mrgctx)
3631                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3632         else
3633                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3634         MONO_INST_NEW (cfg, ins, OP_MOVE);
3635         ins->dreg = res_reg;
3636         ins->sreg1 = call->dreg;
3637         MONO_ADD_INS (cfg->cbb, ins);
3638         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3639
3640         MONO_START_BB (cfg, end_bb);
3641
3642         return res;
3643 #endif
3644 }
3645
3646 /*
3647  * emit_rgctx_fetch:
3648  *
3649  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3650  * given by RGCTX.
3651  */
3652 static inline MonoInst*
3653 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3654 {
3655         if (cfg->llvm_only)
3656                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3657         else
3658                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3659 }
3660
3661 static MonoInst*
3662 emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3663                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3664 {
3665         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3666         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3667
3668         return emit_rgctx_fetch (cfg, rgctx, entry);
3669 }
3670
3671 static MonoInst*
3672 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3673                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3674 {
3675         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3676         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3677
3678         return emit_rgctx_fetch (cfg, rgctx, entry);
3679 }
3680
3681 static MonoInst*
3682 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3683                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3684 {
3685         MonoJumpInfoGSharedVtCall *call_info;
3686         MonoJumpInfoRgctxEntry *entry;
3687         MonoInst *rgctx;
3688
3689         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3690         call_info->sig = sig;
3691         call_info->method = cmethod;
3692
3693         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3694         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3695
3696         return emit_rgctx_fetch (cfg, rgctx, entry);
3697 }
3698
3699 /*
3700  * emit_get_rgctx_virt_method:
3701  *
3702  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3703  */
3704 static MonoInst*
3705 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3706                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3707 {
3708         MonoJumpInfoVirtMethod *info;
3709         MonoJumpInfoRgctxEntry *entry;
3710         MonoInst *rgctx;
3711
3712         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3713         info->klass = klass;
3714         info->method = virt_method;
3715
3716         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3717         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3718
3719         return emit_rgctx_fetch (cfg, rgctx, entry);
3720 }
3721
3722 static MonoInst*
3723 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3724                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3725 {
3726         MonoJumpInfoRgctxEntry *entry;
3727         MonoInst *rgctx;
3728
3729         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3730         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3731
3732         return emit_rgctx_fetch (cfg, rgctx, entry);
3733 }
3734
3735 /*
3736  * emit_get_rgctx_method:
3737  *
3738  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3739  * normal constants, else emit a load from the rgctx.
3740  */
3741 static MonoInst*
3742 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3743                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3744 {
3745         if (!context_used) {
3746                 MonoInst *ins;
3747
3748                 switch (rgctx_type) {
3749                 case MONO_RGCTX_INFO_METHOD:
3750                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3751                         return ins;
3752                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3753                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3754                         return ins;
3755                 default:
3756                         g_assert_not_reached ();
3757                 }
3758         } else {
3759                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3760                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3761
3762                 return emit_rgctx_fetch (cfg, rgctx, entry);
3763         }
3764 }
3765
3766 static MonoInst*
3767 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3768                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3769 {
3770         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3771         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3772
3773         return emit_rgctx_fetch (cfg, rgctx, entry);
3774 }
3775
3776 static int
3777 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3778 {
3779         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3780         MonoRuntimeGenericContextInfoTemplate *template_;
3781         int i, idx;
3782
3783         g_assert (info);
3784
3785         for (i = 0; i < info->num_entries; ++i) {
3786                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3787
3788                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3789                         return i;
3790         }
3791
3792         if (info->num_entries == info->count_entries) {
3793                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3794                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3795
3796                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3797
3798                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3799                 info->entries = new_entries;
3800                 info->count_entries = new_count_entries;
3801         }
3802
3803         idx = info->num_entries;
3804         template_ = &info->entries [idx];
3805         template_->info_type = rgctx_type;
3806         template_->data = data;
3807
3808         info->num_entries ++;
3809
3810         return idx;
3811 }
3812
3813 /*
3814  * emit_get_gsharedvt_info:
3815  *
3816  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3817  */
3818 static MonoInst*
3819 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3820 {
3821         MonoInst *ins;
3822         int idx, dreg;
3823
3824         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3825         /* Load info->entries [idx] */
3826         dreg = alloc_preg (cfg);
3827         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3828
3829         return ins;
3830 }
3831
3832 static MonoInst*
3833 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3834 {
3835         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3836 }
3837
3838 /*
3839  * On return the caller must check @klass for load errors.
3840  */
3841 static void
3842 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3843 {
3844         MonoInst *vtable_arg;
3845         int context_used;
3846
3847         context_used = mini_class_check_context_used (cfg, klass);
3848
3849         if (context_used) {
3850                 vtable_arg = emit_get_rgctx_klass (cfg, context_used,
3851                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3852         } else {
3853                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3854
3855                 if (!vtable)
3856                         return;
3857                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3858         }
3859
3860         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3861                 MonoInst *ins;
3862
3863                 /*
3864                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3865                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3866                  */
3867                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3868                 ins->sreg1 = vtable_arg->dreg;
3869                 MONO_ADD_INS (cfg->cbb, ins);
3870         } else {
3871                 static int byte_offset = -1;
3872                 static guint8 bitmask;
3873                 int bits_reg, inited_reg;
3874                 MonoBasicBlock *inited_bb;
3875                 MonoInst *args [16];
3876
3877                 if (byte_offset < 0)
3878                         mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
3879
3880                 bits_reg = alloc_ireg (cfg);
3881                 inited_reg = alloc_ireg (cfg);
3882
3883                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, bits_reg, vtable_arg->dreg, byte_offset);
3884                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, inited_reg, bits_reg, bitmask);
3885
3886                 NEW_BBLOCK (cfg, inited_bb);
3887
3888                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3889                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3890
3891                 args [0] = vtable_arg;
3892                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3893
3894                 MONO_START_BB (cfg, inited_bb);
3895         }
3896 }
3897
3898 static void
3899 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3900 {
3901         MonoInst *ins;
3902
3903         if (cfg->gen_seq_points && cfg->method == method) {
3904                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3905                 if (nonempty_stack)
3906                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3907                 MONO_ADD_INS (cfg->cbb, ins);
3908         }
3909 }
3910
3911 static void
3912 save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3913 {
3914         if (mini_get_debug_options ()->better_cast_details) {
3915                 int vtable_reg = alloc_preg (cfg);
3916                 int klass_reg = alloc_preg (cfg);
3917                 MonoBasicBlock *is_null_bb = NULL;
3918                 MonoInst *tls_get;
3919                 int to_klass_reg, context_used;
3920
3921                 if (null_check) {
3922                         NEW_BBLOCK (cfg, is_null_bb);
3923
3924                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3925                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3926                 }
3927
3928                 tls_get = mono_get_jit_tls_intrinsic (cfg);
3929                 if (!tls_get) {
3930                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3931                         exit (1);
3932                 }
3933
3934                 MONO_ADD_INS (cfg->cbb, tls_get);
3935                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3936                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3937
3938                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3939
3940                 context_used = mini_class_check_context_used (cfg, klass);
3941                 if (context_used) {
3942                         MonoInst *class_ins;
3943
3944                         class_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3945                         to_klass_reg = class_ins->dreg;
3946                 } else {
3947                         to_klass_reg = alloc_preg (cfg);
3948                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3949                 }
3950                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3951
3952                 if (null_check)
3953                         MONO_START_BB (cfg, is_null_bb);
3954         }
3955 }
3956
3957 static void
3958 reset_cast_details (MonoCompile *cfg)
3959 {
3960         /* Reset the variables holding the cast details */
3961         if (mini_get_debug_options ()->better_cast_details) {
3962                 MonoInst *tls_get = mono_get_jit_tls_intrinsic (cfg);
3963
3964                 MONO_ADD_INS (cfg->cbb, tls_get);
3965                 /* It is enough to reset the from field */
3966                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3967         }
3968 }
3969
3970 /*
3971  * On return the caller must check @array_class for load errors
3972  */
3973 static void
3974 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3975 {
3976         int vtable_reg = alloc_preg (cfg);
3977         int context_used;
3978
3979         context_used = mini_class_check_context_used (cfg, array_class);
3980
3981         save_cast_details (cfg, array_class, obj->dreg, FALSE);
3982
3983         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3984
3985         if (cfg->opt & MONO_OPT_SHARED) {
3986                 int class_reg = alloc_preg (cfg);
3987                 MonoInst *ins;
3988
3989                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3990                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3991                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3992         } else if (context_used) {
3993                 MonoInst *vtable_ins;
3994
3995                 vtable_ins = emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3996                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3997         } else {
3998                 if (cfg->compile_aot) {
3999                         int vt_reg;
4000                         MonoVTable *vtable;
4001
4002                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
4003                                 return;
4004                         vt_reg = alloc_preg (cfg);
4005                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
4006                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
4007                 } else {
4008                         MonoVTable *vtable;
4009                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
4010                                 return;
4011                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
4012                 }
4013         }
4014         
4015         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
4016
4017         reset_cast_details (cfg);
4018 }
4019
4020 /**
4021  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
4022  * generic code is generated.
4023  */
4024 static MonoInst*
4025 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
4026 {
4027         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
4028
4029         if (context_used) {
4030                 MonoInst *rgctx, *addr;
4031
4032                 /* FIXME: What if the class is shared?  We might not
4033                    have to get the address of the method from the
4034                    RGCTX. */
4035                 addr = emit_get_rgctx_method (cfg, context_used, method,
4036                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4037                 if (cfg->llvm_only && cfg->gsharedvt) {
4038                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4039                 } else {
4040                         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
4041
4042                         return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4043                 }
4044         } else {
4045                 gboolean pass_vtable, pass_mrgctx;
4046                 MonoInst *rgctx_arg = NULL;
4047
4048                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4049                 g_assert (!pass_mrgctx);
4050
4051                 if (pass_vtable) {
4052                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4053
4054                         g_assert (vtable);
4055                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4056                 }
4057
4058                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4059         }
4060 }
4061
4062 static MonoInst*
4063 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
4064 {
4065         MonoInst *add;
4066         int obj_reg;
4067         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
4068         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
4069         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
4070         int rank_reg = alloc_dreg (cfg ,STACK_I4);
4071
4072         obj_reg = sp [0]->dreg;
4073         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4074         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
4075
4076         /* FIXME: generics */
4077         g_assert (klass->rank == 0);
4078                         
4079         // Check rank == 0
4080         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
4081         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4082
4083         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4084         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
4085
4086         if (context_used) {
4087                 MonoInst *element_class;
4088
4089                 /* This assertion is from the unboxcast insn */
4090                 g_assert (klass->rank == 0);
4091
4092                 element_class = emit_get_rgctx_klass (cfg, context_used,
4093                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
4094
4095                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
4096                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4097         } else {
4098                 save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
4099                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
4100                 reset_cast_details (cfg);
4101         }
4102
4103         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
4104         MONO_ADD_INS (cfg->cbb, add);
4105         add->type = STACK_MP;
4106         add->klass = klass;
4107
4108         return add;
4109 }
4110
4111 static MonoInst*
4112 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
4113 {
4114         MonoInst *addr, *klass_inst, *is_ref, *args[16];
4115         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4116         MonoInst *ins;
4117         int dreg, addr_reg;
4118
4119         klass_inst = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
4120
4121         /* obj */
4122         args [0] = obj;
4123
4124         /* klass */
4125         args [1] = klass_inst;
4126
4127         /* CASTCLASS */
4128         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
4129
4130         NEW_BBLOCK (cfg, is_ref_bb);
4131         NEW_BBLOCK (cfg, is_nullable_bb);
4132         NEW_BBLOCK (cfg, end_bb);
4133         is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4134         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4135         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4136
4137         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4138         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4139
4140         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
4141         addr_reg = alloc_dreg (cfg, STACK_MP);
4142
4143         /* Non-ref case */
4144         /* UNBOX */
4145         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
4146         MONO_ADD_INS (cfg->cbb, addr);
4147
4148         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4149
4150         /* Ref case */
4151         MONO_START_BB (cfg, is_ref_bb);
4152
4153         /* Save the ref to a temporary */
4154         dreg = alloc_ireg (cfg);
4155         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
4156         addr->dreg = addr_reg;
4157         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
4158         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4159
4160         /* Nullable case */
4161         MONO_START_BB (cfg, is_nullable_bb);
4162
4163         {
4164                 MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
4165                 MonoInst *unbox_call;
4166                 MonoMethodSignature *unbox_sig;
4167
4168                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4169                 unbox_sig->ret = &klass->byval_arg;
4170                 unbox_sig->param_count = 1;
4171                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
4172
4173                 if (cfg->llvm_only)
4174                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
4175                 else
4176                         unbox_call = mono_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
4177
4178                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
4179                 addr->dreg = addr_reg;
4180         }
4181
4182         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4183
4184         /* End */
4185         MONO_START_BB (cfg, end_bb);
4186
4187         /* LDOBJ */
4188         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
4189
4190         return ins;
4191 }
4192
4193 /*
4194  * Returns NULL and set the cfg exception on error.
4195  */
4196 static MonoInst*
4197 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
4198 {
4199         MonoInst *iargs [2];
4200         void *alloc_ftn;
4201
4202         if (context_used) {
4203                 MonoInst *data;
4204                 MonoRgctxInfoType rgctx_info;
4205                 MonoInst *iargs [2];
4206                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
4207
4208                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
4209
4210                 if (cfg->opt & MONO_OPT_SHARED)
4211                         rgctx_info = MONO_RGCTX_INFO_KLASS;
4212                 else
4213                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
4214                 data = emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
4215
4216                 if (cfg->opt & MONO_OPT_SHARED) {
4217                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4218                         iargs [1] = data;
4219                         alloc_ftn = ves_icall_object_new;
4220                 } else {
4221                         iargs [0] = data;
4222                         alloc_ftn = ves_icall_object_new_specific;
4223                 }
4224
4225                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
4226                         if (known_instance_size) {
4227                                 int size = mono_class_instance_size (klass);
4228                                 if (size < sizeof (MonoObject))
4229                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4230
4231                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
4232                         }
4233                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4234                 }
4235
4236                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4237         }
4238
4239         if (cfg->opt & MONO_OPT_SHARED) {
4240                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4241                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
4242
4243                 alloc_ftn = ves_icall_object_new;
4244         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !klass->generic_class) {
4245                 /* This happens often in argument checking code, eg. throw new FooException... */
4246                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
4247                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
4248                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
4249         } else {
4250                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4251                 MonoMethod *managed_alloc = NULL;
4252                 gboolean pass_lw;
4253
4254                 if (!vtable) {
4255                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4256                         cfg->exception_ptr = klass;
4257                         return NULL;
4258                 }
4259
4260                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
4261
4262                 if (managed_alloc) {
4263                         int size = mono_class_instance_size (klass);
4264                         if (size < sizeof (MonoObject))
4265                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4266
4267                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4268                         EMIT_NEW_ICONST (cfg, iargs [1], size);
4269                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4270                 }
4271                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
4272                 if (pass_lw) {
4273                         guint32 lw = vtable->klass->instance_size;
4274                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
4275                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
4276                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
4277                 }
4278                 else {
4279                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4280                 }
4281         }
4282
4283         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4284 }
4285         
4286 /*
4287  * Returns NULL and set the cfg exception on error.
4288  */     
4289 static MonoInst*
4290 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
4291 {
4292         MonoInst *alloc, *ins;
4293
4294         if (mono_class_is_nullable (klass)) {
4295                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4296
4297                 if (context_used) {
4298                         if (cfg->llvm_only && cfg->gsharedvt) {
4299                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4300                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4301                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4302                         } else {
4303                                 /* FIXME: What if the class is shared?  We might not
4304                                    have to get the method address from the RGCTX. */
4305                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4306                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4307                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
4308
4309                                 return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4310                         }
4311                 } else {
4312                         gboolean pass_vtable, pass_mrgctx;
4313                         MonoInst *rgctx_arg = NULL;
4314
4315                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4316                         g_assert (!pass_mrgctx);
4317
4318                         if (pass_vtable) {
4319                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4320
4321                                 g_assert (vtable);
4322                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4323                         }
4324
4325                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4326                 }
4327         }
4328
4329         if (mini_is_gsharedvt_klass (klass)) {
4330                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4331                 MonoInst *res, *is_ref, *src_var, *addr;
4332                 int dreg;
4333
4334                 dreg = alloc_ireg (cfg);
4335
4336                 NEW_BBLOCK (cfg, is_ref_bb);
4337                 NEW_BBLOCK (cfg, is_nullable_bb);
4338                 NEW_BBLOCK (cfg, end_bb);
4339                 is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4340                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4341                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4342
4343                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4344                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4345
4346                 /* Non-ref case */
4347                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4348                 if (!alloc)
4349                         return NULL;
4350                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4351                 ins->opcode = OP_STOREV_MEMBASE;
4352
4353                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4354                 res->type = STACK_OBJ;
4355                 res->klass = klass;
4356                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4357                 
4358                 /* Ref case */
4359                 MONO_START_BB (cfg, is_ref_bb);
4360
4361                 /* val is a vtype, so has to load the value manually */
4362                 src_var = get_vreg_to_inst (cfg, val->dreg);
4363                 if (!src_var)
4364                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4365                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4366                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4367                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4368
4369                 /* Nullable case */
4370                 MONO_START_BB (cfg, is_nullable_bb);
4371
4372                 {
4373                         MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass,
4374                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4375                         MonoInst *box_call;
4376                         MonoMethodSignature *box_sig;
4377
4378                         /*
4379                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4380                          * construct that method at JIT time, so have to do things by hand.
4381                          */
4382                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4383                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4384                         box_sig->param_count = 1;
4385                         box_sig->params [0] = &klass->byval_arg;
4386
4387                         if (cfg->llvm_only)
4388                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4389                         else
4390                                 box_call = mono_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4391                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4392                         res->type = STACK_OBJ;
4393                         res->klass = klass;
4394                 }
4395
4396                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4397
4398                 MONO_START_BB (cfg, end_bb);
4399
4400                 return res;
4401         } else {
4402                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4403                 if (!alloc)
4404                         return NULL;
4405
4406                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4407                 return alloc;
4408         }
4409 }
4410
4411 static gboolean
4412 mini_class_has_reference_variant_generic_argument (MonoCompile *cfg, MonoClass *klass, int context_used)
4413 {
4414         int i;
4415         MonoGenericContainer *container;
4416         MonoGenericInst *ginst;
4417
4418         if (klass->generic_class) {
4419                 container = klass->generic_class->container_class->generic_container;
4420                 ginst = klass->generic_class->context.class_inst;
4421         } else if (klass->generic_container && context_used) {
4422                 container = klass->generic_container;
4423                 ginst = container->context.class_inst;
4424         } else {
4425                 return FALSE;
4426         }
4427
4428         for (i = 0; i < container->type_argc; ++i) {
4429                 MonoType *type;
4430                 if (!(mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT)))
4431                         continue;
4432                 type = ginst->type_argv [i];
4433                 if (mini_type_is_reference (type))
4434                         return TRUE;
4435         }
4436         return FALSE;
4437 }
4438
4439 static GHashTable* direct_icall_type_hash;
4440
4441 static gboolean
4442 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4443 {
4444         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4445         if (!direct_icalls_enabled (cfg))
4446                 return FALSE;
4447
4448         /*
4449          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4450          * Whitelist a few icalls for now.
4451          */
4452         if (!direct_icall_type_hash) {
4453                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4454
4455                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4456                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4457                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4458                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4459                 mono_memory_barrier ();
4460                 direct_icall_type_hash = h;
4461         }
4462
4463         if (cmethod->klass == mono_defaults.math_class)
4464                 return TRUE;
4465         /* No locking needed */
4466         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4467                 return TRUE;
4468         return FALSE;
4469 }
4470
4471 #define is_complex_isinst(klass) ((klass->flags & TYPE_ATTRIBUTE_INTERFACE) || klass->rank || mono_class_is_nullable (klass) || mono_class_is_marshalbyref (klass) || (klass->flags & TYPE_ATTRIBUTE_SEALED) || klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR)
4472
4473 static MonoInst*
4474 emit_castclass_with_cache (MonoCompile *cfg, MonoClass *klass, MonoInst **args)
4475 {
4476         MonoMethod *mono_castclass;
4477         MonoInst *res;
4478
4479         mono_castclass = mono_marshal_get_castclass_with_cache ();
4480
4481         save_cast_details (cfg, klass, args [0]->dreg, TRUE);
4482         res = mono_emit_method_call (cfg, mono_castclass, args, NULL);
4483         reset_cast_details (cfg);
4484
4485         return res;
4486 }
4487
4488 static int
4489 get_castclass_cache_idx (MonoCompile *cfg)
4490 {
4491         /* Each CASTCLASS_CACHE patch needs a unique index which identifies the call site */
4492         cfg->castclass_cache_index ++;
4493         return (cfg->method_index << 16) | cfg->castclass_cache_index;
4494 }
4495
4496 static MonoInst*
4497 emit_castclass_with_cache_nonshared (MonoCompile *cfg, MonoInst *obj, MonoClass *klass)
4498 {
4499         MonoInst *args [3];
4500         int idx;
4501
4502         /* obj */
4503         args [0] = obj;
4504
4505         /* klass */
4506         EMIT_NEW_CLASSCONST (cfg, args [1], klass);
4507
4508         /* inline cache*/
4509         idx = get_castclass_cache_idx (cfg);
4510         args [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CASTCLASS_CACHE, GINT_TO_POINTER (idx));
4511
4512         /*The wrapper doesn't inline well so the bloat of inlining doesn't pay off.*/
4513         return emit_castclass_with_cache (cfg, klass, args);
4514 }
4515
4516 /*
4517  * Returns NULL and set the cfg exception on error.
4518  */
4519 static MonoInst*
4520 handle_castclass (MonoCompile *cfg, MonoClass *klass, MonoInst *src, guint8 *ip, int *inline_costs)
4521 {
4522         MonoBasicBlock *is_null_bb;
4523         int obj_reg = src->dreg;
4524         int vtable_reg = alloc_preg (cfg);
4525         int context_used;
4526         MonoInst *klass_inst = NULL, *res;
4527
4528         if (src->opcode == OP_PCONST && src->inst_p0 == 0)
4529                 return src;
4530
4531         context_used = mini_class_check_context_used (cfg, klass);
4532
4533         if (!context_used && mini_class_has_reference_variant_generic_argument (cfg, klass, context_used)) {
4534                 res = emit_castclass_with_cache_nonshared (cfg, src, klass);
4535                 (*inline_costs) += 2;
4536                 return res;
4537         } else if (!context_used && (mono_class_is_marshalbyref (klass) || klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
4538                 MonoMethod *mono_castclass;
4539                 MonoInst *iargs [1];
4540                 int costs;
4541
4542                 mono_castclass = mono_marshal_get_castclass (klass); 
4543                 iargs [0] = src;
4544                                 
4545                 save_cast_details (cfg, klass, src->dreg, TRUE);
4546                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), 
4547                                                            iargs, ip, cfg->real_offset, TRUE);
4548                 reset_cast_details (cfg);
4549                 CHECK_CFG_EXCEPTION;
4550                 g_assert (costs > 0);
4551                                 
4552                 cfg->real_offset += 5;
4553
4554                 (*inline_costs) += costs;
4555
4556                 return src;
4557         }
4558
4559         if (context_used) {
4560                 MonoInst *args [3];
4561
4562                 if (mini_class_has_reference_variant_generic_argument (cfg, klass, context_used) || is_complex_isinst (klass)) {
4563                         MonoInst *cache_ins;
4564
4565                         cache_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_CAST_CACHE);
4566
4567                         /* obj */
4568                         args [0] = src;
4569
4570                         /* klass - it's the second element of the cache entry*/
4571                         EMIT_NEW_LOAD_MEMBASE (cfg, args [1], OP_LOAD_MEMBASE, alloc_preg (cfg), cache_ins->dreg, sizeof (gpointer));
4572
4573                         /* cache */
4574                         args [2] = cache_ins;
4575
4576                         return emit_castclass_with_cache (cfg, klass, args);
4577                 }
4578
4579                 klass_inst = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
4580         }
4581
4582         NEW_BBLOCK (cfg, is_null_bb);
4583
4584         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4585         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
4586
4587         save_cast_details (cfg, klass, obj_reg, FALSE);
4588
4589         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4590                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4591                 mini_emit_iface_cast (cfg, vtable_reg, klass, NULL, NULL);
4592         } else {
4593                 int klass_reg = alloc_preg (cfg);
4594
4595                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4596
4597                 if (!klass->rank && !cfg->compile_aot && !(cfg->opt & MONO_OPT_SHARED) && (klass->flags & TYPE_ATTRIBUTE_SEALED)) {
4598                         /* the remoting code is broken, access the class for now */
4599                         if (0) { /*FIXME what exactly is broken? This change refers to r39380 from 2005 and mention some remoting fixes were due.*/
4600                                 MonoVTable *vt = mono_class_vtable (cfg->domain, klass);
4601                                 if (!vt) {
4602                                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4603                                         cfg->exception_ptr = klass;
4604                                         return NULL;
4605                                 }
4606                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vt);
4607                         } else {
4608                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4609                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
4610                         }
4611                         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4612                 } else {
4613                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4614                         mini_emit_castclass_inst (cfg, obj_reg, klass_reg, klass, klass_inst, is_null_bb);
4615                 }
4616         }
4617
4618         MONO_START_BB (cfg, is_null_bb);
4619
4620         reset_cast_details (cfg);
4621
4622         return src;
4623
4624 exception_exit:
4625         return NULL;
4626 }
4627
4628 /*
4629  * Returns NULL and set the cfg exception on error.
4630  */
4631 static MonoInst*
4632 handle_isinst (MonoCompile *cfg, MonoClass *klass, MonoInst *src, int context_used)
4633 {
4634         MonoInst *ins;
4635         MonoBasicBlock *is_null_bb, *false_bb, *end_bb;
4636         int obj_reg = src->dreg;
4637         int vtable_reg = alloc_preg (cfg);
4638         int res_reg = alloc_ireg_ref (cfg);
4639         MonoInst *klass_inst = NULL;
4640
4641         if (context_used) {
4642                 MonoInst *args [3];
4643
4644                 if(mini_class_has_reference_variant_generic_argument (cfg, klass, context_used) || is_complex_isinst (klass)) {
4645                         MonoMethod *mono_isinst = mono_marshal_get_isinst_with_cache ();
4646                         MonoInst *cache_ins;
4647
4648                         cache_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_CAST_CACHE);
4649
4650                         /* obj */
4651                         args [0] = src;
4652
4653                         /* klass - it's the second element of the cache entry*/
4654                         EMIT_NEW_LOAD_MEMBASE (cfg, args [1], OP_LOAD_MEMBASE, alloc_preg (cfg), cache_ins->dreg, sizeof (gpointer));
4655
4656                         /* cache */
4657                         args [2] = cache_ins;
4658
4659                         return mono_emit_method_call (cfg, mono_isinst, args, NULL);
4660                 }
4661
4662                 klass_inst = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
4663         }
4664
4665         NEW_BBLOCK (cfg, is_null_bb);
4666         NEW_BBLOCK (cfg, false_bb);
4667         NEW_BBLOCK (cfg, end_bb);
4668
4669         /* Do the assignment at the beginning, so the other assignment can be if converted */
4670         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, res_reg, obj_reg);
4671         ins->type = STACK_OBJ;
4672         ins->klass = klass;
4673
4674         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4675         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_null_bb);
4676
4677         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4678
4679         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4680                 g_assert (!context_used);
4681                 /* the is_null_bb target simply copies the input register to the output */
4682                 mini_emit_iface_cast (cfg, vtable_reg, klass, false_bb, is_null_bb);
4683         } else {
4684                 int klass_reg = alloc_preg (cfg);
4685
4686                 if (klass->rank) {
4687                         int rank_reg = alloc_preg (cfg);
4688                         int eclass_reg = alloc_preg (cfg);
4689
4690                         g_assert (!context_used);
4691                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
4692                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, klass->rank);
4693                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4694                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4695                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, cast_class));
4696                         if (klass->cast_class == mono_defaults.object_class) {
4697                                 int parent_reg = alloc_preg (cfg);
4698                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, parent_reg, eclass_reg, MONO_STRUCT_OFFSET (MonoClass, parent));
4699                                 mini_emit_class_check_branch (cfg, parent_reg, mono_defaults.enum_class->parent, OP_PBNE_UN, is_null_bb);
4700                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);
4701                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4702                         } else if (klass->cast_class == mono_defaults.enum_class->parent) {
4703                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class->parent, OP_PBEQ, is_null_bb);
4704                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);                          
4705                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4706                         } else if (klass->cast_class == mono_defaults.enum_class) {
4707                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);
4708                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4709                         } else if (klass->cast_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
4710                                 mini_emit_iface_class_cast (cfg, eclass_reg, klass->cast_class, false_bb, is_null_bb);
4711                         } else {
4712                                 if ((klass->rank == 1) && (klass->byval_arg.type == MONO_TYPE_SZARRAY)) {
4713                                         /* Check that the object is a vector too */
4714                                         int bounds_reg = alloc_preg (cfg);
4715                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, obj_reg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4716                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
4717                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4718                                 }
4719
4720                                 /* the is_null_bb target simply copies the input register to the output */
4721                                 mini_emit_isninst_cast (cfg, eclass_reg, klass->cast_class, false_bb, is_null_bb);
4722                         }
4723                 } else if (mono_class_is_nullable (klass)) {
4724                         g_assert (!context_used);
4725                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4726                         /* the is_null_bb target simply copies the input register to the output */
4727                         mini_emit_isninst_cast (cfg, klass_reg, klass->cast_class, false_bb, is_null_bb);
4728                 } else {
4729                         if (!cfg->compile_aot && !(cfg->opt & MONO_OPT_SHARED) && (klass->flags & TYPE_ATTRIBUTE_SEALED)) {
4730                                 g_assert (!context_used);
4731                                 /* the remoting code is broken, access the class for now */
4732                                 if (0) {/*FIXME what exactly is broken? This change refers to r39380 from 2005 and mention some remoting fixes were due.*/
4733                                         MonoVTable *vt = mono_class_vtable (cfg->domain, klass);
4734                                         if (!vt) {
4735                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4736                                                 cfg->exception_ptr = klass;
4737                                                 return NULL;
4738                                         }
4739                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vt);
4740                                 } else {
4741                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4742                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
4743                                 }
4744                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4745                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, is_null_bb);
4746                         } else {
4747                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4748                                 /* the is_null_bb target simply copies the input register to the output */
4749                                 mini_emit_isninst_cast_inst (cfg, klass_reg, klass, klass_inst, false_bb, is_null_bb);
4750                         }
4751                 }
4752         }
4753
4754         MONO_START_BB (cfg, false_bb);
4755
4756         MONO_EMIT_NEW_PCONST (cfg, res_reg, 0);
4757         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4758
4759         MONO_START_BB (cfg, is_null_bb);
4760
4761         MONO_START_BB (cfg, end_bb);
4762
4763         return ins;
4764 }
4765
4766 static MonoInst*
4767 handle_cisinst (MonoCompile *cfg, MonoClass *klass, MonoInst *src)
4768 {
4769         /* This opcode takes as input an object reference and a class, and returns:
4770         0) if the object is an instance of the class,
4771         1) if the object is not instance of the class,
4772         2) if the object is a proxy whose type cannot be determined */
4773
4774         MonoInst *ins;
4775 #ifndef DISABLE_REMOTING
4776         MonoBasicBlock *true_bb, *false_bb, *false2_bb, *end_bb, *no_proxy_bb, *interface_fail_bb;
4777 #else
4778         MonoBasicBlock *true_bb, *false_bb, *end_bb;
4779 #endif
4780         int obj_reg = src->dreg;
4781         int dreg = alloc_ireg (cfg);
4782         int tmp_reg;
4783 #ifndef DISABLE_REMOTING
4784         int klass_reg = alloc_preg (cfg);
4785 #endif
4786
4787         NEW_BBLOCK (cfg, true_bb);
4788         NEW_BBLOCK (cfg, false_bb);
4789         NEW_BBLOCK (cfg, end_bb);
4790 #ifndef DISABLE_REMOTING
4791         NEW_BBLOCK (cfg, false2_bb);
4792         NEW_BBLOCK (cfg, no_proxy_bb);
4793 #endif
4794
4795         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4796         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, false_bb);
4797
4798         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4799 #ifndef DISABLE_REMOTING
4800                 NEW_BBLOCK (cfg, interface_fail_bb);
4801 #endif
4802
4803                 tmp_reg = alloc_preg (cfg);
4804                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4805 #ifndef DISABLE_REMOTING
4806                 mini_emit_iface_cast (cfg, tmp_reg, klass, interface_fail_bb, true_bb);
4807                 MONO_START_BB (cfg, interface_fail_bb);
4808                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4809                 
4810                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, false_bb);
4811
4812                 tmp_reg = alloc_preg (cfg);
4813                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4814                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4815                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false2_bb);                
4816 #else
4817                 mini_emit_iface_cast (cfg, tmp_reg, klass, false_bb, true_bb);
4818 #endif
4819         } else {
4820 #ifndef DISABLE_REMOTING
4821                 tmp_reg = alloc_preg (cfg);
4822                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4823                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4824
4825                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, no_proxy_bb);          
4826                 tmp_reg = alloc_preg (cfg);
4827                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
4828                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
4829
4830                 tmp_reg = alloc_preg (cfg);             
4831                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4832                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4833                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, no_proxy_bb);
4834                 
4835                 mini_emit_isninst_cast (cfg, klass_reg, klass, false2_bb, true_bb);
4836                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false2_bb);
4837
4838                 MONO_START_BB (cfg, no_proxy_bb);
4839
4840                 mini_emit_isninst_cast (cfg, klass_reg, klass, false_bb, true_bb);
4841 #else
4842                 g_error ("transparent proxy support is disabled while trying to JIT code that uses it");
4843 #endif
4844         }
4845
4846         MONO_START_BB (cfg, false_bb);
4847
4848         MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4849         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4850
4851 #ifndef DISABLE_REMOTING
4852         MONO_START_BB (cfg, false2_bb);
4853
4854         MONO_EMIT_NEW_ICONST (cfg, dreg, 2);
4855         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4856 #endif
4857
4858         MONO_START_BB (cfg, true_bb);
4859
4860         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4861
4862         MONO_START_BB (cfg, end_bb);
4863
4864         /* FIXME: */
4865         MONO_INST_NEW (cfg, ins, OP_ICONST);
4866         ins->dreg = dreg;
4867         ins->type = STACK_I4;
4868
4869         return ins;
4870 }
4871
4872 static MonoInst*
4873 handle_ccastclass (MonoCompile *cfg, MonoClass *klass, MonoInst *src)
4874 {
4875         /* This opcode takes as input an object reference and a class, and returns:
4876         0) if the object is an instance of the class,
4877         1) if the object is a proxy whose type cannot be determined
4878         an InvalidCastException exception is thrown otherwhise*/
4879         
4880         MonoInst *ins;
4881 #ifndef DISABLE_REMOTING
4882         MonoBasicBlock *end_bb, *ok_result_bb, *no_proxy_bb, *interface_fail_bb, *fail_1_bb;
4883 #else
4884         MonoBasicBlock *ok_result_bb;
4885 #endif
4886         int obj_reg = src->dreg;
4887         int dreg = alloc_ireg (cfg);
4888         int tmp_reg = alloc_preg (cfg);
4889
4890 #ifndef DISABLE_REMOTING
4891         int klass_reg = alloc_preg (cfg);
4892         NEW_BBLOCK (cfg, end_bb);
4893 #endif
4894
4895         NEW_BBLOCK (cfg, ok_result_bb);
4896
4897         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4898         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, ok_result_bb);
4899
4900         save_cast_details (cfg, klass, obj_reg, FALSE);
4901
4902         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4903 #ifndef DISABLE_REMOTING
4904                 NEW_BBLOCK (cfg, interface_fail_bb);
4905         
4906                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4907                 mini_emit_iface_cast (cfg, tmp_reg, klass, interface_fail_bb, ok_result_bb);
4908                 MONO_START_BB (cfg, interface_fail_bb);
4909                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4910
4911                 mini_emit_class_check (cfg, klass_reg, mono_defaults.transparent_proxy_class);
4912
4913                 tmp_reg = alloc_preg (cfg);             
4914                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4915                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4916                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");
4917                 
4918                 MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4919                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4920 #else
4921                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4922                 mini_emit_iface_cast (cfg, tmp_reg, klass, NULL, NULL);
4923                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, ok_result_bb);
4924 #endif
4925         } else {
4926 #ifndef DISABLE_REMOTING
4927                 NEW_BBLOCK (cfg, no_proxy_bb);
4928
4929                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4930                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4931                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, no_proxy_bb);          
4932
4933                 tmp_reg = alloc_preg (cfg);
4934                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
4935                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
4936
4937                 tmp_reg = alloc_preg (cfg);
4938                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4939                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4940                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, no_proxy_bb);
4941
4942                 NEW_BBLOCK (cfg, fail_1_bb);
4943                 
4944                 mini_emit_isninst_cast (cfg, klass_reg, klass, fail_1_bb, ok_result_bb);
4945
4946                 MONO_START_BB (cfg, fail_1_bb);
4947
4948                 MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4949                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4950
4951                 MONO_START_BB (cfg, no_proxy_bb);
4952
4953                 mini_emit_castclass (cfg, obj_reg, klass_reg, klass, ok_result_bb);
4954 #else
4955                 g_error ("Transparent proxy support is disabled while trying to JIT code that uses it");
4956 #endif
4957         }
4958
4959         MONO_START_BB (cfg, ok_result_bb);
4960
4961         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4962
4963 #ifndef DISABLE_REMOTING
4964         MONO_START_BB (cfg, end_bb);
4965 #endif
4966
4967         /* FIXME: */
4968         MONO_INST_NEW (cfg, ins, OP_ICONST);
4969         ins->dreg = dreg;
4970         ins->type = STACK_I4;
4971
4972         return ins;
4973 }
4974
4975 static G_GNUC_UNUSED MonoInst*
4976 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4977 {
4978         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4979         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4980         gboolean is_i4;
4981
4982         switch (enum_type->type) {
4983         case MONO_TYPE_I8:
4984         case MONO_TYPE_U8:
4985 #if SIZEOF_REGISTER == 8
4986         case MONO_TYPE_I:
4987         case MONO_TYPE_U:
4988 #endif
4989                 is_i4 = FALSE;
4990                 break;
4991         default:
4992                 is_i4 = TRUE;
4993                 break;
4994         }
4995
4996         {
4997                 MonoInst *load, *and_, *cmp, *ceq;
4998                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4999                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
5000                 int dest_reg = alloc_ireg (cfg);
5001
5002                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
5003                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
5004                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
5005                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
5006
5007                 ceq->type = STACK_I4;
5008
5009                 if (!is_i4) {
5010                         load = mono_decompose_opcode (cfg, load);
5011                         and_ = mono_decompose_opcode (cfg, and_);
5012                         cmp = mono_decompose_opcode (cfg, cmp);
5013                         ceq = mono_decompose_opcode (cfg, ceq);
5014                 }
5015
5016                 return ceq;
5017         }
5018 }
5019
5020 /*
5021  * Returns NULL and set the cfg exception on error.
5022  */
5023 static G_GNUC_UNUSED MonoInst*
5024 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
5025 {
5026         MonoInst *ptr;
5027         int dreg;
5028         gpointer trampoline;
5029         MonoInst *obj, *method_ins, *tramp_ins;
5030         MonoDomain *domain;
5031         guint8 **code_slot;
5032
5033         if (virtual_ && !cfg->llvm_only) {
5034                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
5035                 g_assert (invoke);
5036
5037                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
5038                         return NULL;
5039         }
5040
5041         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
5042         if (!obj)
5043                 return NULL;
5044
5045         /* Inline the contents of mono_delegate_ctor */
5046
5047         /* Set target field */
5048         /* Optimize away setting of NULL target */
5049         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
5050                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
5051                 if (cfg->gen_write_barriers) {
5052                         dreg = alloc_preg (cfg);
5053                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
5054                         emit_write_barrier (cfg, ptr, target);
5055                 }
5056         }
5057
5058         /* Set method field */
5059         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
5060         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
5061
5062         /* 
5063          * To avoid looking up the compiled code belonging to the target method
5064          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
5065          * store it, and we fill it after the method has been compiled.
5066          */
5067         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
5068                 MonoInst *code_slot_ins;
5069
5070                 if (context_used) {
5071                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
5072                 } else {
5073                         domain = mono_domain_get ();
5074                         mono_domain_lock (domain);
5075                         if (!domain_jit_info (domain)->method_code_hash)
5076                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
5077                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
5078                         if (!code_slot) {
5079                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
5080                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
5081                         }
5082                         mono_domain_unlock (domain);
5083
5084                         code_slot_ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
5085                 }
5086                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
5087         }
5088
5089         if (cfg->llvm_only) {
5090                 MonoInst *args [16];
5091
5092                 if (virtual_) {
5093                         args [0] = obj;
5094                         args [1] = target;
5095                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
5096                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
5097                 } else {
5098                         args [0] = obj;
5099                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
5100                 }
5101
5102                 return obj;
5103         }
5104
5105         if (cfg->compile_aot) {
5106                 MonoDelegateClassMethodPair *del_tramp;
5107
5108                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
5109                 del_tramp->klass = klass;
5110                 del_tramp->method = context_used ? NULL : method;
5111                 del_tramp->is_virtual = virtual_;
5112                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
5113         } else {
5114                 if (virtual_)
5115                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
5116                 else
5117                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
5118                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
5119         }
5120
5121         /* Set invoke_impl field */
5122         if (virtual_) {
5123                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
5124         } else {
5125                 dreg = alloc_preg (cfg);
5126                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
5127                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
5128
5129                 dreg = alloc_preg (cfg);
5130                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
5131                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
5132         }
5133
5134         dreg = alloc_preg (cfg);
5135         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
5136         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
5137
5138         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
5139
5140         return obj;
5141 }
5142
5143 static MonoInst*
5144 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
5145 {
5146         MonoJitICallInfo *info;
5147
5148         /* Need to register the icall so it gets an icall wrapper */
5149         info = mono_get_array_new_va_icall (rank);
5150
5151         cfg->flags |= MONO_CFG_HAS_VARARGS;
5152
5153         /* mono_array_new_va () needs a vararg calling convention */
5154         cfg->exception_message = g_strdup ("array-new");
5155         cfg->disable_llvm = TRUE;
5156
5157         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
5158         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
5159 }
5160
5161 /*
5162  * handle_constrained_gsharedvt_call:
5163  *
5164  *   Handle constrained calls where the receiver is a gsharedvt type.
5165  * Return the instruction representing the call. Set the cfg exception on failure.
5166  */
5167 static MonoInst*
5168 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
5169                                                                    gboolean *ref_emit_widen)
5170 {
5171         MonoInst *ins = NULL;
5172         gboolean emit_widen = *ref_emit_widen;
5173
5174         /*
5175          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
5176          * 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
5177          * pack the arguments into an array, and do the rest of the work in in an icall.
5178          */
5179         if (((cmethod->klass == mono_defaults.object_class) || (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
5180                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mini_is_gsharedvt_type (fsig->ret)) &&
5181                 (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]))))) {
5182                 MonoInst *args [16];
5183
5184                 /*
5185                  * This case handles calls to
5186                  * - object:ToString()/Equals()/GetHashCode(),
5187                  * - System.IComparable<T>:CompareTo()
5188                  * - System.IEquatable<T>:Equals ()
5189                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
5190                  */
5191
5192                 args [0] = sp [0];
5193                 if (mono_method_check_context_used (cmethod))
5194                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
5195                 else
5196                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
5197                 args [2] = emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
5198
5199                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
5200                 if (fsig->hasthis && fsig->param_count) {
5201                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
5202                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
5203                         ins->dreg = alloc_preg (cfg);
5204                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
5205                         MONO_ADD_INS (cfg->cbb, ins);
5206                         args [4] = ins;
5207
5208                         if (mini_is_gsharedvt_type (fsig->params [0])) {
5209                                 int addr_reg, deref_arg_reg;
5210
5211                                 ins = emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
5212                                 deref_arg_reg = alloc_preg (cfg);
5213                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
5214                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
5215
5216                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
5217                                 addr_reg = ins->dreg;
5218                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
5219                         } else {
5220                                 EMIT_NEW_ICONST (cfg, args [3], 0);
5221                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
5222                         }
5223                 } else {
5224                         EMIT_NEW_ICONST (cfg, args [3], 0);
5225                         EMIT_NEW_ICONST (cfg, args [4], 0);
5226                 }
5227                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
5228                 emit_widen = FALSE;
5229
5230                 if (mini_is_gsharedvt_type (fsig->ret)) {
5231                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
5232                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret)) {
5233                         MonoInst *add;
5234
5235                         /* Unbox */
5236                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
5237                         MONO_ADD_INS (cfg->cbb, add);
5238                         /* Load value */
5239                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
5240                         MONO_ADD_INS (cfg->cbb, ins);
5241                         /* ins represents the call result */
5242                 }
5243         } else {
5244                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
5245         }
5246
5247         *ref_emit_widen = emit_widen;
5248
5249         return ins;
5250
5251  exception_exit:
5252         return NULL;
5253 }
5254
5255 static void
5256 mono_emit_load_got_addr (MonoCompile *cfg)
5257 {
5258         MonoInst *getaddr, *dummy_use;
5259
5260         if (!cfg->got_var || cfg->got_var_allocated)
5261                 return;
5262
5263         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
5264         getaddr->cil_code = cfg->header->code;
5265         getaddr->dreg = cfg->got_var->dreg;
5266
5267         /* Add it to the start of the first bblock */
5268         if (cfg->bb_entry->code) {
5269                 getaddr->next = cfg->bb_entry->code;
5270                 cfg->bb_entry->code = getaddr;
5271         }
5272         else
5273                 MONO_ADD_INS (cfg->bb_entry, getaddr);
5274
5275         cfg->got_var_allocated = TRUE;
5276
5277         /* 
5278          * Add a dummy use to keep the got_var alive, since real uses might
5279          * only be generated by the back ends.
5280          * Add it to end_bblock, so the variable's lifetime covers the whole
5281          * method.
5282          * It would be better to make the usage of the got var explicit in all
5283          * cases when the backend needs it (i.e. calls, throw etc.), so this
5284          * wouldn't be needed.
5285          */
5286         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
5287         MONO_ADD_INS (cfg->bb_exit, dummy_use);
5288 }
5289
5290 static int inline_limit;
5291 static gboolean inline_limit_inited;
5292
5293 static gboolean
5294 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
5295 {
5296         MonoMethodHeaderSummary header;
5297         MonoVTable *vtable;
5298 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
5299         MonoMethodSignature *sig = mono_method_signature (method);
5300         int i;
5301 #endif
5302
5303         if (cfg->disable_inline)
5304                 return FALSE;
5305         if (cfg->gshared)
5306                 return FALSE;
5307
5308         if (cfg->inline_depth > 10)
5309                 return FALSE;
5310
5311         if (!mono_method_get_header_summary (method, &header))
5312                 return FALSE;
5313
5314         /*runtime, icall and pinvoke are checked by summary call*/
5315         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
5316             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
5317             (mono_class_is_marshalbyref (method->klass)) ||
5318             header.has_clauses)
5319                 return FALSE;
5320
5321         /* also consider num_locals? */
5322         /* Do the size check early to avoid creating vtables */
5323         if (!inline_limit_inited) {
5324                 if (g_getenv ("MONO_INLINELIMIT"))
5325                         inline_limit = atoi (g_getenv ("MONO_INLINELIMIT"));
5326                 else
5327                         inline_limit = INLINE_LENGTH_LIMIT;
5328                 inline_limit_inited = TRUE;
5329         }
5330         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
5331                 return FALSE;
5332
5333         /*
5334          * if we can initialize the class of the method right away, we do,
5335          * otherwise we don't allow inlining if the class needs initialization,
5336          * since it would mean inserting a call to mono_runtime_class_init()
5337          * inside the inlined code
5338          */
5339         if (!(cfg->opt & MONO_OPT_SHARED)) {
5340                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
5341                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
5342                         vtable = mono_class_vtable (cfg->domain, method->klass);
5343                         if (!vtable)
5344                                 return FALSE;
5345                         if (!cfg->compile_aot) {
5346                                 MonoError error;
5347                                 if (!mono_runtime_class_init_full (vtable, &error)) {
5348                                         mono_error_cleanup (&error);
5349                                         return FALSE;
5350                                 }
5351                         }
5352                 } else if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
5353                         if (cfg->run_cctors && method->klass->has_cctor) {
5354                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
5355                                 if (!method->klass->runtime_info)
5356                                         /* No vtable created yet */
5357                                         return FALSE;
5358                                 vtable = mono_class_vtable (cfg->domain, method->klass);
5359                                 if (!vtable)
5360                                         return FALSE;
5361                                 /* This makes so that inline cannot trigger */
5362                                 /* .cctors: too many apps depend on them */
5363                                 /* running with a specific order... */
5364                                 if (! vtable->initialized)
5365                                         return FALSE;
5366                                 MonoError error;
5367                                 if (!mono_runtime_class_init_full (vtable, &error)) {
5368                                         mono_error_cleanup (&error);
5369                                         return FALSE;
5370                                 }
5371                         }
5372                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
5373                         if (!method->klass->runtime_info)
5374                                 /* No vtable created yet */
5375                                 return FALSE;
5376                         vtable = mono_class_vtable (cfg->domain, method->klass);
5377                         if (!vtable)
5378                                 return FALSE;
5379                         if (!vtable->initialized)
5380                                 return FALSE;
5381                 }
5382         } else {
5383                 /* 
5384                  * If we're compiling for shared code
5385                  * the cctor will need to be run at aot method load time, for example,
5386                  * or at the end of the compilation of the inlining method.
5387                  */
5388                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5389                         return FALSE;
5390         }
5391
5392 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
5393         if (mono_arch_is_soft_float ()) {
5394                 /* FIXME: */
5395                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
5396                         return FALSE;
5397                 for (i = 0; i < sig->param_count; ++i)
5398                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
5399                                 return FALSE;
5400         }
5401 #endif
5402
5403         if (g_list_find (cfg->dont_inline, method))
5404                 return FALSE;
5405
5406         return TRUE;
5407 }
5408
5409 static gboolean
5410 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
5411 {
5412         if (!cfg->compile_aot) {
5413                 g_assert (vtable);
5414                 if (vtable->initialized)
5415                         return FALSE;
5416         }
5417
5418         if (klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
5419                 if (cfg->method == method)
5420                         return FALSE;
5421         }
5422
5423         if (!mono_class_needs_cctor_run (klass, method))
5424                 return FALSE;
5425
5426         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
5427                 /* The initialization is already done before the method is called */
5428                 return FALSE;
5429
5430         return TRUE;
5431 }
5432
5433 static MonoInst*
5434 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
5435 {
5436         MonoInst *ins;
5437         guint32 size;
5438         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
5439         int context_used;
5440
5441         if (mini_is_gsharedvt_variable_klass (klass)) {
5442                 size = -1;
5443         } else {
5444                 mono_class_init (klass);
5445                 size = mono_class_array_element_size (klass);
5446         }
5447
5448         mult_reg = alloc_preg (cfg);
5449         array_reg = arr->dreg;
5450         index_reg = index->dreg;
5451
5452 #if SIZEOF_REGISTER == 8
5453         /* The array reg is 64 bits but the index reg is only 32 */
5454         if (COMPILE_LLVM (cfg)) {
5455                 /* Not needed */
5456                 index2_reg = index_reg;
5457         } else {
5458                 index2_reg = alloc_preg (cfg);
5459                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
5460         }
5461 #else
5462         if (index->type == STACK_I8) {
5463                 index2_reg = alloc_preg (cfg);
5464                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
5465         } else {
5466                 index2_reg = index_reg;
5467         }
5468 #endif
5469
5470         if (bcheck)
5471                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
5472
5473 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5474         if (size == 1 || size == 2 || size == 4 || size == 8) {
5475                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
5476
5477                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
5478                 ins->klass = mono_class_get_element_class (klass);
5479                 ins->type = STACK_MP;
5480
5481                 return ins;
5482         }
5483 #endif          
5484
5485         add_reg = alloc_ireg_mp (cfg);
5486
5487         if (size == -1) {
5488                 MonoInst *rgctx_ins;
5489
5490                 /* gsharedvt */
5491                 g_assert (cfg->gshared);
5492                 context_used = mini_class_check_context_used (cfg, klass);
5493                 g_assert (context_used);
5494                 rgctx_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
5495                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
5496         } else {
5497                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
5498         }
5499         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
5500         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
5501         ins->klass = mono_class_get_element_class (klass);
5502         ins->type = STACK_MP;
5503         MONO_ADD_INS (cfg->cbb, ins);
5504
5505         return ins;
5506 }
5507
5508 static MonoInst*
5509 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
5510 {
5511         int bounds_reg = alloc_preg (cfg);
5512         int add_reg = alloc_ireg_mp (cfg);
5513         int mult_reg = alloc_preg (cfg);
5514         int mult2_reg = alloc_preg (cfg);
5515         int low1_reg = alloc_preg (cfg);
5516         int low2_reg = alloc_preg (cfg);
5517         int high1_reg = alloc_preg (cfg);
5518         int high2_reg = alloc_preg (cfg);
5519         int realidx1_reg = alloc_preg (cfg);
5520         int realidx2_reg = alloc_preg (cfg);
5521         int sum_reg = alloc_preg (cfg);
5522         int index1, index2, tmpreg;
5523         MonoInst *ins;
5524         guint32 size;
5525
5526         mono_class_init (klass);
5527         size = mono_class_array_element_size (klass);
5528
5529         index1 = index_ins1->dreg;
5530         index2 = index_ins2->dreg;
5531
5532 #if SIZEOF_REGISTER == 8
5533         /* The array reg is 64 bits but the index reg is only 32 */
5534         if (COMPILE_LLVM (cfg)) {
5535                 /* Not needed */
5536         } else {
5537                 tmpreg = alloc_preg (cfg);
5538                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
5539                 index1 = tmpreg;
5540                 tmpreg = alloc_preg (cfg);
5541                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
5542                 index2 = tmpreg;
5543         }
5544 #else
5545         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
5546         tmpreg = -1;
5547 #endif
5548
5549         /* range checking */
5550         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
5551                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5552
5553         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
5554                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5555         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
5556         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
5557                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5558         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
5559         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
5560
5561         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
5562                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5563         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
5564         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
5565                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5566         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
5567         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
5568
5569         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
5570         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
5571         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
5572         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
5573         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
5574
5575         ins->type = STACK_MP;
5576         ins->klass = klass;
5577         MONO_ADD_INS (cfg->cbb, ins);
5578
5579         return ins;
5580 }
5581
5582 static MonoInst*
5583 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
5584 {
5585         int rank;
5586         MonoInst *addr;
5587         MonoMethod *addr_method;
5588         int element_size;
5589         MonoClass *eclass = cmethod->klass->element_class;
5590
5591         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
5592
5593         if (rank == 1)
5594                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
5595
5596         /* emit_ldelema_2 depends on OP_LMUL */
5597         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
5598                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
5599         }
5600
5601         if (mini_is_gsharedvt_variable_klass (eclass))
5602                 element_size = 0;
5603         else
5604                 element_size = mono_class_array_element_size (eclass);
5605         addr_method = mono_marshal_get_array_address (rank, element_size);
5606         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
5607
5608         return addr;
5609 }
5610
5611 static MonoBreakPolicy
5612 always_insert_breakpoint (MonoMethod *method)
5613 {
5614         return MONO_BREAK_POLICY_ALWAYS;
5615 }
5616
5617 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
5618
5619 /**
5620  * mono_set_break_policy:
5621  * policy_callback: the new callback function
5622  *
5623  * Allow embedders to decide wherther to actually obey breakpoint instructions
5624  * (both break IL instructions and Debugger.Break () method calls), for example
5625  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
5626  * untrusted or semi-trusted code.
5627  *
5628  * @policy_callback will be called every time a break point instruction needs to
5629  * be inserted with the method argument being the method that calls Debugger.Break()
5630  * or has the IL break instruction. The callback should return #MONO_BREAK_POLICY_NEVER
5631  * if it wants the breakpoint to not be effective in the given method.
5632  * #MONO_BREAK_POLICY_ALWAYS is the default.
5633  */
5634 void
5635 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
5636 {
5637         if (policy_callback)
5638                 break_policy_func = policy_callback;
5639         else
5640                 break_policy_func = always_insert_breakpoint;
5641 }
5642
5643 static gboolean
5644 should_insert_brekpoint (MonoMethod *method) {
5645         switch (break_policy_func (method)) {
5646         case MONO_BREAK_POLICY_ALWAYS:
5647                 return TRUE;
5648         case MONO_BREAK_POLICY_NEVER:
5649                 return FALSE;
5650         case MONO_BREAK_POLICY_ON_DBG:
5651                 g_warning ("mdb no longer supported");
5652                 return FALSE;
5653         default:
5654                 g_warning ("Incorrect value returned from break policy callback");
5655                 return FALSE;
5656         }
5657 }
5658
5659 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
5660 static MonoInst*
5661 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5662 {
5663         MonoInst *addr, *store, *load;
5664         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
5665
5666         /* the bounds check is already done by the callers */
5667         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5668         if (is_set) {
5669                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
5670                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
5671                 if (mini_type_is_reference (fsig->params [2]))
5672                         emit_write_barrier (cfg, addr, load);
5673         } else {
5674                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
5675                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
5676         }
5677         return store;
5678 }
5679
5680
5681 static gboolean
5682 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
5683 {
5684         return mini_type_is_reference (&klass->byval_arg);
5685 }
5686
5687 static MonoInst*
5688 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
5689 {
5690         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
5691                 !(sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL)) {
5692                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
5693                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
5694                 MonoInst *iargs [3];
5695
5696                 if (!helper->slot)
5697                         mono_class_setup_vtable (obj_array);
5698                 g_assert (helper->slot);
5699
5700                 if (sp [0]->type != STACK_OBJ)
5701                         return NULL;
5702                 if (sp [2]->type != STACK_OBJ)
5703                         return NULL;
5704
5705                 iargs [2] = sp [2];
5706                 iargs [1] = sp [1];
5707                 iargs [0] = sp [0];
5708
5709                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
5710         } else {
5711                 MonoInst *ins;
5712
5713                 if (mini_is_gsharedvt_variable_klass (klass)) {
5714                         MonoInst *addr;
5715
5716                         // FIXME-VT: OP_ICONST optimization
5717                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
5718                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5719                         ins->opcode = OP_STOREV_MEMBASE;
5720                 } else if (sp [1]->opcode == OP_ICONST) {
5721                         int array_reg = sp [0]->dreg;
5722                         int index_reg = sp [1]->dreg;
5723                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
5724
5725                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
5726                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
5727
5728                         if (safety_checks)
5729                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
5730                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
5731                 } else {
5732                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
5733                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5734                         if (generic_class_is_reference_type (cfg, klass))
5735                                 emit_write_barrier (cfg, addr, sp [2]);
5736                 }
5737                 return ins;
5738         }
5739 }
5740
5741 static MonoInst*
5742 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5743 {
5744         MonoClass *eklass;
5745         
5746         if (is_set)
5747                 eklass = mono_class_from_mono_type (fsig->params [2]);
5748         else
5749                 eklass = mono_class_from_mono_type (fsig->ret);
5750
5751         if (is_set) {
5752                 return emit_array_store (cfg, eklass, args, FALSE);
5753         } else {
5754                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5755                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
5756                 return ins;
5757         }
5758 }
5759
5760 static gboolean
5761 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
5762 {
5763         uint32_t align;
5764         int param_size, return_size;
5765
5766         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
5767         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
5768
5769         if (cfg->verbose_level > 3)
5770                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
5771
5772         //Don't allow mixing reference types with value types
5773         if (param_klass->valuetype != return_klass->valuetype) {
5774                 if (cfg->verbose_level > 3)
5775                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
5776                 return FALSE;
5777         }
5778
5779         if (!param_klass->valuetype) {
5780                 if (cfg->verbose_level > 3)
5781                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
5782                 return TRUE;
5783         }
5784
5785         //That are blitable
5786         if (param_klass->has_references || return_klass->has_references)
5787                 return FALSE;
5788
5789         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
5790         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
5791                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
5792                         if (cfg->verbose_level > 3)
5793                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
5794                 return FALSE;
5795         }
5796
5797         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
5798                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
5799                 if (cfg->verbose_level > 3)
5800                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
5801                 return FALSE;
5802         }
5803
5804         param_size = mono_class_value_size (param_klass, &align);
5805         return_size = mono_class_value_size (return_klass, &align);
5806
5807         //We can do it if sizes match
5808         if (param_size == return_size) {
5809                 if (cfg->verbose_level > 3)
5810                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
5811                 return TRUE;
5812         }
5813
5814         //No simple way to handle struct if sizes don't match
5815         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
5816                 if (cfg->verbose_level > 3)
5817                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
5818                 return FALSE;
5819         }
5820
5821         /*
5822          * Same reg size category.
5823          * A quick note on why we don't require widening here.
5824          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
5825          *
5826          * Since the source value comes from a function argument, the JIT will already have
5827          * the value in a VREG and performed any widening needed before (say, when loading from a field).
5828          */
5829         if (param_size <= 4 && return_size <= 4) {
5830                 if (cfg->verbose_level > 3)
5831                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
5832                 return TRUE;
5833         }
5834
5835         return FALSE;
5836 }
5837
5838 static MonoInst*
5839 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
5840 {
5841         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
5842         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
5843
5844         if (mini_is_gsharedvt_variable_type (fsig->ret))
5845                 return NULL;
5846
5847         //Valuetypes that are semantically equivalent or numbers than can be widened to
5848         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5849                 return args [0];
5850
5851         //Arrays of valuetypes that are semantically equivalent
5852         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5853                 return args [0];
5854
5855         return NULL;
5856 }
5857
5858 static MonoInst*
5859 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5860 {
5861 #ifdef MONO_ARCH_SIMD_INTRINSICS
5862         MonoInst *ins = NULL;
5863
5864         if (cfg->opt & MONO_OPT_SIMD) {
5865                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5866                 if (ins)
5867                         return ins;
5868         }
5869 #endif
5870
5871         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5872 }
5873
5874 static MonoInst*
5875 emit_memory_barrier (MonoCompile *cfg, int kind)
5876 {
5877         MonoInst *ins = NULL;
5878         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5879         MONO_ADD_INS (cfg->cbb, ins);
5880         ins->backend.memory_barrier_kind = kind;
5881
5882         return ins;
5883 }
5884
5885 static MonoInst*
5886 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5887 {
5888         MonoInst *ins = NULL;
5889         int opcode = 0;
5890
5891         /* The LLVM backend supports these intrinsics */
5892         if (cmethod->klass == mono_defaults.math_class) {
5893                 if (strcmp (cmethod->name, "Sin") == 0) {
5894                         opcode = OP_SIN;
5895                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5896                         opcode = OP_COS;
5897                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5898                         opcode = OP_SQRT;
5899                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5900                         opcode = OP_ABS;
5901                 }
5902
5903                 if (opcode && fsig->param_count == 1) {
5904                         MONO_INST_NEW (cfg, ins, opcode);
5905                         ins->type = STACK_R8;
5906                         ins->dreg = mono_alloc_freg (cfg);
5907                         ins->sreg1 = args [0]->dreg;
5908                         MONO_ADD_INS (cfg->cbb, ins);
5909                 }
5910
5911                 opcode = 0;
5912                 if (cfg->opt & MONO_OPT_CMOV) {
5913                         if (strcmp (cmethod->name, "Min") == 0) {
5914                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5915                                         opcode = OP_IMIN;
5916                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5917                                         opcode = OP_IMIN_UN;
5918                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5919                                         opcode = OP_LMIN;
5920                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5921                                         opcode = OP_LMIN_UN;
5922                         } else if (strcmp (cmethod->name, "Max") == 0) {
5923                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5924                                         opcode = OP_IMAX;
5925                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5926                                         opcode = OP_IMAX_UN;
5927                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5928                                         opcode = OP_LMAX;
5929                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5930                                         opcode = OP_LMAX_UN;
5931                         }
5932                 }
5933
5934                 if (opcode && fsig->param_count == 2) {
5935                         MONO_INST_NEW (cfg, ins, opcode);
5936                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5937                         ins->dreg = mono_alloc_ireg (cfg);
5938                         ins->sreg1 = args [0]->dreg;
5939                         ins->sreg2 = args [1]->dreg;
5940                         MONO_ADD_INS (cfg->cbb, ins);
5941                 }
5942         }
5943
5944         return ins;
5945 }
5946
5947 static MonoInst*
5948 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5949 {
5950         if (cmethod->klass == mono_defaults.array_class) {
5951                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5952                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5953                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5954                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5955                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5956                         return emit_array_unsafe_mov (cfg, fsig, args);
5957         }
5958
5959         return NULL;
5960 }
5961
5962 static MonoInst*
5963 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5964 {
5965         MonoInst *ins = NULL;
5966
5967          MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5968
5969         if (cmethod->klass == mono_defaults.string_class) {
5970                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5971                         int dreg = alloc_ireg (cfg);
5972                         int index_reg = alloc_preg (cfg);
5973                         int add_reg = alloc_preg (cfg);
5974
5975 #if SIZEOF_REGISTER == 8
5976                         if (COMPILE_LLVM (cfg)) {
5977                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5978                         } else {
5979                                 /* The array reg is 64 bits but the index reg is only 32 */
5980                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5981                         }
5982 #else
5983                         index_reg = args [1]->dreg;
5984 #endif  
5985                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5986
5987 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5988                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5989                         add_reg = ins->dreg;
5990                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5991                                                                    add_reg, 0);
5992 #else
5993                         int mult_reg = alloc_preg (cfg);
5994                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5995                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5996                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5997                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
5998 #endif
5999                         type_from_op (cfg, ins, NULL, NULL);
6000                         return ins;
6001                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
6002                         int dreg = alloc_ireg (cfg);
6003                         /* Decompose later to allow more optimizations */
6004                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
6005                         ins->type = STACK_I4;
6006                         ins->flags |= MONO_INST_FAULT;
6007                         cfg->cbb->has_array_access = TRUE;
6008                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
6009
6010                         return ins;
6011                 } else 
6012                         return NULL;
6013         } else if (cmethod->klass == mono_defaults.object_class) {
6014                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
6015                         int dreg = alloc_ireg_ref (cfg);
6016                         int vt_reg = alloc_preg (cfg);
6017                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6018                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
6019                         type_from_op (cfg, ins, NULL, NULL);
6020
6021                         return ins;
6022                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
6023                         int dreg = alloc_ireg (cfg);
6024                         int t1 = alloc_ireg (cfg);
6025         
6026                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
6027                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
6028                         ins->type = STACK_I4;
6029
6030                         return ins;
6031                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
6032                         MONO_INST_NEW (cfg, ins, OP_NOP);
6033                         MONO_ADD_INS (cfg->cbb, ins);
6034                         return ins;
6035                 } else
6036                         return NULL;
6037         } else if (cmethod->klass == mono_defaults.array_class) {
6038                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
6039                         return emit_array_generic_access (cfg, fsig, args, FALSE);
6040                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
6041                         return emit_array_generic_access (cfg, fsig, args, TRUE);
6042
6043 #ifndef MONO_BIG_ARRAYS
6044                 /*
6045                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
6046                  * Array methods.
6047                  */
6048                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
6049                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
6050                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
6051                         int dreg = alloc_ireg (cfg);
6052                         int bounds_reg = alloc_ireg_mp (cfg);
6053                         MonoBasicBlock *end_bb, *szarray_bb;
6054                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
6055
6056                         NEW_BBLOCK (cfg, end_bb);
6057                         NEW_BBLOCK (cfg, szarray_bb);
6058
6059                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
6060                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
6061                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
6062                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
6063                         /* Non-szarray case */
6064                         if (get_length)
6065                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6066                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
6067                         else
6068                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6069                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
6070                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6071                         MONO_START_BB (cfg, szarray_bb);
6072                         /* Szarray case */
6073                         if (get_length)
6074                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6075                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
6076                         else
6077                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6078                         MONO_START_BB (cfg, end_bb);
6079
6080                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
6081                         ins->type = STACK_I4;
6082                         
6083                         return ins;
6084                 }
6085 #endif
6086
6087                 if (cmethod->name [0] != 'g')
6088                         return NULL;
6089
6090                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
6091                         int dreg = alloc_ireg (cfg);
6092                         int vtable_reg = alloc_preg (cfg);
6093                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
6094                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6095                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
6096                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
6097                         type_from_op (cfg, ins, NULL, NULL);
6098
6099                         return ins;
6100                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
6101                         int dreg = alloc_ireg (cfg);
6102
6103                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
6104                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
6105                         type_from_op (cfg, ins, NULL, NULL);
6106
6107                         return ins;
6108                 } else
6109                         return NULL;
6110         } else if (cmethod->klass == runtime_helpers_class) {
6111                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
6112                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
6113                         return ins;
6114                 } else
6115                         return NULL;
6116         } else if (cmethod->klass == mono_defaults.monitor_class) {
6117                 gboolean is_enter = FALSE;
6118
6119                 if (!strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1)
6120                         is_enter = TRUE;
6121
6122                 if (is_enter) {
6123                         /*
6124                          * To make async stack traces work, icalls which can block should have a wrapper.
6125                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
6126                          */
6127                         MonoBasicBlock *end_bb;
6128
6129                         NEW_BBLOCK (cfg, end_bb);
6130
6131                         ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter_fast, args);
6132                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
6133                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
6134                         ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter, args);
6135                         MONO_START_BB (cfg, end_bb);
6136                         return ins;
6137                 }
6138         } else if (cmethod->klass == mono_defaults.thread_class) {
6139                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
6140                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
6141                         MONO_ADD_INS (cfg->cbb, ins);
6142                         return ins;
6143                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
6144                         return emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6145                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
6146                         guint32 opcode = 0;
6147                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6148
6149                         if (fsig->params [0]->type == MONO_TYPE_I1)
6150                                 opcode = OP_LOADI1_MEMBASE;
6151                         else if (fsig->params [0]->type == MONO_TYPE_U1)
6152                                 opcode = OP_LOADU1_MEMBASE;
6153                         else if (fsig->params [0]->type == MONO_TYPE_I2)
6154                                 opcode = OP_LOADI2_MEMBASE;
6155                         else if (fsig->params [0]->type == MONO_TYPE_U2)
6156                                 opcode = OP_LOADU2_MEMBASE;
6157                         else if (fsig->params [0]->type == MONO_TYPE_I4)
6158                                 opcode = OP_LOADI4_MEMBASE;
6159                         else if (fsig->params [0]->type == MONO_TYPE_U4)
6160                                 opcode = OP_LOADU4_MEMBASE;
6161                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
6162                                 opcode = OP_LOADI8_MEMBASE;
6163                         else if (fsig->params [0]->type == MONO_TYPE_R4)
6164                                 opcode = OP_LOADR4_MEMBASE;
6165                         else if (fsig->params [0]->type == MONO_TYPE_R8)
6166                                 opcode = OP_LOADR8_MEMBASE;
6167                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
6168                                 opcode = OP_LOAD_MEMBASE;
6169
6170                         if (opcode) {
6171                                 MONO_INST_NEW (cfg, ins, opcode);
6172                                 ins->inst_basereg = args [0]->dreg;
6173                                 ins->inst_offset = 0;
6174                                 MONO_ADD_INS (cfg->cbb, ins);
6175
6176                                 switch (fsig->params [0]->type) {
6177                                 case MONO_TYPE_I1:
6178                                 case MONO_TYPE_U1:
6179                                 case MONO_TYPE_I2:
6180                                 case MONO_TYPE_U2:
6181                                 case MONO_TYPE_I4:
6182                                 case MONO_TYPE_U4:
6183                                         ins->dreg = mono_alloc_ireg (cfg);
6184                                         ins->type = STACK_I4;
6185                                         break;
6186                                 case MONO_TYPE_I8:
6187                                 case MONO_TYPE_U8:
6188                                         ins->dreg = mono_alloc_lreg (cfg);
6189                                         ins->type = STACK_I8;
6190                                         break;
6191                                 case MONO_TYPE_I:
6192                                 case MONO_TYPE_U:
6193                                         ins->dreg = mono_alloc_ireg (cfg);
6194 #if SIZEOF_REGISTER == 8
6195                                         ins->type = STACK_I8;
6196 #else
6197                                         ins->type = STACK_I4;
6198 #endif
6199                                         break;
6200                                 case MONO_TYPE_R4:
6201                                 case MONO_TYPE_R8:
6202                                         ins->dreg = mono_alloc_freg (cfg);
6203                                         ins->type = STACK_R8;
6204                                         break;
6205                                 default:
6206                                         g_assert (mini_type_is_reference (fsig->params [0]));
6207                                         ins->dreg = mono_alloc_ireg_ref (cfg);
6208                                         ins->type = STACK_OBJ;
6209                                         break;
6210                                 }
6211
6212                                 if (opcode == OP_LOADI8_MEMBASE)
6213                                         ins = mono_decompose_opcode (cfg, ins);
6214
6215                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6216
6217                                 return ins;
6218                         }
6219                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
6220                         guint32 opcode = 0;
6221                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6222
6223                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
6224                                 opcode = OP_STOREI1_MEMBASE_REG;
6225                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
6226                                 opcode = OP_STOREI2_MEMBASE_REG;
6227                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
6228                                 opcode = OP_STOREI4_MEMBASE_REG;
6229                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
6230                                 opcode = OP_STOREI8_MEMBASE_REG;
6231                         else if (fsig->params [0]->type == MONO_TYPE_R4)
6232                                 opcode = OP_STORER4_MEMBASE_REG;
6233                         else if (fsig->params [0]->type == MONO_TYPE_R8)
6234                                 opcode = OP_STORER8_MEMBASE_REG;
6235                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
6236                                 opcode = OP_STORE_MEMBASE_REG;
6237
6238                         if (opcode) {
6239                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6240
6241                                 MONO_INST_NEW (cfg, ins, opcode);
6242                                 ins->sreg1 = args [1]->dreg;
6243                                 ins->inst_destbasereg = args [0]->dreg;
6244                                 ins->inst_offset = 0;
6245                                 MONO_ADD_INS (cfg->cbb, ins);
6246
6247                                 if (opcode == OP_STOREI8_MEMBASE_REG)
6248                                         ins = mono_decompose_opcode (cfg, ins);
6249
6250                                 return ins;
6251                         }
6252                 }
6253         } else if (cmethod->klass->image == mono_defaults.corlib &&
6254                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
6255                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
6256                 ins = NULL;
6257
6258 #if SIZEOF_REGISTER == 8
6259                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
6260                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
6261                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
6262                                 ins->dreg = mono_alloc_preg (cfg);
6263                                 ins->sreg1 = args [0]->dreg;
6264                                 ins->type = STACK_I8;
6265                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
6266                                 MONO_ADD_INS (cfg->cbb, ins);
6267                         } else {
6268                                 MonoInst *load_ins;
6269
6270                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6271
6272                                 /* 64 bit reads are already atomic */
6273                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
6274                                 load_ins->dreg = mono_alloc_preg (cfg);
6275                                 load_ins->inst_basereg = args [0]->dreg;
6276                                 load_ins->inst_offset = 0;
6277                                 load_ins->type = STACK_I8;
6278                                 MONO_ADD_INS (cfg->cbb, load_ins);
6279
6280                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6281
6282                                 ins = load_ins;
6283                         }
6284                 }
6285 #endif
6286
6287                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
6288                         MonoInst *ins_iconst;
6289                         guint32 opcode = 0;
6290
6291                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6292                                 opcode = OP_ATOMIC_ADD_I4;
6293                                 cfg->has_atomic_add_i4 = TRUE;
6294                         }
6295 #if SIZEOF_REGISTER == 8
6296                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6297                                 opcode = OP_ATOMIC_ADD_I8;
6298 #endif
6299                         if (opcode) {
6300                                 if (!mono_arch_opcode_supported (opcode))
6301                                         return NULL;
6302                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
6303                                 ins_iconst->inst_c0 = 1;
6304                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
6305                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
6306
6307                                 MONO_INST_NEW (cfg, ins, opcode);
6308                                 ins->dreg = mono_alloc_ireg (cfg);
6309                                 ins->inst_basereg = args [0]->dreg;
6310                                 ins->inst_offset = 0;
6311                                 ins->sreg2 = ins_iconst->dreg;
6312                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6313                                 MONO_ADD_INS (cfg->cbb, ins);
6314                         }
6315                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
6316                         MonoInst *ins_iconst;
6317                         guint32 opcode = 0;
6318
6319                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6320                                 opcode = OP_ATOMIC_ADD_I4;
6321                                 cfg->has_atomic_add_i4 = TRUE;
6322                         }
6323 #if SIZEOF_REGISTER == 8
6324                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6325                                 opcode = OP_ATOMIC_ADD_I8;
6326 #endif
6327                         if (opcode) {
6328                                 if (!mono_arch_opcode_supported (opcode))
6329                                         return NULL;
6330                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
6331                                 ins_iconst->inst_c0 = -1;
6332                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
6333                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
6334
6335                                 MONO_INST_NEW (cfg, ins, opcode);
6336                                 ins->dreg = mono_alloc_ireg (cfg);
6337                                 ins->inst_basereg = args [0]->dreg;
6338                                 ins->inst_offset = 0;
6339                                 ins->sreg2 = ins_iconst->dreg;
6340                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6341                                 MONO_ADD_INS (cfg->cbb, ins);
6342                         }
6343                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
6344                         guint32 opcode = 0;
6345
6346                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6347                                 opcode = OP_ATOMIC_ADD_I4;
6348                                 cfg->has_atomic_add_i4 = TRUE;
6349                         }
6350 #if SIZEOF_REGISTER == 8
6351                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6352                                 opcode = OP_ATOMIC_ADD_I8;
6353 #endif
6354                         if (opcode) {
6355                                 if (!mono_arch_opcode_supported (opcode))
6356                                         return NULL;
6357                                 MONO_INST_NEW (cfg, ins, opcode);
6358                                 ins->dreg = mono_alloc_ireg (cfg);
6359                                 ins->inst_basereg = args [0]->dreg;
6360                                 ins->inst_offset = 0;
6361                                 ins->sreg2 = args [1]->dreg;
6362                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6363                                 MONO_ADD_INS (cfg->cbb, ins);
6364                         }
6365                 }
6366                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
6367                         MonoInst *f2i = NULL, *i2f;
6368                         guint32 opcode, f2i_opcode, i2f_opcode;
6369                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6370                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
6371
6372                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
6373                             fsig->params [0]->type == MONO_TYPE_R4) {
6374                                 opcode = OP_ATOMIC_EXCHANGE_I4;
6375                                 f2i_opcode = OP_MOVE_F_TO_I4;
6376                                 i2f_opcode = OP_MOVE_I4_TO_F;
6377                                 cfg->has_atomic_exchange_i4 = TRUE;
6378                         }
6379 #if SIZEOF_REGISTER == 8
6380                         else if (is_ref ||
6381                                  fsig->params [0]->type == MONO_TYPE_I8 ||
6382                                  fsig->params [0]->type == MONO_TYPE_R8 ||
6383                                  fsig->params [0]->type == MONO_TYPE_I) {
6384                                 opcode = OP_ATOMIC_EXCHANGE_I8;
6385                                 f2i_opcode = OP_MOVE_F_TO_I8;
6386                                 i2f_opcode = OP_MOVE_I8_TO_F;
6387                         }
6388 #else
6389                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
6390                                 opcode = OP_ATOMIC_EXCHANGE_I4;
6391                                 cfg->has_atomic_exchange_i4 = TRUE;
6392                         }
6393 #endif
6394                         else
6395                                 return NULL;
6396
6397                         if (!mono_arch_opcode_supported (opcode))
6398                                 return NULL;
6399
6400                         if (is_float) {
6401                                 /* TODO: Decompose these opcodes instead of bailing here. */
6402                                 if (COMPILE_SOFT_FLOAT (cfg))
6403                                         return NULL;
6404
6405                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
6406                                 f2i->dreg = mono_alloc_ireg (cfg);
6407                                 f2i->sreg1 = args [1]->dreg;
6408                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6409                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6410                                 MONO_ADD_INS (cfg->cbb, f2i);
6411                         }
6412
6413                         MONO_INST_NEW (cfg, ins, opcode);
6414                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
6415                         ins->inst_basereg = args [0]->dreg;
6416                         ins->inst_offset = 0;
6417                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
6418                         MONO_ADD_INS (cfg->cbb, ins);
6419
6420                         switch (fsig->params [0]->type) {
6421                         case MONO_TYPE_I4:
6422                                 ins->type = STACK_I4;
6423                                 break;
6424                         case MONO_TYPE_I8:
6425                                 ins->type = STACK_I8;
6426                                 break;
6427                         case MONO_TYPE_I:
6428 #if SIZEOF_REGISTER == 8
6429                                 ins->type = STACK_I8;
6430 #else
6431                                 ins->type = STACK_I4;
6432 #endif
6433                                 break;
6434                         case MONO_TYPE_R4:
6435                         case MONO_TYPE_R8:
6436                                 ins->type = STACK_R8;
6437                                 break;
6438                         default:
6439                                 g_assert (mini_type_is_reference (fsig->params [0]));
6440                                 ins->type = STACK_OBJ;
6441                                 break;
6442                         }
6443
6444                         if (is_float) {
6445                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
6446                                 i2f->dreg = mono_alloc_freg (cfg);
6447                                 i2f->sreg1 = ins->dreg;
6448                                 i2f->type = STACK_R8;
6449                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
6450                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6451                                 MONO_ADD_INS (cfg->cbb, i2f);
6452
6453                                 ins = i2f;
6454                         }
6455
6456                         if (cfg->gen_write_barriers && is_ref)
6457                                 emit_write_barrier (cfg, args [0], args [1]);
6458                 }
6459                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
6460                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
6461                         guint32 opcode, f2i_opcode, i2f_opcode;
6462                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
6463                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
6464
6465                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
6466                             fsig->params [1]->type == MONO_TYPE_R4) {
6467                                 opcode = OP_ATOMIC_CAS_I4;
6468                                 f2i_opcode = OP_MOVE_F_TO_I4;
6469                                 i2f_opcode = OP_MOVE_I4_TO_F;
6470                                 cfg->has_atomic_cas_i4 = TRUE;
6471                         }
6472 #if SIZEOF_REGISTER == 8
6473                         else if (is_ref ||
6474                                  fsig->params [1]->type == MONO_TYPE_I8 ||
6475                                  fsig->params [1]->type == MONO_TYPE_R8 ||
6476                                  fsig->params [1]->type == MONO_TYPE_I) {
6477                                 opcode = OP_ATOMIC_CAS_I8;
6478                                 f2i_opcode = OP_MOVE_F_TO_I8;
6479                                 i2f_opcode = OP_MOVE_I8_TO_F;
6480                         }
6481 #else
6482                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
6483                                 opcode = OP_ATOMIC_CAS_I4;
6484                                 cfg->has_atomic_cas_i4 = TRUE;
6485                         }
6486 #endif
6487                         else
6488                                 return NULL;
6489
6490                         if (!mono_arch_opcode_supported (opcode))
6491                                 return NULL;
6492
6493                         if (is_float) {
6494                                 /* TODO: Decompose these opcodes instead of bailing here. */
6495                                 if (COMPILE_SOFT_FLOAT (cfg))
6496                                         return NULL;
6497
6498                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
6499                                 f2i_new->dreg = mono_alloc_ireg (cfg);
6500                                 f2i_new->sreg1 = args [1]->dreg;
6501                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6502                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6503                                 MONO_ADD_INS (cfg->cbb, f2i_new);
6504
6505                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
6506                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
6507                                 f2i_cmp->sreg1 = args [2]->dreg;
6508                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6509                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6510                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
6511                         }
6512
6513                         MONO_INST_NEW (cfg, ins, opcode);
6514                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
6515                         ins->sreg1 = args [0]->dreg;
6516                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
6517                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
6518                         MONO_ADD_INS (cfg->cbb, ins);
6519
6520                         switch (fsig->params [1]->type) {
6521                         case MONO_TYPE_I4:
6522                                 ins->type = STACK_I4;
6523                                 break;
6524                         case MONO_TYPE_I8:
6525                                 ins->type = STACK_I8;
6526                                 break;
6527                         case MONO_TYPE_I:
6528 #if SIZEOF_REGISTER == 8
6529                                 ins->type = STACK_I8;
6530 #else
6531                                 ins->type = STACK_I4;
6532 #endif
6533                                 break;
6534                         case MONO_TYPE_R4:
6535                                 ins->type = cfg->r4_stack_type;
6536                                 break;
6537                         case MONO_TYPE_R8:
6538                                 ins->type = STACK_R8;
6539                                 break;
6540                         default:
6541                                 g_assert (mini_type_is_reference (fsig->params [1]));
6542                                 ins->type = STACK_OBJ;
6543                                 break;
6544                         }
6545
6546                         if (is_float) {
6547                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
6548                                 i2f->dreg = mono_alloc_freg (cfg);
6549                                 i2f->sreg1 = ins->dreg;
6550                                 i2f->type = STACK_R8;
6551                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
6552                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6553                                 MONO_ADD_INS (cfg->cbb, i2f);
6554
6555                                 ins = i2f;
6556                         }
6557
6558                         if (cfg->gen_write_barriers && is_ref)
6559                                 emit_write_barrier (cfg, args [0], args [1]);
6560                 }
6561                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
6562                          fsig->params [1]->type == MONO_TYPE_I4) {
6563                         MonoInst *cmp, *ceq;
6564
6565                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
6566                                 return NULL;
6567
6568                         /* int32 r = CAS (location, value, comparand); */
6569                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
6570                         ins->dreg = alloc_ireg (cfg);
6571                         ins->sreg1 = args [0]->dreg;
6572                         ins->sreg2 = args [1]->dreg;
6573                         ins->sreg3 = args [2]->dreg;
6574                         ins->type = STACK_I4;
6575                         MONO_ADD_INS (cfg->cbb, ins);
6576
6577                         /* bool result = r == comparand; */
6578                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
6579                         cmp->sreg1 = ins->dreg;
6580                         cmp->sreg2 = args [2]->dreg;
6581                         cmp->type = STACK_I4;
6582                         MONO_ADD_INS (cfg->cbb, cmp);
6583
6584                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
6585                         ceq->dreg = alloc_ireg (cfg);
6586                         ceq->type = STACK_I4;
6587                         MONO_ADD_INS (cfg->cbb, ceq);
6588
6589                         /* *success = result; */
6590                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
6591
6592                         cfg->has_atomic_cas_i4 = TRUE;
6593                 }
6594                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
6595                         ins = emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6596
6597                 if (ins)
6598                         return ins;
6599         } else if (cmethod->klass->image == mono_defaults.corlib &&
6600                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
6601                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
6602                 ins = NULL;
6603
6604                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
6605                         guint32 opcode = 0;
6606                         MonoType *t = fsig->params [0];
6607                         gboolean is_ref;
6608                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
6609
6610                         g_assert (t->byref);
6611                         /* t is a byref type, so the reference check is more complicated */
6612                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
6613                         if (t->type == MONO_TYPE_I1)
6614                                 opcode = OP_ATOMIC_LOAD_I1;
6615                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
6616                                 opcode = OP_ATOMIC_LOAD_U1;
6617                         else if (t->type == MONO_TYPE_I2)
6618                                 opcode = OP_ATOMIC_LOAD_I2;
6619                         else if (t->type == MONO_TYPE_U2)
6620                                 opcode = OP_ATOMIC_LOAD_U2;
6621                         else if (t->type == MONO_TYPE_I4)
6622                                 opcode = OP_ATOMIC_LOAD_I4;
6623                         else if (t->type == MONO_TYPE_U4)
6624                                 opcode = OP_ATOMIC_LOAD_U4;
6625                         else if (t->type == MONO_TYPE_R4)
6626                                 opcode = OP_ATOMIC_LOAD_R4;
6627                         else if (t->type == MONO_TYPE_R8)
6628                                 opcode = OP_ATOMIC_LOAD_R8;
6629 #if SIZEOF_REGISTER == 8
6630                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
6631                                 opcode = OP_ATOMIC_LOAD_I8;
6632                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
6633                                 opcode = OP_ATOMIC_LOAD_U8;
6634 #else
6635                         else if (t->type == MONO_TYPE_I)
6636                                 opcode = OP_ATOMIC_LOAD_I4;
6637                         else if (is_ref || t->type == MONO_TYPE_U)
6638                                 opcode = OP_ATOMIC_LOAD_U4;
6639 #endif
6640
6641                         if (opcode) {
6642                                 if (!mono_arch_opcode_supported (opcode))
6643                                         return NULL;
6644
6645                                 MONO_INST_NEW (cfg, ins, opcode);
6646                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
6647                                 ins->sreg1 = args [0]->dreg;
6648                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
6649                                 MONO_ADD_INS (cfg->cbb, ins);
6650
6651                                 switch (t->type) {
6652                                 case MONO_TYPE_BOOLEAN:
6653                                 case MONO_TYPE_I1:
6654                                 case MONO_TYPE_U1:
6655                                 case MONO_TYPE_I2:
6656                                 case MONO_TYPE_U2:
6657                                 case MONO_TYPE_I4:
6658                                 case MONO_TYPE_U4:
6659                                         ins->type = STACK_I4;
6660                                         break;
6661                                 case MONO_TYPE_I8:
6662                                 case MONO_TYPE_U8:
6663                                         ins->type = STACK_I8;
6664                                         break;
6665                                 case MONO_TYPE_I:
6666                                 case MONO_TYPE_U:
6667 #if SIZEOF_REGISTER == 8
6668                                         ins->type = STACK_I8;
6669 #else
6670                                         ins->type = STACK_I4;
6671 #endif
6672                                         break;
6673                                 case MONO_TYPE_R4:
6674                                         ins->type = cfg->r4_stack_type;
6675                                         break;
6676                                 case MONO_TYPE_R8:
6677                                         ins->type = STACK_R8;
6678                                         break;
6679                                 default:
6680                                         g_assert (is_ref);
6681                                         ins->type = STACK_OBJ;
6682                                         break;
6683                                 }
6684                         }
6685                 }
6686
6687                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
6688                         guint32 opcode = 0;
6689                         MonoType *t = fsig->params [0];
6690                         gboolean is_ref;
6691
6692                         g_assert (t->byref);
6693                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
6694                         if (t->type == MONO_TYPE_I1)
6695                                 opcode = OP_ATOMIC_STORE_I1;
6696                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
6697                                 opcode = OP_ATOMIC_STORE_U1;
6698                         else if (t->type == MONO_TYPE_I2)
6699                                 opcode = OP_ATOMIC_STORE_I2;
6700                         else if (t->type == MONO_TYPE_U2)
6701                                 opcode = OP_ATOMIC_STORE_U2;
6702                         else if (t->type == MONO_TYPE_I4)
6703                                 opcode = OP_ATOMIC_STORE_I4;
6704                         else if (t->type == MONO_TYPE_U4)
6705                                 opcode = OP_ATOMIC_STORE_U4;
6706                         else if (t->type == MONO_TYPE_R4)
6707                                 opcode = OP_ATOMIC_STORE_R4;
6708                         else if (t->type == MONO_TYPE_R8)
6709                                 opcode = OP_ATOMIC_STORE_R8;
6710 #if SIZEOF_REGISTER == 8
6711                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
6712                                 opcode = OP_ATOMIC_STORE_I8;
6713                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
6714                                 opcode = OP_ATOMIC_STORE_U8;
6715 #else
6716                         else if (t->type == MONO_TYPE_I)
6717                                 opcode = OP_ATOMIC_STORE_I4;
6718                         else if (is_ref || t->type == MONO_TYPE_U)
6719                                 opcode = OP_ATOMIC_STORE_U4;
6720 #endif
6721
6722                         if (opcode) {
6723                                 if (!mono_arch_opcode_supported (opcode))
6724                                         return NULL;
6725
6726                                 MONO_INST_NEW (cfg, ins, opcode);
6727                                 ins->dreg = args [0]->dreg;
6728                                 ins->sreg1 = args [1]->dreg;
6729                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
6730                                 MONO_ADD_INS (cfg->cbb, ins);
6731
6732                                 if (cfg->gen_write_barriers && is_ref)
6733                                         emit_write_barrier (cfg, args [0], args [1]);
6734                         }
6735                 }
6736
6737                 if (ins)
6738                         return ins;
6739         } else if (cmethod->klass->image == mono_defaults.corlib &&
6740                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
6741                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
6742                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
6743                         if (should_insert_brekpoint (cfg->method)) {
6744                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
6745                         } else {
6746                                 MONO_INST_NEW (cfg, ins, OP_NOP);
6747                                 MONO_ADD_INS (cfg->cbb, ins);
6748                         }
6749                         return ins;
6750                 }
6751         } else if (cmethod->klass->image == mono_defaults.corlib &&
6752                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
6753                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
6754                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
6755 #ifdef TARGET_WIN32
6756                         EMIT_NEW_ICONST (cfg, ins, 1);
6757 #else
6758                         EMIT_NEW_ICONST (cfg, ins, 0);
6759 #endif
6760                 }
6761         } else if (cmethod->klass->image == mono_defaults.corlib &&
6762                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6763                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
6764                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
6765                         /* No stack walks are currently available, so implement this as an intrinsic */
6766                         MonoInst *assembly_ins;
6767
6768                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
6769                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
6770                         return ins;
6771                 }
6772         } else if (cmethod->klass->image == mono_defaults.corlib &&
6773                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6774                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
6775                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
6776                         /* No stack walks are currently available, so implement this as an intrinsic */
6777                         MonoInst *method_ins;
6778                         MonoMethod *declaring = cfg->method;
6779
6780                         /* This returns the declaring generic method */
6781                         if (declaring->is_inflated)
6782                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
6783                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
6784                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
6785                         cfg->no_inline = TRUE;
6786                         if (cfg->method != cfg->current_method)
6787                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
6788                         return ins;
6789                 }
6790         } else if (cmethod->klass == mono_defaults.math_class) {
6791                 /* 
6792                  * There is general branchless code for Min/Max, but it does not work for 
6793                  * all inputs:
6794                  * http://everything2.com/?node_id=1051618
6795                  */
6796         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
6797                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
6798                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
6799                                 !strcmp (cmethod->klass->name, "Selector")) ||
6800                            (!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") &&
6801                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6802                                 !strcmp (cmethod->klass->name, "Selector"))
6803                            ) {
6804                 if (cfg->backend->have_objc_get_selector &&
6805                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6806                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6807                     cfg->compile_aot && !cfg->llvm_only) {
6808                         MonoInst *pi;
6809                         MonoJumpInfoToken *ji;
6810                         MonoString *s;
6811
6812                         // FIXME: llvmonly
6813
6814                         cfg->exception_message = g_strdup ("GetHandle");
6815                         cfg->disable_llvm = TRUE;
6816
6817                         if (args [0]->opcode == OP_GOT_ENTRY) {
6818                                 pi = (MonoInst *)args [0]->inst_p1;
6819                                 g_assert (pi->opcode == OP_PATCH_INFO);
6820                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6821                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6822                         } else {
6823                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6824                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6825                         }
6826
6827                         NULLIFY_INS (args [0]);
6828
6829                         // FIXME: Ugly
6830                         s = mono_ldstr_checked (cfg->domain, ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6831                         return_val_if_nok (&cfg->error, NULL);
6832                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6833                         ins->dreg = mono_alloc_ireg (cfg);
6834                         // FIXME: Leaks
6835                         ins->inst_p0 = mono_string_to_utf8_checked (s, &cfg->error);
6836                         return_val_if_nok (&cfg->error, NULL);
6837                         MONO_ADD_INS (cfg->cbb, ins);
6838                         return ins;
6839                 }
6840         }
6841
6842 #ifdef MONO_ARCH_SIMD_INTRINSICS
6843         if (cfg->opt & MONO_OPT_SIMD) {
6844                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6845                 if (ins)
6846                         return ins;
6847         }
6848 #endif
6849
6850         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6851         if (ins)
6852                 return ins;
6853
6854         if (COMPILE_LLVM (cfg)) {
6855                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6856                 if (ins)
6857                         return ins;
6858         }
6859
6860         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6861 }
6862
6863 /*
6864  * This entry point could be used later for arbitrary method
6865  * redirection.
6866  */
6867 inline static MonoInst*
6868 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6869                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6870 {
6871         if (method->klass == mono_defaults.string_class) {
6872                 /* managed string allocation support */
6873                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6874                         MonoInst *iargs [2];
6875                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6876                         MonoMethod *managed_alloc = NULL;
6877
6878                         g_assert (vtable); /*Should not fail since it System.String*/
6879 #ifndef MONO_CROSS_COMPILE
6880                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6881 #endif
6882                         if (!managed_alloc)
6883                                 return NULL;
6884                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6885                         iargs [1] = args [0];
6886                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6887                 }
6888         }
6889         return NULL;
6890 }
6891
6892 static void
6893 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6894 {
6895         MonoInst *store, *temp;
6896         int i;
6897
6898         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6899                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6900
6901                 /*
6902                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6903                  * would be different than the MonoInst's used to represent arguments, and
6904                  * the ldelema implementation can't deal with that.
6905                  * Solution: When ldelema is used on an inline argument, create a var for 
6906                  * it, emit ldelema on that var, and emit the saving code below in
6907                  * inline_method () if needed.
6908                  */
6909                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6910                 cfg->args [i] = temp;
6911                 /* This uses cfg->args [i] which is set by the preceeding line */
6912                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6913                 store->cil_code = sp [0]->cil_code;
6914                 sp++;
6915         }
6916 }
6917
6918 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6919 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6920
6921 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6922 static gboolean
6923 check_inline_called_method_name_limit (MonoMethod *called_method)
6924 {
6925         int strncmp_result;
6926         static const char *limit = NULL;
6927         
6928         if (limit == NULL) {
6929                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6930
6931                 if (limit_string != NULL)
6932                         limit = limit_string;
6933                 else
6934                         limit = "";
6935         }
6936
6937         if (limit [0] != '\0') {
6938                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6939
6940                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6941                 g_free (called_method_name);
6942         
6943                 //return (strncmp_result <= 0);
6944                 return (strncmp_result == 0);
6945         } else {
6946                 return TRUE;
6947         }
6948 }
6949 #endif
6950
6951 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6952 static gboolean
6953 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6954 {
6955         int strncmp_result;
6956         static const char *limit = NULL;
6957         
6958         if (limit == NULL) {
6959                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6960                 if (limit_string != NULL) {
6961                         limit = limit_string;
6962                 } else {
6963                         limit = "";
6964                 }
6965         }
6966
6967         if (limit [0] != '\0') {
6968                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6969
6970                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6971                 g_free (caller_method_name);
6972         
6973                 //return (strncmp_result <= 0);
6974                 return (strncmp_result == 0);
6975         } else {
6976                 return TRUE;
6977         }
6978 }
6979 #endif
6980
6981 static void
6982 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6983 {
6984         static double r8_0 = 0.0;
6985         static float r4_0 = 0.0;
6986         MonoInst *ins;
6987         int t;
6988
6989         rtype = mini_get_underlying_type (rtype);
6990         t = rtype->type;
6991
6992         if (rtype->byref) {
6993                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6994         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6995                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6996         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6997                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6998         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6999                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
7000                 ins->type = STACK_R4;
7001                 ins->inst_p0 = (void*)&r4_0;
7002                 ins->dreg = dreg;
7003                 MONO_ADD_INS (cfg->cbb, ins);
7004         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7005                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7006                 ins->type = STACK_R8;
7007                 ins->inst_p0 = (void*)&r8_0;
7008                 ins->dreg = dreg;
7009                 MONO_ADD_INS (cfg->cbb, ins);
7010         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7011                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
7012                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
7013         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
7014                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
7015         } else {
7016                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
7017         }
7018 }
7019
7020 static void
7021 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
7022 {
7023         int t;
7024
7025         rtype = mini_get_underlying_type (rtype);
7026         t = rtype->type;
7027
7028         if (rtype->byref) {
7029                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
7030         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
7031                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
7032         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
7033                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
7034         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
7035                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
7036         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7037                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
7038         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7039                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
7040                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
7041         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
7042                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
7043         } else {
7044                 emit_init_rvar (cfg, dreg, rtype);
7045         }
7046 }
7047
7048 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
7049 static void
7050 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
7051 {
7052         MonoInst *var = cfg->locals [local];
7053         if (COMPILE_SOFT_FLOAT (cfg)) {
7054                 MonoInst *store;
7055                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
7056                 emit_init_rvar (cfg, reg, type);
7057                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
7058         } else {
7059                 if (init)
7060                         emit_init_rvar (cfg, var->dreg, type);
7061                 else
7062                         emit_dummy_init_rvar (cfg, var->dreg, type);
7063         }
7064 }
7065
7066 /*
7067  * inline_method:
7068  *
7069  *   Return the cost of inlining CMETHOD.
7070  */
7071 static int
7072 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
7073                            guchar *ip, guint real_offset, gboolean inline_always)
7074 {
7075         MonoError error;
7076         MonoInst *ins, *rvar = NULL;
7077         MonoMethodHeader *cheader;
7078         MonoBasicBlock *ebblock, *sbblock;
7079         int i, costs;
7080         MonoMethod *prev_inlined_method;
7081         MonoInst **prev_locals, **prev_args;
7082         MonoType **prev_arg_types;
7083         guint prev_real_offset;
7084         GHashTable *prev_cbb_hash;
7085         MonoBasicBlock **prev_cil_offset_to_bb;
7086         MonoBasicBlock *prev_cbb;
7087         unsigned char* prev_cil_start;
7088         guint32 prev_cil_offset_to_bb_len;
7089         MonoMethod *prev_current_method;
7090         MonoGenericContext *prev_generic_context;
7091         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
7092
7093         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
7094
7095 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
7096         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
7097                 return 0;
7098 #endif
7099 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
7100         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
7101                 return 0;
7102 #endif
7103
7104         if (!fsig)
7105                 fsig = mono_method_signature (cmethod);
7106
7107         if (cfg->verbose_level > 2)
7108                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
7109
7110         if (!cmethod->inline_info) {
7111                 cfg->stat_inlineable_methods++;
7112                 cmethod->inline_info = 1;
7113         }
7114
7115         /* allocate local variables */
7116         cheader = mono_method_get_header_checked (cmethod, &error);
7117         if (!cheader) {
7118                 if (inline_always) {
7119                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7120                         mono_error_move (&cfg->error, &error);
7121                 } else {
7122                         mono_error_cleanup (&error);
7123                 }
7124                 return 0;
7125         }
7126
7127         /*Must verify before creating locals as it can cause the JIT to assert.*/
7128         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
7129                 mono_metadata_free_mh (cheader);
7130                 return 0;
7131         }
7132
7133         /* allocate space to store the return value */
7134         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
7135                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
7136         }
7137
7138         prev_locals = cfg->locals;
7139         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
7140         for (i = 0; i < cheader->num_locals; ++i)
7141                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
7142
7143         /* allocate start and end blocks */
7144         /* This is needed so if the inline is aborted, we can clean up */
7145         NEW_BBLOCK (cfg, sbblock);
7146         sbblock->real_offset = real_offset;
7147
7148         NEW_BBLOCK (cfg, ebblock);
7149         ebblock->block_num = cfg->num_bblocks++;
7150         ebblock->real_offset = real_offset;
7151
7152         prev_args = cfg->args;
7153         prev_arg_types = cfg->arg_types;
7154         prev_inlined_method = cfg->inlined_method;
7155         cfg->inlined_method = cmethod;
7156         cfg->ret_var_set = FALSE;
7157         cfg->inline_depth ++;
7158         prev_real_offset = cfg->real_offset;
7159         prev_cbb_hash = cfg->cbb_hash;
7160         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
7161         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
7162         prev_cil_start = cfg->cil_start;
7163         prev_cbb = cfg->cbb;
7164         prev_current_method = cfg->current_method;
7165         prev_generic_context = cfg->generic_context;
7166         prev_ret_var_set = cfg->ret_var_set;
7167         prev_disable_inline = cfg->disable_inline;
7168
7169         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
7170                 virtual_ = TRUE;
7171
7172         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
7173
7174         ret_var_set = cfg->ret_var_set;
7175
7176         cfg->inlined_method = prev_inlined_method;
7177         cfg->real_offset = prev_real_offset;
7178         cfg->cbb_hash = prev_cbb_hash;
7179         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
7180         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
7181         cfg->cil_start = prev_cil_start;
7182         cfg->locals = prev_locals;
7183         cfg->args = prev_args;
7184         cfg->arg_types = prev_arg_types;
7185         cfg->current_method = prev_current_method;
7186         cfg->generic_context = prev_generic_context;
7187         cfg->ret_var_set = prev_ret_var_set;
7188         cfg->disable_inline = prev_disable_inline;
7189         cfg->inline_depth --;
7190
7191         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
7192                 if (cfg->verbose_level > 2)
7193                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
7194                 
7195                 cfg->stat_inlined_methods++;
7196
7197                 /* always add some code to avoid block split failures */
7198                 MONO_INST_NEW (cfg, ins, OP_NOP);
7199                 MONO_ADD_INS (prev_cbb, ins);
7200
7201                 prev_cbb->next_bb = sbblock;
7202                 link_bblock (cfg, prev_cbb, sbblock);
7203
7204                 /* 
7205                  * Get rid of the begin and end bblocks if possible to aid local
7206                  * optimizations.
7207                  */
7208                 mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
7209
7210                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
7211                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
7212
7213                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
7214                         MonoBasicBlock *prev = ebblock->in_bb [0];
7215
7216                         if (prev->next_bb == ebblock) {
7217                                 mono_merge_basic_blocks (cfg, prev, ebblock);
7218                                 cfg->cbb = prev;
7219                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
7220                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
7221                                         cfg->cbb = prev_cbb;
7222                                 }
7223                         } else {
7224                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
7225                                 cfg->cbb = ebblock;
7226                         }
7227                 } else {
7228                         /* 
7229                          * Its possible that the rvar is set in some prev bblock, but not in others.
7230                          * (#1835).
7231                          */
7232                         if (rvar) {
7233                                 MonoBasicBlock *bb;
7234
7235                                 for (i = 0; i < ebblock->in_count; ++i) {
7236                                         bb = ebblock->in_bb [i];
7237
7238                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
7239                                                 cfg->cbb = bb;
7240
7241                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
7242                                         }
7243                                 }
7244                         }
7245
7246                         cfg->cbb = ebblock;
7247                 }
7248
7249                 if (rvar) {
7250                         /*
7251                          * If the inlined method contains only a throw, then the ret var is not 
7252                          * set, so set it to a dummy value.
7253                          */
7254                         if (!ret_var_set)
7255                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
7256
7257                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
7258                         *sp++ = ins;
7259                 }
7260                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
7261                 return costs + 1;
7262         } else {
7263                 if (cfg->verbose_level > 2)
7264                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
7265                 cfg->exception_type = MONO_EXCEPTION_NONE;
7266
7267                 /* This gets rid of the newly added bblocks */
7268                 cfg->cbb = prev_cbb;
7269         }
7270         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
7271         return 0;
7272 }
7273
7274 /*
7275  * Some of these comments may well be out-of-date.
7276  * Design decisions: we do a single pass over the IL code (and we do bblock 
7277  * splitting/merging in the few cases when it's required: a back jump to an IL
7278  * address that was not already seen as bblock starting point).
7279  * Code is validated as we go (full verification is still better left to metadata/verify.c).
7280  * Complex operations are decomposed in simpler ones right away. We need to let the 
7281  * arch-specific code peek and poke inside this process somehow (except when the 
7282  * optimizations can take advantage of the full semantic info of coarse opcodes).
7283  * All the opcodes of the form opcode.s are 'normalized' to opcode.
7284  * MonoInst->opcode initially is the IL opcode or some simplification of that 
7285  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
7286  * opcode with value bigger than OP_LAST.
7287  * At this point the IR can be handed over to an interpreter, a dumb code generator
7288  * or to the optimizing code generator that will translate it to SSA form.
7289  *
7290  * Profiling directed optimizations.
7291  * We may compile by default with few or no optimizations and instrument the code
7292  * or the user may indicate what methods to optimize the most either in a config file
7293  * or through repeated runs where the compiler applies offline the optimizations to 
7294  * each method and then decides if it was worth it.
7295  */
7296
7297 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
7298 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
7299 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
7300 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
7301 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
7302 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
7303 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
7304 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
7305
7306 /* offset from br.s -> br like opcodes */
7307 #define BIG_BRANCH_OFFSET 13
7308
7309 static gboolean
7310 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
7311 {
7312         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
7313
7314         return b == NULL || b == bb;
7315 }
7316
7317 static int
7318 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
7319 {
7320         unsigned char *ip = start;
7321         unsigned char *target;
7322         int i;
7323         guint cli_addr;
7324         MonoBasicBlock *bblock;
7325         const MonoOpcode *opcode;
7326
7327         while (ip < end) {
7328                 cli_addr = ip - start;
7329                 i = mono_opcode_value ((const guint8 **)&ip, end);
7330                 if (i < 0)
7331                         UNVERIFIED;
7332                 opcode = &mono_opcodes [i];
7333                 switch (opcode->argument) {
7334                 case MonoInlineNone:
7335                         ip++; 
7336                         break;
7337                 case MonoInlineString:
7338                 case MonoInlineType:
7339                 case MonoInlineField:
7340                 case MonoInlineMethod:
7341                 case MonoInlineTok:
7342                 case MonoInlineSig:
7343                 case MonoShortInlineR:
7344                 case MonoInlineI:
7345                         ip += 5;
7346                         break;
7347                 case MonoInlineVar:
7348                         ip += 3;
7349                         break;
7350                 case MonoShortInlineVar:
7351                 case MonoShortInlineI:
7352                         ip += 2;
7353                         break;
7354                 case MonoShortInlineBrTarget:
7355                         target = start + cli_addr + 2 + (signed char)ip [1];
7356                         GET_BBLOCK (cfg, bblock, target);
7357                         ip += 2;
7358                         if (ip < end)
7359                                 GET_BBLOCK (cfg, bblock, ip);
7360                         break;
7361                 case MonoInlineBrTarget:
7362                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
7363                         GET_BBLOCK (cfg, bblock, target);
7364                         ip += 5;
7365                         if (ip < end)
7366                                 GET_BBLOCK (cfg, bblock, ip);
7367                         break;
7368                 case MonoInlineSwitch: {
7369                         guint32 n = read32 (ip + 1);
7370                         guint32 j;
7371                         ip += 5;
7372                         cli_addr += 5 + 4 * n;
7373                         target = start + cli_addr;
7374                         GET_BBLOCK (cfg, bblock, target);
7375                         
7376                         for (j = 0; j < n; ++j) {
7377                                 target = start + cli_addr + (gint32)read32 (ip);
7378                                 GET_BBLOCK (cfg, bblock, target);
7379                                 ip += 4;
7380                         }
7381                         break;
7382                 }
7383                 case MonoInlineR:
7384                 case MonoInlineI8:
7385                         ip += 9;
7386                         break;
7387                 default:
7388                         g_assert_not_reached ();
7389                 }
7390
7391                 if (i == CEE_THROW) {
7392                         unsigned char *bb_start = ip - 1;
7393                         
7394                         /* Find the start of the bblock containing the throw */
7395                         bblock = NULL;
7396                         while ((bb_start >= start) && !bblock) {
7397                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
7398                                 bb_start --;
7399                         }
7400                         if (bblock)
7401                                 bblock->out_of_line = 1;
7402                 }
7403         }
7404         return 0;
7405 unverified:
7406 exception_exit:
7407         *pos = ip;
7408         return 1;
7409 }
7410
7411 static inline MonoMethod *
7412 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
7413 {
7414         MonoMethod *method;
7415
7416         mono_error_init (error);
7417
7418         if (m->wrapper_type != MONO_WRAPPER_NONE) {
7419                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
7420                 if (context) {
7421                         method = mono_class_inflate_generic_method_checked (method, context, error);
7422                 }
7423         } else {
7424                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
7425         }
7426
7427         return method;
7428 }
7429
7430 static inline MonoMethod *
7431 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
7432 {
7433         MonoError error;
7434         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
7435
7436         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
7437                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
7438                 method = NULL;
7439         }
7440
7441         if (!method && !cfg)
7442                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7443
7444         return method;
7445 }
7446
7447 static inline MonoClass*
7448 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
7449 {
7450         MonoError error;
7451         MonoClass *klass;
7452
7453         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7454                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7455                 if (context) {
7456                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
7457                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7458                 }
7459         } else {
7460                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
7461                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7462         }
7463         if (klass)
7464                 mono_class_init (klass);
7465         return klass;
7466 }
7467
7468 static inline MonoMethodSignature*
7469 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
7470 {
7471         MonoMethodSignature *fsig;
7472
7473         mono_error_init (error);
7474         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7475                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
7476         } else {
7477                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
7478                 return_val_if_nok (error, NULL);
7479         }
7480         if (context) {
7481                 fsig = mono_inflate_generic_signature(fsig, context, error);
7482         }
7483         return fsig;
7484 }
7485
7486 static MonoMethod*
7487 throw_exception (void)
7488 {
7489         static MonoMethod *method = NULL;
7490
7491         if (!method) {
7492                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
7493                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
7494         }
7495         g_assert (method);
7496         return method;
7497 }
7498
7499 static void
7500 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
7501 {
7502         MonoMethod *thrower = throw_exception ();
7503         MonoInst *args [1];
7504
7505         EMIT_NEW_PCONST (cfg, args [0], ex);
7506         mono_emit_method_call (cfg, thrower, args, NULL);
7507 }
7508
7509 /*
7510  * Return the original method is a wrapper is specified. We can only access 
7511  * the custom attributes from the original method.
7512  */
7513 static MonoMethod*
7514 get_original_method (MonoMethod *method)
7515 {
7516         if (method->wrapper_type == MONO_WRAPPER_NONE)
7517                 return method;
7518
7519         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
7520         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
7521                 return NULL;
7522
7523         /* in other cases we need to find the original method */
7524         return mono_marshal_method_from_wrapper (method);
7525 }
7526
7527 static void
7528 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
7529 {
7530         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
7531         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
7532         if (ex)
7533                 emit_throw_exception (cfg, ex);
7534 }
7535
7536 static void
7537 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
7538 {
7539         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
7540         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
7541         if (ex)
7542                 emit_throw_exception (cfg, ex);
7543 }
7544
7545 /*
7546  * Check that the IL instructions at ip are the array initialization
7547  * sequence and return the pointer to the data and the size.
7548  */
7549 static const char*
7550 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
7551 {
7552         /*
7553          * newarr[System.Int32]
7554          * dup
7555          * ldtoken field valuetype ...
7556          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
7557          */
7558         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
7559                 MonoError error;
7560                 guint32 token = read32 (ip + 7);
7561                 guint32 field_token = read32 (ip + 2);
7562                 guint32 field_index = field_token & 0xffffff;
7563                 guint32 rva;
7564                 const char *data_ptr;
7565                 int size = 0;
7566                 MonoMethod *cmethod;
7567                 MonoClass *dummy_class;
7568                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
7569                 int dummy_align;
7570
7571                 if (!field) {
7572                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7573                         return NULL;
7574                 }
7575
7576                 *out_field_token = field_token;
7577
7578                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
7579                 if (!cmethod)
7580                         return NULL;
7581                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
7582                         return NULL;
7583                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
7584                 case MONO_TYPE_BOOLEAN:
7585                 case MONO_TYPE_I1:
7586                 case MONO_TYPE_U1:
7587                         size = 1; break;
7588                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
7589 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
7590                 case MONO_TYPE_CHAR:
7591                 case MONO_TYPE_I2:
7592                 case MONO_TYPE_U2:
7593                         size = 2; break;
7594                 case MONO_TYPE_I4:
7595                 case MONO_TYPE_U4:
7596                 case MONO_TYPE_R4:
7597                         size = 4; break;
7598                 case MONO_TYPE_R8:
7599                 case MONO_TYPE_I8:
7600                 case MONO_TYPE_U8:
7601                         size = 8; break;
7602 #endif
7603                 default:
7604                         return NULL;
7605                 }
7606                 size *= len;
7607                 if (size > mono_type_size (field->type, &dummy_align))
7608                     return NULL;
7609                 *out_size = size;
7610                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
7611                 if (!image_is_dynamic (method->klass->image)) {
7612                         field_index = read32 (ip + 2) & 0xffffff;
7613                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
7614                         data_ptr = mono_image_rva_map (method->klass->image, rva);
7615                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
7616                         /* for aot code we do the lookup on load */
7617                         if (aot && data_ptr)
7618                                 return (const char *)GUINT_TO_POINTER (rva);
7619                 } else {
7620                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
7621                         g_assert (!aot);
7622                         data_ptr = mono_field_get_data (field);
7623                 }
7624                 return data_ptr;
7625         }
7626         return NULL;
7627 }
7628
7629 static void
7630 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
7631 {
7632         MonoError error;
7633         char *method_fname = mono_method_full_name (method, TRUE);
7634         char *method_code;
7635         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
7636
7637         if (!header) {
7638                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
7639                 mono_error_cleanup (&error);
7640         } else if (header->code_size == 0)
7641                 method_code = g_strdup ("method body is empty.");
7642         else
7643                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
7644         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
7645         g_free (method_fname);
7646         g_free (method_code);
7647         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7648 }
7649
7650 static void
7651 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
7652 {
7653         MonoInst *ins;
7654         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
7655         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
7656                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
7657                 /* Optimize reg-reg moves away */
7658                 /* 
7659                  * Can't optimize other opcodes, since sp[0] might point to
7660                  * the last ins of a decomposed opcode.
7661                  */
7662                 sp [0]->dreg = (cfg)->locals [n]->dreg;
7663         } else {
7664                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
7665         }
7666 }
7667
7668 /*
7669  * ldloca inhibits many optimizations so try to get rid of it in common
7670  * cases.
7671  */
7672 static inline unsigned char *
7673 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
7674 {
7675         int local, token;
7676         MonoClass *klass;
7677         MonoType *type;
7678
7679         if (size == 1) {
7680                 local = ip [1];
7681                 ip += 2;
7682         } else {
7683                 local = read16 (ip + 2);
7684                 ip += 4;
7685         }
7686         
7687         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
7688                 /* From the INITOBJ case */
7689                 token = read32 (ip + 2);
7690                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
7691                 CHECK_TYPELOAD (klass);
7692                 type = mini_get_underlying_type (&klass->byval_arg);
7693                 emit_init_local (cfg, local, type, TRUE);
7694                 return ip + 6;
7695         }
7696  exception_exit:
7697         return NULL;
7698 }
7699
7700 static MonoInst*
7701 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
7702 {
7703         MonoInst *icall_args [16];
7704         MonoInst *call_target, *ins, *vtable_ins;
7705         int arg_reg, this_reg, vtable_reg;
7706         gboolean is_iface = cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE;
7707         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
7708         gboolean variant_iface = FALSE;
7709         guint32 slot;
7710         int offset;
7711
7712         /*
7713          * In llvm-only mode, vtables contain function descriptors instead of
7714          * method addresses/trampolines.
7715          */
7716         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
7717
7718         if (is_iface)
7719                 slot = mono_method_get_imt_slot (cmethod);
7720         else
7721                 slot = mono_method_get_vtable_index (cmethod);
7722
7723         this_reg = sp [0]->dreg;
7724
7725         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
7726                 variant_iface = TRUE;
7727
7728         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
7729                 /*
7730                  * The simplest case, a normal virtual call.
7731                  */
7732                 int slot_reg = alloc_preg (cfg);
7733                 int addr_reg = alloc_preg (cfg);
7734                 int arg_reg = alloc_preg (cfg);
7735                 MonoBasicBlock *non_null_bb;
7736
7737                 vtable_reg = alloc_preg (cfg);
7738                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7739                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7740
7741                 /* Load the vtable slot, which contains a function descriptor. */
7742                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7743
7744                 NEW_BBLOCK (cfg, non_null_bb);
7745
7746                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7747                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
7748                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
7749
7750                 /* Slow path */
7751                 // FIXME: Make the wrapper use the preserveall cconv
7752                 // FIXME: Use one icall per slot for small slot numbers ?
7753                 icall_args [0] = vtable_ins;
7754                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7755                 /* Make the icall return the vtable slot value to save some code space */
7756                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
7757                 ins->dreg = slot_reg;
7758                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
7759
7760                 /* Fastpath */
7761                 MONO_START_BB (cfg, non_null_bb);
7762                 /* Load the address + arg from the vtable slot */
7763                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7764                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
7765
7766                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7767         }
7768
7769         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt) {
7770                 /*
7771                  * A simple interface call
7772                  *
7773                  * We make a call through an imt slot to obtain the function descriptor we need to call.
7774                  * The imt slot contains a function descriptor for a runtime function + arg.
7775                  */
7776                 int slot_reg = alloc_preg (cfg);
7777                 int addr_reg = alloc_preg (cfg);
7778                 int arg_reg = alloc_preg (cfg);
7779                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7780
7781                 vtable_reg = alloc_preg (cfg);
7782                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7783                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7784
7785                 /*
7786                  * The slot is already initialized when the vtable is created so there is no need
7787                  * to check it here.
7788                  */
7789
7790                 /* Load the imt slot, which contains a function descriptor. */
7791                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7792
7793                 /* Load the address + arg of the imt thunk from the imt slot */
7794                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7795                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7796                 /*
7797                  * IMT thunks in llvm-only mode are C functions which take an info argument
7798                  * plus the imt method and return the ftndesc to call.
7799                  */
7800                 icall_args [0] = thunk_arg_ins;
7801                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7802                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7803                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_thunk, icall_args, thunk_addr_ins, NULL, NULL);
7804
7805                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7806         }
7807
7808         if ((fsig->generic_param_count || variant_iface) && !is_gsharedvt) {
7809                 /*
7810                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7811                  * dynamically extended as more instantiations are discovered.
7812                  * This handles generic virtual methods both on classes and interfaces.
7813                  */
7814                 int slot_reg = alloc_preg (cfg);
7815                 int addr_reg = alloc_preg (cfg);
7816                 int arg_reg = alloc_preg (cfg);
7817                 int ftndesc_reg = alloc_preg (cfg);
7818                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7819                 MonoBasicBlock *slowpath_bb, *end_bb;
7820
7821                 NEW_BBLOCK (cfg, slowpath_bb);
7822                 NEW_BBLOCK (cfg, end_bb);
7823
7824                 vtable_reg = alloc_preg (cfg);
7825                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7826                 if (is_iface)
7827                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7828                 else
7829                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7830
7831                 /* Load the slot, which contains a function descriptor. */
7832                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7833
7834                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7835                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7836                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7837                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7838
7839                 /* Fastpath */
7840                 /* Same as with iface calls */
7841                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7842                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7843                 icall_args [0] = thunk_arg_ins;
7844                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7845                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7846                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_thunk, icall_args, thunk_addr_ins, NULL, NULL);
7847                 ftndesc_ins->dreg = ftndesc_reg;
7848                 /*
7849                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7850                  * they don't know about yet. Fall back to the slowpath in that case.
7851                  */
7852                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7853                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7854
7855                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7856
7857                 /* Slowpath */
7858                 MONO_START_BB (cfg, slowpath_bb);
7859                 icall_args [0] = vtable_ins;
7860                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7861                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7862                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7863                 if (is_iface)
7864                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7865                 else
7866                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7867                 ftndesc_ins->dreg = ftndesc_reg;
7868                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7869
7870                 /* Common case */
7871                 MONO_START_BB (cfg, end_bb);
7872                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7873         }
7874
7875         /*
7876          * Non-optimized cases
7877          */
7878         icall_args [0] = sp [0];
7879         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7880
7881         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7882                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7883
7884         arg_reg = alloc_preg (cfg);
7885         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7886         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7887
7888         g_assert (is_gsharedvt);
7889         if (is_iface)
7890                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7891         else
7892                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7893
7894         /*
7895          * Pass the extra argument even if the callee doesn't receive it, most
7896          * calling conventions allow this.
7897          */
7898         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7899 }
7900
7901 static gboolean
7902 is_exception_class (MonoClass *klass)
7903 {
7904         while (klass) {
7905                 if (klass == mono_defaults.exception_class)
7906                         return TRUE;
7907                 klass = klass->parent;
7908         }
7909         return FALSE;
7910 }
7911
7912 /*
7913  * is_jit_optimizer_disabled:
7914  *
7915  *   Determine whenever M's assembly has a DebuggableAttribute with the
7916  * IsJITOptimizerDisabled flag set.
7917  */
7918 static gboolean
7919 is_jit_optimizer_disabled (MonoMethod *m)
7920 {
7921         MonoError error;
7922         MonoAssembly *ass = m->klass->image->assembly;
7923         MonoCustomAttrInfo* attrs;
7924         MonoClass *klass;
7925         int i;
7926         gboolean val = FALSE;
7927
7928         g_assert (ass);
7929         if (ass->jit_optimizer_disabled_inited)
7930                 return ass->jit_optimizer_disabled;
7931
7932         klass = mono_class_try_get_debuggable_attribute_class ();
7933
7934         if (!klass) {
7935                 /* Linked away */
7936                 ass->jit_optimizer_disabled = FALSE;
7937                 mono_memory_barrier ();
7938                 ass->jit_optimizer_disabled_inited = TRUE;
7939                 return FALSE;
7940         }
7941
7942         attrs = mono_custom_attrs_from_assembly_checked (ass, &error);
7943         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7944         if (attrs) {
7945                 for (i = 0; i < attrs->num_attrs; ++i) {
7946                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7947                         const gchar *p;
7948                         MonoMethodSignature *sig;
7949
7950                         if (!attr->ctor || attr->ctor->klass != klass)
7951                                 continue;
7952                         /* Decode the attribute. See reflection.c */
7953                         p = (const char*)attr->data;
7954                         g_assert (read16 (p) == 0x0001);
7955                         p += 2;
7956
7957                         // FIXME: Support named parameters
7958                         sig = mono_method_signature (attr->ctor);
7959                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7960                                 continue;
7961                         /* Two boolean arguments */
7962                         p ++;
7963                         val = *p;
7964                 }
7965                 mono_custom_attrs_free (attrs);
7966         }
7967
7968         ass->jit_optimizer_disabled = val;
7969         mono_memory_barrier ();
7970         ass->jit_optimizer_disabled_inited = TRUE;
7971
7972         return val;
7973 }
7974
7975 static gboolean
7976 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7977 {
7978         gboolean supported_tail_call;
7979         int i;
7980
7981         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7982
7983         for (i = 0; i < fsig->param_count; ++i) {
7984                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7985                         /* These can point to the current method's stack */
7986                         supported_tail_call = FALSE;
7987         }
7988         if (fsig->hasthis && cmethod->klass->valuetype)
7989                 /* this might point to the current method's stack */
7990                 supported_tail_call = FALSE;
7991         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7992                 supported_tail_call = FALSE;
7993         if (cfg->method->save_lmf)
7994                 supported_tail_call = FALSE;
7995         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7996                 supported_tail_call = FALSE;
7997         if (call_opcode != CEE_CALL)
7998                 supported_tail_call = FALSE;
7999
8000         /* Debugging support */
8001 #if 0
8002         if (supported_tail_call) {
8003                 if (!mono_debug_count ())
8004                         supported_tail_call = FALSE;
8005         }
8006 #endif
8007
8008         return supported_tail_call;
8009 }
8010
8011 /*
8012  * handle_ctor_call:
8013  *
8014  *   Handle calls made to ctors from NEWOBJ opcodes.
8015  */
8016 static void
8017 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
8018                                   MonoInst **sp, guint8 *ip, int *inline_costs)
8019 {
8020         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
8021
8022         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
8023                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
8024                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
8025                         mono_class_vtable (cfg->domain, cmethod->klass);
8026                         CHECK_TYPELOAD (cmethod->klass);
8027
8028                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
8029                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8030                 } else {
8031                         if (context_used) {
8032                                 vtable_arg = emit_get_rgctx_klass (cfg, context_used,
8033                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8034                         } else {
8035                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8036
8037                                 CHECK_TYPELOAD (cmethod->klass);
8038                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8039                         }
8040                 }
8041         }
8042
8043         /* Avoid virtual calls to ctors if possible */
8044         if (mono_class_is_marshalbyref (cmethod->klass))
8045                 callvirt_this_arg = sp [0];
8046
8047         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
8048                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
8049                 CHECK_CFG_EXCEPTION;
8050         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
8051                            mono_method_check_inlining (cfg, cmethod) &&
8052                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
8053                 int costs;
8054
8055                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
8056                         cfg->real_offset += 5;
8057
8058                         *inline_costs += costs - 5;
8059                 } else {
8060                         INLINE_FAILURE ("inline failure");
8061                         // FIXME-VT: Clean this up
8062                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8063                                 GSHAREDVT_FAILURE(*ip);
8064                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
8065                 }
8066         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8067                 MonoInst *addr;
8068
8069                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
8070
8071                 if (cfg->llvm_only) {
8072                         // FIXME: Avoid initializing vtable_arg
8073                         emit_llvmonly_calli (cfg, fsig, sp, addr);
8074                 } else {
8075                         mono_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
8076                 }
8077         } else if (context_used &&
8078                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8079                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
8080                 MonoInst *cmethod_addr;
8081
8082                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
8083
8084                 if (cfg->llvm_only) {
8085                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
8086                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8087                         emit_llvmonly_calli (cfg, fsig, sp, addr);
8088                 } else {
8089                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
8090                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8091
8092                         mono_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
8093                 }
8094         } else {
8095                 INLINE_FAILURE ("ctor call");
8096                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
8097                                                                                   callvirt_this_arg, NULL, vtable_arg);
8098         }
8099  exception_exit:
8100         return;
8101 }
8102
8103 static void
8104 emit_setret (MonoCompile *cfg, MonoInst *val)
8105 {
8106         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
8107         MonoInst *ins;
8108
8109         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
8110                 MonoInst *ret_addr;
8111
8112                 if (!cfg->vret_addr) {
8113                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
8114                 } else {
8115                         EMIT_NEW_RETLOADA (cfg, ret_addr);
8116
8117                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
8118                         ins->klass = mono_class_from_mono_type (ret_type);
8119                 }
8120         } else {
8121 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
8122                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
8123                         MonoInst *iargs [1];
8124                         MonoInst *conv;
8125
8126                         iargs [0] = val;
8127                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
8128                         mono_arch_emit_setret (cfg, cfg->method, conv);
8129                 } else {
8130                         mono_arch_emit_setret (cfg, cfg->method, val);
8131                 }
8132 #else
8133                 mono_arch_emit_setret (cfg, cfg->method, val);
8134 #endif
8135         }
8136 }
8137
8138 /*
8139  * mono_method_to_ir:
8140  *
8141  *   Translate the .net IL into linear IR.
8142  */
8143 int
8144 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
8145                    MonoInst *return_var, MonoInst **inline_args, 
8146                    guint inline_offset, gboolean is_virtual_call)
8147 {
8148         MonoError error;
8149         MonoInst *ins, **sp, **stack_start;
8150         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
8151         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
8152         MonoMethod *cmethod, *method_definition;
8153         MonoInst **arg_array;
8154         MonoMethodHeader *header;
8155         MonoImage *image;
8156         guint32 token, ins_flag;
8157         MonoClass *klass;
8158         MonoClass *constrained_class = NULL;
8159         unsigned char *ip, *end, *target, *err_pos;
8160         MonoMethodSignature *sig;
8161         MonoGenericContext *generic_context = NULL;
8162         MonoGenericContainer *generic_container = NULL;
8163         MonoType **param_types;
8164         int i, n, start_new_bblock, dreg;
8165         int num_calls = 0, inline_costs = 0;
8166         int breakpoint_id = 0;
8167         guint num_args;
8168         GSList *class_inits = NULL;
8169         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
8170         int context_used;
8171         gboolean init_locals, seq_points, skip_dead_blocks;
8172         gboolean sym_seq_points = FALSE;
8173         MonoDebugMethodInfo *minfo;
8174         MonoBitSet *seq_point_locs = NULL;
8175         MonoBitSet *seq_point_set_locs = NULL;
8176
8177         cfg->disable_inline = is_jit_optimizer_disabled (method);
8178
8179         /* serialization and xdomain stuff may need access to private fields and methods */
8180         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
8181         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
8182         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
8183         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
8184         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
8185         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
8186
8187         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
8188         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
8189         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
8190         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
8191         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
8192
8193         image = method->klass->image;
8194         header = mono_method_get_header_checked (method, &cfg->error);
8195         if (!header) {
8196                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
8197                 goto exception_exit;
8198         }
8199         generic_container = mono_method_get_generic_container (method);
8200         sig = mono_method_signature (method);
8201         num_args = sig->hasthis + sig->param_count;
8202         ip = (unsigned char*)header->code;
8203         cfg->cil_start = ip;
8204         end = ip + header->code_size;
8205         cfg->stat_cil_code_size += header->code_size;
8206
8207         seq_points = cfg->gen_seq_points && cfg->method == method;
8208
8209         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
8210                 /* We could hit a seq point before attaching to the JIT (#8338) */
8211                 seq_points = FALSE;
8212         }
8213
8214         if (cfg->gen_sdb_seq_points && cfg->method == method) {
8215                 minfo = mono_debug_lookup_method (method);
8216                 if (minfo) {
8217                         MonoSymSeqPoint *sps;
8218                         int i, n_il_offsets;
8219
8220                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
8221                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8222                         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);
8223                         sym_seq_points = TRUE;
8224                         for (i = 0; i < n_il_offsets; ++i) {
8225                                 if (sps [i].il_offset < header->code_size)
8226                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
8227                         }
8228                         g_free (sps);
8229                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
8230                         /* Methods without line number info like auto-generated property accessors */
8231                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8232                         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);
8233                         sym_seq_points = TRUE;
8234                 }
8235         }
8236
8237         /* 
8238          * Methods without init_locals set could cause asserts in various passes
8239          * (#497220). To work around this, we emit dummy initialization opcodes
8240          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
8241          * on some platforms.
8242          */
8243         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
8244                 init_locals = header->init_locals;
8245         else
8246                 init_locals = TRUE;
8247
8248         method_definition = method;
8249         while (method_definition->is_inflated) {
8250                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
8251                 method_definition = imethod->declaring;
8252         }
8253
8254         /* SkipVerification is not allowed if core-clr is enabled */
8255         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
8256                 dont_verify = TRUE;
8257                 dont_verify_stloc = TRUE;
8258         }
8259
8260         if (sig->is_inflated)
8261                 generic_context = mono_method_get_context (method);
8262         else if (generic_container)
8263                 generic_context = &generic_container->context;
8264         cfg->generic_context = generic_context;
8265
8266         if (!cfg->gshared)
8267                 g_assert (!sig->has_type_parameters);
8268
8269         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
8270                 g_assert (method->is_inflated);
8271                 g_assert (mono_method_get_context (method)->method_inst);
8272         }
8273         if (method->is_inflated && mono_method_get_context (method)->method_inst)
8274                 g_assert (sig->generic_param_count);
8275
8276         if (cfg->method == method) {
8277                 cfg->real_offset = 0;
8278         } else {
8279                 cfg->real_offset = inline_offset;
8280         }
8281
8282         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
8283         cfg->cil_offset_to_bb_len = header->code_size;
8284
8285         cfg->current_method = method;
8286
8287         if (cfg->verbose_level > 2)
8288                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
8289
8290         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
8291         if (sig->hasthis)
8292                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
8293         for (n = 0; n < sig->param_count; ++n)
8294                 param_types [n + sig->hasthis] = sig->params [n];
8295         cfg->arg_types = param_types;
8296
8297         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
8298         if (cfg->method == method) {
8299
8300                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
8301                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
8302
8303                 /* ENTRY BLOCK */
8304                 NEW_BBLOCK (cfg, start_bblock);
8305                 cfg->bb_entry = start_bblock;
8306                 start_bblock->cil_code = NULL;
8307                 start_bblock->cil_length = 0;
8308
8309                 /* EXIT BLOCK */
8310                 NEW_BBLOCK (cfg, end_bblock);
8311                 cfg->bb_exit = end_bblock;
8312                 end_bblock->cil_code = NULL;
8313                 end_bblock->cil_length = 0;
8314                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
8315                 g_assert (cfg->num_bblocks == 2);
8316
8317                 arg_array = cfg->args;
8318
8319                 if (header->num_clauses) {
8320                         cfg->spvars = g_hash_table_new (NULL, NULL);
8321                         cfg->exvars = g_hash_table_new (NULL, NULL);
8322                 }
8323                 /* handle exception clauses */
8324                 for (i = 0; i < header->num_clauses; ++i) {
8325                         MonoBasicBlock *try_bb;
8326                         MonoExceptionClause *clause = &header->clauses [i];
8327                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
8328
8329                         try_bb->real_offset = clause->try_offset;
8330                         try_bb->try_start = TRUE;
8331                         try_bb->region = ((i + 1) << 8) | clause->flags;
8332                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
8333                         tblock->real_offset = clause->handler_offset;
8334                         tblock->flags |= BB_EXCEPTION_HANDLER;
8335
8336                         /*
8337                          * Linking the try block with the EH block hinders inlining as we won't be able to 
8338                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
8339                          */
8340                         if (COMPILE_LLVM (cfg))
8341                                 link_bblock (cfg, try_bb, tblock);
8342
8343                         if (*(ip + clause->handler_offset) == CEE_POP)
8344                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
8345
8346                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
8347                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
8348                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
8349                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
8350                                 MONO_ADD_INS (tblock, ins);
8351
8352                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
8353                                         /* finally clauses already have a seq point */
8354                                         /* seq points for filter clauses are emitted below */
8355                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
8356                                         MONO_ADD_INS (tblock, ins);
8357                                 }
8358
8359                                 /* todo: is a fault block unsafe to optimize? */
8360                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
8361                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
8362                         }
8363
8364                         /*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);
8365                           while (p < end) {
8366                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
8367                           }*/
8368                         /* catch and filter blocks get the exception object on the stack */
8369                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
8370                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8371
8372                                 /* mostly like handle_stack_args (), but just sets the input args */
8373                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
8374                                 tblock->in_scount = 1;
8375                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
8376                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
8377
8378                                 cfg->cbb = tblock;
8379
8380 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
8381                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
8382                                 if (!cfg->compile_llvm) {
8383                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
8384                                         ins->dreg = tblock->in_stack [0]->dreg;
8385                                         MONO_ADD_INS (tblock, ins);
8386                                 }
8387 #else
8388                                 MonoInst *dummy_use;
8389
8390                                 /* 
8391                                  * Add a dummy use for the exvar so its liveness info will be
8392                                  * correct.
8393                                  */
8394                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
8395 #endif
8396
8397                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8398                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
8399                                         MONO_ADD_INS (tblock, ins);
8400                                 }
8401                                 
8402                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8403                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
8404                                         tblock->flags |= BB_EXCEPTION_HANDLER;
8405                                         tblock->real_offset = clause->data.filter_offset;
8406                                         tblock->in_scount = 1;
8407                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
8408                                         /* The filter block shares the exvar with the handler block */
8409                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
8410                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
8411                                         MONO_ADD_INS (tblock, ins);
8412                                 }
8413                         }
8414
8415                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
8416                                         clause->data.catch_class &&
8417                                         cfg->gshared &&
8418                                         mono_class_check_context_used (clause->data.catch_class)) {
8419                                 /*
8420                                  * In shared generic code with catch
8421                                  * clauses containing type variables
8422                                  * the exception handling code has to
8423                                  * be able to get to the rgctx.
8424                                  * Therefore we have to make sure that
8425                                  * the vtable/mrgctx argument (for
8426                                  * static or generic methods) or the
8427                                  * "this" argument (for non-static
8428                                  * methods) are live.
8429                                  */
8430                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
8431                                                 mini_method_get_context (method)->method_inst ||
8432                                                 method->klass->valuetype) {
8433                                         mono_get_vtable_var (cfg);
8434                                 } else {
8435                                         MonoInst *dummy_use;
8436
8437                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
8438                                 }
8439                         }
8440                 }
8441         } else {
8442                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
8443                 cfg->cbb = start_bblock;
8444                 cfg->args = arg_array;
8445                 mono_save_args (cfg, sig, inline_args);
8446         }
8447
8448         /* FIRST CODE BLOCK */
8449         NEW_BBLOCK (cfg, tblock);
8450         tblock->cil_code = ip;
8451         cfg->cbb = tblock;
8452         cfg->ip = ip;
8453
8454         ADD_BBLOCK (cfg, tblock);
8455
8456         if (cfg->method == method) {
8457                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
8458                 if (breakpoint_id) {
8459                         MONO_INST_NEW (cfg, ins, OP_BREAK);
8460                         MONO_ADD_INS (cfg->cbb, ins);
8461                 }
8462         }
8463
8464         /* we use a separate basic block for the initialization code */
8465         NEW_BBLOCK (cfg, init_localsbb);
8466         cfg->bb_init = init_localsbb;
8467         init_localsbb->real_offset = cfg->real_offset;
8468         start_bblock->next_bb = init_localsbb;
8469         init_localsbb->next_bb = cfg->cbb;
8470         link_bblock (cfg, start_bblock, init_localsbb);
8471         link_bblock (cfg, init_localsbb, cfg->cbb);
8472                 
8473         cfg->cbb = init_localsbb;
8474
8475         if (cfg->gsharedvt && cfg->method == method) {
8476                 MonoGSharedVtMethodInfo *info;
8477                 MonoInst *var, *locals_var;
8478                 int dreg;
8479
8480                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
8481                 info->method = cfg->method;
8482                 info->count_entries = 16;
8483                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
8484                 cfg->gsharedvt_info = info;
8485
8486                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8487                 /* prevent it from being register allocated */
8488                 //var->flags |= MONO_INST_VOLATILE;
8489                 cfg->gsharedvt_info_var = var;
8490
8491                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
8492                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
8493
8494                 /* Allocate locals */
8495                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8496                 /* prevent it from being register allocated */
8497                 //locals_var->flags |= MONO_INST_VOLATILE;
8498                 cfg->gsharedvt_locals_var = locals_var;
8499
8500                 dreg = alloc_ireg (cfg);
8501                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
8502
8503                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8504                 ins->dreg = locals_var->dreg;
8505                 ins->sreg1 = dreg;
8506                 MONO_ADD_INS (cfg->cbb, ins);
8507                 cfg->gsharedvt_locals_var_ins = ins;
8508                 
8509                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8510                 /*
8511                 if (init_locals)
8512                         ins->flags |= MONO_INST_INIT;
8513                 */
8514         }
8515
8516         if (mono_security_core_clr_enabled ()) {
8517                 /* check if this is native code, e.g. an icall or a p/invoke */
8518                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
8519                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
8520                         if (wrapped) {
8521                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
8522                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
8523
8524                                 /* if this ia a native call then it can only be JITted from platform code */
8525                                 if ((icall || pinvk) && method->klass && method->klass->image) {
8526                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
8527                                                 MonoException *ex = icall ? mono_get_exception_security () : 
8528                                                         mono_get_exception_method_access ();
8529                                                 emit_throw_exception (cfg, ex);
8530                                         }
8531                                 }
8532                         }
8533                 }
8534         }
8535
8536         CHECK_CFG_EXCEPTION;
8537
8538         if (header->code_size == 0)
8539                 UNVERIFIED;
8540
8541         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
8542                 ip = err_pos;
8543                 UNVERIFIED;
8544         }
8545
8546         if (cfg->method == method)
8547                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
8548
8549         for (n = 0; n < header->num_locals; ++n) {
8550                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
8551                         UNVERIFIED;
8552         }
8553         class_inits = NULL;
8554
8555         /* We force the vtable variable here for all shared methods
8556            for the possibility that they might show up in a stack
8557            trace where their exact instantiation is needed. */
8558         if (cfg->gshared && method == cfg->method) {
8559                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
8560                                 mini_method_get_context (method)->method_inst ||
8561                                 method->klass->valuetype) {
8562                         mono_get_vtable_var (cfg);
8563                 } else {
8564                         /* FIXME: Is there a better way to do this?
8565                            We need the variable live for the duration
8566                            of the whole method. */
8567                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
8568                 }
8569         }
8570
8571         /* add a check for this != NULL to inlined methods */
8572         if (is_virtual_call) {
8573                 MonoInst *arg_ins;
8574
8575                 NEW_ARGLOAD (cfg, arg_ins, 0);
8576                 MONO_ADD_INS (cfg->cbb, arg_ins);
8577                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
8578         }
8579
8580         skip_dead_blocks = !dont_verify;
8581         if (skip_dead_blocks) {
8582                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
8583                 CHECK_CFG_ERROR;
8584                 g_assert (bb);
8585         }
8586
8587         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
8588         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
8589
8590         ins_flag = 0;
8591         start_new_bblock = 0;
8592         while (ip < end) {
8593                 if (cfg->method == method)
8594                         cfg->real_offset = ip - header->code;
8595                 else
8596                         cfg->real_offset = inline_offset;
8597                 cfg->ip = ip;
8598
8599                 context_used = 0;
8600
8601                 if (start_new_bblock) {
8602                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
8603                         if (start_new_bblock == 2) {
8604                                 g_assert (ip == tblock->cil_code);
8605                         } else {
8606                                 GET_BBLOCK (cfg, tblock, ip);
8607                         }
8608                         cfg->cbb->next_bb = tblock;
8609                         cfg->cbb = tblock;
8610                         start_new_bblock = 0;
8611                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
8612                                 if (cfg->verbose_level > 3)
8613                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
8614                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
8615                                 *sp++ = ins;
8616                         }
8617                         if (class_inits)
8618                                 g_slist_free (class_inits);
8619                         class_inits = NULL;
8620                 } else {
8621                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
8622                                 link_bblock (cfg, cfg->cbb, tblock);
8623                                 if (sp != stack_start) {
8624                                         handle_stack_args (cfg, stack_start, sp - stack_start);
8625                                         sp = stack_start;
8626                                         CHECK_UNVERIFIABLE (cfg);
8627                                 }
8628                                 cfg->cbb->next_bb = tblock;
8629                                 cfg->cbb = tblock;
8630                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
8631                                         if (cfg->verbose_level > 3)
8632                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
8633                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
8634                                         *sp++ = ins;
8635                                 }
8636                                 g_slist_free (class_inits);
8637                                 class_inits = NULL;
8638                         }
8639                 }
8640
8641                 if (skip_dead_blocks) {
8642                         int ip_offset = ip - header->code;
8643
8644                         if (ip_offset == bb->end)
8645                                 bb = bb->next;
8646
8647                         if (bb->dead) {
8648                                 int op_size = mono_opcode_size (ip, end);
8649                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
8650
8651                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
8652
8653                                 if (ip_offset + op_size == bb->end) {
8654                                         MONO_INST_NEW (cfg, ins, OP_NOP);
8655                                         MONO_ADD_INS (cfg->cbb, ins);
8656                                         start_new_bblock = 1;
8657                                 }
8658
8659                                 ip += op_size;
8660                                 continue;
8661                         }
8662                 }
8663                 /*
8664                  * Sequence points are points where the debugger can place a breakpoint.
8665                  * Currently, we generate these automatically at points where the IL
8666                  * stack is empty.
8667                  */
8668                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
8669                         /*
8670                          * Make methods interruptable at the beginning, and at the targets of
8671                          * backward branches.
8672                          * Also, do this at the start of every bblock in methods with clauses too,
8673                          * to be able to handle instructions with inprecise control flow like
8674                          * throw/endfinally.
8675                          * Backward branches are handled at the end of method-to-ir ().
8676                          */
8677                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
8678                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
8679
8680                         /* Avoid sequence points on empty IL like .volatile */
8681                         // FIXME: Enable this
8682                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
8683                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
8684                         if ((sp != stack_start) && !sym_seq_point)
8685                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
8686                         MONO_ADD_INS (cfg->cbb, ins);
8687
8688                         if (sym_seq_points)
8689                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
8690                 }
8691
8692                 cfg->cbb->real_offset = cfg->real_offset;
8693
8694                 if ((cfg->method == method) && cfg->coverage_info) {
8695                         guint32 cil_offset = ip - header->code;
8696                         cfg->coverage_info->data [cil_offset].cil_code = ip;
8697
8698                         /* TODO: Use an increment here */
8699 #if defined(TARGET_X86)
8700                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
8701                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
8702                         ins->inst_imm = 1;
8703                         MONO_ADD_INS (cfg->cbb, ins);
8704 #else
8705                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
8706                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
8707 #endif
8708                 }
8709
8710                 if (cfg->verbose_level > 3)
8711                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8712
8713                 switch (*ip) {
8714                 case CEE_NOP:
8715                         if (seq_points && !sym_seq_points && sp != stack_start) {
8716                                 /*
8717                                  * The C# compiler uses these nops to notify the JIT that it should
8718                                  * insert seq points.
8719                                  */
8720                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
8721                                 MONO_ADD_INS (cfg->cbb, ins);
8722                         }
8723                         if (cfg->keep_cil_nops)
8724                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
8725                         else
8726                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8727                         ip++;
8728                         MONO_ADD_INS (cfg->cbb, ins);
8729                         break;
8730                 case CEE_BREAK:
8731                         if (should_insert_brekpoint (cfg->method)) {
8732                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
8733                         } else {
8734                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8735                         }
8736                         ip++;
8737                         MONO_ADD_INS (cfg->cbb, ins);
8738                         break;
8739                 case CEE_LDARG_0:
8740                 case CEE_LDARG_1:
8741                 case CEE_LDARG_2:
8742                 case CEE_LDARG_3:
8743                         CHECK_STACK_OVF (1);
8744                         n = (*ip)-CEE_LDARG_0;
8745                         CHECK_ARG (n);
8746                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8747                         ip++;
8748                         *sp++ = ins;
8749                         break;
8750                 case CEE_LDLOC_0:
8751                 case CEE_LDLOC_1:
8752                 case CEE_LDLOC_2:
8753                 case CEE_LDLOC_3:
8754                         CHECK_STACK_OVF (1);
8755                         n = (*ip)-CEE_LDLOC_0;
8756                         CHECK_LOCAL (n);
8757                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8758                         ip++;
8759                         *sp++ = ins;
8760                         break;
8761                 case CEE_STLOC_0:
8762                 case CEE_STLOC_1:
8763                 case CEE_STLOC_2:
8764                 case CEE_STLOC_3: {
8765                         CHECK_STACK (1);
8766                         n = (*ip)-CEE_STLOC_0;
8767                         CHECK_LOCAL (n);
8768                         --sp;
8769                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8770                                 UNVERIFIED;
8771                         emit_stloc_ir (cfg, sp, header, n);
8772                         ++ip;
8773                         inline_costs += 1;
8774                         break;
8775                         }
8776                 case CEE_LDARG_S:
8777                         CHECK_OPSIZE (2);
8778                         CHECK_STACK_OVF (1);
8779                         n = ip [1];
8780                         CHECK_ARG (n);
8781                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8782                         *sp++ = ins;
8783                         ip += 2;
8784                         break;
8785                 case CEE_LDARGA_S:
8786                         CHECK_OPSIZE (2);
8787                         CHECK_STACK_OVF (1);
8788                         n = ip [1];
8789                         CHECK_ARG (n);
8790                         NEW_ARGLOADA (cfg, ins, n);
8791                         MONO_ADD_INS (cfg->cbb, ins);
8792                         *sp++ = ins;
8793                         ip += 2;
8794                         break;
8795                 case CEE_STARG_S:
8796                         CHECK_OPSIZE (2);
8797                         CHECK_STACK (1);
8798                         --sp;
8799                         n = ip [1];
8800                         CHECK_ARG (n);
8801                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8802                                 UNVERIFIED;
8803                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8804                         ip += 2;
8805                         break;
8806                 case CEE_LDLOC_S:
8807                         CHECK_OPSIZE (2);
8808                         CHECK_STACK_OVF (1);
8809                         n = ip [1];
8810                         CHECK_LOCAL (n);
8811                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8812                         *sp++ = ins;
8813                         ip += 2;
8814                         break;
8815                 case CEE_LDLOCA_S: {
8816                         unsigned char *tmp_ip;
8817                         CHECK_OPSIZE (2);
8818                         CHECK_STACK_OVF (1);
8819                         CHECK_LOCAL (ip [1]);
8820
8821                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8822                                 ip = tmp_ip;
8823                                 inline_costs += 1;
8824                                 break;
8825                         }
8826
8827                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8828                         *sp++ = ins;
8829                         ip += 2;
8830                         break;
8831                 }
8832                 case CEE_STLOC_S:
8833                         CHECK_OPSIZE (2);
8834                         CHECK_STACK (1);
8835                         --sp;
8836                         CHECK_LOCAL (ip [1]);
8837                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8838                                 UNVERIFIED;
8839                         emit_stloc_ir (cfg, sp, header, ip [1]);
8840                         ip += 2;
8841                         inline_costs += 1;
8842                         break;
8843                 case CEE_LDNULL:
8844                         CHECK_STACK_OVF (1);
8845                         EMIT_NEW_PCONST (cfg, ins, NULL);
8846                         ins->type = STACK_OBJ;
8847                         ++ip;
8848                         *sp++ = ins;
8849                         break;
8850                 case CEE_LDC_I4_M1:
8851                         CHECK_STACK_OVF (1);
8852                         EMIT_NEW_ICONST (cfg, ins, -1);
8853                         ++ip;
8854                         *sp++ = ins;
8855                         break;
8856                 case CEE_LDC_I4_0:
8857                 case CEE_LDC_I4_1:
8858                 case CEE_LDC_I4_2:
8859                 case CEE_LDC_I4_3:
8860                 case CEE_LDC_I4_4:
8861                 case CEE_LDC_I4_5:
8862                 case CEE_LDC_I4_6:
8863                 case CEE_LDC_I4_7:
8864                 case CEE_LDC_I4_8:
8865                         CHECK_STACK_OVF (1);
8866                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8867                         ++ip;
8868                         *sp++ = ins;
8869                         break;
8870                 case CEE_LDC_I4_S:
8871                         CHECK_OPSIZE (2);
8872                         CHECK_STACK_OVF (1);
8873                         ++ip;
8874                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8875                         ++ip;
8876                         *sp++ = ins;
8877                         break;
8878                 case CEE_LDC_I4:
8879                         CHECK_OPSIZE (5);
8880                         CHECK_STACK_OVF (1);
8881                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8882                         ip += 5;
8883                         *sp++ = ins;
8884                         break;
8885                 case CEE_LDC_I8:
8886                         CHECK_OPSIZE (9);
8887                         CHECK_STACK_OVF (1);
8888                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8889                         ins->type = STACK_I8;
8890                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8891                         ++ip;
8892                         ins->inst_l = (gint64)read64 (ip);
8893                         MONO_ADD_INS (cfg->cbb, ins);
8894                         ip += 8;
8895                         *sp++ = ins;
8896                         break;
8897                 case CEE_LDC_R4: {
8898                         float *f;
8899                         gboolean use_aotconst = FALSE;
8900
8901 #ifdef TARGET_POWERPC
8902                         /* FIXME: Clean this up */
8903                         if (cfg->compile_aot)
8904                                 use_aotconst = TRUE;
8905 #endif
8906
8907                         /* FIXME: we should really allocate this only late in the compilation process */
8908                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8909                         CHECK_OPSIZE (5);
8910                         CHECK_STACK_OVF (1);
8911
8912                         if (use_aotconst) {
8913                                 MonoInst *cons;
8914                                 int dreg;
8915
8916                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8917
8918                                 dreg = alloc_freg (cfg);
8919                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8920                                 ins->type = cfg->r4_stack_type;
8921                         } else {
8922                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8923                                 ins->type = cfg->r4_stack_type;
8924                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8925                                 ins->inst_p0 = f;
8926                                 MONO_ADD_INS (cfg->cbb, ins);
8927                         }
8928                         ++ip;
8929                         readr4 (ip, f);
8930                         ip += 4;
8931                         *sp++ = ins;                    
8932                         break;
8933                 }
8934                 case CEE_LDC_R8: {
8935                         double *d;
8936                         gboolean use_aotconst = FALSE;
8937
8938 #ifdef TARGET_POWERPC
8939                         /* FIXME: Clean this up */
8940                         if (cfg->compile_aot)
8941                                 use_aotconst = TRUE;
8942 #endif
8943
8944                         /* FIXME: we should really allocate this only late in the compilation process */
8945                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8946                         CHECK_OPSIZE (9);
8947                         CHECK_STACK_OVF (1);
8948
8949                         if (use_aotconst) {
8950                                 MonoInst *cons;
8951                                 int dreg;
8952
8953                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8954
8955                                 dreg = alloc_freg (cfg);
8956                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8957                                 ins->type = STACK_R8;
8958                         } else {
8959                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8960                                 ins->type = STACK_R8;
8961                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8962                                 ins->inst_p0 = d;
8963                                 MONO_ADD_INS (cfg->cbb, ins);
8964                         }
8965                         ++ip;
8966                         readr8 (ip, d);
8967                         ip += 8;
8968                         *sp++ = ins;
8969                         break;
8970                 }
8971                 case CEE_DUP: {
8972                         MonoInst *temp, *store;
8973                         CHECK_STACK (1);
8974                         CHECK_STACK_OVF (1);
8975                         sp--;
8976                         ins = *sp;
8977
8978                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8979                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8980
8981                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8982                         *sp++ = ins;
8983
8984                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8985                         *sp++ = ins;
8986
8987                         ++ip;
8988                         inline_costs += 2;
8989                         break;
8990                 }
8991                 case CEE_POP:
8992                         CHECK_STACK (1);
8993                         ip++;
8994                         --sp;
8995
8996 #ifdef TARGET_X86
8997                         if (sp [0]->type == STACK_R8)
8998                                 /* we need to pop the value from the x86 FP stack */
8999                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
9000 #endif
9001                         break;
9002                 case CEE_JMP: {
9003                         MonoCallInst *call;
9004                         MonoMethodSignature *fsig;
9005                         int i, n;
9006
9007                         INLINE_FAILURE ("jmp");
9008                         GSHAREDVT_FAILURE (*ip);
9009
9010                         CHECK_OPSIZE (5);
9011                         if (stack_start != sp)
9012                                 UNVERIFIED;
9013                         token = read32 (ip + 1);
9014                         /* FIXME: check the signature matches */
9015                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9016                         CHECK_CFG_ERROR;
9017  
9018                         if (cfg->gshared && mono_method_check_context_used (cmethod))
9019                                 GENERIC_SHARING_FAILURE (CEE_JMP);
9020
9021                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9022
9023                         fsig = mono_method_signature (cmethod);
9024                         n = fsig->param_count + fsig->hasthis;
9025                         if (cfg->llvm_only) {
9026                                 MonoInst **args;
9027
9028                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
9029                                 for (i = 0; i < n; ++i)
9030                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
9031                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
9032                                 /*
9033                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
9034                                  * have to emit a normal return since llvm expects it.
9035                                  */
9036                                 if (cfg->ret)
9037                                         emit_setret (cfg, ins);
9038                                 MONO_INST_NEW (cfg, ins, OP_BR);
9039                                 ins->inst_target_bb = end_bblock;
9040                                 MONO_ADD_INS (cfg->cbb, ins);
9041                                 link_bblock (cfg, cfg->cbb, end_bblock);
9042                                 ip += 5;
9043                                 break;
9044                         } else if (cfg->backend->have_op_tail_call) {
9045                                 /* Handle tail calls similarly to calls */
9046                                 DISABLE_AOT (cfg);
9047
9048                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
9049                                 call->method = cmethod;
9050                                 call->tail_call = TRUE;
9051                                 call->signature = mono_method_signature (cmethod);
9052                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
9053                                 call->inst.inst_p0 = cmethod;
9054                                 for (i = 0; i < n; ++i)
9055                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
9056
9057                                 mono_arch_emit_call (cfg, call);
9058                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
9059                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
9060                         } else {
9061                                 for (i = 0; i < num_args; ++i)
9062                                         /* Prevent arguments from being optimized away */
9063                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
9064
9065                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9066                                 ins = (MonoInst*)call;
9067                                 ins->inst_p0 = cmethod;
9068                                 MONO_ADD_INS (cfg->cbb, ins);
9069                         }
9070
9071                         ip += 5;
9072                         start_new_bblock = 1;
9073                         break;
9074                 }
9075                 case CEE_CALLI: {
9076                         MonoInst *addr;
9077                         MonoMethodSignature *fsig;
9078
9079                         CHECK_OPSIZE (5);
9080                         token = read32 (ip + 1);
9081
9082                         ins = NULL;
9083
9084                         //GSHAREDVT_FAILURE (*ip);
9085                         cmethod = NULL;
9086                         CHECK_STACK (1);
9087                         --sp;
9088                         addr = *sp;
9089                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
9090                         CHECK_CFG_ERROR;
9091
9092                         if (method->dynamic && fsig->pinvoke) {
9093                                 MonoInst *args [3];
9094
9095                                 /*
9096                                  * This is a call through a function pointer using a pinvoke
9097                                  * signature. Have to create a wrapper and call that instead.
9098                                  * FIXME: This is very slow, need to create a wrapper at JIT time
9099                                  * instead based on the signature.
9100                                  */
9101                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
9102                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
9103                                 args [2] = addr;
9104                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
9105                         }
9106
9107                         n = fsig->param_count + fsig->hasthis;
9108
9109                         CHECK_STACK (n);
9110
9111                         //g_assert (!virtual_ || fsig->hasthis);
9112
9113                         sp -= n;
9114
9115                         inline_costs += 10 * num_calls++;
9116
9117                         /*
9118                          * Making generic calls out of gsharedvt methods.
9119                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9120                          * patching gshared method addresses into a gsharedvt method.
9121                          */
9122                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
9123                                 /*
9124                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
9125                                  */
9126                                 MonoInst *callee = addr;
9127
9128                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
9129                                         /* Not tested */
9130                                         GSHAREDVT_FAILURE (*ip);
9131
9132                                 if (cfg->llvm_only)
9133                                         // FIXME:
9134                                         GSHAREDVT_FAILURE (*ip);
9135
9136                                 addr = emit_get_rgctx_sig (cfg, context_used,
9137                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
9138                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
9139                                 goto calli_end;
9140                         }
9141
9142                         /* Prevent inlining of methods with indirect calls */
9143                         INLINE_FAILURE ("indirect call");
9144
9145                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
9146                                 MonoJumpInfoType info_type;
9147                                 gpointer info_data;
9148
9149                                 /*
9150                                  * Instead of emitting an indirect call, emit a direct call
9151                                  * with the contents of the aotconst as the patch info.
9152                                  */
9153                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
9154                                         info_type = (MonoJumpInfoType)addr->inst_c1;
9155                                         info_data = addr->inst_p0;
9156                                 } else {
9157                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
9158                                         info_data = addr->inst_right->inst_left;
9159                                 }
9160
9161                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
9162                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
9163                                         NULLIFY_INS (addr);
9164                                         goto calli_end;
9165                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9166                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
9167                                         NULLIFY_INS (addr);
9168                                         goto calli_end;
9169                                 }
9170                         }
9171                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9172
9173                         calli_end:
9174
9175                         /* End of call, INS should contain the result of the call, if any */
9176
9177                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9178                                 g_assert (ins);
9179                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9180                         }
9181
9182                         CHECK_CFG_EXCEPTION;
9183
9184                         ip += 5;
9185                         ins_flag = 0;
9186                         constrained_class = NULL;
9187                         break;
9188                 }
9189                 case CEE_CALL:
9190                 case CEE_CALLVIRT: {
9191                         MonoInst *addr = NULL;
9192                         MonoMethodSignature *fsig = NULL;
9193                         int array_rank = 0;
9194                         int virtual_ = *ip == CEE_CALLVIRT;
9195                         gboolean pass_imt_from_rgctx = FALSE;
9196                         MonoInst *imt_arg = NULL;
9197                         MonoInst *keep_this_alive = NULL;
9198                         gboolean pass_vtable = FALSE;
9199                         gboolean pass_mrgctx = FALSE;
9200                         MonoInst *vtable_arg = NULL;
9201                         gboolean check_this = FALSE;
9202                         gboolean supported_tail_call = FALSE;
9203                         gboolean tail_call = FALSE;
9204                         gboolean need_seq_point = FALSE;
9205                         guint32 call_opcode = *ip;
9206                         gboolean emit_widen = TRUE;
9207                         gboolean push_res = TRUE;
9208                         gboolean skip_ret = FALSE;
9209                         gboolean delegate_invoke = FALSE;
9210                         gboolean direct_icall = FALSE;
9211                         gboolean constrained_partial_call = FALSE;
9212                         MonoMethod *cil_method;
9213
9214                         CHECK_OPSIZE (5);
9215                         token = read32 (ip + 1);
9216
9217                         ins = NULL;
9218
9219                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9220                         CHECK_CFG_ERROR;
9221
9222                         cil_method = cmethod;
9223                                 
9224                         if (constrained_class) {
9225                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
9226                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
9227                                                 g_assert (!cmethod->klass->valuetype);
9228                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
9229                                                         constrained_partial_call = TRUE;
9230                                         }
9231                                 }
9232
9233                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
9234                                         if (cfg->verbose_level > 2)
9235                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
9236                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
9237                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
9238                                                   cfg->gshared)) {
9239                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
9240                                                 CHECK_CFG_ERROR;
9241                                         }
9242                                 } else {
9243                                         if (cfg->verbose_level > 2)
9244                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
9245
9246                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
9247                                                 /* 
9248                                                  * This is needed since get_method_constrained can't find 
9249                                                  * the method in klass representing a type var.
9250                                                  * The type var is guaranteed to be a reference type in this
9251                                                  * case.
9252                                                  */
9253                                                 if (!mini_is_gsharedvt_klass (constrained_class))
9254                                                         g_assert (!cmethod->klass->valuetype);
9255                                         } else {
9256                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
9257                                                 CHECK_CFG_ERROR;
9258                                         }
9259                                 }
9260                         }
9261                                         
9262                         if (!dont_verify && !cfg->skip_visibility) {
9263                                 MonoMethod *target_method = cil_method;
9264                                 if (method->is_inflated) {
9265                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
9266                                         CHECK_CFG_ERROR;
9267                                 }
9268                                 if (!mono_method_can_access_method (method_definition, target_method) &&
9269                                         !mono_method_can_access_method (method, cil_method))
9270                                         emit_method_access_failure (cfg, method, cil_method);
9271                         }
9272
9273                         if (mono_security_core_clr_enabled ())
9274                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
9275
9276                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
9277                                 /* MS.NET seems to silently convert this to a callvirt */
9278                                 virtual_ = 1;
9279
9280                         {
9281                                 /*
9282                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
9283                                  * converts to a callvirt.
9284                                  *
9285                                  * tests/bug-515884.il is an example of this behavior
9286                                  */
9287                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
9288                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
9289                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
9290                                         virtual_ = 1;
9291                         }
9292
9293                         if (!cmethod->klass->inited)
9294                                 if (!mono_class_init (cmethod->klass))
9295                                         TYPE_LOAD_ERROR (cmethod->klass);
9296
9297                         fsig = mono_method_signature (cmethod);
9298                         if (!fsig)
9299                                 LOAD_ERROR;
9300                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
9301                                 mini_class_is_system_array (cmethod->klass)) {
9302                                 array_rank = cmethod->klass->rank;
9303                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
9304                                 direct_icall = TRUE;
9305                         } else if (fsig->pinvoke) {
9306                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9307                                 fsig = mono_method_signature (wrapper);
9308                         } else if (constrained_class) {
9309                         } else {
9310                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9311                                 CHECK_CFG_ERROR;
9312                         }
9313
9314                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
9315                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
9316
9317                         /* See code below */
9318                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
9319                                 MonoBasicBlock *tbb;
9320
9321                                 GET_BBLOCK (cfg, tbb, ip + 5);
9322                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9323                                         /*
9324                                          * We want to extend the try block to cover the call, but we can't do it if the
9325                                          * call is made directly since its followed by an exception check.
9326                                          */
9327                                         direct_icall = FALSE;
9328                                 }
9329                         }
9330
9331                         mono_save_token_info (cfg, image, token, cil_method);
9332
9333                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
9334                                 need_seq_point = TRUE;
9335
9336                         /* Don't support calls made using type arguments for now */
9337                         /*
9338                           if (cfg->gsharedvt) {
9339                           if (mini_is_gsharedvt_signature (fsig))
9340                           GSHAREDVT_FAILURE (*ip);
9341                           }
9342                         */
9343
9344                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
9345                                 g_assert_not_reached ();
9346
9347                         n = fsig->param_count + fsig->hasthis;
9348
9349                         if (!cfg->gshared && cmethod->klass->generic_container)
9350                                 UNVERIFIED;
9351
9352                         if (!cfg->gshared)
9353                                 g_assert (!mono_method_check_context_used (cmethod));
9354
9355                         CHECK_STACK (n);
9356
9357                         //g_assert (!virtual_ || fsig->hasthis);
9358
9359                         sp -= n;
9360
9361                         /*
9362                          * We have the `constrained.' prefix opcode.
9363                          */
9364                         if (constrained_class) {
9365                                 if (mini_is_gsharedvt_klass (constrained_class)) {
9366                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
9367                                                 /* The 'Own method' case below */
9368                                         } else if (cmethod->klass->image != mono_defaults.corlib && !(cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) && !cmethod->klass->valuetype) {
9369                                                 /* 'The type parameter is instantiated as a reference type' case below. */
9370                                         } else {
9371                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
9372                                                 CHECK_CFG_EXCEPTION;
9373                                                 g_assert (ins);
9374                                                 goto call_end;
9375                                         }
9376                                 }
9377
9378                                 if (constrained_partial_call) {
9379                                         gboolean need_box = TRUE;
9380
9381                                         /*
9382                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
9383                                          * called method is not known at compile time either. The called method could end up being
9384                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
9385                                          * to box the receiver.
9386                                          * A simple solution would be to box always and make a normal virtual call, but that would
9387                                          * be bad performance wise.
9388                                          */
9389                                         if (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE && cmethod->klass->generic_class) {
9390                                                 /*
9391                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
9392                                                  */
9393                                                 need_box = FALSE;
9394                                         }
9395
9396                                         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)) {
9397                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
9398                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9399                                                 ins->klass = constrained_class;
9400                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9401                                                 CHECK_CFG_EXCEPTION;
9402                                         } else if (need_box) {
9403                                                 MonoInst *box_type;
9404                                                 MonoBasicBlock *is_ref_bb, *end_bb;
9405                                                 MonoInst *nonbox_call;
9406
9407                                                 /*
9408                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
9409                                                  * if needed.
9410                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
9411                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
9412                                                  */
9413                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
9414
9415                                                 NEW_BBLOCK (cfg, is_ref_bb);
9416                                                 NEW_BBLOCK (cfg, end_bb);
9417
9418                                                 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);
9419                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
9420                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
9421
9422                                                 /* Non-ref case */
9423                                                 nonbox_call = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9424
9425                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
9426
9427                                                 /* Ref case */
9428                                                 MONO_START_BB (cfg, is_ref_bb);
9429                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9430                                                 ins->klass = constrained_class;
9431                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9432                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9433
9434                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
9435
9436                                                 MONO_START_BB (cfg, end_bb);
9437                                                 cfg->cbb = end_bb;
9438
9439                                                 nonbox_call->dreg = ins->dreg;
9440                                                 goto call_end;
9441                                         } else {
9442                                                 g_assert (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE);
9443                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
9444                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9445                                                 goto call_end;
9446                                         }
9447                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
9448                                         /*
9449                                          * The type parameter is instantiated as a valuetype,
9450                                          * but that type doesn't override the method we're
9451                                          * calling, so we need to box `this'.
9452                                          */
9453                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9454                                         ins->klass = constrained_class;
9455                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9456                                         CHECK_CFG_EXCEPTION;
9457                                 } else if (!constrained_class->valuetype) {
9458                                         int dreg = alloc_ireg_ref (cfg);
9459
9460                                         /*
9461                                          * The type parameter is instantiated as a reference
9462                                          * type.  We have a managed pointer on the stack, so
9463                                          * we need to dereference it here.
9464                                          */
9465                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
9466                                         ins->type = STACK_OBJ;
9467                                         sp [0] = ins;
9468                                 } else {
9469                                         if (cmethod->klass->valuetype) {
9470                                                 /* Own method */
9471                                         } else {
9472                                                 /* Interface method */
9473                                                 int ioffset, slot;
9474
9475                                                 mono_class_setup_vtable (constrained_class);
9476                                                 CHECK_TYPELOAD (constrained_class);
9477                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
9478                                                 if (ioffset == -1)
9479                                                         TYPE_LOAD_ERROR (constrained_class);
9480                                                 slot = mono_method_get_vtable_slot (cmethod);
9481                                                 if (slot == -1)
9482                                                         TYPE_LOAD_ERROR (cmethod->klass);
9483                                                 cmethod = constrained_class->vtable [ioffset + slot];
9484
9485                                                 if (cmethod->klass == mono_defaults.enum_class) {
9486                                                         /* Enum implements some interfaces, so treat this as the first case */
9487                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9488                                                         ins->klass = constrained_class;
9489                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9490                                                         CHECK_CFG_EXCEPTION;
9491                                                 }
9492                                         }
9493                                         virtual_ = 0;
9494                                 }
9495                                 constrained_class = NULL;
9496                         }
9497
9498                         if (check_call_signature (cfg, fsig, sp))
9499                                 UNVERIFIED;
9500
9501                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
9502                                 delegate_invoke = TRUE;
9503
9504                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
9505                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9506                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9507                                         emit_widen = FALSE;
9508                                 }
9509
9510                                 goto call_end;
9511                         }
9512
9513                         /* 
9514                          * If the callee is a shared method, then its static cctor
9515                          * might not get called after the call was patched.
9516                          */
9517                         if (cfg->gshared && cmethod->klass != method->klass && cmethod->klass->generic_class && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
9518                                 emit_class_init (cfg, cmethod->klass);
9519                                 CHECK_TYPELOAD (cmethod->klass);
9520                         }
9521
9522                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
9523
9524                         if (cfg->gshared) {
9525                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
9526
9527                                 context_used = mini_method_check_context_used (cfg, cmethod);
9528
9529                                 if (context_used && (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
9530                                         /* Generic method interface
9531                                            calls are resolved via a
9532                                            helper function and don't
9533                                            need an imt. */
9534                                         if (!cmethod_context || !cmethod_context->method_inst)
9535                                                 pass_imt_from_rgctx = TRUE;
9536                                 }
9537
9538                                 /*
9539                                  * If a shared method calls another
9540                                  * shared method then the caller must
9541                                  * have a generic sharing context
9542                                  * because the magic trampoline
9543                                  * requires it.  FIXME: We shouldn't
9544                                  * have to force the vtable/mrgctx
9545                                  * variable here.  Instead there
9546                                  * should be a flag in the cfg to
9547                                  * request a generic sharing context.
9548                                  */
9549                                 if (context_used &&
9550                                                 ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype))
9551                                         mono_get_vtable_var (cfg);
9552                         }
9553
9554                         if (pass_vtable) {
9555                                 if (context_used) {
9556                                         vtable_arg = emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
9557                                 } else {
9558                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
9559
9560                                         CHECK_TYPELOAD (cmethod->klass);
9561                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
9562                                 }
9563                         }
9564
9565                         if (pass_mrgctx) {
9566                                 g_assert (!vtable_arg);
9567
9568                                 if (!cfg->compile_aot) {
9569                                         /* 
9570                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
9571                                          * for type load errors before.
9572                                          */
9573                                         mono_class_setup_vtable (cmethod->klass);
9574                                         CHECK_TYPELOAD (cmethod->klass);
9575                                 }
9576
9577                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
9578
9579                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
9580                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
9581                                          MONO_METHOD_IS_FINAL (cmethod)) &&
9582                                         !mono_class_is_marshalbyref (cmethod->klass)) {
9583                                         if (virtual_)
9584                                                 check_this = TRUE;
9585                                         virtual_ = 0;
9586                                 }
9587                         }
9588
9589                         if (pass_imt_from_rgctx) {
9590                                 g_assert (!pass_vtable);
9591
9592                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9593                                         cmethod, MONO_RGCTX_INFO_METHOD);
9594                         }
9595
9596                         if (check_this)
9597                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9598
9599                         /* Calling virtual generic methods */
9600                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
9601                             !(MONO_METHOD_IS_FINAL (cmethod) && 
9602                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
9603                             fsig->generic_param_count && 
9604                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
9605                                 !cfg->llvm_only) {
9606                                 MonoInst *this_temp, *this_arg_temp, *store;
9607                                 MonoInst *iargs [4];
9608
9609                                 g_assert (fsig->is_inflated);
9610
9611                                 /* Prevent inlining of methods that contain indirect calls */
9612                                 INLINE_FAILURE ("virtual generic call");
9613
9614                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
9615                                         GSHAREDVT_FAILURE (*ip);
9616
9617                                 if (cfg->backend->have_generalized_imt_thunk && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
9618                                         g_assert (!imt_arg);
9619                                         if (!context_used)
9620                                                 g_assert (cmethod->is_inflated);
9621                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
9622                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9623                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
9624                                 } else {
9625                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
9626                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
9627                                         MONO_ADD_INS (cfg->cbb, store);
9628
9629                                         /* FIXME: This should be a managed pointer */
9630                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
9631
9632                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
9633                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
9634                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
9635                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
9636                                         addr = mono_emit_jit_icall (cfg,
9637                                                                                                 mono_helper_compile_generic_method, iargs);
9638
9639                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
9640
9641                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9642                                 }
9643
9644                                 goto call_end;
9645                         }
9646
9647                         /*
9648                          * Implement a workaround for the inherent races involved in locking:
9649                          * Monitor.Enter ()
9650                          * try {
9651                          * } finally {
9652                          *    Monitor.Exit ()
9653                          * }
9654                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
9655                          * try block, the Exit () won't be executed, see:
9656                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
9657                          * To work around this, we extend such try blocks to include the last x bytes
9658                          * of the Monitor.Enter () call.
9659                          */
9660                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
9661                                 MonoBasicBlock *tbb;
9662
9663                                 GET_BBLOCK (cfg, tbb, ip + 5);
9664                                 /* 
9665                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
9666                                  * from Monitor.Enter like ArgumentNullException.
9667                                  */
9668                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9669                                         /* Mark this bblock as needing to be extended */
9670                                         tbb->extend_try_block = TRUE;
9671                                 }
9672                         }
9673
9674                         /* Conversion to a JIT intrinsic */
9675                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
9676                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9677                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9678                                         emit_widen = FALSE;
9679                                 }
9680                                 goto call_end;
9681                         }
9682                         CHECK_CFG_ERROR;
9683                         
9684                         /* Inlining */
9685                         if ((cfg->opt & MONO_OPT_INLINE) &&
9686                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
9687                             mono_method_check_inlining (cfg, cmethod)) {
9688                                 int costs;
9689                                 gboolean always = FALSE;
9690
9691                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9692                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9693                                         /* Prevent inlining of methods that call wrappers */
9694                                         INLINE_FAILURE ("wrapper call");
9695                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
9696                                         always = TRUE;
9697                                 }
9698
9699                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
9700                                 if (costs) {
9701                                         cfg->real_offset += 5;
9702
9703                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9704                                                 /* *sp is already set by inline_method */
9705                                                 sp++;
9706                                                 push_res = FALSE;
9707                                         }
9708
9709                                         inline_costs += costs;
9710
9711                                         goto call_end;
9712                                 }
9713                         }
9714
9715                         /* Tail recursion elimination */
9716                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
9717                                 gboolean has_vtargs = FALSE;
9718                                 int i;
9719
9720                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9721                                 INLINE_FAILURE ("tail call");
9722
9723                                 /* keep it simple */
9724                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
9725                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
9726                                                 has_vtargs = TRUE;
9727                                 }
9728
9729                                 if (!has_vtargs) {
9730                                         for (i = 0; i < n; ++i)
9731                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9732                                         MONO_INST_NEW (cfg, ins, OP_BR);
9733                                         MONO_ADD_INS (cfg->cbb, ins);
9734                                         tblock = start_bblock->out_bb [0];
9735                                         link_bblock (cfg, cfg->cbb, tblock);
9736                                         ins->inst_target_bb = tblock;
9737                                         start_new_bblock = 1;
9738
9739                                         /* skip the CEE_RET, too */
9740                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
9741                                                 skip_ret = TRUE;
9742                                         push_res = FALSE;
9743                                         goto call_end;
9744                                 }
9745                         }
9746
9747                         inline_costs += 10 * num_calls++;
9748
9749                         /*
9750                          * Making generic calls out of gsharedvt methods.
9751                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9752                          * patching gshared method addresses into a gsharedvt method.
9753                          */
9754                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || cmethod->klass->generic_class) &&
9755                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9756                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9757                                 MonoRgctxInfoType info_type;
9758
9759                                 if (virtual_) {
9760                                         //if (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
9761                                                 //GSHAREDVT_FAILURE (*ip);
9762                                         // disable for possible remoting calls
9763                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9764                                                 GSHAREDVT_FAILURE (*ip);
9765                                         if (fsig->generic_param_count) {
9766                                                 /* virtual generic call */
9767                                                 g_assert (!imt_arg);
9768                                                 /* Same as the virtual generic case above */
9769                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9770                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9771                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9772                                                 vtable_arg = NULL;
9773                                         } else if ((cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) && !imt_arg) {
9774                                                 /* This can happen when we call a fully instantiated iface method */
9775                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9776                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9777                                                 vtable_arg = NULL;
9778                                         }
9779                                 }
9780
9781                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9782                                         keep_this_alive = sp [0];
9783
9784                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9785                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9786                                 else
9787                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9788                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9789
9790                                 if (cfg->llvm_only) {
9791                                         // FIXME: Avoid initializing vtable_arg
9792                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9793                                 } else {
9794                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9795                                 }
9796                                 goto call_end;
9797                         }
9798
9799                         /* Generic sharing */
9800
9801                         /*
9802                          * Use this if the callee is gsharedvt sharable too, since
9803                          * at runtime we might find an instantiation so the call cannot
9804                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9805                          */
9806                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9807                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9808                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9809                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9810                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9811                                 INLINE_FAILURE ("gshared");
9812
9813                                 g_assert (cfg->gshared && cmethod);
9814                                 g_assert (!addr);
9815
9816                                 /*
9817                                  * We are compiling a call to a
9818                                  * generic method from shared code,
9819                                  * which means that we have to look up
9820                                  * the method in the rgctx and do an
9821                                  * indirect call.
9822                                  */
9823                                 if (fsig->hasthis)
9824                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9825
9826                                 if (cfg->llvm_only) {
9827                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9828                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9829                                         else
9830                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9831                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9832                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9833                                 } else {
9834                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9835                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9836                                 }
9837                                 goto call_end;
9838                         }
9839
9840                         /* Direct calls to icalls */
9841                         if (direct_icall) {
9842                                 MonoMethod *wrapper;
9843                                 int costs;
9844
9845                                 /* Inline the wrapper */
9846                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9847
9848                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9849                                 g_assert (costs > 0);
9850                                 cfg->real_offset += 5;
9851
9852                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9853                                         /* *sp is already set by inline_method */
9854                                         sp++;
9855                                         push_res = FALSE;
9856                                 }
9857
9858                                 inline_costs += costs;
9859
9860                                 goto call_end;
9861                         }
9862                                         
9863                         /* Array methods */
9864                         if (array_rank) {
9865                                 MonoInst *addr;
9866
9867                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9868                                         MonoInst *val = sp [fsig->param_count];
9869
9870                                         if (val->type == STACK_OBJ) {
9871                                                 MonoInst *iargs [2];
9872
9873                                                 iargs [0] = sp [0];
9874                                                 iargs [1] = val;
9875                                                 
9876                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9877                                         }
9878                                         
9879                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9880                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9881                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !(val->opcode == OP_PCONST && val->inst_c0 == 0))
9882                                                 emit_write_barrier (cfg, addr, val);
9883                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9884                                                 GSHAREDVT_FAILURE (*ip);
9885                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9886                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9887
9888                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9889                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9890                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9891                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9892                                         CHECK_TYPELOAD (cmethod->klass);
9893                                         
9894                                         readonly = FALSE;
9895                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9896                                         ins = addr;
9897                                 } else {
9898                                         g_assert_not_reached ();
9899                                 }
9900
9901                                 emit_widen = FALSE;
9902                                 goto call_end;
9903                         }
9904
9905                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9906                         if (ins)
9907                                 goto call_end;
9908
9909                         /* Tail prefix / tail call optimization */
9910
9911                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9912                         /* FIXME: runtime generic context pointer for jumps? */
9913                         /* FIXME: handle this for generic sharing eventually */
9914                         if ((ins_flag & MONO_INST_TAILCALL) &&
9915                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9916                                 supported_tail_call = TRUE;
9917
9918                         if (supported_tail_call) {
9919                                 MonoCallInst *call;
9920
9921                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9922                                 INLINE_FAILURE ("tail call");
9923
9924                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9925
9926                                 if (cfg->backend->have_op_tail_call) {
9927                                         /* Handle tail calls similarly to normal calls */
9928                                         tail_call = TRUE;
9929                                 } else {
9930                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9931
9932                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9933                                         call->tail_call = TRUE;
9934                                         call->method = cmethod;
9935                                         call->signature = mono_method_signature (cmethod);
9936
9937                                         /*
9938                                          * We implement tail calls by storing the actual arguments into the 
9939                                          * argument variables, then emitting a CEE_JMP.
9940                                          */
9941                                         for (i = 0; i < n; ++i) {
9942                                                 /* Prevent argument from being register allocated */
9943                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9944                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9945                                         }
9946                                         ins = (MonoInst*)call;
9947                                         ins->inst_p0 = cmethod;
9948                                         ins->inst_p1 = arg_array [0];
9949                                         MONO_ADD_INS (cfg->cbb, ins);
9950                                         link_bblock (cfg, cfg->cbb, end_bblock);
9951                                         start_new_bblock = 1;
9952
9953                                         // FIXME: Eliminate unreachable epilogs
9954
9955                                         /*
9956                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9957                                          * only reachable from this call.
9958                                          */
9959                                         GET_BBLOCK (cfg, tblock, ip + 5);
9960                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9961                                                 skip_ret = TRUE;
9962                                         push_res = FALSE;
9963
9964                                         goto call_end;
9965                                 }
9966                         }
9967
9968                         /* 
9969                          * Synchronized wrappers.
9970                          * Its hard to determine where to replace a method with its synchronized
9971                          * wrapper without causing an infinite recursion. The current solution is
9972                          * to add the synchronized wrapper in the trampolines, and to
9973                          * change the called method to a dummy wrapper, and resolve that wrapper
9974                          * to the real method in mono_jit_compile_method ().
9975                          */
9976                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9977                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9978                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9979                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9980                         }
9981
9982                         /*
9983                          * Virtual calls in llvm-only mode.
9984                          */
9985                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9986                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9987                                 goto call_end;
9988                         }
9989
9990                         /* Common call */
9991                         INLINE_FAILURE ("call");
9992                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9993                                                                                           imt_arg, vtable_arg);
9994
9995                         if (tail_call && !cfg->llvm_only) {
9996                                 link_bblock (cfg, cfg->cbb, end_bblock);
9997                                 start_new_bblock = 1;
9998
9999                                 // FIXME: Eliminate unreachable epilogs
10000
10001                                 /*
10002                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
10003                                  * only reachable from this call.
10004                                  */
10005                                 GET_BBLOCK (cfg, tblock, ip + 5);
10006                                 if (tblock == cfg->cbb || tblock->in_count == 0)
10007                                         skip_ret = TRUE;
10008                                 push_res = FALSE;
10009                         }
10010
10011                         call_end:
10012
10013                         /* End of call, INS should contain the result of the call, if any */
10014
10015                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
10016                                 g_assert (ins);
10017                                 if (emit_widen)
10018                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
10019                                 else
10020                                         *sp++ = ins;
10021                         }
10022
10023                         if (keep_this_alive) {
10024                                 MonoInst *dummy_use;
10025
10026                                 /* See mono_emit_method_call_full () */
10027                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
10028                         }
10029
10030                         CHECK_CFG_EXCEPTION;
10031
10032                         ip += 5;
10033                         if (skip_ret) {
10034                                 g_assert (*ip == CEE_RET);
10035                                 ip += 1;
10036                         }
10037                         ins_flag = 0;
10038                         constrained_class = NULL;
10039                         if (need_seq_point)
10040                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10041                         break;
10042                 }
10043                 case CEE_RET:
10044                         if (cfg->method != method) {
10045                                 /* return from inlined method */
10046                                 /* 
10047                                  * If in_count == 0, that means the ret is unreachable due to
10048                                  * being preceeded by a throw. In that case, inline_method () will
10049                                  * handle setting the return value 
10050                                  * (test case: test_0_inline_throw ()).
10051                                  */
10052                                 if (return_var && cfg->cbb->in_count) {
10053                                         MonoType *ret_type = mono_method_signature (method)->ret;
10054
10055                                         MonoInst *store;
10056                                         CHECK_STACK (1);
10057                                         --sp;
10058
10059                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
10060                                                 UNVERIFIED;
10061
10062                                         //g_assert (returnvar != -1);
10063                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
10064                                         cfg->ret_var_set = TRUE;
10065                                 } 
10066                         } else {
10067                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
10068
10069                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
10070                                         emit_pop_lmf (cfg);
10071
10072                                 if (cfg->ret) {
10073                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
10074
10075                                         if (seq_points && !sym_seq_points) {
10076                                                 /* 
10077                                                  * Place a seq point here too even through the IL stack is not
10078                                                  * empty, so a step over on
10079                                                  * call <FOO>
10080                                                  * ret
10081                                                  * will work correctly.
10082                                                  */
10083                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
10084                                                 MONO_ADD_INS (cfg->cbb, ins);
10085                                         }
10086
10087                                         g_assert (!return_var);
10088                                         CHECK_STACK (1);
10089                                         --sp;
10090
10091                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
10092                                                 UNVERIFIED;
10093
10094                                         emit_setret (cfg, *sp);
10095                                 }
10096                         }
10097                         if (sp != stack_start)
10098                                 UNVERIFIED;
10099                         MONO_INST_NEW (cfg, ins, OP_BR);
10100                         ip++;
10101                         ins->inst_target_bb = end_bblock;
10102                         MONO_ADD_INS (cfg->cbb, ins);
10103                         link_bblock (cfg, cfg->cbb, end_bblock);
10104                         start_new_bblock = 1;
10105                         break;
10106                 case CEE_BR_S:
10107                         CHECK_OPSIZE (2);
10108                         MONO_INST_NEW (cfg, ins, OP_BR);
10109                         ip++;
10110                         target = ip + 1 + (signed char)(*ip);
10111                         ++ip;
10112                         GET_BBLOCK (cfg, tblock, target);
10113                         link_bblock (cfg, cfg->cbb, tblock);
10114                         ins->inst_target_bb = tblock;
10115                         if (sp != stack_start) {
10116                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10117                                 sp = stack_start;
10118                                 CHECK_UNVERIFIABLE (cfg);
10119                         }
10120                         MONO_ADD_INS (cfg->cbb, ins);
10121                         start_new_bblock = 1;
10122                         inline_costs += BRANCH_COST;
10123                         break;
10124                 case CEE_BEQ_S:
10125                 case CEE_BGE_S:
10126                 case CEE_BGT_S:
10127                 case CEE_BLE_S:
10128                 case CEE_BLT_S:
10129                 case CEE_BNE_UN_S:
10130                 case CEE_BGE_UN_S:
10131                 case CEE_BGT_UN_S:
10132                 case CEE_BLE_UN_S:
10133                 case CEE_BLT_UN_S:
10134                         CHECK_OPSIZE (2);
10135                         CHECK_STACK (2);
10136                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
10137                         ip++;
10138                         target = ip + 1 + *(signed char*)ip;
10139                         ip++;
10140
10141                         ADD_BINCOND (NULL);
10142
10143                         sp = stack_start;
10144                         inline_costs += BRANCH_COST;
10145                         break;
10146                 case CEE_BR:
10147                         CHECK_OPSIZE (5);
10148                         MONO_INST_NEW (cfg, ins, OP_BR);
10149                         ip++;
10150
10151                         target = ip + 4 + (gint32)read32(ip);
10152                         ip += 4;
10153                         GET_BBLOCK (cfg, tblock, target);
10154                         link_bblock (cfg, cfg->cbb, tblock);
10155                         ins->inst_target_bb = tblock;
10156                         if (sp != stack_start) {
10157                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10158                                 sp = stack_start;
10159                                 CHECK_UNVERIFIABLE (cfg);
10160                         }
10161
10162                         MONO_ADD_INS (cfg->cbb, ins);
10163
10164                         start_new_bblock = 1;
10165                         inline_costs += BRANCH_COST;
10166                         break;
10167                 case CEE_BRFALSE_S:
10168                 case CEE_BRTRUE_S:
10169                 case CEE_BRFALSE:
10170                 case CEE_BRTRUE: {
10171                         MonoInst *cmp;
10172                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
10173                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
10174                         guint32 opsize = is_short ? 1 : 4;
10175
10176                         CHECK_OPSIZE (opsize);
10177                         CHECK_STACK (1);
10178                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
10179                                 UNVERIFIED;
10180                         ip ++;
10181                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
10182                         ip += opsize;
10183
10184                         sp--;
10185
10186                         GET_BBLOCK (cfg, tblock, target);
10187                         link_bblock (cfg, cfg->cbb, tblock);
10188                         GET_BBLOCK (cfg, tblock, ip);
10189                         link_bblock (cfg, cfg->cbb, tblock);
10190
10191                         if (sp != stack_start) {
10192                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10193                                 CHECK_UNVERIFIABLE (cfg);
10194                         }
10195
10196                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
10197                         cmp->sreg1 = sp [0]->dreg;
10198                         type_from_op (cfg, cmp, sp [0], NULL);
10199                         CHECK_TYPE (cmp);
10200
10201 #if SIZEOF_REGISTER == 4
10202                         if (cmp->opcode == OP_LCOMPARE_IMM) {
10203                                 /* Convert it to OP_LCOMPARE */
10204                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
10205                                 ins->type = STACK_I8;
10206                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
10207                                 ins->inst_l = 0;
10208                                 MONO_ADD_INS (cfg->cbb, ins);
10209                                 cmp->opcode = OP_LCOMPARE;
10210                                 cmp->sreg2 = ins->dreg;
10211                         }
10212 #endif
10213                         MONO_ADD_INS (cfg->cbb, cmp);
10214
10215                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
10216                         type_from_op (cfg, ins, sp [0], NULL);
10217                         MONO_ADD_INS (cfg->cbb, ins);
10218                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
10219                         GET_BBLOCK (cfg, tblock, target);
10220                         ins->inst_true_bb = tblock;
10221                         GET_BBLOCK (cfg, tblock, ip);
10222                         ins->inst_false_bb = tblock;
10223                         start_new_bblock = 2;
10224
10225                         sp = stack_start;
10226                         inline_costs += BRANCH_COST;
10227                         break;
10228                 }
10229                 case CEE_BEQ:
10230                 case CEE_BGE:
10231                 case CEE_BGT:
10232                 case CEE_BLE:
10233                 case CEE_BLT:
10234                 case CEE_BNE_UN:
10235                 case CEE_BGE_UN:
10236                 case CEE_BGT_UN:
10237                 case CEE_BLE_UN:
10238                 case CEE_BLT_UN:
10239                         CHECK_OPSIZE (5);
10240                         CHECK_STACK (2);
10241                         MONO_INST_NEW (cfg, ins, *ip);
10242                         ip++;
10243                         target = ip + 4 + (gint32)read32(ip);
10244                         ip += 4;
10245
10246                         ADD_BINCOND (NULL);
10247
10248                         sp = stack_start;
10249                         inline_costs += BRANCH_COST;
10250                         break;
10251                 case CEE_SWITCH: {
10252                         MonoInst *src1;
10253                         MonoBasicBlock **targets;
10254                         MonoBasicBlock *default_bblock;
10255                         MonoJumpInfoBBTable *table;
10256                         int offset_reg = alloc_preg (cfg);
10257                         int target_reg = alloc_preg (cfg);
10258                         int table_reg = alloc_preg (cfg);
10259                         int sum_reg = alloc_preg (cfg);
10260                         gboolean use_op_switch;
10261
10262                         CHECK_OPSIZE (5);
10263                         CHECK_STACK (1);
10264                         n = read32 (ip + 1);
10265                         --sp;
10266                         src1 = sp [0];
10267                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
10268                                 UNVERIFIED;
10269
10270                         ip += 5;
10271                         CHECK_OPSIZE (n * sizeof (guint32));
10272                         target = ip + n * sizeof (guint32);
10273
10274                         GET_BBLOCK (cfg, default_bblock, target);
10275                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
10276
10277                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
10278                         for (i = 0; i < n; ++i) {
10279                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
10280                                 targets [i] = tblock;
10281                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
10282                                 ip += 4;
10283                         }
10284
10285                         if (sp != stack_start) {
10286                                 /* 
10287                                  * Link the current bb with the targets as well, so handle_stack_args
10288                                  * will set their in_stack correctly.
10289                                  */
10290                                 link_bblock (cfg, cfg->cbb, default_bblock);
10291                                 for (i = 0; i < n; ++i)
10292                                         link_bblock (cfg, cfg->cbb, targets [i]);
10293
10294                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10295                                 sp = stack_start;
10296                                 CHECK_UNVERIFIABLE (cfg);
10297
10298                                 /* Undo the links */
10299                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
10300                                 for (i = 0; i < n; ++i)
10301                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
10302                         }
10303
10304                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
10305                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
10306
10307                         for (i = 0; i < n; ++i)
10308                                 link_bblock (cfg, cfg->cbb, targets [i]);
10309
10310                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
10311                         table->table = targets;
10312                         table->table_size = n;
10313
10314                         use_op_switch = FALSE;
10315 #ifdef TARGET_ARM
10316                         /* ARM implements SWITCH statements differently */
10317                         /* FIXME: Make it use the generic implementation */
10318                         if (!cfg->compile_aot)
10319                                 use_op_switch = TRUE;
10320 #endif
10321
10322                         if (COMPILE_LLVM (cfg))
10323                                 use_op_switch = TRUE;
10324
10325                         cfg->cbb->has_jump_table = 1;
10326
10327                         if (use_op_switch) {
10328                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
10329                                 ins->sreg1 = src1->dreg;
10330                                 ins->inst_p0 = table;
10331                                 ins->inst_many_bb = targets;
10332                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
10333                                 MONO_ADD_INS (cfg->cbb, ins);
10334                         } else {
10335                                 if (sizeof (gpointer) == 8)
10336                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
10337                                 else
10338                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
10339
10340 #if SIZEOF_REGISTER == 8
10341                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
10342                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
10343 #endif
10344
10345                                 if (cfg->compile_aot) {
10346                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
10347                                 } else {
10348                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
10349                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
10350                                         ins->inst_p0 = table;
10351                                         ins->dreg = table_reg;
10352                                         MONO_ADD_INS (cfg->cbb, ins);
10353                                 }
10354
10355                                 /* FIXME: Use load_memindex */
10356                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
10357                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
10358                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
10359                         }
10360                         start_new_bblock = 1;
10361                         inline_costs += (BRANCH_COST * 2);
10362                         break;
10363                 }
10364                 case CEE_LDIND_I1:
10365                 case CEE_LDIND_U1:
10366                 case CEE_LDIND_I2:
10367                 case CEE_LDIND_U2:
10368                 case CEE_LDIND_I4:
10369                 case CEE_LDIND_U4:
10370                 case CEE_LDIND_I8:
10371                 case CEE_LDIND_I:
10372                 case CEE_LDIND_R4:
10373                 case CEE_LDIND_R8:
10374                 case CEE_LDIND_REF:
10375                         CHECK_STACK (1);
10376                         --sp;
10377
10378                         switch (*ip) {
10379                         case CEE_LDIND_R4:
10380                         case CEE_LDIND_R8:
10381                                 dreg = alloc_freg (cfg);
10382                                 break;
10383                         case CEE_LDIND_I8:
10384                                 dreg = alloc_lreg (cfg);
10385                                 break;
10386                         case CEE_LDIND_REF:
10387                                 dreg = alloc_ireg_ref (cfg);
10388                                 break;
10389                         default:
10390                                 dreg = alloc_preg (cfg);
10391                         }
10392
10393                         NEW_LOAD_MEMBASE (cfg, ins, ldind_to_load_membase (*ip), dreg, sp [0]->dreg, 0);
10394                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
10395                         if (*ip == CEE_LDIND_R4)
10396                                 ins->type = cfg->r4_stack_type;
10397                         ins->flags |= ins_flag;
10398                         MONO_ADD_INS (cfg->cbb, ins);
10399                         *sp++ = ins;
10400                         if (ins_flag & MONO_INST_VOLATILE) {
10401                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10402                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10403                         }
10404                         ins_flag = 0;
10405                         ++ip;
10406                         break;
10407                 case CEE_STIND_REF:
10408                 case CEE_STIND_I1:
10409                 case CEE_STIND_I2:
10410                 case CEE_STIND_I4:
10411                 case CEE_STIND_I8:
10412                 case CEE_STIND_R4:
10413                 case CEE_STIND_R8:
10414                 case CEE_STIND_I:
10415                         CHECK_STACK (2);
10416                         sp -= 2;
10417
10418                         if (ins_flag & MONO_INST_VOLATILE) {
10419                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10420                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10421                         }
10422
10423                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
10424                         ins->flags |= ins_flag;
10425                         ins_flag = 0;
10426
10427                         MONO_ADD_INS (cfg->cbb, ins);
10428
10429                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [1]->opcode == OP_PCONST) && (sp [1]->inst_p0 == 0)))
10430                                 emit_write_barrier (cfg, sp [0], sp [1]);
10431
10432                         inline_costs += 1;
10433                         ++ip;
10434                         break;
10435
10436                 case CEE_MUL:
10437                         CHECK_STACK (2);
10438
10439                         MONO_INST_NEW (cfg, ins, (*ip));
10440                         sp -= 2;
10441                         ins->sreg1 = sp [0]->dreg;
10442                         ins->sreg2 = sp [1]->dreg;
10443                         type_from_op (cfg, ins, sp [0], sp [1]);
10444                         CHECK_TYPE (ins);
10445                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
10446
10447                         /* Use the immediate opcodes if possible */
10448                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
10449                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
10450                                 if (imm_opcode != -1) {
10451                                         ins->opcode = imm_opcode;
10452                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
10453                                         ins->sreg2 = -1;
10454
10455                                         NULLIFY_INS (sp [1]);
10456                                 }
10457                         }
10458
10459                         MONO_ADD_INS ((cfg)->cbb, (ins));
10460
10461                         *sp++ = mono_decompose_opcode (cfg, ins);
10462                         ip++;
10463                         break;
10464                 case CEE_ADD:
10465                 case CEE_SUB:
10466                 case CEE_DIV:
10467                 case CEE_DIV_UN:
10468                 case CEE_REM:
10469                 case CEE_REM_UN:
10470                 case CEE_AND:
10471                 case CEE_OR:
10472                 case CEE_XOR:
10473                 case CEE_SHL:
10474                 case CEE_SHR:
10475                 case CEE_SHR_UN:
10476                         CHECK_STACK (2);
10477
10478                         MONO_INST_NEW (cfg, ins, (*ip));
10479                         sp -= 2;
10480                         ins->sreg1 = sp [0]->dreg;
10481                         ins->sreg2 = sp [1]->dreg;
10482                         type_from_op (cfg, ins, sp [0], sp [1]);
10483                         CHECK_TYPE (ins);
10484                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
10485                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
10486
10487                         /* FIXME: Pass opcode to is_inst_imm */
10488
10489                         /* Use the immediate opcodes if possible */
10490                         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)) {
10491                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
10492                                 if (imm_opcode != -1) {
10493                                         ins->opcode = imm_opcode;
10494                                         if (sp [1]->opcode == OP_I8CONST) {
10495 #if SIZEOF_REGISTER == 8
10496                                                 ins->inst_imm = sp [1]->inst_l;
10497 #else
10498                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
10499                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
10500 #endif
10501                                         }
10502                                         else
10503                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
10504                                         ins->sreg2 = -1;
10505
10506                                         /* Might be followed by an instruction added by add_widen_op */
10507                                         if (sp [1]->next == NULL)
10508                                                 NULLIFY_INS (sp [1]);
10509                                 }
10510                         }
10511                         MONO_ADD_INS ((cfg)->cbb, (ins));
10512
10513                         *sp++ = mono_decompose_opcode (cfg, ins);
10514                         ip++;
10515                         break;
10516                 case CEE_NEG:
10517                 case CEE_NOT:
10518                 case CEE_CONV_I1:
10519                 case CEE_CONV_I2:
10520                 case CEE_CONV_I4:
10521                 case CEE_CONV_R4:
10522                 case CEE_CONV_R8:
10523                 case CEE_CONV_U4:
10524                 case CEE_CONV_I8:
10525                 case CEE_CONV_U8:
10526                 case CEE_CONV_OVF_I8:
10527                 case CEE_CONV_OVF_U8:
10528                 case CEE_CONV_R_UN:
10529                         CHECK_STACK (1);
10530
10531                         /* Special case this earlier so we have long constants in the IR */
10532                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
10533                                 int data = sp [-1]->inst_c0;
10534                                 sp [-1]->opcode = OP_I8CONST;
10535                                 sp [-1]->type = STACK_I8;
10536 #if SIZEOF_REGISTER == 8
10537                                 if ((*ip) == CEE_CONV_U8)
10538                                         sp [-1]->inst_c0 = (guint32)data;
10539                                 else
10540                                         sp [-1]->inst_c0 = data;
10541 #else
10542                                 sp [-1]->inst_ls_word = data;
10543                                 if ((*ip) == CEE_CONV_U8)
10544                                         sp [-1]->inst_ms_word = 0;
10545                                 else
10546                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
10547 #endif
10548                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
10549                         }
10550                         else {
10551                                 ADD_UNOP (*ip);
10552                         }
10553                         ip++;
10554                         break;
10555                 case CEE_CONV_OVF_I4:
10556                 case CEE_CONV_OVF_I1:
10557                 case CEE_CONV_OVF_I2:
10558                 case CEE_CONV_OVF_I:
10559                 case CEE_CONV_OVF_U:
10560                         CHECK_STACK (1);
10561
10562                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
10563                                 ADD_UNOP (CEE_CONV_OVF_I8);
10564                                 ADD_UNOP (*ip);
10565                         } else {
10566                                 ADD_UNOP (*ip);
10567                         }
10568                         ip++;
10569                         break;
10570                 case CEE_CONV_OVF_U1:
10571                 case CEE_CONV_OVF_U2:
10572                 case CEE_CONV_OVF_U4:
10573                         CHECK_STACK (1);
10574
10575                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
10576                                 ADD_UNOP (CEE_CONV_OVF_U8);
10577                                 ADD_UNOP (*ip);
10578                         } else {
10579                                 ADD_UNOP (*ip);
10580                         }
10581                         ip++;
10582                         break;
10583                 case CEE_CONV_OVF_I1_UN:
10584                 case CEE_CONV_OVF_I2_UN:
10585                 case CEE_CONV_OVF_I4_UN:
10586                 case CEE_CONV_OVF_I8_UN:
10587                 case CEE_CONV_OVF_U1_UN:
10588                 case CEE_CONV_OVF_U2_UN:
10589                 case CEE_CONV_OVF_U4_UN:
10590                 case CEE_CONV_OVF_U8_UN:
10591                 case CEE_CONV_OVF_I_UN:
10592                 case CEE_CONV_OVF_U_UN:
10593                 case CEE_CONV_U2:
10594                 case CEE_CONV_U1:
10595                 case CEE_CONV_I:
10596                 case CEE_CONV_U:
10597                         CHECK_STACK (1);
10598                         ADD_UNOP (*ip);
10599                         CHECK_CFG_EXCEPTION;
10600                         ip++;
10601                         break;
10602                 case CEE_ADD_OVF:
10603                 case CEE_ADD_OVF_UN:
10604                 case CEE_MUL_OVF:
10605                 case CEE_MUL_OVF_UN:
10606                 case CEE_SUB_OVF:
10607                 case CEE_SUB_OVF_UN:
10608                         CHECK_STACK (2);
10609                         ADD_BINOP (*ip);
10610                         ip++;
10611                         break;
10612                 case CEE_CPOBJ:
10613                         GSHAREDVT_FAILURE (*ip);
10614                         CHECK_OPSIZE (5);
10615                         CHECK_STACK (2);
10616                         token = read32 (ip + 1);
10617                         klass = mini_get_class (method, token, generic_context);
10618                         CHECK_TYPELOAD (klass);
10619                         sp -= 2;
10620                         if (generic_class_is_reference_type (cfg, klass)) {
10621                                 MonoInst *store, *load;
10622                                 int dreg = alloc_ireg_ref (cfg);
10623
10624                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
10625                                 load->flags |= ins_flag;
10626                                 MONO_ADD_INS (cfg->cbb, load);
10627
10628                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
10629                                 store->flags |= ins_flag;
10630                                 MONO_ADD_INS (cfg->cbb, store);
10631
10632                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
10633                                         emit_write_barrier (cfg, sp [0], sp [1]);
10634                         } else {
10635                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10636                         }
10637                         ins_flag = 0;
10638                         ip += 5;
10639                         break;
10640                 case CEE_LDOBJ: {
10641                         int loc_index = -1;
10642                         int stloc_len = 0;
10643
10644                         CHECK_OPSIZE (5);
10645                         CHECK_STACK (1);
10646                         --sp;
10647                         token = read32 (ip + 1);
10648                         klass = mini_get_class (method, token, generic_context);
10649                         CHECK_TYPELOAD (klass);
10650
10651                         /* Optimize the common ldobj+stloc combination */
10652                         switch (ip [5]) {
10653                         case CEE_STLOC_S:
10654                                 loc_index = ip [6];
10655                                 stloc_len = 2;
10656                                 break;
10657                         case CEE_STLOC_0:
10658                         case CEE_STLOC_1:
10659                         case CEE_STLOC_2:
10660                         case CEE_STLOC_3:
10661                                 loc_index = ip [5] - CEE_STLOC_0;
10662                                 stloc_len = 1;
10663                                 break;
10664                         default:
10665                                 break;
10666                         }
10667
10668                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
10669                                 CHECK_LOCAL (loc_index);
10670
10671                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10672                                 ins->dreg = cfg->locals [loc_index]->dreg;
10673                                 ins->flags |= ins_flag;
10674                                 ip += 5;
10675                                 ip += stloc_len;
10676                                 if (ins_flag & MONO_INST_VOLATILE) {
10677                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10678                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10679                                 }
10680                                 ins_flag = 0;
10681                                 break;
10682                         }
10683
10684                         /* Optimize the ldobj+stobj combination */
10685                         /* The reference case ends up being a load+store anyway */
10686                         /* Skip this if the operation is volatile. */
10687                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token) && !generic_class_is_reference_type (cfg, klass) && !(ins_flag & MONO_INST_VOLATILE)) {
10688                                 CHECK_STACK (1);
10689
10690                                 sp --;
10691
10692                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10693
10694                                 ip += 5 + 5;
10695                                 ins_flag = 0;
10696                                 break;
10697                         }
10698
10699                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10700                         ins->flags |= ins_flag;
10701                         *sp++ = ins;
10702
10703                         if (ins_flag & MONO_INST_VOLATILE) {
10704                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10705                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10706                         }
10707
10708                         ip += 5;
10709                         ins_flag = 0;
10710                         inline_costs += 1;
10711                         break;
10712                 }
10713                 case CEE_LDSTR:
10714                         CHECK_STACK_OVF (1);
10715                         CHECK_OPSIZE (5);
10716                         n = read32 (ip + 1);
10717
10718                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
10719                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
10720                                 ins->type = STACK_OBJ;
10721                                 *sp = ins;
10722                         }
10723                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
10724                                 MonoInst *iargs [1];
10725                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
10726
10727                                 if (cfg->compile_aot)
10728                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
10729                                 else
10730                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
10731                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
10732                         } else {
10733                                 if (cfg->opt & MONO_OPT_SHARED) {
10734                                         MonoInst *iargs [3];
10735
10736                                         if (cfg->compile_aot) {
10737                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
10738                                         }
10739                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10740                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
10741                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
10742                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
10743                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10744                                         CHECK_CFG_ERROR;
10745                                 } else {
10746                                         if (cfg->cbb->out_of_line) {
10747                                                 MonoInst *iargs [2];
10748
10749                                                 if (image == mono_defaults.corlib) {
10750                                                         /* 
10751                                                          * Avoid relocations in AOT and save some space by using a 
10752                                                          * version of helper_ldstr specialized to mscorlib.
10753                                                          */
10754                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
10755                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
10756                                                 } else {
10757                                                         /* Avoid creating the string object */
10758                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
10759                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
10760                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
10761                                                 }
10762                                         } 
10763                                         else
10764                                         if (cfg->compile_aot) {
10765                                                 NEW_LDSTRCONST (cfg, ins, image, n);
10766                                                 *sp = ins;
10767                                                 MONO_ADD_INS (cfg->cbb, ins);
10768                                         } 
10769                                         else {
10770                                                 NEW_PCONST (cfg, ins, NULL);
10771                                                 ins->type = STACK_OBJ;
10772                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10773                                                 CHECK_CFG_ERROR;
10774                                                 
10775                                                 if (!ins->inst_p0)
10776                                                         OUT_OF_MEMORY_FAILURE;
10777
10778                                                 *sp = ins;
10779                                                 MONO_ADD_INS (cfg->cbb, ins);
10780                                         }
10781                                 }
10782                         }
10783
10784                         sp++;
10785                         ip += 5;
10786                         break;
10787                 case CEE_NEWOBJ: {
10788                         MonoInst *iargs [2];
10789                         MonoMethodSignature *fsig;
10790                         MonoInst this_ins;
10791                         MonoInst *alloc;
10792                         MonoInst *vtable_arg = NULL;
10793
10794                         CHECK_OPSIZE (5);
10795                         token = read32 (ip + 1);
10796                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10797                         CHECK_CFG_ERROR;
10798
10799                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10800                         CHECK_CFG_ERROR;
10801
10802                         mono_save_token_info (cfg, image, token, cmethod);
10803
10804                         if (!mono_class_init (cmethod->klass))
10805                                 TYPE_LOAD_ERROR (cmethod->klass);
10806
10807                         context_used = mini_method_check_context_used (cfg, cmethod);
10808
10809                         if (mono_security_core_clr_enabled ())
10810                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10811
10812                         if (cfg->gshared && cmethod && cmethod->klass != method->klass && cmethod->klass->generic_class && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
10813                                 emit_class_init (cfg, cmethod->klass);
10814                                 CHECK_TYPELOAD (cmethod->klass);
10815                         }
10816
10817                         /*
10818                         if (cfg->gsharedvt) {
10819                                 if (mini_is_gsharedvt_variable_signature (sig))
10820                                         GSHAREDVT_FAILURE (*ip);
10821                         }
10822                         */
10823
10824                         n = fsig->param_count;
10825                         CHECK_STACK (n);
10826
10827                         /* 
10828                          * Generate smaller code for the common newobj <exception> instruction in
10829                          * argument checking code.
10830                          */
10831                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10832                                 is_exception_class (cmethod->klass) && n <= 2 &&
10833                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10834                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10835                                 MonoInst *iargs [3];
10836
10837                                 sp -= n;
10838
10839                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10840                                 switch (n) {
10841                                 case 0:
10842                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10843                                         break;
10844                                 case 1:
10845                                         iargs [1] = sp [0];
10846                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10847                                         break;
10848                                 case 2:
10849                                         iargs [1] = sp [0];
10850                                         iargs [2] = sp [1];
10851                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10852                                         break;
10853                                 default:
10854                                         g_assert_not_reached ();
10855                                 }
10856
10857                                 ip += 5;
10858                                 inline_costs += 5;
10859                                 break;
10860                         }
10861
10862                         /* move the args to allow room for 'this' in the first position */
10863                         while (n--) {
10864                                 --sp;
10865                                 sp [1] = sp [0];
10866                         }
10867
10868                         /* check_call_signature () requires sp[0] to be set */
10869                         this_ins.type = STACK_OBJ;
10870                         sp [0] = &this_ins;
10871                         if (check_call_signature (cfg, fsig, sp))
10872                                 UNVERIFIED;
10873
10874                         iargs [0] = NULL;
10875
10876                         if (mini_class_is_system_array (cmethod->klass)) {
10877                                 *sp = emit_get_rgctx_method (cfg, context_used,
10878                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10879
10880                                 /* Avoid varargs in the common case */
10881                                 if (fsig->param_count == 1)
10882                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10883                                 else if (fsig->param_count == 2)
10884                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10885                                 else if (fsig->param_count == 3)
10886                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10887                                 else if (fsig->param_count == 4)
10888                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10889                                 else
10890                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10891                         } else if (cmethod->string_ctor) {
10892                                 g_assert (!context_used);
10893                                 g_assert (!vtable_arg);
10894                                 /* we simply pass a null pointer */
10895                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10896                                 /* now call the string ctor */
10897                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10898                         } else {
10899                                 if (cmethod->klass->valuetype) {
10900                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10901                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10902                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10903
10904                                         alloc = NULL;
10905
10906                                         /* 
10907                                          * The code generated by mini_emit_virtual_call () expects
10908                                          * iargs [0] to be a boxed instance, but luckily the vcall
10909                                          * will be transformed into a normal call there.
10910                                          */
10911                                 } else if (context_used) {
10912                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10913                                         *sp = alloc;
10914                                 } else {
10915                                         MonoVTable *vtable = NULL;
10916
10917                                         if (!cfg->compile_aot)
10918                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10919                                         CHECK_TYPELOAD (cmethod->klass);
10920
10921                                         /*
10922                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10923                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10924                                          * As a workaround, we call class cctors before allocating objects.
10925                                          */
10926                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10927                                                 emit_class_init (cfg, cmethod->klass);
10928                                                 if (cfg->verbose_level > 2)
10929                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10930                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10931                                         }
10932
10933                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10934                                         *sp = alloc;
10935                                 }
10936                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10937
10938                                 if (alloc)
10939                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10940
10941                                 /* Now call the actual ctor */
10942                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10943                                 CHECK_CFG_EXCEPTION;
10944                         }
10945
10946                         if (alloc == NULL) {
10947                                 /* Valuetype */
10948                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10949                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10950                                 *sp++= ins;
10951                         } else {
10952                                 *sp++ = alloc;
10953                         }
10954                         
10955                         ip += 5;
10956                         inline_costs += 5;
10957                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10958                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10959                         break;
10960                 }
10961                 case CEE_CASTCLASS:
10962                         CHECK_STACK (1);
10963                         --sp;
10964                         CHECK_OPSIZE (5);
10965                         token = read32 (ip + 1);
10966                         klass = mini_get_class (method, token, generic_context);
10967                         CHECK_TYPELOAD (klass);
10968                         if (sp [0]->type != STACK_OBJ)
10969                                 UNVERIFIED;
10970
10971                         ins = handle_castclass (cfg, klass, *sp, ip, &inline_costs);
10972                         CHECK_CFG_EXCEPTION;
10973
10974                         *sp ++ = ins;
10975                         ip += 5;
10976                         break;
10977                 case CEE_ISINST: {
10978                         CHECK_STACK (1);
10979                         --sp;
10980                         CHECK_OPSIZE (5);
10981                         token = read32 (ip + 1);
10982                         klass = mini_get_class (method, token, generic_context);
10983                         CHECK_TYPELOAD (klass);
10984                         if (sp [0]->type != STACK_OBJ)
10985                                 UNVERIFIED;
10986  
10987                         context_used = mini_class_check_context_used (cfg, klass);
10988
10989                         if (!context_used && mini_class_has_reference_variant_generic_argument (cfg, klass, context_used)) {
10990                                 MonoMethod *mono_isinst = mono_marshal_get_isinst_with_cache ();
10991                                 MonoInst *args [3];
10992                                 int idx;
10993
10994                                 /* obj */
10995                                 args [0] = *sp;
10996
10997                                 /* klass */
10998                                 EMIT_NEW_CLASSCONST (cfg, args [1], klass);
10999
11000                                 /* inline cache*/
11001                                 idx = get_castclass_cache_idx (cfg);
11002                                 args [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CASTCLASS_CACHE, GINT_TO_POINTER (idx));
11003
11004                                 *sp++ = mono_emit_method_call (cfg, mono_isinst, args, NULL);
11005                                 ip += 5;
11006                                 inline_costs += 2;
11007                         } else if (!context_used && (mono_class_is_marshalbyref (klass) || klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
11008                                 MonoMethod *mono_isinst;
11009                                 MonoInst *iargs [1];
11010                                 int costs;
11011
11012                                 mono_isinst = mono_marshal_get_isinst (klass); 
11013                                 iargs [0] = sp [0];
11014
11015                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), 
11016                                                                            iargs, ip, cfg->real_offset, TRUE);
11017                                 CHECK_CFG_EXCEPTION;
11018                                 g_assert (costs > 0);
11019                                 
11020                                 ip += 5;
11021                                 cfg->real_offset += 5;
11022
11023                                 *sp++= iargs [0];
11024
11025                                 inline_costs += costs;
11026                         }
11027                         else {
11028                                 ins = handle_isinst (cfg, klass, *sp, context_used);
11029                                 CHECK_CFG_EXCEPTION;
11030                                 *sp ++ = ins;
11031                                 ip += 5;
11032                         }
11033                         break;
11034                 }
11035                 case CEE_UNBOX_ANY: {
11036                         MonoInst *res, *addr;
11037
11038                         CHECK_STACK (1);
11039                         --sp;
11040                         CHECK_OPSIZE (5);
11041                         token = read32 (ip + 1);
11042                         klass = mini_get_class (method, token, generic_context);
11043                         CHECK_TYPELOAD (klass);
11044
11045                         mono_save_token_info (cfg, image, token, klass);
11046
11047                         context_used = mini_class_check_context_used (cfg, klass);
11048
11049                         if (mini_is_gsharedvt_klass (klass)) {
11050                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
11051                                 inline_costs += 2;
11052                         } else if (generic_class_is_reference_type (cfg, klass)) {
11053                                 res = handle_castclass (cfg, klass, *sp, ip, &inline_costs);
11054                                 CHECK_CFG_EXCEPTION;
11055                         } else if (mono_class_is_nullable (klass)) {
11056                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
11057                         } else {
11058                                 addr = handle_unbox (cfg, klass, sp, context_used);
11059                                 /* LDOBJ */
11060                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11061                                 res = ins;
11062                                 inline_costs += 2;
11063                         }
11064
11065                         *sp ++ = res;
11066                         ip += 5;
11067                         break;
11068                 }
11069                 case CEE_BOX: {
11070                         MonoInst *val;
11071                         MonoClass *enum_class;
11072                         MonoMethod *has_flag;
11073
11074                         CHECK_STACK (1);
11075                         --sp;
11076                         val = *sp;
11077                         CHECK_OPSIZE (5);
11078                         token = read32 (ip + 1);
11079                         klass = mini_get_class (method, token, generic_context);
11080                         CHECK_TYPELOAD (klass);
11081
11082                         mono_save_token_info (cfg, image, token, klass);
11083
11084                         context_used = mini_class_check_context_used (cfg, klass);
11085
11086                         if (generic_class_is_reference_type (cfg, klass)) {
11087                                 *sp++ = val;
11088                                 ip += 5;
11089                                 break;
11090                         }
11091
11092                         if (klass == mono_defaults.void_class)
11093                                 UNVERIFIED;
11094                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
11095                                 UNVERIFIED;
11096                         /* frequent check in generic code: box (struct), brtrue */
11097
11098                         /*
11099                          * Look for:
11100                          *
11101                          *   <push int/long ptr>
11102                          *   <push int/long>
11103                          *   box MyFlags
11104                          *   constrained. MyFlags
11105                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
11106                          *
11107                          * If we find this sequence and the operand types on box and constrained
11108                          * are equal, we can emit a specialized instruction sequence instead of
11109                          * the very slow HasFlag () call.
11110                          */
11111                         if ((cfg->opt & MONO_OPT_INTRINS) &&
11112                             /* Cheap checks first. */
11113                             ip + 5 + 6 + 5 < end &&
11114                             ip [5] == CEE_PREFIX1 &&
11115                             ip [6] == CEE_CONSTRAINED_ &&
11116                             ip [11] == CEE_CALLVIRT &&
11117                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
11118                             mono_class_is_enum (klass) &&
11119                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
11120                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
11121                             has_flag->klass == mono_defaults.enum_class &&
11122                             !strcmp (has_flag->name, "HasFlag") &&
11123                             has_flag->signature->hasthis &&
11124                             has_flag->signature->param_count == 1) {
11125                                 CHECK_TYPELOAD (enum_class);
11126
11127                                 if (enum_class == klass) {
11128                                         MonoInst *enum_this, *enum_flag;
11129
11130                                         ip += 5 + 6 + 5;
11131                                         --sp;
11132
11133                                         enum_this = sp [0];
11134                                         enum_flag = sp [1];
11135
11136                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
11137                                         break;
11138                                 }
11139                         }
11140
11141                         // FIXME: LLVM can't handle the inconsistent bb linking
11142                         if (!mono_class_is_nullable (klass) &&
11143                                 !mini_is_gsharedvt_klass (klass) &&
11144                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
11145                                 (ip [5] == CEE_BRTRUE || 
11146                                  ip [5] == CEE_BRTRUE_S ||
11147                                  ip [5] == CEE_BRFALSE ||
11148                                  ip [5] == CEE_BRFALSE_S)) {
11149                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
11150                                 int dreg;
11151                                 MonoBasicBlock *true_bb, *false_bb;
11152
11153                                 ip += 5;
11154
11155                                 if (cfg->verbose_level > 3) {
11156                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
11157                                         printf ("<box+brtrue opt>\n");
11158                                 }
11159
11160                                 switch (*ip) {
11161                                 case CEE_BRTRUE_S:
11162                                 case CEE_BRFALSE_S:
11163                                         CHECK_OPSIZE (2);
11164                                         ip++;
11165                                         target = ip + 1 + (signed char)(*ip);
11166                                         ip++;
11167                                         break;
11168                                 case CEE_BRTRUE:
11169                                 case CEE_BRFALSE:
11170                                         CHECK_OPSIZE (5);
11171                                         ip++;
11172                                         target = ip + 4 + (gint)(read32 (ip));
11173                                         ip += 4;
11174                                         break;
11175                                 default:
11176                                         g_assert_not_reached ();
11177                                 }
11178
11179                                 /* 
11180                                  * We need to link both bblocks, since it is needed for handling stack
11181                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
11182                                  * Branching to only one of them would lead to inconsistencies, so
11183                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
11184                                  */
11185                                 GET_BBLOCK (cfg, true_bb, target);
11186                                 GET_BBLOCK (cfg, false_bb, ip);
11187
11188                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
11189                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
11190
11191                                 if (sp != stack_start) {
11192                                         handle_stack_args (cfg, stack_start, sp - stack_start);
11193                                         sp = stack_start;
11194                                         CHECK_UNVERIFIABLE (cfg);
11195                                 }
11196
11197                                 if (COMPILE_LLVM (cfg)) {
11198                                         dreg = alloc_ireg (cfg);
11199                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
11200                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
11201
11202                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
11203                                 } else {
11204                                         /* The JIT can't eliminate the iconst+compare */
11205                                         MONO_INST_NEW (cfg, ins, OP_BR);
11206                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
11207                                         MONO_ADD_INS (cfg->cbb, ins);
11208                                 }
11209
11210                                 start_new_bblock = 1;
11211                                 break;
11212                         }
11213
11214                         *sp++ = handle_box (cfg, val, klass, context_used);
11215
11216                         CHECK_CFG_EXCEPTION;
11217                         ip += 5;
11218                         inline_costs += 1;
11219                         break;
11220                 }
11221                 case CEE_UNBOX: {
11222                         CHECK_STACK (1);
11223                         --sp;
11224                         CHECK_OPSIZE (5);
11225                         token = read32 (ip + 1);
11226                         klass = mini_get_class (method, token, generic_context);
11227                         CHECK_TYPELOAD (klass);
11228
11229                         mono_save_token_info (cfg, image, token, klass);
11230
11231                         context_used = mini_class_check_context_used (cfg, klass);
11232
11233                         if (mono_class_is_nullable (klass)) {
11234                                 MonoInst *val;
11235
11236                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
11237                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
11238
11239                                 *sp++= ins;
11240                         } else {
11241                                 ins = handle_unbox (cfg, klass, sp, context_used);
11242                                 *sp++ = ins;
11243                         }
11244                         ip += 5;
11245                         inline_costs += 2;
11246                         break;
11247                 }
11248                 case CEE_LDFLD:
11249                 case CEE_LDFLDA:
11250                 case CEE_STFLD:
11251                 case CEE_LDSFLD:
11252                 case CEE_LDSFLDA:
11253                 case CEE_STSFLD: {
11254                         MonoClassField *field;
11255 #ifndef DISABLE_REMOTING
11256                         int costs;
11257 #endif
11258                         guint foffset;
11259                         gboolean is_instance;
11260                         int op;
11261                         gpointer addr = NULL;
11262                         gboolean is_special_static;
11263                         MonoType *ftype;
11264                         MonoInst *store_val = NULL;
11265                         MonoInst *thread_ins;
11266
11267                         op = *ip;
11268                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
11269                         if (is_instance) {
11270                                 if (op == CEE_STFLD) {
11271                                         CHECK_STACK (2);
11272                                         sp -= 2;
11273                                         store_val = sp [1];
11274                                 } else {
11275                                         CHECK_STACK (1);
11276                                         --sp;
11277                                 }
11278                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
11279                                         UNVERIFIED;
11280                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
11281                                         UNVERIFIED;
11282                         } else {
11283                                 if (op == CEE_STSFLD) {
11284                                         CHECK_STACK (1);
11285                                         sp--;
11286                                         store_val = sp [0];
11287                                 }
11288                         }
11289
11290                         CHECK_OPSIZE (5);
11291                         token = read32 (ip + 1);
11292                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
11293                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
11294                                 klass = field->parent;
11295                         }
11296                         else {
11297                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
11298                                 CHECK_CFG_ERROR;
11299                         }
11300                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
11301                                 FIELD_ACCESS_FAILURE (method, field);
11302                         mono_class_init (klass);
11303
11304                         /* if the class is Critical then transparent code cannot access it's fields */
11305                         if (!is_instance && mono_security_core_clr_enabled ())
11306                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
11307
11308                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
11309                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
11310                         if (mono_security_core_clr_enabled ())
11311                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
11312                         */
11313
11314                         ftype = mono_field_get_type (field);
11315
11316                         /*
11317                          * LDFLD etc. is usable on static fields as well, so convert those cases to
11318                          * the static case.
11319                          */
11320                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
11321                                 switch (op) {
11322                                 case CEE_LDFLD:
11323                                         op = CEE_LDSFLD;
11324                                         break;
11325                                 case CEE_STFLD:
11326                                         op = CEE_STSFLD;
11327                                         break;
11328                                 case CEE_LDFLDA:
11329                                         op = CEE_LDSFLDA;
11330                                         break;
11331                                 default:
11332                                         g_assert_not_reached ();
11333                                 }
11334                                 is_instance = FALSE;
11335                         }
11336
11337                         context_used = mini_class_check_context_used (cfg, klass);
11338
11339                         /* INSTANCE CASE */
11340
11341                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
11342                         if (op == CEE_STFLD) {
11343                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
11344                                         UNVERIFIED;
11345 #ifndef DISABLE_REMOTING
11346                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
11347                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
11348                                         MonoInst *iargs [5];
11349
11350                                         GSHAREDVT_FAILURE (op);
11351
11352                                         iargs [0] = sp [0];
11353                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11354                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
11355                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
11356                                                     field->offset);
11357                                         iargs [4] = sp [1];
11358
11359                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
11360                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
11361                                                                                            iargs, ip, cfg->real_offset, TRUE);
11362                                                 CHECK_CFG_EXCEPTION;
11363                                                 g_assert (costs > 0);
11364                                                       
11365                                                 cfg->real_offset += 5;
11366
11367                                                 inline_costs += costs;
11368                                         } else {
11369                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
11370                                         }
11371                                 } else
11372 #endif
11373                                 {
11374                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
11375
11376                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
11377
11378                                         if (mini_is_gsharedvt_klass (klass)) {
11379                                                 MonoInst *offset_ins;
11380
11381                                                 context_used = mini_class_check_context_used (cfg, klass);
11382
11383                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11384                                                 /* The value is offset by 1 */
11385                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11386                                                 dreg = alloc_ireg_mp (cfg);
11387                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11388                                                 wbarrier_ptr_ins = ins;
11389                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
11390                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
11391                                         } else {
11392                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
11393                                         }
11394                                         if (sp [0]->opcode != OP_LDADDR)
11395                                                 store->flags |= MONO_INST_FAULT;
11396
11397                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
11398                                                 if (mini_is_gsharedvt_klass (klass)) {
11399                                                         g_assert (wbarrier_ptr_ins);
11400                                                         emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
11401                                                 } else {
11402                                                         /* insert call to write barrier */
11403                                                         MonoInst *ptr;
11404                                                         int dreg;
11405
11406                                                         dreg = alloc_ireg_mp (cfg);
11407                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
11408                                                         emit_write_barrier (cfg, ptr, sp [1]);
11409                                                 }
11410                                         }
11411
11412                                         store->flags |= ins_flag;
11413                                 }
11414                                 ins_flag = 0;
11415                                 ip += 5;
11416                                 break;
11417                         }
11418
11419 #ifndef DISABLE_REMOTING
11420                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
11421                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
11422                                 MonoInst *iargs [4];
11423
11424                                 GSHAREDVT_FAILURE (op);
11425
11426                                 iargs [0] = sp [0];
11427                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11428                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
11429                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
11430                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
11431                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
11432                                                                                    iargs, ip, cfg->real_offset, TRUE);
11433                                         CHECK_CFG_EXCEPTION;
11434                                         g_assert (costs > 0);
11435                                                       
11436                                         cfg->real_offset += 5;
11437
11438                                         *sp++ = iargs [0];
11439
11440                                         inline_costs += costs;
11441                                 } else {
11442                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
11443                                         *sp++ = ins;
11444                                 }
11445                         } else 
11446 #endif
11447                         if (is_instance) {
11448                                 if (sp [0]->type == STACK_VTYPE) {
11449                                         MonoInst *var;
11450
11451                                         /* Have to compute the address of the variable */
11452
11453                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
11454                                         if (!var)
11455                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
11456                                         else
11457                                                 g_assert (var->klass == klass);
11458                                         
11459                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
11460                                         sp [0] = ins;
11461                                 }
11462
11463                                 if (op == CEE_LDFLDA) {
11464                                         if (sp [0]->type == STACK_OBJ) {
11465                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
11466                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
11467                                         }
11468
11469                                         dreg = alloc_ireg_mp (cfg);
11470
11471                                         if (mini_is_gsharedvt_klass (klass)) {
11472                                                 MonoInst *offset_ins;
11473
11474                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11475                                                 /* The value is offset by 1 */
11476                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11477                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11478                                         } else {
11479                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
11480                                         }
11481                                         ins->klass = mono_class_from_mono_type (field->type);
11482                                         ins->type = STACK_MP;
11483                                         *sp++ = ins;
11484                                 } else {
11485                                         MonoInst *load;
11486
11487                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
11488
11489                                         if (mini_is_gsharedvt_klass (klass)) {
11490                                                 MonoInst *offset_ins;
11491
11492                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11493                                                 /* The value is offset by 1 */
11494                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11495                                                 dreg = alloc_ireg_mp (cfg);
11496                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11497                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, dreg, 0);
11498                                         } else {
11499                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, sp [0]->dreg, foffset);
11500                                         }
11501                                         load->flags |= ins_flag;
11502                                         if (sp [0]->opcode != OP_LDADDR)
11503                                                 load->flags |= MONO_INST_FAULT;
11504                                         *sp++ = load;
11505                                 }
11506                         }
11507
11508                         if (is_instance) {
11509                                 ins_flag = 0;
11510                                 ip += 5;
11511                                 break;
11512                         }
11513
11514                         /* STATIC CASE */
11515                         context_used = mini_class_check_context_used (cfg, klass);
11516
11517                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
11518                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
11519                                 CHECK_CFG_ERROR;
11520                         }
11521
11522                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
11523                          * to be called here.
11524                          */
11525                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
11526                                 mono_class_vtable (cfg->domain, klass);
11527                                 CHECK_TYPELOAD (klass);
11528                         }
11529                         mono_domain_lock (cfg->domain);
11530                         if (cfg->domain->special_static_fields)
11531                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
11532                         mono_domain_unlock (cfg->domain);
11533
11534                         is_special_static = mono_class_field_is_special_static (field);
11535
11536                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
11537                                 thread_ins = mono_get_thread_intrinsic (cfg);
11538                         else
11539                                 thread_ins = NULL;
11540
11541                         /* Generate IR to compute the field address */
11542                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
11543                                 /*
11544                                  * Fast access to TLS data
11545                                  * Inline version of get_thread_static_data () in
11546                                  * threads.c.
11547                                  */
11548                                 guint32 offset;
11549                                 int idx, static_data_reg, array_reg, dreg;
11550
11551                                 GSHAREDVT_FAILURE (op);
11552
11553                                 MONO_ADD_INS (cfg->cbb, thread_ins);
11554                                 static_data_reg = alloc_ireg (cfg);
11555                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
11556
11557                                 if (cfg->compile_aot) {
11558                                         int offset_reg, offset2_reg, idx_reg;
11559
11560                                         /* For TLS variables, this will return the TLS offset */
11561                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
11562                                         offset_reg = ins->dreg;
11563                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
11564                                         idx_reg = alloc_ireg (cfg);
11565                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
11566                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
11567                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
11568                                         array_reg = alloc_ireg (cfg);
11569                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
11570                                         offset2_reg = alloc_ireg (cfg);
11571                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
11572                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
11573                                         dreg = alloc_ireg (cfg);
11574                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
11575                                 } else {
11576                                         offset = (gsize)addr & 0x7fffffff;
11577                                         idx = offset & 0x3f;
11578
11579                                         array_reg = alloc_ireg (cfg);
11580                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
11581                                         dreg = alloc_ireg (cfg);
11582                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
11583                                 }
11584                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
11585                                         (cfg->compile_aot && is_special_static) ||
11586                                         (context_used && is_special_static)) {
11587                                 MonoInst *iargs [2];
11588
11589                                 g_assert (field->parent);
11590                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11591                                 if (context_used) {
11592                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
11593                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
11594                                 } else {
11595                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
11596                                 }
11597                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
11598                         } else if (context_used) {
11599                                 MonoInst *static_data;
11600
11601                                 /*
11602                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
11603                                         method->klass->name_space, method->klass->name, method->name,
11604                                         depth, field->offset);
11605                                 */
11606
11607                                 if (mono_class_needs_cctor_run (klass, method))
11608                                         emit_class_init (cfg, klass);
11609
11610                                 /*
11611                                  * The pointer we're computing here is
11612                                  *
11613                                  *   super_info.static_data + field->offset
11614                                  */
11615                                 static_data = emit_get_rgctx_klass (cfg, context_used,
11616                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
11617
11618                                 if (mini_is_gsharedvt_klass (klass)) {
11619                                         MonoInst *offset_ins;
11620
11621                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11622                                         /* The value is offset by 1 */
11623                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11624                                         dreg = alloc_ireg_mp (cfg);
11625                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
11626                                 } else if (field->offset == 0) {
11627                                         ins = static_data;
11628                                 } else {
11629                                         int addr_reg = mono_alloc_preg (cfg);
11630                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
11631                                 }
11632                                 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
11633                                 MonoInst *iargs [2];
11634
11635                                 g_assert (field->parent);
11636                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11637                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
11638                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
11639                         } else {
11640                                 MonoVTable *vtable = NULL;
11641
11642                                 if (!cfg->compile_aot)
11643                                         vtable = mono_class_vtable (cfg->domain, klass);
11644                                 CHECK_TYPELOAD (klass);
11645
11646                                 if (!addr) {
11647                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
11648                                                 if (!(g_slist_find (class_inits, klass))) {
11649                                                         emit_class_init (cfg, klass);
11650                                                         if (cfg->verbose_level > 2)
11651                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
11652                                                         class_inits = g_slist_prepend (class_inits, klass);
11653                                                 }
11654                                         } else {
11655                                                 if (cfg->run_cctors) {
11656                                                         /* This makes so that inline cannot trigger */
11657                                                         /* .cctors: too many apps depend on them */
11658                                                         /* running with a specific order... */
11659                                                         g_assert (vtable);
11660                                                         if (! vtable->initialized)
11661                                                                 INLINE_FAILURE ("class init");
11662                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
11663                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
11664                                                                 goto exception_exit;
11665                                                         }
11666                                                 }
11667                                         }
11668                                         if (cfg->compile_aot)
11669                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
11670                                         else {
11671                                                 g_assert (vtable);
11672                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11673                                                 g_assert (addr);
11674                                                 EMIT_NEW_PCONST (cfg, ins, addr);
11675                                         }
11676                                 } else {
11677                                         MonoInst *iargs [1];
11678                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
11679                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
11680                                 }
11681                         }
11682
11683                         /* Generate IR to do the actual load/store operation */
11684
11685                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11686                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11687                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11688                         }
11689
11690                         if (op == CEE_LDSFLDA) {
11691                                 ins->klass = mono_class_from_mono_type (ftype);
11692                                 ins->type = STACK_PTR;
11693                                 *sp++ = ins;
11694                         } else if (op == CEE_STSFLD) {
11695                                 MonoInst *store;
11696
11697                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
11698                                 store->flags |= ins_flag;
11699                         } else {
11700                                 gboolean is_const = FALSE;
11701                                 MonoVTable *vtable = NULL;
11702                                 gpointer addr = NULL;
11703
11704                                 if (!context_used) {
11705                                         vtable = mono_class_vtable (cfg->domain, klass);
11706                                         CHECK_TYPELOAD (klass);
11707                                 }
11708                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
11709                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
11710                                         int ro_type = ftype->type;
11711                                         if (!addr)
11712                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11713                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
11714                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
11715                                         }
11716
11717                                         GSHAREDVT_FAILURE (op);
11718
11719                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
11720                                         is_const = TRUE;
11721                                         switch (ro_type) {
11722                                         case MONO_TYPE_BOOLEAN:
11723                                         case MONO_TYPE_U1:
11724                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
11725                                                 sp++;
11726                                                 break;
11727                                         case MONO_TYPE_I1:
11728                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
11729                                                 sp++;
11730                                                 break;                                          
11731                                         case MONO_TYPE_CHAR:
11732                                         case MONO_TYPE_U2:
11733                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
11734                                                 sp++;
11735                                                 break;
11736                                         case MONO_TYPE_I2:
11737                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
11738                                                 sp++;
11739                                                 break;
11740                                                 break;
11741                                         case MONO_TYPE_I4:
11742                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
11743                                                 sp++;
11744                                                 break;                                          
11745                                         case MONO_TYPE_U4:
11746                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
11747                                                 sp++;
11748                                                 break;
11749                                         case MONO_TYPE_I:
11750                                         case MONO_TYPE_U:
11751                                         case MONO_TYPE_PTR:
11752                                         case MONO_TYPE_FNPTR:
11753                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11754                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
11755                                                 sp++;
11756                                                 break;
11757                                         case MONO_TYPE_STRING:
11758                                         case MONO_TYPE_OBJECT:
11759                                         case MONO_TYPE_CLASS:
11760                                         case MONO_TYPE_SZARRAY:
11761                                         case MONO_TYPE_ARRAY:
11762                                                 if (!mono_gc_is_moving ()) {
11763                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11764                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
11765                                                         sp++;
11766                                                 } else {
11767                                                         is_const = FALSE;
11768                                                 }
11769                                                 break;
11770                                         case MONO_TYPE_I8:
11771                                         case MONO_TYPE_U8:
11772                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
11773                                                 sp++;
11774                                                 break;
11775                                         case MONO_TYPE_R4:
11776                                         case MONO_TYPE_R8:
11777                                         case MONO_TYPE_VALUETYPE:
11778                                         default:
11779                                                 is_const = FALSE;
11780                                                 break;
11781                                         }
11782                                 }
11783
11784                                 if (!is_const) {
11785                                         MonoInst *load;
11786
11787                                         CHECK_STACK_OVF (1);
11788
11789                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
11790                                         load->flags |= ins_flag;
11791                                         ins_flag = 0;
11792                                         *sp++ = load;
11793                                 }
11794                         }
11795
11796                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11797                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11798                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11799                         }
11800
11801                         ins_flag = 0;
11802                         ip += 5;
11803                         break;
11804                 }
11805                 case CEE_STOBJ:
11806                         CHECK_STACK (2);
11807                         sp -= 2;
11808                         CHECK_OPSIZE (5);
11809                         token = read32 (ip + 1);
11810                         klass = mini_get_class (method, token, generic_context);
11811                         CHECK_TYPELOAD (klass);
11812                         if (ins_flag & MONO_INST_VOLATILE) {
11813                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11814                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11815                         }
11816                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11817                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
11818                         ins->flags |= ins_flag;
11819                         if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
11820                                         generic_class_is_reference_type (cfg, klass)) {
11821                                 /* insert call to write barrier */
11822                                 emit_write_barrier (cfg, sp [0], sp [1]);
11823                         }
11824                         ins_flag = 0;
11825                         ip += 5;
11826                         inline_costs += 1;
11827                         break;
11828
11829                         /*
11830                          * Array opcodes
11831                          */
11832                 case CEE_NEWARR: {
11833                         MonoInst *len_ins;
11834                         const char *data_ptr;
11835                         int data_size = 0;
11836                         guint32 field_token;
11837
11838                         CHECK_STACK (1);
11839                         --sp;
11840
11841                         CHECK_OPSIZE (5);
11842                         token = read32 (ip + 1);
11843
11844                         klass = mini_get_class (method, token, generic_context);
11845                         CHECK_TYPELOAD (klass);
11846
11847                         context_used = mini_class_check_context_used (cfg, klass);
11848
11849                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11850                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11851                                 ins->sreg1 = sp [0]->dreg;
11852                                 ins->type = STACK_I4;
11853                                 ins->dreg = alloc_ireg (cfg);
11854                                 MONO_ADD_INS (cfg->cbb, ins);
11855                                 *sp = mono_decompose_opcode (cfg, ins);
11856                         }
11857
11858                         if (context_used) {
11859                                 MonoInst *args [3];
11860                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11861                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11862
11863                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11864
11865                                 /* vtable */
11866                                 args [0] = emit_get_rgctx_klass (cfg, context_used,
11867                                         array_class, MONO_RGCTX_INFO_VTABLE);
11868                                 /* array len */
11869                                 args [1] = sp [0];
11870
11871                                 if (managed_alloc)
11872                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11873                                 else
11874                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11875                         } else {
11876                                 if (cfg->opt & MONO_OPT_SHARED) {
11877                                         /* Decompose now to avoid problems with references to the domainvar */
11878                                         MonoInst *iargs [3];
11879
11880                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11881                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11882                                         iargs [2] = sp [0];
11883
11884                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11885                                 } else {
11886                                         /* Decompose later since it is needed by abcrem */
11887                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11888                                         mono_class_vtable (cfg->domain, array_type);
11889                                         CHECK_TYPELOAD (array_type);
11890
11891                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11892                                         ins->dreg = alloc_ireg_ref (cfg);
11893                                         ins->sreg1 = sp [0]->dreg;
11894                                         ins->inst_newa_class = klass;
11895                                         ins->type = STACK_OBJ;
11896                                         ins->klass = array_type;
11897                                         MONO_ADD_INS (cfg->cbb, ins);
11898                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11899                                         cfg->cbb->has_array_access = TRUE;
11900
11901                                         /* Needed so mono_emit_load_get_addr () gets called */
11902                                         mono_get_got_var (cfg);
11903                                 }
11904                         }
11905
11906                         len_ins = sp [0];
11907                         ip += 5;
11908                         *sp++ = ins;
11909                         inline_costs += 1;
11910
11911                         /* 
11912                          * we inline/optimize the initialization sequence if possible.
11913                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11914                          * for small sizes open code the memcpy
11915                          * ensure the rva field is big enough
11916                          */
11917                         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))) {
11918                                 MonoMethod *memcpy_method = get_memcpy_method ();
11919                                 MonoInst *iargs [3];
11920                                 int add_reg = alloc_ireg_mp (cfg);
11921
11922                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11923                                 if (cfg->compile_aot) {
11924                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11925                                 } else {
11926                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11927                                 }
11928                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11929                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11930                                 ip += 11;
11931                         }
11932
11933                         break;
11934                 }
11935                 case CEE_LDLEN:
11936                         CHECK_STACK (1);
11937                         --sp;
11938                         if (sp [0]->type != STACK_OBJ)
11939                                 UNVERIFIED;
11940
11941                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11942                         ins->dreg = alloc_preg (cfg);
11943                         ins->sreg1 = sp [0]->dreg;
11944                         ins->type = STACK_I4;
11945                         /* This flag will be inherited by the decomposition */
11946                         ins->flags |= MONO_INST_FAULT;
11947                         MONO_ADD_INS (cfg->cbb, ins);
11948                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11949                         cfg->cbb->has_array_access = TRUE;
11950                         ip ++;
11951                         *sp++ = ins;
11952                         break;
11953                 case CEE_LDELEMA:
11954                         CHECK_STACK (2);
11955                         sp -= 2;
11956                         CHECK_OPSIZE (5);
11957                         if (sp [0]->type != STACK_OBJ)
11958                                 UNVERIFIED;
11959
11960                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11961
11962                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11963                         CHECK_TYPELOAD (klass);
11964                         /* we need to make sure that this array is exactly the type it needs
11965                          * to be for correctness. the wrappers are lax with their usage
11966                          * so we need to ignore them here
11967                          */
11968                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11969                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11970                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11971                                 CHECK_TYPELOAD (array_class);
11972                         }
11973
11974                         readonly = FALSE;
11975                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11976                         *sp++ = ins;
11977                         ip += 5;
11978                         break;
11979                 case CEE_LDELEM:
11980                 case CEE_LDELEM_I1:
11981                 case CEE_LDELEM_U1:
11982                 case CEE_LDELEM_I2:
11983                 case CEE_LDELEM_U2:
11984                 case CEE_LDELEM_I4:
11985                 case CEE_LDELEM_U4:
11986                 case CEE_LDELEM_I8:
11987                 case CEE_LDELEM_I:
11988                 case CEE_LDELEM_R4:
11989                 case CEE_LDELEM_R8:
11990                 case CEE_LDELEM_REF: {
11991                         MonoInst *addr;
11992
11993                         CHECK_STACK (2);
11994                         sp -= 2;
11995
11996                         if (*ip == CEE_LDELEM) {
11997                                 CHECK_OPSIZE (5);
11998                                 token = read32 (ip + 1);
11999                                 klass = mini_get_class (method, token, generic_context);
12000                                 CHECK_TYPELOAD (klass);
12001                                 mono_class_init (klass);
12002                         }
12003                         else
12004                                 klass = array_access_to_klass (*ip);
12005
12006                         if (sp [0]->type != STACK_OBJ)
12007                                 UNVERIFIED;
12008
12009                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
12010
12011                         if (mini_is_gsharedvt_variable_klass (klass)) {
12012                                 // FIXME-VT: OP_ICONST optimization
12013                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
12014                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
12015                                 ins->opcode = OP_LOADV_MEMBASE;
12016                         } else if (sp [1]->opcode == OP_ICONST) {
12017                                 int array_reg = sp [0]->dreg;
12018                                 int index_reg = sp [1]->dreg;
12019                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
12020
12021                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
12022                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
12023
12024                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
12025                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
12026                         } else {
12027                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
12028                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
12029                         }
12030                         *sp++ = ins;
12031                         if (*ip == CEE_LDELEM)
12032                                 ip += 5;
12033                         else
12034                                 ++ip;
12035                         break;
12036                 }
12037                 case CEE_STELEM_I:
12038                 case CEE_STELEM_I1:
12039                 case CEE_STELEM_I2:
12040                 case CEE_STELEM_I4:
12041                 case CEE_STELEM_I8:
12042                 case CEE_STELEM_R4:
12043                 case CEE_STELEM_R8:
12044                 case CEE_STELEM_REF:
12045                 case CEE_STELEM: {
12046                         CHECK_STACK (3);
12047                         sp -= 3;
12048
12049                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
12050
12051                         if (*ip == CEE_STELEM) {
12052                                 CHECK_OPSIZE (5);
12053                                 token = read32 (ip + 1);
12054                                 klass = mini_get_class (method, token, generic_context);
12055                                 CHECK_TYPELOAD (klass);
12056                                 mono_class_init (klass);
12057                         }
12058                         else
12059                                 klass = array_access_to_klass (*ip);
12060
12061                         if (sp [0]->type != STACK_OBJ)
12062                                 UNVERIFIED;
12063
12064                         emit_array_store (cfg, klass, sp, TRUE);
12065
12066                         if (*ip == CEE_STELEM)
12067                                 ip += 5;
12068                         else
12069                                 ++ip;
12070                         inline_costs += 1;
12071                         break;
12072                 }
12073                 case CEE_CKFINITE: {
12074                         CHECK_STACK (1);
12075                         --sp;
12076
12077                         if (cfg->llvm_only) {
12078                                 MonoInst *iargs [1];
12079
12080                                 iargs [0] = sp [0];
12081                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
12082                         } else  {
12083                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
12084                                 ins->sreg1 = sp [0]->dreg;
12085                                 ins->dreg = alloc_freg (cfg);
12086                                 ins->type = STACK_R8;
12087                                 MONO_ADD_INS (cfg->cbb, ins);
12088
12089                                 *sp++ = mono_decompose_opcode (cfg, ins);
12090                         }
12091
12092                         ++ip;
12093                         break;
12094                 }
12095                 case CEE_REFANYVAL: {
12096                         MonoInst *src_var, *src;
12097
12098                         int klass_reg = alloc_preg (cfg);
12099                         int dreg = alloc_preg (cfg);
12100
12101                         GSHAREDVT_FAILURE (*ip);
12102
12103                         CHECK_STACK (1);
12104                         MONO_INST_NEW (cfg, ins, *ip);
12105                         --sp;
12106                         CHECK_OPSIZE (5);
12107                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
12108                         CHECK_TYPELOAD (klass);
12109
12110                         context_used = mini_class_check_context_used (cfg, klass);
12111
12112                         // FIXME:
12113                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12114                         if (!src_var)
12115                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12116                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12117                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
12118
12119                         if (context_used) {
12120                                 MonoInst *klass_ins;
12121
12122                                 klass_ins = emit_get_rgctx_klass (cfg, context_used,
12123                                                 klass, MONO_RGCTX_INFO_KLASS);
12124
12125                                 // FIXME:
12126                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
12127                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
12128                         } else {
12129                                 mini_emit_class_check (cfg, klass_reg, klass);
12130                         }
12131                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
12132                         ins->type = STACK_MP;
12133                         ins->klass = klass;
12134                         *sp++ = ins;
12135                         ip += 5;
12136                         break;
12137                 }
12138                 case CEE_MKREFANY: {
12139                         MonoInst *loc, *addr;
12140
12141                         GSHAREDVT_FAILURE (*ip);
12142
12143                         CHECK_STACK (1);
12144                         MONO_INST_NEW (cfg, ins, *ip);
12145                         --sp;
12146                         CHECK_OPSIZE (5);
12147                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
12148                         CHECK_TYPELOAD (klass);
12149
12150                         context_used = mini_class_check_context_used (cfg, klass);
12151
12152                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
12153                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
12154
12155                         if (context_used) {
12156                                 MonoInst *const_ins;
12157                                 int type_reg = alloc_preg (cfg);
12158
12159                                 const_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
12160                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
12161                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
12162                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
12163                         } else if (cfg->compile_aot) {
12164                                 int const_reg = alloc_preg (cfg);
12165                                 int type_reg = alloc_preg (cfg);
12166
12167                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
12168                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
12169                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
12170                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
12171                         } else {
12172                                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREP_MEMBASE_IMM, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), &klass->byval_arg);
12173                                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREP_MEMBASE_IMM, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), klass);
12174                         }
12175                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
12176
12177                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
12178                         ins->type = STACK_VTYPE;
12179                         ins->klass = mono_defaults.typed_reference_class;
12180                         *sp++ = ins;
12181                         ip += 5;
12182                         break;
12183                 }
12184                 case CEE_LDTOKEN: {
12185                         gpointer handle;
12186                         MonoClass *handle_class;
12187
12188                         CHECK_STACK_OVF (1);
12189
12190                         CHECK_OPSIZE (5);
12191                         n = read32 (ip + 1);
12192
12193                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
12194                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
12195                                 handle = mono_method_get_wrapper_data (method, n);
12196                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
12197                                 if (handle_class == mono_defaults.typehandle_class)
12198                                         handle = &((MonoClass*)handle)->byval_arg;
12199                         }
12200                         else {
12201                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
12202                                 CHECK_CFG_ERROR;
12203                         }
12204                         if (!handle)
12205                                 LOAD_ERROR;
12206                         mono_class_init (handle_class);
12207                         if (cfg->gshared) {
12208                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
12209                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
12210                                         /* This case handles ldtoken
12211                                            of an open type, like for
12212                                            typeof(Gen<>). */
12213                                         context_used = 0;
12214                                 } else if (handle_class == mono_defaults.typehandle_class) {
12215                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
12216                                 } else if (handle_class == mono_defaults.fieldhandle_class)
12217                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
12218                                 else if (handle_class == mono_defaults.methodhandle_class)
12219                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
12220                                 else
12221                                         g_assert_not_reached ();
12222                         }
12223
12224                         if ((cfg->opt & MONO_OPT_SHARED) &&
12225                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
12226                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
12227                                 MonoInst *addr, *vtvar, *iargs [3];
12228                                 int method_context_used;
12229
12230                                 method_context_used = mini_method_check_context_used (cfg, method);
12231
12232                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
12233
12234                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
12235                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
12236                                 if (method_context_used) {
12237                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
12238                                                 method, MONO_RGCTX_INFO_METHOD);
12239                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
12240                                 } else {
12241                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
12242                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
12243                                 }
12244                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12245
12246                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
12247
12248                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12249                         } else {
12250                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
12251                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
12252                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
12253                                         (cmethod->klass == mono_defaults.systemtype_class) &&
12254                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
12255                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
12256
12257                                         mono_class_init (tclass);
12258                                         if (context_used) {
12259                                                 ins = emit_get_rgctx_klass (cfg, context_used,
12260                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
12261                                         } else if (cfg->compile_aot) {
12262                                                 if (method->wrapper_type) {
12263                                                         mono_error_init (&error); //got to do it since there are multiple conditionals below
12264                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
12265                                                                 /* Special case for static synchronized wrappers */
12266                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
12267                                                         } else {
12268                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
12269                                                                 /* FIXME: n is not a normal token */
12270                                                                 DISABLE_AOT (cfg);
12271                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12272                                                         }
12273                                                 } else {
12274                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
12275                                                 }
12276                                         } else {
12277                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
12278                                                 CHECK_CFG_ERROR;
12279                                                 EMIT_NEW_PCONST (cfg, ins, rt);
12280                                         }
12281                                         ins->type = STACK_OBJ;
12282                                         ins->klass = cmethod->klass;
12283                                         ip += 5;
12284                                 } else {
12285                                         MonoInst *addr, *vtvar;
12286
12287                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
12288
12289                                         if (context_used) {
12290                                                 if (handle_class == mono_defaults.typehandle_class) {
12291                                                         ins = emit_get_rgctx_klass (cfg, context_used,
12292                                                                         mono_class_from_mono_type ((MonoType *)handle),
12293                                                                         MONO_RGCTX_INFO_TYPE);
12294                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
12295                                                         ins = emit_get_rgctx_method (cfg, context_used,
12296                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
12297                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
12298                                                         ins = emit_get_rgctx_field (cfg, context_used,
12299                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
12300                                                 } else {
12301                                                         g_assert_not_reached ();
12302                                                 }
12303                                         } else if (cfg->compile_aot) {
12304                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
12305                                         } else {
12306                                                 EMIT_NEW_PCONST (cfg, ins, handle);
12307                                         }
12308                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12309                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
12310                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12311                                 }
12312                         }
12313
12314                         *sp++ = ins;
12315                         ip += 5;
12316                         break;
12317                 }
12318                 case CEE_THROW:
12319                         CHECK_STACK (1);
12320                         MONO_INST_NEW (cfg, ins, OP_THROW);
12321                         --sp;
12322                         ins->sreg1 = sp [0]->dreg;
12323                         ip++;
12324                         cfg->cbb->out_of_line = TRUE;
12325                         MONO_ADD_INS (cfg->cbb, ins);
12326                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12327                         MONO_ADD_INS (cfg->cbb, ins);
12328                         sp = stack_start;
12329                         
12330                         link_bblock (cfg, cfg->cbb, end_bblock);
12331                         start_new_bblock = 1;
12332                         /* This can complicate code generation for llvm since the return value might not be defined */
12333                         if (COMPILE_LLVM (cfg))
12334                                 INLINE_FAILURE ("throw");
12335                         break;
12336                 case CEE_ENDFINALLY:
12337                         /* mono_save_seq_point_info () depends on this */
12338                         if (sp != stack_start)
12339                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
12340                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
12341                         MONO_ADD_INS (cfg->cbb, ins);
12342                         ip++;
12343                         start_new_bblock = 1;
12344
12345                         /*
12346                          * Control will leave the method so empty the stack, otherwise
12347                          * the next basic block will start with a nonempty stack.
12348                          */
12349                         while (sp != stack_start) {
12350                                 sp--;
12351                         }
12352                         break;
12353                 case CEE_LEAVE:
12354                 case CEE_LEAVE_S: {
12355                         GList *handlers;
12356
12357                         if (*ip == CEE_LEAVE) {
12358                                 CHECK_OPSIZE (5);
12359                                 target = ip + 5 + (gint32)read32(ip + 1);
12360                         } else {
12361                                 CHECK_OPSIZE (2);
12362                                 target = ip + 2 + (signed char)(ip [1]);
12363                         }
12364
12365                         /* empty the stack */
12366                         while (sp != stack_start) {
12367                                 sp--;
12368                         }
12369
12370                         /* 
12371                          * If this leave statement is in a catch block, check for a
12372                          * pending exception, and rethrow it if necessary.
12373                          * We avoid doing this in runtime invoke wrappers, since those are called
12374                          * by native code which excepts the wrapper to catch all exceptions.
12375                          */
12376                         for (i = 0; i < header->num_clauses; ++i) {
12377                                 MonoExceptionClause *clause = &header->clauses [i];
12378
12379                                 /* 
12380                                  * Use <= in the final comparison to handle clauses with multiple
12381                                  * leave statements, like in bug #78024.
12382                                  * The ordering of the exception clauses guarantees that we find the
12383                                  * innermost clause.
12384                                  */
12385                                 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) {
12386                                         MonoInst *exc_ins;
12387                                         MonoBasicBlock *dont_throw;
12388
12389                                         /*
12390                                           MonoInst *load;
12391
12392                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
12393                                         */
12394
12395                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
12396
12397                                         NEW_BBLOCK (cfg, dont_throw);
12398
12399                                         /*
12400                                          * Currently, we always rethrow the abort exception, despite the 
12401                                          * fact that this is not correct. See thread6.cs for an example. 
12402                                          * But propagating the abort exception is more important than 
12403                                          * getting the sematics right.
12404                                          */
12405                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
12406                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
12407                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
12408
12409                                         MONO_START_BB (cfg, dont_throw);
12410                                 }
12411                         }
12412
12413 #ifdef ENABLE_LLVM
12414                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
12415 #endif
12416
12417                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
12418                                 GList *tmp;
12419                                 MonoExceptionClause *clause;
12420
12421                                 for (tmp = handlers; tmp; tmp = tmp->next) {
12422                                         clause = (MonoExceptionClause *)tmp->data;
12423                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
12424                                         g_assert (tblock);
12425                                         link_bblock (cfg, cfg->cbb, tblock);
12426                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
12427                                         ins->inst_target_bb = tblock;
12428                                         ins->inst_eh_block = clause;
12429                                         MONO_ADD_INS (cfg->cbb, ins);
12430                                         cfg->cbb->has_call_handler = 1;
12431                                         if (COMPILE_LLVM (cfg)) {
12432                                                 MonoBasicBlock *target_bb;
12433
12434                                                 /* 
12435                                                  * Link the finally bblock with the target, since it will
12436                                                  * conceptually branch there.
12437                                                  */
12438                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
12439                                                 GET_BBLOCK (cfg, target_bb, target);
12440                                                 link_bblock (cfg, tblock, target_bb);
12441                                         }
12442                                 }
12443                                 g_list_free (handlers);
12444                         } 
12445
12446                         MONO_INST_NEW (cfg, ins, OP_BR);
12447                         MONO_ADD_INS (cfg->cbb, ins);
12448                         GET_BBLOCK (cfg, tblock, target);
12449                         link_bblock (cfg, cfg->cbb, tblock);
12450                         ins->inst_target_bb = tblock;
12451
12452                         start_new_bblock = 1;
12453
12454                         if (*ip == CEE_LEAVE)
12455                                 ip += 5;
12456                         else
12457                                 ip += 2;
12458
12459                         break;
12460                 }
12461
12462                         /*
12463                          * Mono specific opcodes
12464                          */
12465                 case MONO_CUSTOM_PREFIX: {
12466
12467                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
12468
12469                         CHECK_OPSIZE (2);
12470                         switch (ip [1]) {
12471                         case CEE_MONO_ICALL: {
12472                                 gpointer func;
12473                                 MonoJitICallInfo *info;
12474
12475                                 token = read32 (ip + 2);
12476                                 func = mono_method_get_wrapper_data (method, token);
12477                                 info = mono_find_jit_icall_by_addr (func);
12478                                 if (!info)
12479                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
12480                                 g_assert (info);
12481
12482                                 CHECK_STACK (info->sig->param_count);
12483                                 sp -= info->sig->param_count;
12484
12485                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
12486                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
12487                                         *sp++ = ins;
12488
12489                                 ip += 6;
12490                                 inline_costs += 10 * num_calls++;
12491
12492                                 break;
12493                         }
12494                         case CEE_MONO_LDPTR_CARD_TABLE:
12495                         case CEE_MONO_LDPTR_NURSERY_START:
12496                         case CEE_MONO_LDPTR_NURSERY_BITS:
12497                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
12498                                 CHECK_STACK_OVF (1);
12499
12500                                 switch (ip [1]) {
12501                                         case CEE_MONO_LDPTR_CARD_TABLE:
12502                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
12503                                                 break;
12504                                         case CEE_MONO_LDPTR_NURSERY_START:
12505                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
12506                                                 break;
12507                                         case CEE_MONO_LDPTR_NURSERY_BITS:
12508                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
12509                                                 break;
12510                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
12511                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
12512                                                 break;
12513                                 }
12514
12515                                 *sp++ = ins;
12516                                 ip += 2;
12517                                 inline_costs += 10 * num_calls++;
12518                                 break;
12519                         }
12520                         case CEE_MONO_LDPTR: {
12521                                 gpointer ptr;
12522
12523                                 CHECK_STACK_OVF (1);
12524                                 CHECK_OPSIZE (6);
12525                                 token = read32 (ip + 2);
12526
12527                                 ptr = mono_method_get_wrapper_data (method, token);
12528                                 EMIT_NEW_PCONST (cfg, ins, ptr);
12529                                 *sp++ = ins;
12530                                 ip += 6;
12531                                 inline_costs += 10 * num_calls++;
12532                                 /* Can't embed random pointers into AOT code */
12533                                 DISABLE_AOT (cfg);
12534                                 break;
12535                         }
12536                         case CEE_MONO_JIT_ICALL_ADDR: {
12537                                 MonoJitICallInfo *callinfo;
12538                                 gpointer ptr;
12539
12540                                 CHECK_STACK_OVF (1);
12541                                 CHECK_OPSIZE (6);
12542                                 token = read32 (ip + 2);
12543
12544                                 ptr = mono_method_get_wrapper_data (method, token);
12545                                 callinfo = mono_find_jit_icall_by_addr (ptr);
12546                                 g_assert (callinfo);
12547                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
12548                                 *sp++ = ins;
12549                                 ip += 6;
12550                                 inline_costs += 10 * num_calls++;
12551                                 break;
12552                         }
12553                         case CEE_MONO_ICALL_ADDR: {
12554                                 MonoMethod *cmethod;
12555                                 gpointer ptr;
12556
12557                                 CHECK_STACK_OVF (1);
12558                                 CHECK_OPSIZE (6);
12559                                 token = read32 (ip + 2);
12560
12561                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
12562
12563                                 if (cfg->compile_aot) {
12564                                         EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
12565                                 } else {
12566                                         ptr = mono_lookup_internal_call (cmethod);
12567                                         g_assert (ptr);
12568                                         EMIT_NEW_PCONST (cfg, ins, ptr);
12569                                 }
12570                                 *sp++ = ins;
12571                                 ip += 6;
12572                                 break;
12573                         }
12574                         case CEE_MONO_VTADDR: {
12575                                 MonoInst *src_var, *src;
12576
12577                                 CHECK_STACK (1);
12578                                 --sp;
12579
12580                                 // FIXME:
12581                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12582                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
12583                                 *sp++ = src;
12584                                 ip += 2;
12585                                 break;
12586                         }
12587                         case CEE_MONO_NEWOBJ: {
12588                                 MonoInst *iargs [2];
12589
12590                                 CHECK_STACK_OVF (1);
12591                                 CHECK_OPSIZE (6);
12592                                 token = read32 (ip + 2);
12593                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12594                                 mono_class_init (klass);
12595                                 NEW_DOMAINCONST (cfg, iargs [0]);
12596                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
12597                                 NEW_CLASSCONST (cfg, iargs [1], klass);
12598                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
12599                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
12600                                 ip += 6;
12601                                 inline_costs += 10 * num_calls++;
12602                                 break;
12603                         }
12604                         case CEE_MONO_OBJADDR:
12605                                 CHECK_STACK (1);
12606                                 --sp;
12607                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12608                                 ins->dreg = alloc_ireg_mp (cfg);
12609                                 ins->sreg1 = sp [0]->dreg;
12610                                 ins->type = STACK_MP;
12611                                 MONO_ADD_INS (cfg->cbb, ins);
12612                                 *sp++ = ins;
12613                                 ip += 2;
12614                                 break;
12615                         case CEE_MONO_LDNATIVEOBJ:
12616                                 /*
12617                                  * Similar to LDOBJ, but instead load the unmanaged 
12618                                  * representation of the vtype to the stack.
12619                                  */
12620                                 CHECK_STACK (1);
12621                                 CHECK_OPSIZE (6);
12622                                 --sp;
12623                                 token = read32 (ip + 2);
12624                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12625                                 g_assert (klass->valuetype);
12626                                 mono_class_init (klass);
12627
12628                                 {
12629                                         MonoInst *src, *dest, *temp;
12630
12631                                         src = sp [0];
12632                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
12633                                         temp->backend.is_pinvoke = 1;
12634                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
12635                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
12636
12637                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
12638                                         dest->type = STACK_VTYPE;
12639                                         dest->klass = klass;
12640
12641                                         *sp ++ = dest;
12642                                         ip += 6;
12643                                 }
12644                                 break;
12645                         case CEE_MONO_RETOBJ: {
12646                                 /*
12647                                  * Same as RET, but return the native representation of a vtype
12648                                  * to the caller.
12649                                  */
12650                                 g_assert (cfg->ret);
12651                                 g_assert (mono_method_signature (method)->pinvoke); 
12652                                 CHECK_STACK (1);
12653                                 --sp;
12654                                 
12655                                 CHECK_OPSIZE (6);
12656                                 token = read32 (ip + 2);    
12657                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12658
12659                                 if (!cfg->vret_addr) {
12660                                         g_assert (cfg->ret_var_is_local);
12661
12662                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
12663                                 } else {
12664                                         EMIT_NEW_RETLOADA (cfg, ins);
12665                                 }
12666                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
12667                                 
12668                                 if (sp != stack_start)
12669                                         UNVERIFIED;
12670                                 
12671                                 MONO_INST_NEW (cfg, ins, OP_BR);
12672                                 ins->inst_target_bb = end_bblock;
12673                                 MONO_ADD_INS (cfg->cbb, ins);
12674                                 link_bblock (cfg, cfg->cbb, end_bblock);
12675                                 start_new_bblock = 1;
12676                                 ip += 6;
12677                                 break;
12678                         }
12679                         case CEE_MONO_CISINST:
12680                         case CEE_MONO_CCASTCLASS: {
12681                                 int token;
12682                                 CHECK_STACK (1);
12683                                 --sp;
12684                                 CHECK_OPSIZE (6);
12685                                 token = read32 (ip + 2);
12686                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12687                                 if (ip [1] == CEE_MONO_CISINST)
12688                                         ins = handle_cisinst (cfg, klass, sp [0]);
12689                                 else
12690                                         ins = handle_ccastclass (cfg, klass, sp [0]);
12691                                 *sp++ = ins;
12692                                 ip += 6;
12693                                 break;
12694                         }
12695                         case CEE_MONO_SAVE_LMF:
12696                         case CEE_MONO_RESTORE_LMF:
12697                                 ip += 2;
12698                                 break;
12699                         case CEE_MONO_CLASSCONST:
12700                                 CHECK_STACK_OVF (1);
12701                                 CHECK_OPSIZE (6);
12702                                 token = read32 (ip + 2);
12703                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
12704                                 *sp++ = ins;
12705                                 ip += 6;
12706                                 inline_costs += 10 * num_calls++;
12707                                 break;
12708                         case CEE_MONO_NOT_TAKEN:
12709                                 cfg->cbb->out_of_line = TRUE;
12710                                 ip += 2;
12711                                 break;
12712                         case CEE_MONO_TLS: {
12713                                 MonoTlsKey key;
12714
12715                                 CHECK_STACK_OVF (1);
12716                                 CHECK_OPSIZE (6);
12717                                 key = (MonoTlsKey)read32 (ip + 2);
12718                                 g_assert (key < TLS_KEY_NUM);
12719
12720                                 ins = mono_create_tls_get (cfg, key);
12721                                 if (!ins) {
12722                                         if (cfg->compile_aot) {
12723                                                 DISABLE_AOT (cfg);
12724                                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
12725                                                 ins->dreg = alloc_preg (cfg);
12726                                                 ins->type = STACK_PTR;
12727                                         } else {
12728                                                 g_assert_not_reached ();
12729                                         }
12730                                 }
12731                                 ins->type = STACK_PTR;
12732                                 MONO_ADD_INS (cfg->cbb, ins);
12733                                 *sp++ = ins;
12734                                 ip += 6;
12735                                 break;
12736                         }
12737                         case CEE_MONO_DYN_CALL: {
12738                                 MonoCallInst *call;
12739
12740                                 /* It would be easier to call a trampoline, but that would put an
12741                                  * extra frame on the stack, confusing exception handling. So
12742                                  * implement it inline using an opcode for now.
12743                                  */
12744
12745                                 if (!cfg->dyn_call_var) {
12746                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12747                                         /* prevent it from being register allocated */
12748                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
12749                                 }
12750
12751                                 /* Has to use a call inst since it local regalloc expects it */
12752                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
12753                                 ins = (MonoInst*)call;
12754                                 sp -= 2;
12755                                 ins->sreg1 = sp [0]->dreg;
12756                                 ins->sreg2 = sp [1]->dreg;
12757                                 MONO_ADD_INS (cfg->cbb, ins);
12758
12759                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
12760
12761                                 ip += 2;
12762                                 inline_costs += 10 * num_calls++;
12763
12764                                 break;
12765                         }
12766                         case CEE_MONO_MEMORY_BARRIER: {
12767                                 CHECK_OPSIZE (6);
12768                                 emit_memory_barrier (cfg, (int)read32 (ip + 2));
12769                                 ip += 6;
12770                                 break;
12771                         }
12772                         case CEE_MONO_ATOMIC_STORE_I4: {
12773                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
12774
12775                                 CHECK_OPSIZE (6);
12776                                 CHECK_STACK (2);
12777                                 sp -= 2;
12778
12779                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
12780                                 ins->dreg = sp [0]->dreg;
12781                                 ins->sreg1 = sp [1]->dreg;
12782                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
12783                                 MONO_ADD_INS (cfg->cbb, ins);
12784
12785                                 ip += 6;
12786                                 break;
12787                         }
12788                         case CEE_MONO_JIT_ATTACH: {
12789                                 MonoInst *args [16], *domain_ins;
12790                                 MonoInst *ad_ins, *jit_tls_ins;
12791                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
12792
12793                                 g_assert (!mono_threads_is_coop_enabled ());
12794
12795                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12796
12797                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12798                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12799
12800                                 ad_ins = mono_get_domain_intrinsic (cfg);
12801                                 jit_tls_ins = mono_get_jit_tls_intrinsic (cfg);
12802
12803                                 if (cfg->backend->have_tls_get && ad_ins && jit_tls_ins) {
12804                                         NEW_BBLOCK (cfg, next_bb);
12805                                         NEW_BBLOCK (cfg, call_bb);
12806
12807                                         if (cfg->compile_aot) {
12808                                                 /* AOT code is only used in the root domain */
12809                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12810                                         } else {
12811                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12812                                         }
12813                                         MONO_ADD_INS (cfg->cbb, ad_ins);
12814                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12815                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12816
12817                                         MONO_ADD_INS (cfg->cbb, jit_tls_ins);
12818                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12819                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12820
12821                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12822                                         MONO_START_BB (cfg, call_bb);
12823                                 }
12824
12825                                 /* AOT code is only used in the root domain */
12826                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12827                                 ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12828                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12829
12830                                 if (next_bb)
12831                                         MONO_START_BB (cfg, next_bb);
12832
12833
12834                                 ip += 2;
12835                                 break;
12836                         }
12837                         case CEE_MONO_JIT_DETACH: {
12838                                 MonoInst *args [16];
12839
12840                                 /* Restore the original domain */
12841                                 dreg = alloc_ireg (cfg);
12842                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12843                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12844                                 ip += 2;
12845                                 break;
12846                         }
12847                         case CEE_MONO_CALLI_EXTRA_ARG: {
12848                                 MonoInst *addr;
12849                                 MonoMethodSignature *fsig;
12850                                 MonoInst *arg;
12851
12852                                 /*
12853                                  * This is the same as CEE_CALLI, but passes an additional argument
12854                                  * to the called method in llvmonly mode.
12855                                  * This is only used by delegate invoke wrappers to call the
12856                                  * actual delegate method.
12857                                  */
12858                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12859
12860                                 CHECK_OPSIZE (6);
12861                                 token = read32 (ip + 2);
12862
12863                                 ins = NULL;
12864
12865                                 cmethod = NULL;
12866                                 CHECK_STACK (1);
12867                                 --sp;
12868                                 addr = *sp;
12869                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12870                                 CHECK_CFG_ERROR;
12871
12872                                 if (cfg->llvm_only)
12873                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12874
12875                                 n = fsig->param_count + fsig->hasthis + 1;
12876
12877                                 CHECK_STACK (n);
12878
12879                                 sp -= n;
12880                                 arg = sp [n - 1];
12881
12882                                 if (cfg->llvm_only) {
12883                                         /*
12884                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12885                                          * cconv. This is set by mono_init_delegate ().
12886                                          */
12887                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12888                                                 MonoInst *callee = addr;
12889                                                 MonoInst *call, *localloc_ins;
12890                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12891                                                 int low_bit_reg = alloc_preg (cfg);
12892
12893                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12894                                                 NEW_BBLOCK (cfg, end_bb);
12895
12896                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12897                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12898                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12899
12900                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12901                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12902                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12903                                                 /*
12904                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12905                                                  */
12906                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12907                                                 ins->dreg = alloc_preg (cfg);
12908                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12909                                                 MONO_ADD_INS (cfg->cbb, ins);
12910                                                 localloc_ins = ins;
12911                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12912                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12913                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12914
12915                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12916                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12917
12918                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12919                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12920                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12921                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12922                                                 ins->dreg = call->dreg;
12923
12924                                                 MONO_START_BB (cfg, end_bb);
12925                                         } else {
12926                                                 /* Caller uses a normal calling conv */
12927
12928                                                 MonoInst *callee = addr;
12929                                                 MonoInst *call, *localloc_ins;
12930                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12931                                                 int low_bit_reg = alloc_preg (cfg);
12932
12933                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12934                                                 NEW_BBLOCK (cfg, end_bb);
12935
12936                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12937                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12938                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12939
12940                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12941                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12942                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12943                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12944                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12945                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12946                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12947                                                 MONO_ADD_INS (cfg->cbb, addr);
12948                                                 /*
12949                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12950                                                  */
12951                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12952                                                 ins->dreg = alloc_preg (cfg);
12953                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12954                                                 MONO_ADD_INS (cfg->cbb, ins);
12955                                                 localloc_ins = ins;
12956                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12957                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12958                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12959
12960                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12961                                                 ins->dreg = call->dreg;
12962                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12963
12964                                                 MONO_START_BB (cfg, end_bb);
12965                                         }
12966                                 } else {
12967                                         /* Same as CEE_CALLI */
12968                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12969                                                 /*
12970                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12971                                                  */
12972                                                 MonoInst *callee = addr;
12973
12974                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12975                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12976                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12977                                         } else {
12978                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12979                                         }
12980                                 }
12981
12982                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12983                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12984
12985                                 CHECK_CFG_EXCEPTION;
12986
12987                                 ip += 6;
12988                                 ins_flag = 0;
12989                                 constrained_class = NULL;
12990                                 break;
12991                         }
12992                         case CEE_MONO_LDDOMAIN:
12993                                 CHECK_STACK_OVF (1);
12994                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12995                                 ip += 2;
12996                                 *sp++ = ins;
12997                                 break;
12998                         default:
12999                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
13000                                 break;
13001                         }
13002                         break;
13003                 }
13004
13005                 case CEE_PREFIX1: {
13006                         CHECK_OPSIZE (2);
13007                         switch (ip [1]) {
13008                         case CEE_ARGLIST: {
13009                                 /* somewhat similar to LDTOKEN */
13010                                 MonoInst *addr, *vtvar;
13011                                 CHECK_STACK_OVF (1);
13012                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
13013
13014                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
13015                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
13016
13017                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
13018                                 ins->type = STACK_VTYPE;
13019                                 ins->klass = mono_defaults.argumenthandle_class;
13020                                 *sp++ = ins;
13021                                 ip += 2;
13022                                 break;
13023                         }
13024                         case CEE_CEQ:
13025                         case CEE_CGT:
13026                         case CEE_CGT_UN:
13027                         case CEE_CLT:
13028                         case CEE_CLT_UN: {
13029                                 MonoInst *cmp, *arg1, *arg2;
13030
13031                                 CHECK_STACK (2);
13032                                 sp -= 2;
13033                                 arg1 = sp [0];
13034                                 arg2 = sp [1];
13035
13036                                 /*
13037                                  * The following transforms:
13038                                  *    CEE_CEQ    into OP_CEQ
13039                                  *    CEE_CGT    into OP_CGT
13040                                  *    CEE_CGT_UN into OP_CGT_UN
13041                                  *    CEE_CLT    into OP_CLT
13042                                  *    CEE_CLT_UN into OP_CLT_UN
13043                                  */
13044                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
13045
13046                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
13047                                 cmp->sreg1 = arg1->dreg;
13048                                 cmp->sreg2 = arg2->dreg;
13049                                 type_from_op (cfg, cmp, arg1, arg2);
13050                                 CHECK_TYPE (cmp);
13051                                 add_widen_op (cfg, cmp, &arg1, &arg2);
13052                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
13053                                         cmp->opcode = OP_LCOMPARE;
13054                                 else if (arg1->type == STACK_R4)
13055                                         cmp->opcode = OP_RCOMPARE;
13056                                 else if (arg1->type == STACK_R8)
13057                                         cmp->opcode = OP_FCOMPARE;
13058                                 else
13059                                         cmp->opcode = OP_ICOMPARE;
13060                                 MONO_ADD_INS (cfg->cbb, cmp);
13061                                 ins->type = STACK_I4;
13062                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
13063                                 type_from_op (cfg, ins, arg1, arg2);
13064
13065                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
13066                                         /*
13067                                          * The backends expect the fceq opcodes to do the
13068                                          * comparison too.
13069                                          */
13070                                         ins->sreg1 = cmp->sreg1;
13071                                         ins->sreg2 = cmp->sreg2;
13072                                         NULLIFY_INS (cmp);
13073                                 }
13074                                 MONO_ADD_INS (cfg->cbb, ins);
13075                                 *sp++ = ins;
13076                                 ip += 2;
13077                                 break;
13078                         }
13079                         case CEE_LDFTN: {
13080                                 MonoInst *argconst;
13081                                 MonoMethod *cil_method;
13082
13083                                 CHECK_STACK_OVF (1);
13084                                 CHECK_OPSIZE (6);
13085                                 n = read32 (ip + 2);
13086                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
13087                                 CHECK_CFG_ERROR;
13088
13089                                 mono_class_init (cmethod->klass);
13090
13091                                 mono_save_token_info (cfg, image, n, cmethod);
13092
13093                                 context_used = mini_method_check_context_used (cfg, cmethod);
13094
13095                                 cil_method = cmethod;
13096                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
13097                                         emit_method_access_failure (cfg, method, cil_method);
13098
13099                                 if (mono_security_core_clr_enabled ())
13100                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
13101
13102                                 /* 
13103                                  * Optimize the common case of ldftn+delegate creation
13104                                  */
13105                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
13106                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
13107                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
13108                                                 MonoInst *target_ins, *handle_ins;
13109                                                 MonoMethod *invoke;
13110                                                 int invoke_context_used;
13111
13112                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
13113                                                 if (!invoke || !mono_method_signature (invoke))
13114                                                         LOAD_ERROR;
13115
13116                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
13117
13118                                                 target_ins = sp [-1];
13119
13120                                                 if (mono_security_core_clr_enabled ())
13121                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
13122
13123                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
13124                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
13125                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
13126                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
13127                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
13128                                                         }
13129                                                 }
13130
13131                                                 /* FIXME: SGEN support */
13132                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
13133                                                         ip += 6;
13134                                                         if (cfg->verbose_level > 3)
13135                                                                 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));
13136                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
13137                                                                 sp --;
13138                                                                 *sp = handle_ins;
13139                                                                 CHECK_CFG_EXCEPTION;
13140                                                                 ip += 5;
13141                                                                 sp ++;
13142                                                                 break;
13143                                                         }
13144                                                         ip -= 6;
13145                                                 }
13146                                         }
13147                                 }
13148
13149                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
13150                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
13151                                 *sp++ = ins;
13152                                 
13153                                 ip += 6;
13154                                 inline_costs += 10 * num_calls++;
13155                                 break;
13156                         }
13157                         case CEE_LDVIRTFTN: {
13158                                 MonoInst *args [2];
13159
13160                                 CHECK_STACK (1);
13161                                 CHECK_OPSIZE (6);
13162                                 n = read32 (ip + 2);
13163                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
13164                                 CHECK_CFG_ERROR;
13165
13166                                 mono_class_init (cmethod->klass);
13167  
13168                                 context_used = mini_method_check_context_used (cfg, cmethod);
13169
13170                                 if (mono_security_core_clr_enabled ())
13171                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
13172
13173                                 /*
13174                                  * Optimize the common case of ldvirtftn+delegate creation
13175                                  */
13176                                 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)) {
13177                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
13178                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
13179                                                 MonoInst *target_ins, *handle_ins;
13180                                                 MonoMethod *invoke;
13181                                                 int invoke_context_used;
13182                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
13183
13184                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
13185                                                 if (!invoke || !mono_method_signature (invoke))
13186                                                         LOAD_ERROR;
13187
13188                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
13189
13190                                                 target_ins = sp [-1];
13191
13192                                                 if (mono_security_core_clr_enabled ())
13193                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
13194
13195                                                 /* FIXME: SGEN support */
13196                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
13197                                                         ip += 6;
13198                                                         if (cfg->verbose_level > 3)
13199                                                                 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));
13200                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
13201                                                                 sp -= 2;
13202                                                                 *sp = handle_ins;
13203                                                                 CHECK_CFG_EXCEPTION;
13204                                                                 ip += 5;
13205                                                                 sp ++;
13206                                                                 break;
13207                                                         }
13208                                                         ip -= 6;
13209                                                 }
13210                                         }
13211                                 }
13212
13213                                 --sp;
13214                                 args [0] = *sp;
13215
13216                                 args [1] = emit_get_rgctx_method (cfg, context_used,
13217                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
13218
13219                                 if (context_used)
13220                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
13221                                 else
13222                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
13223
13224                                 ip += 6;
13225                                 inline_costs += 10 * num_calls++;
13226                                 break;
13227                         }
13228                         case CEE_LDARG:
13229                                 CHECK_STACK_OVF (1);
13230                                 CHECK_OPSIZE (4);
13231                                 n = read16 (ip + 2);
13232                                 CHECK_ARG (n);
13233                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
13234                                 *sp++ = ins;
13235                                 ip += 4;
13236                                 break;
13237                         case CEE_LDARGA:
13238                                 CHECK_STACK_OVF (1);
13239                                 CHECK_OPSIZE (4);
13240                                 n = read16 (ip + 2);
13241                                 CHECK_ARG (n);
13242                                 NEW_ARGLOADA (cfg, ins, n);
13243                                 MONO_ADD_INS (cfg->cbb, ins);
13244                                 *sp++ = ins;
13245                                 ip += 4;
13246                                 break;
13247                         case CEE_STARG:
13248                                 CHECK_STACK (1);
13249                                 --sp;
13250                                 CHECK_OPSIZE (4);
13251                                 n = read16 (ip + 2);
13252                                 CHECK_ARG (n);
13253                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
13254                                         UNVERIFIED;
13255                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
13256                                 ip += 4;
13257                                 break;
13258                         case CEE_LDLOC:
13259                                 CHECK_STACK_OVF (1);
13260                                 CHECK_OPSIZE (4);
13261                                 n = read16 (ip + 2);
13262                                 CHECK_LOCAL (n);
13263                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
13264                                 *sp++ = ins;
13265                                 ip += 4;
13266                                 break;
13267                         case CEE_LDLOCA: {
13268                                 unsigned char *tmp_ip;
13269                                 CHECK_STACK_OVF (1);
13270                                 CHECK_OPSIZE (4);
13271                                 n = read16 (ip + 2);
13272                                 CHECK_LOCAL (n);
13273
13274                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
13275                                         ip = tmp_ip;
13276                                         inline_costs += 1;
13277                                         break;
13278                                 }                       
13279                                 
13280                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
13281                                 *sp++ = ins;
13282                                 ip += 4;
13283                                 break;
13284                         }
13285                         case CEE_STLOC:
13286                                 CHECK_STACK (1);
13287                                 --sp;
13288                                 CHECK_OPSIZE (4);
13289                                 n = read16 (ip + 2);
13290                                 CHECK_LOCAL (n);
13291                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
13292                                         UNVERIFIED;
13293                                 emit_stloc_ir (cfg, sp, header, n);
13294                                 ip += 4;
13295                                 inline_costs += 1;
13296                                 break;
13297                         case CEE_LOCALLOC:
13298                                 CHECK_STACK (1);
13299                                 --sp;
13300                                 if (sp != stack_start) 
13301                                         UNVERIFIED;
13302                                 if (cfg->method != method) 
13303                                         /* 
13304                                          * Inlining this into a loop in a parent could lead to 
13305                                          * stack overflows which is different behavior than the
13306                                          * non-inlined case, thus disable inlining in this case.
13307                                          */
13308                                         INLINE_FAILURE("localloc");
13309
13310                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
13311                                 ins->dreg = alloc_preg (cfg);
13312                                 ins->sreg1 = sp [0]->dreg;
13313                                 ins->type = STACK_PTR;
13314                                 MONO_ADD_INS (cfg->cbb, ins);
13315
13316                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
13317                                 if (init_locals)
13318                                         ins->flags |= MONO_INST_INIT;
13319
13320                                 *sp++ = ins;
13321                                 ip += 2;
13322                                 break;
13323                         case CEE_ENDFILTER: {
13324                                 MonoExceptionClause *clause, *nearest;
13325                                 int cc;
13326
13327                                 CHECK_STACK (1);
13328                                 --sp;
13329                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
13330                                         UNVERIFIED;
13331                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
13332                                 ins->sreg1 = (*sp)->dreg;
13333                                 MONO_ADD_INS (cfg->cbb, ins);
13334                                 start_new_bblock = 1;
13335                                 ip += 2;
13336
13337                                 nearest = NULL;
13338                                 for (cc = 0; cc < header->num_clauses; ++cc) {
13339                                         clause = &header->clauses [cc];
13340                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
13341                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
13342                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
13343                                                 nearest = clause;
13344                                 }
13345                                 g_assert (nearest);
13346                                 if ((ip - header->code) != nearest->handler_offset)
13347                                         UNVERIFIED;
13348
13349                                 break;
13350                         }
13351                         case CEE_UNALIGNED_:
13352                                 ins_flag |= MONO_INST_UNALIGNED;
13353                                 /* FIXME: record alignment? we can assume 1 for now */
13354                                 CHECK_OPSIZE (3);
13355                                 ip += 3;
13356                                 break;
13357                         case CEE_VOLATILE_:
13358                                 ins_flag |= MONO_INST_VOLATILE;
13359                                 ip += 2;
13360                                 break;
13361                         case CEE_TAIL_:
13362                                 ins_flag   |= MONO_INST_TAILCALL;
13363                                 cfg->flags |= MONO_CFG_HAS_TAIL;
13364                                 /* Can't inline tail calls at this time */
13365                                 inline_costs += 100000;
13366                                 ip += 2;
13367                                 break;
13368                         case CEE_INITOBJ:
13369                                 CHECK_STACK (1);
13370                                 --sp;
13371                                 CHECK_OPSIZE (6);
13372                                 token = read32 (ip + 2);
13373                                 klass = mini_get_class (method, token, generic_context);
13374                                 CHECK_TYPELOAD (klass);
13375                                 if (generic_class_is_reference_type (cfg, klass))
13376                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
13377                                 else
13378                                         mini_emit_initobj (cfg, *sp, NULL, klass);
13379                                 ip += 6;
13380                                 inline_costs += 1;
13381                                 break;
13382                         case CEE_CONSTRAINED_:
13383                                 CHECK_OPSIZE (6);
13384                                 token = read32 (ip + 2);
13385                                 constrained_class = mini_get_class (method, token, generic_context);
13386                                 CHECK_TYPELOAD (constrained_class);
13387                                 ip += 6;
13388                                 break;
13389                         case CEE_CPBLK:
13390                         case CEE_INITBLK: {
13391                                 MonoInst *iargs [3];
13392                                 CHECK_STACK (3);
13393                                 sp -= 3;
13394
13395                                 /* Skip optimized paths for volatile operations. */
13396                                 if ((ip [1] == CEE_CPBLK) && !(ins_flag & MONO_INST_VOLATILE) && (cfg->opt & MONO_OPT_INTRINS) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
13397                                         mini_emit_memcpy (cfg, sp [0]->dreg, 0, sp [1]->dreg, 0, sp [2]->inst_c0, 0);
13398                                 } else if ((ip [1] == CEE_INITBLK) && !(ins_flag & MONO_INST_VOLATILE) && (cfg->opt & MONO_OPT_INTRINS) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5) && (sp [1]->opcode == OP_ICONST) && (sp [1]->inst_c0 == 0)) {
13399                                         /* emit_memset only works when val == 0 */
13400                                         mini_emit_memset (cfg, sp [0]->dreg, 0, sp [2]->inst_c0, sp [1]->inst_c0, 0);
13401                                 } else {
13402                                         MonoInst *call;
13403                                         iargs [0] = sp [0];
13404                                         iargs [1] = sp [1];
13405                                         iargs [2] = sp [2];
13406                                         if (ip [1] == CEE_CPBLK) {
13407                                                 /*
13408                                                  * FIXME: It's unclear whether we should be emitting both the acquire
13409                                                  * and release barriers for cpblk. It is technically both a load and
13410                                                  * store operation, so it seems like that's the sensible thing to do.
13411                                                  *
13412                                                  * FIXME: We emit full barriers on both sides of the operation for
13413                                                  * simplicity. We should have a separate atomic memcpy method instead.
13414                                                  */
13415                                                 MonoMethod *memcpy_method = get_memcpy_method ();
13416
13417                                                 if (ins_flag & MONO_INST_VOLATILE)
13418                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
13419
13420                                                 call = mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
13421                                                 call->flags |= ins_flag;
13422
13423                                                 if (ins_flag & MONO_INST_VOLATILE)
13424                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
13425                                         } else {
13426                                                 MonoMethod *memset_method = get_memset_method ();
13427                                                 if (ins_flag & MONO_INST_VOLATILE) {
13428                                                         /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
13429                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
13430                                                 }
13431                                                 call = mono_emit_method_call (cfg, memset_method, iargs, NULL);
13432                                                 call->flags |= ins_flag;
13433                                         }
13434                                 }
13435                                 ip += 2;
13436                                 ins_flag = 0;
13437                                 inline_costs += 1;
13438                                 break;
13439                         }
13440                         case CEE_NO_:
13441                                 CHECK_OPSIZE (3);
13442                                 if (ip [2] & 0x1)
13443                                         ins_flag |= MONO_INST_NOTYPECHECK;
13444                                 if (ip [2] & 0x2)
13445                                         ins_flag |= MONO_INST_NORANGECHECK;
13446                                 /* we ignore the no-nullcheck for now since we
13447                                  * really do it explicitly only when doing callvirt->call
13448                                  */
13449                                 ip += 3;
13450                                 break;
13451                         case CEE_RETHROW: {
13452                                 MonoInst *load;
13453                                 int handler_offset = -1;
13454
13455                                 for (i = 0; i < header->num_clauses; ++i) {
13456                                         MonoExceptionClause *clause = &header->clauses [i];
13457                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
13458                                                 handler_offset = clause->handler_offset;
13459                                                 break;
13460                                         }
13461                                 }
13462
13463                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
13464
13465                                 if (handler_offset == -1)
13466                                         UNVERIFIED;
13467
13468                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
13469                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
13470                                 ins->sreg1 = load->dreg;
13471                                 MONO_ADD_INS (cfg->cbb, ins);
13472
13473                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
13474                                 MONO_ADD_INS (cfg->cbb, ins);
13475
13476                                 sp = stack_start;
13477                                 link_bblock (cfg, cfg->cbb, end_bblock);
13478                                 start_new_bblock = 1;
13479                                 ip += 2;
13480                                 break;
13481                         }
13482                         case CEE_SIZEOF: {
13483                                 guint32 val;
13484                                 int ialign;
13485
13486                                 CHECK_STACK_OVF (1);
13487                                 CHECK_OPSIZE (6);
13488                                 token = read32 (ip + 2);
13489                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
13490                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
13491                                         CHECK_CFG_ERROR;
13492
13493                                         val = mono_type_size (type, &ialign);
13494                                 } else {
13495                                         MonoClass *klass = mini_get_class (method, token, generic_context);
13496                                         CHECK_TYPELOAD (klass);
13497
13498                                         val = mono_type_size (&klass->byval_arg, &ialign);
13499
13500                                         if (mini_is_gsharedvt_klass (klass))
13501                                                 GSHAREDVT_FAILURE (*ip);
13502                                 }
13503                                 EMIT_NEW_ICONST (cfg, ins, val);
13504                                 *sp++= ins;
13505                                 ip += 6;
13506                                 break;
13507                         }
13508                         case CEE_REFANYTYPE: {
13509                                 MonoInst *src_var, *src;
13510
13511                                 GSHAREDVT_FAILURE (*ip);
13512
13513                                 CHECK_STACK (1);
13514                                 --sp;
13515
13516                                 // FIXME:
13517                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
13518                                 if (!src_var)
13519                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
13520                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
13521                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
13522                                 *sp++ = ins;
13523                                 ip += 2;
13524                                 break;
13525                         }
13526                         case CEE_READONLY_:
13527                                 readonly = TRUE;
13528                                 ip += 2;
13529                                 break;
13530
13531                         case CEE_UNUSED56:
13532                         case CEE_UNUSED57:
13533                         case CEE_UNUSED70:
13534                         case CEE_UNUSED:
13535                         case CEE_UNUSED99:
13536                                 UNVERIFIED;
13537                                 
13538                         default:
13539                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
13540                                 UNVERIFIED;
13541                         }
13542                         break;
13543                 }
13544                 case CEE_UNUSED58:
13545                 case CEE_UNUSED1:
13546                         UNVERIFIED;
13547
13548                 default:
13549                         g_warning ("opcode 0x%02x not handled", *ip);
13550                         UNVERIFIED;
13551                 }
13552         }
13553         if (start_new_bblock != 1)
13554                 UNVERIFIED;
13555
13556         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
13557         if (cfg->cbb->next_bb) {
13558                 /* This could already be set because of inlining, #693905 */
13559                 MonoBasicBlock *bb = cfg->cbb;
13560
13561                 while (bb->next_bb)
13562                         bb = bb->next_bb;
13563                 bb->next_bb = end_bblock;
13564         } else {
13565                 cfg->cbb->next_bb = end_bblock;
13566         }
13567
13568         if (cfg->method == method && cfg->domainvar) {
13569                 MonoInst *store;
13570                 MonoInst *get_domain;
13571
13572                 cfg->cbb = init_localsbb;
13573
13574                 if ((get_domain = mono_get_domain_intrinsic (cfg))) {
13575                         MONO_ADD_INS (cfg->cbb, get_domain);
13576                 } else {
13577                         get_domain = mono_emit_jit_icall (cfg, mono_domain_get, NULL);
13578                 }
13579                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
13580                 MONO_ADD_INS (cfg->cbb, store);
13581         }
13582
13583 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
13584         if (cfg->compile_aot)
13585                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
13586                 mono_get_got_var (cfg);
13587 #endif
13588
13589         if (cfg->method == method && cfg->got_var)
13590                 mono_emit_load_got_addr (cfg);
13591
13592         if (init_localsbb) {
13593                 cfg->cbb = init_localsbb;
13594                 cfg->ip = NULL;
13595                 for (i = 0; i < header->num_locals; ++i) {
13596                         emit_init_local (cfg, i, header->locals [i], init_locals);
13597                 }
13598         }
13599
13600         if (cfg->init_ref_vars && cfg->method == method) {
13601                 /* Emit initialization for ref vars */
13602                 // FIXME: Avoid duplication initialization for IL locals.
13603                 for (i = 0; i < cfg->num_varinfo; ++i) {
13604                         MonoInst *ins = cfg->varinfo [i];
13605
13606                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
13607                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
13608                 }
13609         }
13610
13611         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
13612                 cfg->cbb = init_localsbb;
13613                 emit_push_lmf (cfg);
13614         }
13615
13616         cfg->cbb = init_localsbb;
13617         emit_instrumentation_call (cfg, mono_profiler_method_enter);
13618
13619         if (seq_points) {
13620                 MonoBasicBlock *bb;
13621
13622                 /*
13623                  * Make seq points at backward branch targets interruptable.
13624                  */
13625                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
13626                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
13627                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
13628         }
13629
13630         /* Add a sequence point for method entry/exit events */
13631         if (seq_points && cfg->gen_sdb_seq_points) {
13632                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
13633                 MONO_ADD_INS (init_localsbb, ins);
13634                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
13635                 MONO_ADD_INS (cfg->bb_exit, ins);
13636         }
13637
13638         /*
13639          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
13640          * the code they refer to was dead (#11880).
13641          */
13642         if (sym_seq_points) {
13643                 for (i = 0; i < header->code_size; ++i) {
13644                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
13645                                 MonoInst *ins;
13646
13647                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
13648                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
13649                         }
13650                 }
13651         }
13652
13653         cfg->ip = NULL;
13654
13655         if (cfg->method == method) {
13656                 MonoBasicBlock *bb;
13657                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13658                         bb->region = mono_find_block_region (cfg, bb->real_offset);
13659                         if (cfg->spvars)
13660                                 mono_create_spvar_for_region (cfg, bb->region);
13661                         if (cfg->verbose_level > 2)
13662                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
13663                 }
13664         } else {
13665                 MonoBasicBlock *bb;
13666                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
13667                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
13668                         bb->real_offset = inline_offset;
13669                 }
13670         }
13671
13672         if (inline_costs < 0) {
13673                 char *mname;
13674
13675                 /* Method is too large */
13676                 mname = mono_method_full_name (method, TRUE);
13677                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
13678                 g_free (mname);
13679         }
13680
13681         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
13682                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
13683
13684         goto cleanup;
13685
13686 mono_error_exit:
13687         g_assert (!mono_error_ok (&cfg->error));
13688         goto cleanup;
13689  
13690  exception_exit:
13691         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
13692         goto cleanup;
13693
13694  unverified:
13695         set_exception_type_from_invalid_il (cfg, method, ip);
13696         goto cleanup;
13697
13698  cleanup:
13699         g_slist_free (class_inits);
13700         mono_basic_block_free (original_bb);
13701         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
13702         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
13703         if (cfg->exception_type)
13704                 return -1;
13705         else
13706                 return inline_costs;
13707 }
13708
13709 static int
13710 store_membase_reg_to_store_membase_imm (int opcode)
13711 {
13712         switch (opcode) {
13713         case OP_STORE_MEMBASE_REG:
13714                 return OP_STORE_MEMBASE_IMM;
13715         case OP_STOREI1_MEMBASE_REG:
13716                 return OP_STOREI1_MEMBASE_IMM;
13717         case OP_STOREI2_MEMBASE_REG:
13718                 return OP_STOREI2_MEMBASE_IMM;
13719         case OP_STOREI4_MEMBASE_REG:
13720                 return OP_STOREI4_MEMBASE_IMM;
13721         case OP_STOREI8_MEMBASE_REG:
13722                 return OP_STOREI8_MEMBASE_IMM;
13723         default:
13724                 g_assert_not_reached ();
13725         }
13726
13727         return -1;
13728 }               
13729
13730 int
13731 mono_op_to_op_imm (int opcode)
13732 {
13733         switch (opcode) {
13734         case OP_IADD:
13735                 return OP_IADD_IMM;
13736         case OP_ISUB:
13737                 return OP_ISUB_IMM;
13738         case OP_IDIV:
13739                 return OP_IDIV_IMM;
13740         case OP_IDIV_UN:
13741                 return OP_IDIV_UN_IMM;
13742         case OP_IREM:
13743                 return OP_IREM_IMM;
13744         case OP_IREM_UN:
13745                 return OP_IREM_UN_IMM;
13746         case OP_IMUL:
13747                 return OP_IMUL_IMM;
13748         case OP_IAND:
13749                 return OP_IAND_IMM;
13750         case OP_IOR:
13751                 return OP_IOR_IMM;
13752         case OP_IXOR:
13753                 return OP_IXOR_IMM;
13754         case OP_ISHL:
13755                 return OP_ISHL_IMM;
13756         case OP_ISHR:
13757                 return OP_ISHR_IMM;
13758         case OP_ISHR_UN:
13759                 return OP_ISHR_UN_IMM;
13760
13761         case OP_LADD:
13762                 return OP_LADD_IMM;
13763         case OP_LSUB:
13764                 return OP_LSUB_IMM;
13765         case OP_LAND:
13766                 return OP_LAND_IMM;
13767         case OP_LOR:
13768                 return OP_LOR_IMM;
13769         case OP_LXOR:
13770                 return OP_LXOR_IMM;
13771         case OP_LSHL:
13772                 return OP_LSHL_IMM;
13773         case OP_LSHR:
13774                 return OP_LSHR_IMM;
13775         case OP_LSHR_UN:
13776                 return OP_LSHR_UN_IMM;
13777 #if SIZEOF_REGISTER == 8
13778         case OP_LREM:
13779                 return OP_LREM_IMM;
13780 #endif
13781
13782         case OP_COMPARE:
13783                 return OP_COMPARE_IMM;
13784         case OP_ICOMPARE:
13785                 return OP_ICOMPARE_IMM;
13786         case OP_LCOMPARE:
13787                 return OP_LCOMPARE_IMM;
13788
13789         case OP_STORE_MEMBASE_REG:
13790                 return OP_STORE_MEMBASE_IMM;
13791         case OP_STOREI1_MEMBASE_REG:
13792                 return OP_STOREI1_MEMBASE_IMM;
13793         case OP_STOREI2_MEMBASE_REG:
13794                 return OP_STOREI2_MEMBASE_IMM;
13795         case OP_STOREI4_MEMBASE_REG:
13796                 return OP_STOREI4_MEMBASE_IMM;
13797
13798 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13799         case OP_X86_PUSH:
13800                 return OP_X86_PUSH_IMM;
13801         case OP_X86_COMPARE_MEMBASE_REG:
13802                 return OP_X86_COMPARE_MEMBASE_IMM;
13803 #endif
13804 #if defined(TARGET_AMD64)
13805         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13806                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13807 #endif
13808         case OP_VOIDCALL_REG:
13809                 return OP_VOIDCALL;
13810         case OP_CALL_REG:
13811                 return OP_CALL;
13812         case OP_LCALL_REG:
13813                 return OP_LCALL;
13814         case OP_FCALL_REG:
13815                 return OP_FCALL;
13816         case OP_LOCALLOC:
13817                 return OP_LOCALLOC_IMM;
13818         }
13819
13820         return -1;
13821 }
13822
13823 static int
13824 ldind_to_load_membase (int opcode)
13825 {
13826         switch (opcode) {
13827         case CEE_LDIND_I1:
13828                 return OP_LOADI1_MEMBASE;
13829         case CEE_LDIND_U1:
13830                 return OP_LOADU1_MEMBASE;
13831         case CEE_LDIND_I2:
13832                 return OP_LOADI2_MEMBASE;
13833         case CEE_LDIND_U2:
13834                 return OP_LOADU2_MEMBASE;
13835         case CEE_LDIND_I4:
13836                 return OP_LOADI4_MEMBASE;
13837         case CEE_LDIND_U4:
13838                 return OP_LOADU4_MEMBASE;
13839         case CEE_LDIND_I:
13840                 return OP_LOAD_MEMBASE;
13841         case CEE_LDIND_REF:
13842                 return OP_LOAD_MEMBASE;
13843         case CEE_LDIND_I8:
13844                 return OP_LOADI8_MEMBASE;
13845         case CEE_LDIND_R4:
13846                 return OP_LOADR4_MEMBASE;
13847         case CEE_LDIND_R8:
13848                 return OP_LOADR8_MEMBASE;
13849         default:
13850                 g_assert_not_reached ();
13851         }
13852
13853         return -1;
13854 }
13855
13856 static int
13857 stind_to_store_membase (int opcode)
13858 {
13859         switch (opcode) {
13860         case CEE_STIND_I1:
13861                 return OP_STOREI1_MEMBASE_REG;
13862         case CEE_STIND_I2:
13863                 return OP_STOREI2_MEMBASE_REG;
13864         case CEE_STIND_I4:
13865                 return OP_STOREI4_MEMBASE_REG;
13866         case CEE_STIND_I:
13867         case CEE_STIND_REF:
13868                 return OP_STORE_MEMBASE_REG;
13869         case CEE_STIND_I8:
13870                 return OP_STOREI8_MEMBASE_REG;
13871         case CEE_STIND_R4:
13872                 return OP_STORER4_MEMBASE_REG;
13873         case CEE_STIND_R8:
13874                 return OP_STORER8_MEMBASE_REG;
13875         default:
13876                 g_assert_not_reached ();
13877         }
13878
13879         return -1;
13880 }
13881
13882 int
13883 mono_load_membase_to_load_mem (int opcode)
13884 {
13885         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13886 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13887         switch (opcode) {
13888         case OP_LOAD_MEMBASE:
13889                 return OP_LOAD_MEM;
13890         case OP_LOADU1_MEMBASE:
13891                 return OP_LOADU1_MEM;
13892         case OP_LOADU2_MEMBASE:
13893                 return OP_LOADU2_MEM;
13894         case OP_LOADI4_MEMBASE:
13895                 return OP_LOADI4_MEM;
13896         case OP_LOADU4_MEMBASE:
13897                 return OP_LOADU4_MEM;
13898 #if SIZEOF_REGISTER == 8
13899         case OP_LOADI8_MEMBASE:
13900                 return OP_LOADI8_MEM;
13901 #endif
13902         }
13903 #endif
13904
13905         return -1;
13906 }
13907
13908 static inline int
13909 op_to_op_dest_membase (int store_opcode, int opcode)
13910 {
13911 #if defined(TARGET_X86)
13912         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13913                 return -1;
13914
13915         switch (opcode) {
13916         case OP_IADD:
13917                 return OP_X86_ADD_MEMBASE_REG;
13918         case OP_ISUB:
13919                 return OP_X86_SUB_MEMBASE_REG;
13920         case OP_IAND:
13921                 return OP_X86_AND_MEMBASE_REG;
13922         case OP_IOR:
13923                 return OP_X86_OR_MEMBASE_REG;
13924         case OP_IXOR:
13925                 return OP_X86_XOR_MEMBASE_REG;
13926         case OP_ADD_IMM:
13927         case OP_IADD_IMM:
13928                 return OP_X86_ADD_MEMBASE_IMM;
13929         case OP_SUB_IMM:
13930         case OP_ISUB_IMM:
13931                 return OP_X86_SUB_MEMBASE_IMM;
13932         case OP_AND_IMM:
13933         case OP_IAND_IMM:
13934                 return OP_X86_AND_MEMBASE_IMM;
13935         case OP_OR_IMM:
13936         case OP_IOR_IMM:
13937                 return OP_X86_OR_MEMBASE_IMM;
13938         case OP_XOR_IMM:
13939         case OP_IXOR_IMM:
13940                 return OP_X86_XOR_MEMBASE_IMM;
13941         case OP_MOVE:
13942                 return OP_NOP;
13943         }
13944 #endif
13945
13946 #if defined(TARGET_AMD64)
13947         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13948                 return -1;
13949
13950         switch (opcode) {
13951         case OP_IADD:
13952                 return OP_X86_ADD_MEMBASE_REG;
13953         case OP_ISUB:
13954                 return OP_X86_SUB_MEMBASE_REG;
13955         case OP_IAND:
13956                 return OP_X86_AND_MEMBASE_REG;
13957         case OP_IOR:
13958                 return OP_X86_OR_MEMBASE_REG;
13959         case OP_IXOR:
13960                 return OP_X86_XOR_MEMBASE_REG;
13961         case OP_IADD_IMM:
13962                 return OP_X86_ADD_MEMBASE_IMM;
13963         case OP_ISUB_IMM:
13964                 return OP_X86_SUB_MEMBASE_IMM;
13965         case OP_IAND_IMM:
13966                 return OP_X86_AND_MEMBASE_IMM;
13967         case OP_IOR_IMM:
13968                 return OP_X86_OR_MEMBASE_IMM;
13969         case OP_IXOR_IMM:
13970                 return OP_X86_XOR_MEMBASE_IMM;
13971         case OP_LADD:
13972                 return OP_AMD64_ADD_MEMBASE_REG;
13973         case OP_LSUB:
13974                 return OP_AMD64_SUB_MEMBASE_REG;
13975         case OP_LAND:
13976                 return OP_AMD64_AND_MEMBASE_REG;
13977         case OP_LOR:
13978                 return OP_AMD64_OR_MEMBASE_REG;
13979         case OP_LXOR:
13980                 return OP_AMD64_XOR_MEMBASE_REG;
13981         case OP_ADD_IMM:
13982         case OP_LADD_IMM:
13983                 return OP_AMD64_ADD_MEMBASE_IMM;
13984         case OP_SUB_IMM:
13985         case OP_LSUB_IMM:
13986                 return OP_AMD64_SUB_MEMBASE_IMM;
13987         case OP_AND_IMM:
13988         case OP_LAND_IMM:
13989                 return OP_AMD64_AND_MEMBASE_IMM;
13990         case OP_OR_IMM:
13991         case OP_LOR_IMM:
13992                 return OP_AMD64_OR_MEMBASE_IMM;
13993         case OP_XOR_IMM:
13994         case OP_LXOR_IMM:
13995                 return OP_AMD64_XOR_MEMBASE_IMM;
13996         case OP_MOVE:
13997                 return OP_NOP;
13998         }
13999 #endif
14000
14001         return -1;
14002 }
14003
14004 static inline int
14005 op_to_op_store_membase (int store_opcode, int opcode)
14006 {
14007 #if defined(TARGET_X86) || defined(TARGET_AMD64)
14008         switch (opcode) {
14009         case OP_ICEQ:
14010                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
14011                         return OP_X86_SETEQ_MEMBASE;
14012         case OP_CNE:
14013                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
14014                         return OP_X86_SETNE_MEMBASE;
14015         }
14016 #endif
14017
14018         return -1;
14019 }
14020
14021 static inline int
14022 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
14023 {
14024 #ifdef TARGET_X86
14025         /* FIXME: This has sign extension issues */
14026         /*
14027         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
14028                 return OP_X86_COMPARE_MEMBASE8_IMM;
14029         */
14030
14031         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
14032                 return -1;
14033
14034         switch (opcode) {
14035         case OP_X86_PUSH:
14036                 return OP_X86_PUSH_MEMBASE;
14037         case OP_COMPARE_IMM:
14038         case OP_ICOMPARE_IMM:
14039                 return OP_X86_COMPARE_MEMBASE_IMM;
14040         case OP_COMPARE:
14041         case OP_ICOMPARE:
14042                 return OP_X86_COMPARE_MEMBASE_REG;
14043         }
14044 #endif
14045
14046 #ifdef TARGET_AMD64
14047         /* FIXME: This has sign extension issues */
14048         /*
14049         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
14050                 return OP_X86_COMPARE_MEMBASE8_IMM;
14051         */
14052
14053         switch (opcode) {
14054         case OP_X86_PUSH:
14055                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
14056                         return OP_X86_PUSH_MEMBASE;
14057                 break;
14058                 /* FIXME: This only works for 32 bit immediates
14059         case OP_COMPARE_IMM:
14060         case OP_LCOMPARE_IMM:
14061                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
14062                         return OP_AMD64_COMPARE_MEMBASE_IMM;
14063                 */
14064         case OP_ICOMPARE_IMM:
14065                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
14066                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
14067                 break;
14068         case OP_COMPARE:
14069         case OP_LCOMPARE:
14070                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
14071                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
14072                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
14073                         return OP_AMD64_COMPARE_MEMBASE_REG;
14074                 break;
14075         case OP_ICOMPARE:
14076                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
14077                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
14078                 break;
14079         }
14080 #endif
14081
14082         return -1;
14083 }
14084
14085 static inline int
14086 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
14087 {
14088 #ifdef TARGET_X86
14089         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
14090                 return -1;
14091         
14092         switch (opcode) {
14093         case OP_COMPARE:
14094         case OP_ICOMPARE:
14095                 return OP_X86_COMPARE_REG_MEMBASE;
14096         case OP_IADD:
14097                 return OP_X86_ADD_REG_MEMBASE;
14098         case OP_ISUB:
14099                 return OP_X86_SUB_REG_MEMBASE;
14100         case OP_IAND:
14101                 return OP_X86_AND_REG_MEMBASE;
14102         case OP_IOR:
14103                 return OP_X86_OR_REG_MEMBASE;
14104         case OP_IXOR:
14105                 return OP_X86_XOR_REG_MEMBASE;
14106         }
14107 #endif
14108
14109 #ifdef TARGET_AMD64
14110         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
14111                 switch (opcode) {
14112                 case OP_ICOMPARE:
14113                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
14114                 case OP_IADD:
14115                         return OP_X86_ADD_REG_MEMBASE;
14116                 case OP_ISUB:
14117                         return OP_X86_SUB_REG_MEMBASE;
14118                 case OP_IAND:
14119                         return OP_X86_AND_REG_MEMBASE;
14120                 case OP_IOR:
14121                         return OP_X86_OR_REG_MEMBASE;
14122                 case OP_IXOR:
14123                         return OP_X86_XOR_REG_MEMBASE;
14124                 }
14125         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
14126                 switch (opcode) {
14127                 case OP_COMPARE:
14128                 case OP_LCOMPARE:
14129                         return OP_AMD64_COMPARE_REG_MEMBASE;
14130                 case OP_LADD:
14131                         return OP_AMD64_ADD_REG_MEMBASE;
14132                 case OP_LSUB:
14133                         return OP_AMD64_SUB_REG_MEMBASE;
14134                 case OP_LAND:
14135                         return OP_AMD64_AND_REG_MEMBASE;
14136                 case OP_LOR:
14137                         return OP_AMD64_OR_REG_MEMBASE;
14138                 case OP_LXOR:
14139                         return OP_AMD64_XOR_REG_MEMBASE;
14140                 }
14141         }
14142 #endif
14143
14144         return -1;
14145 }
14146
14147 int
14148 mono_op_to_op_imm_noemul (int opcode)
14149 {
14150         switch (opcode) {
14151 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
14152         case OP_LSHR:
14153         case OP_LSHL:
14154         case OP_LSHR_UN:
14155                 return -1;
14156 #endif
14157 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
14158         case OP_IDIV:
14159         case OP_IDIV_UN:
14160         case OP_IREM:
14161         case OP_IREM_UN:
14162                 return -1;
14163 #endif
14164 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
14165         case OP_IMUL:
14166                 return -1;
14167 #endif
14168         default:
14169                 return mono_op_to_op_imm (opcode);
14170         }
14171 }
14172
14173 /**
14174  * mono_handle_global_vregs:
14175  *
14176  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
14177  * for them.
14178  */
14179 void
14180 mono_handle_global_vregs (MonoCompile *cfg)
14181 {
14182         gint32 *vreg_to_bb;
14183         MonoBasicBlock *bb;
14184         int i, pos;
14185
14186         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
14187
14188 #ifdef MONO_ARCH_SIMD_INTRINSICS
14189         if (cfg->uses_simd_intrinsics)
14190                 mono_simd_simplify_indirection (cfg);
14191 #endif
14192
14193         /* Find local vregs used in more than one bb */
14194         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
14195                 MonoInst *ins = bb->code;       
14196                 int block_num = bb->block_num;
14197
14198                 if (cfg->verbose_level > 2)
14199                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
14200
14201                 cfg->cbb = bb;
14202                 for (; ins; ins = ins->next) {
14203                         const char *spec = INS_INFO (ins->opcode);
14204                         int regtype = 0, regindex;
14205                         gint32 prev_bb;
14206
14207                         if (G_UNLIKELY (cfg->verbose_level > 2))
14208                                 mono_print_ins (ins);
14209
14210                         g_assert (ins->opcode >= MONO_CEE_LAST);
14211
14212                         for (regindex = 0; regindex < 4; regindex ++) {
14213                                 int vreg = 0;
14214
14215                                 if (regindex == 0) {
14216                                         regtype = spec [MONO_INST_DEST];
14217                                         if (regtype == ' ')
14218                                                 continue;
14219                                         vreg = ins->dreg;
14220                                 } else if (regindex == 1) {
14221                                         regtype = spec [MONO_INST_SRC1];
14222                                         if (regtype == ' ')
14223                                                 continue;
14224                                         vreg = ins->sreg1;
14225                                 } else if (regindex == 2) {
14226                                         regtype = spec [MONO_INST_SRC2];
14227                                         if (regtype == ' ')
14228                                                 continue;
14229                                         vreg = ins->sreg2;
14230                                 } else if (regindex == 3) {
14231                                         regtype = spec [MONO_INST_SRC3];
14232                                         if (regtype == ' ')
14233                                                 continue;
14234                                         vreg = ins->sreg3;
14235                                 }
14236
14237 #if SIZEOF_REGISTER == 4
14238                                 /* In the LLVM case, the long opcodes are not decomposed */
14239                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
14240                                         /*
14241                                          * Since some instructions reference the original long vreg,
14242                                          * and some reference the two component vregs, it is quite hard
14243                                          * to determine when it needs to be global. So be conservative.
14244                                          */
14245                                         if (!get_vreg_to_inst (cfg, vreg)) {
14246                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
14247
14248                                                 if (cfg->verbose_level > 2)
14249                                                         printf ("LONG VREG R%d made global.\n", vreg);
14250                                         }
14251
14252                                         /*
14253                                          * Make the component vregs volatile since the optimizations can
14254                                          * get confused otherwise.
14255                                          */
14256                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
14257                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
14258                                 }
14259 #endif
14260
14261                                 g_assert (vreg != -1);
14262
14263                                 prev_bb = vreg_to_bb [vreg];
14264                                 if (prev_bb == 0) {
14265                                         /* 0 is a valid block num */
14266                                         vreg_to_bb [vreg] = block_num + 1;
14267                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
14268                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
14269                                                 continue;
14270
14271                                         if (!get_vreg_to_inst (cfg, vreg)) {
14272                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14273                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
14274
14275                                                 switch (regtype) {
14276                                                 case 'i':
14277                                                         if (vreg_is_ref (cfg, vreg))
14278                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
14279                                                         else
14280                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
14281                                                         break;
14282                                                 case 'l':
14283                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
14284                                                         break;
14285                                                 case 'f':
14286                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
14287                                                         break;
14288                                                 case 'v':
14289                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
14290                                                         break;
14291                                                 default:
14292                                                         g_assert_not_reached ();
14293                                                 }
14294                                         }
14295
14296                                         /* Flag as having been used in more than one bb */
14297                                         vreg_to_bb [vreg] = -1;
14298                                 }
14299                         }
14300                 }
14301         }
14302
14303         /* If a variable is used in only one bblock, convert it into a local vreg */
14304         for (i = 0; i < cfg->num_varinfo; i++) {
14305                 MonoInst *var = cfg->varinfo [i];
14306                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
14307
14308                 switch (var->type) {
14309                 case STACK_I4:
14310                 case STACK_OBJ:
14311                 case STACK_PTR:
14312                 case STACK_MP:
14313                 case STACK_VTYPE:
14314 #if SIZEOF_REGISTER == 8
14315                 case STACK_I8:
14316 #endif
14317 #if !defined(TARGET_X86)
14318                 /* Enabling this screws up the fp stack on x86 */
14319                 case STACK_R8:
14320 #endif
14321                         if (mono_arch_is_soft_float ())
14322                                 break;
14323
14324                         /*
14325                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
14326                                 break;
14327                         */
14328
14329                         /* Arguments are implicitly global */
14330                         /* Putting R4 vars into registers doesn't work currently */
14331                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
14332                         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) {
14333                                 /* 
14334                                  * Make that the variable's liveness interval doesn't contain a call, since
14335                                  * that would cause the lvreg to be spilled, making the whole optimization
14336                                  * useless.
14337                                  */
14338                                 /* This is too slow for JIT compilation */
14339 #if 0
14340                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
14341                                         MonoInst *ins;
14342                                         int def_index, call_index, ins_index;
14343                                         gboolean spilled = FALSE;
14344
14345                                         def_index = -1;
14346                                         call_index = -1;
14347                                         ins_index = 0;
14348                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
14349                                                 const char *spec = INS_INFO (ins->opcode);
14350
14351                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
14352                                                         def_index = ins_index;
14353
14354                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
14355                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
14356                                                         if (call_index > def_index) {
14357                                                                 spilled = TRUE;
14358                                                                 break;
14359                                                         }
14360                                                 }
14361
14362                                                 if (MONO_IS_CALL (ins))
14363                                                         call_index = ins_index;
14364
14365                                                 ins_index ++;
14366                                         }
14367
14368                                         if (spilled)
14369                                                 break;
14370                                 }
14371 #endif
14372
14373                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14374                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
14375                                 var->flags |= MONO_INST_IS_DEAD;
14376                                 cfg->vreg_to_inst [var->dreg] = NULL;
14377                         }
14378                         break;
14379                 }
14380         }
14381
14382         /* 
14383          * Compress the varinfo and vars tables so the liveness computation is faster and
14384          * takes up less space.
14385          */
14386         pos = 0;
14387         for (i = 0; i < cfg->num_varinfo; ++i) {
14388                 MonoInst *var = cfg->varinfo [i];
14389                 if (pos < i && cfg->locals_start == i)
14390                         cfg->locals_start = pos;
14391                 if (!(var->flags & MONO_INST_IS_DEAD)) {
14392                         if (pos < i) {
14393                                 cfg->varinfo [pos] = cfg->varinfo [i];
14394                                 cfg->varinfo [pos]->inst_c0 = pos;
14395                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
14396                                 cfg->vars [pos].idx = pos;
14397 #if SIZEOF_REGISTER == 4
14398                                 if (cfg->varinfo [pos]->type == STACK_I8) {
14399                                         /* Modify the two component vars too */
14400                                         MonoInst *var1;
14401
14402                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
14403                                         var1->inst_c0 = pos;
14404                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
14405                                         var1->inst_c0 = pos;
14406                                 }
14407 #endif
14408                         }
14409                         pos ++;
14410                 }
14411         }
14412         cfg->num_varinfo = pos;
14413         if (cfg->locals_start > cfg->num_varinfo)
14414                 cfg->locals_start = cfg->num_varinfo;
14415 }
14416
14417 /*
14418  * mono_allocate_gsharedvt_vars:
14419  *
14420  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
14421  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
14422  */
14423 void
14424 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
14425 {
14426         int i;
14427
14428         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
14429
14430         for (i = 0; i < cfg->num_varinfo; ++i) {
14431                 MonoInst *ins = cfg->varinfo [i];
14432                 int idx;
14433
14434                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
14435                         if (i >= cfg->locals_start) {
14436                                 /* Local */
14437                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
14438                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
14439                                 ins->opcode = OP_GSHAREDVT_LOCAL;
14440                                 ins->inst_imm = idx;
14441                         } else {
14442                                 /* Arg */
14443                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
14444                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
14445                         }
14446                 }
14447         }
14448 }
14449
14450 /**
14451  * mono_spill_global_vars:
14452  *
14453  *   Generate spill code for variables which are not allocated to registers, 
14454  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
14455  * code is generated which could be optimized by the local optimization passes.
14456  */
14457 void
14458 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
14459 {
14460         MonoBasicBlock *bb;
14461         char spec2 [16];
14462         int orig_next_vreg;
14463         guint32 *vreg_to_lvreg;
14464         guint32 *lvregs;
14465         guint32 i, lvregs_len;
14466         gboolean dest_has_lvreg = FALSE;
14467         MonoStackType stacktypes [128];
14468         MonoInst **live_range_start, **live_range_end;
14469         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
14470
14471         *need_local_opts = FALSE;
14472
14473         memset (spec2, 0, sizeof (spec2));
14474
14475         /* FIXME: Move this function to mini.c */
14476         stacktypes ['i'] = STACK_PTR;
14477         stacktypes ['l'] = STACK_I8;
14478         stacktypes ['f'] = STACK_R8;
14479 #ifdef MONO_ARCH_SIMD_INTRINSICS
14480         stacktypes ['x'] = STACK_VTYPE;
14481 #endif
14482
14483 #if SIZEOF_REGISTER == 4
14484         /* Create MonoInsts for longs */
14485         for (i = 0; i < cfg->num_varinfo; i++) {
14486                 MonoInst *ins = cfg->varinfo [i];
14487
14488                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
14489                         switch (ins->type) {
14490                         case STACK_R8:
14491                         case STACK_I8: {
14492                                 MonoInst *tree;
14493
14494                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
14495                                         break;
14496
14497                                 g_assert (ins->opcode == OP_REGOFFSET);
14498
14499                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
14500                                 g_assert (tree);
14501                                 tree->opcode = OP_REGOFFSET;
14502                                 tree->inst_basereg = ins->inst_basereg;
14503                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
14504
14505                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
14506                                 g_assert (tree);
14507                                 tree->opcode = OP_REGOFFSET;
14508                                 tree->inst_basereg = ins->inst_basereg;
14509                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
14510                                 break;
14511                         }
14512                         default:
14513                                 break;
14514                         }
14515                 }
14516         }
14517 #endif
14518
14519         if (cfg->compute_gc_maps) {
14520                 /* registers need liveness info even for !non refs */
14521                 for (i = 0; i < cfg->num_varinfo; i++) {
14522                         MonoInst *ins = cfg->varinfo [i];
14523
14524                         if (ins->opcode == OP_REGVAR)
14525                                 ins->flags |= MONO_INST_GC_TRACK;
14526                 }
14527         }
14528                 
14529         /* FIXME: widening and truncation */
14530
14531         /*
14532          * As an optimization, when a variable allocated to the stack is first loaded into 
14533          * an lvreg, we will remember the lvreg and use it the next time instead of loading
14534          * the variable again.
14535          */
14536         orig_next_vreg = cfg->next_vreg;
14537         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
14538         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * 1024);
14539         lvregs_len = 0;
14540
14541         /* 
14542          * These arrays contain the first and last instructions accessing a given
14543          * variable.
14544          * Since we emit bblocks in the same order we process them here, and we
14545          * don't split live ranges, these will precisely describe the live range of
14546          * the variable, i.e. the instruction range where a valid value can be found
14547          * in the variables location.
14548          * The live range is computed using the liveness info computed by the liveness pass.
14549          * We can't use vmv->range, since that is an abstract live range, and we need
14550          * one which is instruction precise.
14551          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
14552          */
14553         /* FIXME: Only do this if debugging info is requested */
14554         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
14555         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
14556         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
14557         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
14558         
14559         /* Add spill loads/stores */
14560         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
14561                 MonoInst *ins;
14562
14563                 if (cfg->verbose_level > 2)
14564                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
14565
14566                 /* Clear vreg_to_lvreg array */
14567                 for (i = 0; i < lvregs_len; i++)
14568                         vreg_to_lvreg [lvregs [i]] = 0;
14569                 lvregs_len = 0;
14570
14571                 cfg->cbb = bb;
14572                 MONO_BB_FOR_EACH_INS (bb, ins) {
14573                         const char *spec = INS_INFO (ins->opcode);
14574                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
14575                         gboolean store, no_lvreg;
14576                         int sregs [MONO_MAX_SRC_REGS];
14577
14578                         if (G_UNLIKELY (cfg->verbose_level > 2))
14579                                 mono_print_ins (ins);
14580
14581                         if (ins->opcode == OP_NOP)
14582                                 continue;
14583
14584                         /* 
14585                          * We handle LDADDR here as well, since it can only be decomposed
14586                          * when variable addresses are known.
14587                          */
14588                         if (ins->opcode == OP_LDADDR) {
14589                                 MonoInst *var = (MonoInst *)ins->inst_p0;
14590
14591                                 if (var->opcode == OP_VTARG_ADDR) {
14592                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
14593                                         MonoInst *vtaddr = var->inst_left;
14594                                         if (vtaddr->opcode == OP_REGVAR) {
14595                                                 ins->opcode = OP_MOVE;
14596                                                 ins->sreg1 = vtaddr->dreg;
14597                                         }
14598                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
14599                                                 ins->opcode = OP_LOAD_MEMBASE;
14600                                                 ins->inst_basereg = vtaddr->inst_basereg;
14601                                                 ins->inst_offset = vtaddr->inst_offset;
14602                                         } else
14603                                                 NOT_IMPLEMENTED;
14604                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
14605                                         /* gsharedvt arg passed by ref */
14606                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
14607
14608                                         ins->opcode = OP_LOAD_MEMBASE;
14609                                         ins->inst_basereg = var->inst_basereg;
14610                                         ins->inst_offset = var->inst_offset;
14611                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
14612                                         MonoInst *load, *load2, *load3;
14613                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
14614                                         int reg1, reg2, reg3;
14615                                         MonoInst *info_var = cfg->gsharedvt_info_var;
14616                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
14617
14618                                         /*
14619                                          * gsharedvt local.
14620                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
14621                                          */
14622
14623                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
14624
14625                                         g_assert (info_var);
14626                                         g_assert (locals_var);
14627
14628                                         /* Mark the instruction used to compute the locals var as used */
14629                                         cfg->gsharedvt_locals_var_ins = NULL;
14630
14631                                         /* Load the offset */
14632                                         if (info_var->opcode == OP_REGOFFSET) {
14633                                                 reg1 = alloc_ireg (cfg);
14634                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
14635                                         } else if (info_var->opcode == OP_REGVAR) {
14636                                                 load = NULL;
14637                                                 reg1 = info_var->dreg;
14638                                         } else {
14639                                                 g_assert_not_reached ();
14640                                         }
14641                                         reg2 = alloc_ireg (cfg);
14642                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
14643                                         /* Load the locals area address */
14644                                         reg3 = alloc_ireg (cfg);
14645                                         if (locals_var->opcode == OP_REGOFFSET) {
14646                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
14647                                         } else if (locals_var->opcode == OP_REGVAR) {
14648                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
14649                                         } else {
14650                                                 g_assert_not_reached ();
14651                                         }
14652                                         /* Compute the address */
14653                                         ins->opcode = OP_PADD;
14654                                         ins->sreg1 = reg3;
14655                                         ins->sreg2 = reg2;
14656
14657                                         mono_bblock_insert_before_ins (bb, ins, load3);
14658                                         mono_bblock_insert_before_ins (bb, load3, load2);
14659                                         if (load)
14660                                                 mono_bblock_insert_before_ins (bb, load2, load);
14661                                 } else {
14662                                         g_assert (var->opcode == OP_REGOFFSET);
14663
14664                                         ins->opcode = OP_ADD_IMM;
14665                                         ins->sreg1 = var->inst_basereg;
14666                                         ins->inst_imm = var->inst_offset;
14667                                 }
14668
14669                                 *need_local_opts = TRUE;
14670                                 spec = INS_INFO (ins->opcode);
14671                         }
14672
14673                         if (ins->opcode < MONO_CEE_LAST) {
14674                                 mono_print_ins (ins);
14675                                 g_assert_not_reached ();
14676                         }
14677
14678                         /*
14679                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
14680                          * src register.
14681                          * FIXME:
14682                          */
14683                         if (MONO_IS_STORE_MEMBASE (ins)) {
14684                                 tmp_reg = ins->dreg;
14685                                 ins->dreg = ins->sreg2;
14686                                 ins->sreg2 = tmp_reg;
14687                                 store = TRUE;
14688
14689                                 spec2 [MONO_INST_DEST] = ' ';
14690                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14691                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14692                                 spec2 [MONO_INST_SRC3] = ' ';
14693                                 spec = spec2;
14694                         } else if (MONO_IS_STORE_MEMINDEX (ins))
14695                                 g_assert_not_reached ();
14696                         else
14697                                 store = FALSE;
14698                         no_lvreg = FALSE;
14699
14700                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
14701                                 printf ("\t %.3s %d", spec, ins->dreg);
14702                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
14703                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
14704                                         printf (" %d", sregs [srcindex]);
14705                                 printf ("\n");
14706                         }
14707
14708                         /***************/
14709                         /*    DREG     */
14710                         /***************/
14711                         regtype = spec [MONO_INST_DEST];
14712                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
14713                         prev_dreg = -1;
14714
14715                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
14716                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
14717                                 MonoInst *store_ins;
14718                                 int store_opcode;
14719                                 MonoInst *def_ins = ins;
14720                                 int dreg = ins->dreg; /* The original vreg */
14721
14722                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
14723
14724                                 if (var->opcode == OP_REGVAR) {
14725                                         ins->dreg = var->dreg;
14726                                 } 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)) {
14727                                         /* 
14728                                          * Instead of emitting a load+store, use a _membase opcode.
14729                                          */
14730                                         g_assert (var->opcode == OP_REGOFFSET);
14731                                         if (ins->opcode == OP_MOVE) {
14732                                                 NULLIFY_INS (ins);
14733                                                 def_ins = NULL;
14734                                         } else {
14735                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
14736                                                 ins->inst_basereg = var->inst_basereg;
14737                                                 ins->inst_offset = var->inst_offset;
14738                                                 ins->dreg = -1;
14739                                         }
14740                                         spec = INS_INFO (ins->opcode);
14741                                 } else {
14742                                         guint32 lvreg;
14743
14744                                         g_assert (var->opcode == OP_REGOFFSET);
14745
14746                                         prev_dreg = ins->dreg;
14747
14748                                         /* Invalidate any previous lvreg for this vreg */
14749                                         vreg_to_lvreg [ins->dreg] = 0;
14750
14751                                         lvreg = 0;
14752
14753                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14754                                                 regtype = 'l';
14755                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14756                                         }
14757
14758                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14759
14760 #if SIZEOF_REGISTER != 8
14761                                         if (regtype == 'l') {
14762                                                 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));
14763                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14764                                                 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));
14765                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14766                                                 def_ins = store_ins;
14767                                         }
14768                                         else
14769 #endif
14770                                         {
14771                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14772
14773                                                 /* Try to fuse the store into the instruction itself */
14774                                                 /* FIXME: Add more instructions */
14775                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14776                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14777                                                         ins->inst_imm = ins->inst_c0;
14778                                                         ins->inst_destbasereg = var->inst_basereg;
14779                                                         ins->inst_offset = var->inst_offset;
14780                                                         spec = INS_INFO (ins->opcode);
14781                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14782                                                         ins->opcode = store_opcode;
14783                                                         ins->inst_destbasereg = var->inst_basereg;
14784                                                         ins->inst_offset = var->inst_offset;
14785
14786                                                         no_lvreg = TRUE;
14787
14788                                                         tmp_reg = ins->dreg;
14789                                                         ins->dreg = ins->sreg2;
14790                                                         ins->sreg2 = tmp_reg;
14791                                                         store = TRUE;
14792
14793                                                         spec2 [MONO_INST_DEST] = ' ';
14794                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14795                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14796                                                         spec2 [MONO_INST_SRC3] = ' ';
14797                                                         spec = spec2;
14798                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14799                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14800                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14801                                                         ins->dreg = -1;
14802                                                         ins->inst_basereg = var->inst_basereg;
14803                                                         ins->inst_offset = var->inst_offset;
14804                                                         spec = INS_INFO (ins->opcode);
14805                                                 } else {
14806                                                         /* printf ("INS: "); mono_print_ins (ins); */
14807                                                         /* Create a store instruction */
14808                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14809
14810                                                         /* Insert it after the instruction */
14811                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14812
14813                                                         def_ins = store_ins;
14814
14815                                                         /* 
14816                                                          * We can't assign ins->dreg to var->dreg here, since the
14817                                                          * sregs could use it. So set a flag, and do it after
14818                                                          * the sregs.
14819                                                          */
14820                                                         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)))
14821                                                                 dest_has_lvreg = TRUE;
14822                                                 }
14823                                         }
14824                                 }
14825
14826                                 if (def_ins && !live_range_start [dreg]) {
14827                                         live_range_start [dreg] = def_ins;
14828                                         live_range_start_bb [dreg] = bb;
14829                                 }
14830
14831                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14832                                         MonoInst *tmp;
14833
14834                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14835                                         tmp->inst_c1 = dreg;
14836                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14837                                 }
14838                         }
14839
14840                         /************/
14841                         /*  SREGS   */
14842                         /************/
14843                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14844                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14845                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14846                                 sreg = sregs [srcindex];
14847
14848                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14849                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14850                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14851                                         MonoInst *use_ins = ins;
14852                                         MonoInst *load_ins;
14853                                         guint32 load_opcode;
14854
14855                                         if (var->opcode == OP_REGVAR) {
14856                                                 sregs [srcindex] = var->dreg;
14857                                                 //mono_inst_set_src_registers (ins, sregs);
14858                                                 live_range_end [sreg] = use_ins;
14859                                                 live_range_end_bb [sreg] = bb;
14860
14861                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14862                                                         MonoInst *tmp;
14863
14864                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14865                                                         /* var->dreg is a hreg */
14866                                                         tmp->inst_c1 = sreg;
14867                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14868                                                 }
14869
14870                                                 continue;
14871                                         }
14872
14873                                         g_assert (var->opcode == OP_REGOFFSET);
14874                                                 
14875                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14876
14877                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14878
14879                                         if (vreg_to_lvreg [sreg]) {
14880                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14881
14882                                                 /* The variable is already loaded to an lvreg */
14883                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14884                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14885                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14886                                                 //mono_inst_set_src_registers (ins, sregs);
14887                                                 continue;
14888                                         }
14889
14890                                         /* Try to fuse the load into the instruction */
14891                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14892                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14893                                                 sregs [0] = var->inst_basereg;
14894                                                 //mono_inst_set_src_registers (ins, sregs);
14895                                                 ins->inst_offset = var->inst_offset;
14896                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14897                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14898                                                 sregs [1] = var->inst_basereg;
14899                                                 //mono_inst_set_src_registers (ins, sregs);
14900                                                 ins->inst_offset = var->inst_offset;
14901                                         } else {
14902                                                 if (MONO_IS_REAL_MOVE (ins)) {
14903                                                         ins->opcode = OP_NOP;
14904                                                         sreg = ins->dreg;
14905                                                 } else {
14906                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14907
14908                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14909
14910                                                         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) {
14911                                                                 if (var->dreg == prev_dreg) {
14912                                                                         /*
14913                                                                          * sreg refers to the value loaded by the load
14914                                                                          * emitted below, but we need to use ins->dreg
14915                                                                          * since it refers to the store emitted earlier.
14916                                                                          */
14917                                                                         sreg = ins->dreg;
14918                                                                 }
14919                                                                 g_assert (sreg != -1);
14920                                                                 vreg_to_lvreg [var->dreg] = sreg;
14921                                                                 g_assert (lvregs_len < 1024);
14922                                                                 lvregs [lvregs_len ++] = var->dreg;
14923                                                         }
14924                                                 }
14925
14926                                                 sregs [srcindex] = sreg;
14927                                                 //mono_inst_set_src_registers (ins, sregs);
14928
14929 #if SIZEOF_REGISTER != 8
14930                                                 if (regtype == 'l') {
14931                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14932                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14933                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14934                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14935                                                         use_ins = load_ins;
14936                                                 }
14937                                                 else
14938 #endif
14939                                                 {
14940 #if SIZEOF_REGISTER == 4
14941                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14942 #endif
14943                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14944                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14945                                                         use_ins = load_ins;
14946                                                 }
14947                                         }
14948
14949                                         if (var->dreg < orig_next_vreg) {
14950                                                 live_range_end [var->dreg] = use_ins;
14951                                                 live_range_end_bb [var->dreg] = bb;
14952                                         }
14953
14954                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14955                                                 MonoInst *tmp;
14956
14957                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14958                                                 tmp->inst_c1 = var->dreg;
14959                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14960                                         }
14961                                 }
14962                         }
14963                         mono_inst_set_src_registers (ins, sregs);
14964
14965                         if (dest_has_lvreg) {
14966                                 g_assert (ins->dreg != -1);
14967                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14968                                 g_assert (lvregs_len < 1024);
14969                                 lvregs [lvregs_len ++] = prev_dreg;
14970                                 dest_has_lvreg = FALSE;
14971                         }
14972
14973                         if (store) {
14974                                 tmp_reg = ins->dreg;
14975                                 ins->dreg = ins->sreg2;
14976                                 ins->sreg2 = tmp_reg;
14977                         }
14978
14979                         if (MONO_IS_CALL (ins)) {
14980                                 /* Clear vreg_to_lvreg array */
14981                                 for (i = 0; i < lvregs_len; i++)
14982                                         vreg_to_lvreg [lvregs [i]] = 0;
14983                                 lvregs_len = 0;
14984                         } else if (ins->opcode == OP_NOP) {
14985                                 ins->dreg = -1;
14986                                 MONO_INST_NULLIFY_SREGS (ins);
14987                         }
14988
14989                         if (cfg->verbose_level > 2)
14990                                 mono_print_ins_index (1, ins);
14991                 }
14992
14993                 /* Extend the live range based on the liveness info */
14994                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14995                         for (i = 0; i < cfg->num_varinfo; i ++) {
14996                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14997
14998                                 if (vreg_is_volatile (cfg, vi->vreg))
14999                                         /* The liveness info is incomplete */
15000                                         continue;
15001
15002                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
15003                                         /* Live from at least the first ins of this bb */
15004                                         live_range_start [vi->vreg] = bb->code;
15005                                         live_range_start_bb [vi->vreg] = bb;
15006                                 }
15007
15008                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
15009                                         /* Live at least until the last ins of this bb */
15010                                         live_range_end [vi->vreg] = bb->last_ins;
15011                                         live_range_end_bb [vi->vreg] = bb;
15012                                 }
15013                         }
15014                 }
15015         }
15016         
15017         /*
15018          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
15019          * by storing the current native offset into MonoMethodVar->live_range_start/end.
15020          */
15021         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
15022                 for (i = 0; i < cfg->num_varinfo; ++i) {
15023                         int vreg = MONO_VARINFO (cfg, i)->vreg;
15024                         MonoInst *ins;
15025
15026                         if (live_range_start [vreg]) {
15027                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
15028                                 ins->inst_c0 = i;
15029                                 ins->inst_c1 = vreg;
15030                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
15031                         }
15032                         if (live_range_end [vreg]) {
15033                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
15034                                 ins->inst_c0 = i;
15035                                 ins->inst_c1 = vreg;
15036                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
15037                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
15038                                 else
15039                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
15040                         }
15041                 }
15042         }
15043
15044         if (cfg->gsharedvt_locals_var_ins) {
15045                 /* Nullify if unused */
15046                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
15047                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
15048         }
15049
15050         g_free (live_range_start);
15051         g_free (live_range_end);
15052         g_free (live_range_start_bb);
15053         g_free (live_range_end_bb);
15054 }
15055
15056 /**
15057  * FIXME:
15058  * - use 'iadd' instead of 'int_add'
15059  * - handling ovf opcodes: decompose in method_to_ir.
15060  * - unify iregs/fregs
15061  *   -> partly done, the missing parts are:
15062  *   - a more complete unification would involve unifying the hregs as well, so
15063  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
15064  *     would no longer map to the machine hregs, so the code generators would need to
15065  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
15066  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
15067  *     fp/non-fp branches speeds it up by about 15%.
15068  * - use sext/zext opcodes instead of shifts
15069  * - add OP_ICALL
15070  * - get rid of TEMPLOADs if possible and use vregs instead
15071  * - clean up usage of OP_P/OP_ opcodes
15072  * - cleanup usage of DUMMY_USE
15073  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
15074  *   stack
15075  * - set the stack type and allocate a dreg in the EMIT_NEW macros
15076  * - get rid of all the <foo>2 stuff when the new JIT is ready.
15077  * - make sure handle_stack_args () is called before the branch is emitted
15078  * - when the new IR is done, get rid of all unused stuff
15079  * - COMPARE/BEQ as separate instructions or unify them ?
15080  *   - keeping them separate allows specialized compare instructions like
15081  *     compare_imm, compare_membase
15082  *   - most back ends unify fp compare+branch, fp compare+ceq
15083  * - integrate mono_save_args into inline_method
15084  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
15085  * - handle long shift opts on 32 bit platforms somehow: they require 
15086  *   3 sregs (2 for arg1 and 1 for arg2)
15087  * - make byref a 'normal' type.
15088  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
15089  *   variable if needed.
15090  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
15091  *   like inline_method.
15092  * - remove inlining restrictions
15093  * - fix LNEG and enable cfold of INEG
15094  * - generalize x86 optimizations like ldelema as a peephole optimization
15095  * - add store_mem_imm for amd64
15096  * - optimize the loading of the interruption flag in the managed->native wrappers
15097  * - avoid special handling of OP_NOP in passes
15098  * - move code inserting instructions into one function/macro.
15099  * - try a coalescing phase after liveness analysis
15100  * - add float -> vreg conversion + local optimizations on !x86
15101  * - figure out how to handle decomposed branches during optimizations, ie.
15102  *   compare+branch, op_jump_table+op_br etc.
15103  * - promote RuntimeXHandles to vregs
15104  * - vtype cleanups:
15105  *   - add a NEW_VARLOADA_VREG macro
15106  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
15107  *   accessing vtype fields.
15108  * - get rid of I8CONST on 64 bit platforms
15109  * - dealing with the increase in code size due to branches created during opcode
15110  *   decomposition:
15111  *   - use extended basic blocks
15112  *     - all parts of the JIT
15113  *     - handle_global_vregs () && local regalloc
15114  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
15115  * - sources of increase in code size:
15116  *   - vtypes
15117  *   - long compares
15118  *   - isinst and castclass
15119  *   - lvregs not allocated to global registers even if used multiple times
15120  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
15121  *   meaningful.
15122  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
15123  * - add all micro optimizations from the old JIT
15124  * - put tree optimizations into the deadce pass
15125  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
15126  *   specific function.
15127  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
15128  *   fcompare + branchCC.
15129  * - create a helper function for allocating a stack slot, taking into account 
15130  *   MONO_CFG_HAS_SPILLUP.
15131  * - merge r68207.
15132  * - merge the ia64 switch changes.
15133  * - optimize mono_regstate2_alloc_int/float.
15134  * - fix the pessimistic handling of variables accessed in exception handler blocks.
15135  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
15136  *   parts of the tree could be separated by other instructions, killing the tree
15137  *   arguments, or stores killing loads etc. Also, should we fold loads into other
15138  *   instructions if the result of the load is used multiple times ?
15139  * - make the REM_IMM optimization in mini-x86.c arch-independent.
15140  * - LAST MERGE: 108395.
15141  * - when returning vtypes in registers, generate IR and append it to the end of the
15142  *   last bb instead of doing it in the epilog.
15143  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
15144  */
15145
15146 /*
15147
15148 NOTES
15149 -----
15150
15151 - When to decompose opcodes:
15152   - earlier: this makes some optimizations hard to implement, since the low level IR
15153   no longer contains the neccessary information. But it is easier to do.
15154   - later: harder to implement, enables more optimizations.
15155 - Branches inside bblocks:
15156   - created when decomposing complex opcodes. 
15157     - branches to another bblock: harmless, but not tracked by the branch 
15158       optimizations, so need to branch to a label at the start of the bblock.
15159     - branches to inside the same bblock: very problematic, trips up the local
15160       reg allocator. Can be fixed by spitting the current bblock, but that is a
15161       complex operation, since some local vregs can become global vregs etc.
15162 - Local/global vregs:
15163   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
15164     local register allocator.
15165   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
15166     structure, created by mono_create_var (). Assigned to hregs or the stack by
15167     the global register allocator.
15168 - When to do optimizations like alu->alu_imm:
15169   - earlier -> saves work later on since the IR will be smaller/simpler
15170   - later -> can work on more instructions
15171 - Handling of valuetypes:
15172   - When a vtype is pushed on the stack, a new temporary is created, an 
15173     instruction computing its address (LDADDR) is emitted and pushed on
15174     the stack. Need to optimize cases when the vtype is used immediately as in
15175     argument passing, stloc etc.
15176 - Instead of the to_end stuff in the old JIT, simply call the function handling
15177   the values on the stack before emitting the last instruction of the bb.
15178 */
15179
15180 #endif /* DISABLE_JIT */