[jit] Remove mini_emit_stobj from method-to-ir.c and move mini_emit_wb_aware_memcpy...
[mono.git] / mono / mini / method-to-ir.c
1 /**
2  * \file
3  * Convert CIL to the JIT internal representation
4  *
5  * Author:
6  *   Paolo Molaro (lupus@ximian.com)
7  *   Dietmar Maurer (dietmar@ximian.com)
8  *
9  * (C) 2002 Ximian, Inc.
10  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
11  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14
15 #include <config.h>
16 #include <mono/utils/mono-compiler.h>
17 #include "mini.h"
18
19 #ifndef DISABLE_JIT
20
21 #include <signal.h>
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include <math.h>
28 #include <string.h>
29 #include <ctype.h>
30
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34
35 #ifdef HAVE_ALLOCA_H
36 #include <alloca.h>
37 #endif
38
39 #include <mono/utils/memcheck.h>
40 #include <mono/metadata/abi-details.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/attrdefs.h>
43 #include <mono/metadata/loader.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/class.h>
46 #include <mono/metadata/object.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/opcodes.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/marshal.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/debug-internals.h>
55 #include <mono/metadata/gc-internals.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/security-core-clr.h>
59 #include <mono/metadata/profiler-private.h>
60 #include <mono/metadata/profiler.h>
61 #include <mono/metadata/monitor.h>
62 #include <mono/utils/mono-memory-model.h>
63 #include <mono/utils/mono-error-internals.h>
64 #include <mono/metadata/mono-basic-block.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/utils/mono-threads-coop.h>
67
68 #include "trace.h"
69
70 #include "ir-emit.h"
71
72 #include "jit-icalls.h"
73 #include "jit.h"
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "aot-compiler.h"
77 #include "mini-llvm.h"
78
79 #define BRANCH_COST 10
80 #define INLINE_LENGTH_LIMIT 20
81
82 /* These have 'cfg' as an implicit argument */
83 #define INLINE_FAILURE(msg) do {                                                                        \
84         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
85                 inline_failure (cfg, msg);                                                                              \
86                 goto exception_exit;                                                                                    \
87         } \
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
91                         goto exception_exit;                                            \
92         } while (0)
93 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
94                 field_access_failure ((cfg), (method), (field));                        \
95                 goto exception_exit;    \
96         } while (0)
97 #define GENERIC_SHARING_FAILURE(opcode) do {            \
98                 if (cfg->gshared) {                                                                     \
99                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
100                         goto exception_exit;    \
101                 }                       \
102         } while (0)
103 #define GSHAREDVT_FAILURE(opcode) do {          \
104         if (cfg->gsharedvt) {                                                                                           \
105                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
106                 goto exception_exit;                                                                                    \
107         }                                                                                                                                       \
108         } while (0)
109 #define OUT_OF_MEMORY_FAILURE do {      \
110                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
111                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
112                 goto exception_exit;    \
113         } while (0)
114 #define DISABLE_AOT(cfg) do { \
115                 if ((cfg)->verbose_level >= 2)                                            \
116                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
117                 (cfg)->disable_aot = TRUE;                                                        \
118         } while (0)
119 #define LOAD_ERROR do { \
120                 break_on_unverified ();                                                         \
121                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
122                 goto exception_exit;                                                                    \
123         } while (0)
124
125 #define TYPE_LOAD_ERROR(klass) do { \
126                 cfg->exception_ptr = klass; \
127                 LOAD_ERROR;                                     \
128         } while (0)
129
130 #define CHECK_CFG_ERROR do {\
131                 if (!mono_error_ok (&cfg->error)) { \
132                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
133                         goto mono_error_exit; \
134                 } \
135         } while (0)
136
137 /* Determine whenever 'ins' represents a load of the 'this' argument */
138 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
139
140 static int ldind_to_load_membase (int opcode);
141 static int stind_to_store_membase (int opcode);
142
143 int mono_op_to_op_imm (int opcode);
144 int mono_op_to_op_imm_noemul (int opcode);
145
146 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
147                                                   guchar *ip, guint real_offset, gboolean inline_always);
148 static MonoInst*
149 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
150
151 /* helper methods signatures */
152 static MonoMethodSignature *helper_sig_domain_get;
153 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
154 static MonoMethodSignature *helper_sig_llvmonly_imt_trampoline;
155 static MonoMethodSignature *helper_sig_jit_thread_attach;
156 static MonoMethodSignature *helper_sig_get_tls_tramp;
157 static MonoMethodSignature *helper_sig_set_tls_tramp;
158
159 /* type loading helpers */
160 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
161 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
162
163 /*
164  * Instruction metadata
165  */
166 #ifdef MINI_OP
167 #undef MINI_OP
168 #endif
169 #ifdef MINI_OP3
170 #undef MINI_OP3
171 #endif
172 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
173 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
174 #define NONE ' '
175 #define IREG 'i'
176 #define FREG 'f'
177 #define VREG 'v'
178 #define XREG 'x'
179 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
180 #define LREG IREG
181 #else
182 #define LREG 'l'
183 #endif
184 /* keep in sync with the enum in mini.h */
185 const char
186 ins_info[] = {
187 #include "mini-ops.h"
188 };
189 #undef MINI_OP
190 #undef MINI_OP3
191
192 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
193 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
194 /* 
195  * This should contain the index of the last sreg + 1. This is not the same
196  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
197  */
198 const gint8 ins_sreg_counts[] = {
199 #include "mini-ops.h"
200 };
201 #undef MINI_OP
202 #undef MINI_OP3
203
204 guint32
205 mono_alloc_ireg (MonoCompile *cfg)
206 {
207         return alloc_ireg (cfg);
208 }
209
210 guint32
211 mono_alloc_lreg (MonoCompile *cfg)
212 {
213         return alloc_lreg (cfg);
214 }
215
216 guint32
217 mono_alloc_freg (MonoCompile *cfg)
218 {
219         return alloc_freg (cfg);
220 }
221
222 guint32
223 mono_alloc_preg (MonoCompile *cfg)
224 {
225         return alloc_preg (cfg);
226 }
227
228 guint32
229 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
230 {
231         return alloc_dreg (cfg, stack_type);
232 }
233
234 /*
235  * mono_alloc_ireg_ref:
236  *
237  *   Allocate an IREG, and mark it as holding a GC ref.
238  */
239 guint32
240 mono_alloc_ireg_ref (MonoCompile *cfg)
241 {
242         return alloc_ireg_ref (cfg);
243 }
244
245 /*
246  * mono_alloc_ireg_mp:
247  *
248  *   Allocate an IREG, and mark it as holding a managed pointer.
249  */
250 guint32
251 mono_alloc_ireg_mp (MonoCompile *cfg)
252 {
253         return alloc_ireg_mp (cfg);
254 }
255
256 /*
257  * mono_alloc_ireg_copy:
258  *
259  *   Allocate an IREG with the same GC type as VREG.
260  */
261 guint32
262 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
263 {
264         if (vreg_is_ref (cfg, vreg))
265                 return alloc_ireg_ref (cfg);
266         else if (vreg_is_mp (cfg, vreg))
267                 return alloc_ireg_mp (cfg);
268         else
269                 return alloc_ireg (cfg);
270 }
271
272 guint
273 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
274 {
275         if (type->byref)
276                 return OP_MOVE;
277
278         type = mini_get_underlying_type (type);
279 handle_enum:
280         switch (type->type) {
281         case MONO_TYPE_I1:
282         case MONO_TYPE_U1:
283                 return OP_MOVE;
284         case MONO_TYPE_I2:
285         case MONO_TYPE_U2:
286                 return OP_MOVE;
287         case MONO_TYPE_I4:
288         case MONO_TYPE_U4:
289                 return OP_MOVE;
290         case MONO_TYPE_I:
291         case MONO_TYPE_U:
292         case MONO_TYPE_PTR:
293         case MONO_TYPE_FNPTR:
294                 return OP_MOVE;
295         case MONO_TYPE_CLASS:
296         case MONO_TYPE_STRING:
297         case MONO_TYPE_OBJECT:
298         case MONO_TYPE_SZARRAY:
299         case MONO_TYPE_ARRAY:    
300                 return OP_MOVE;
301         case MONO_TYPE_I8:
302         case MONO_TYPE_U8:
303 #if SIZEOF_REGISTER == 8
304                 return OP_MOVE;
305 #else
306                 return OP_LMOVE;
307 #endif
308         case MONO_TYPE_R4:
309                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
310         case MONO_TYPE_R8:
311                 return OP_FMOVE;
312         case MONO_TYPE_VALUETYPE:
313                 if (type->data.klass->enumtype) {
314                         type = mono_class_enum_basetype (type->data.klass);
315                         goto handle_enum;
316                 }
317                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
318                         return OP_XMOVE;
319                 return OP_VMOVE;
320         case MONO_TYPE_TYPEDBYREF:
321                 return OP_VMOVE;
322         case MONO_TYPE_GENERICINST:
323                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
324                         return OP_XMOVE;
325                 type = &type->data.generic_class->container_class->byval_arg;
326                 goto handle_enum;
327         case MONO_TYPE_VAR:
328         case MONO_TYPE_MVAR:
329                 g_assert (cfg->gshared);
330                 if (mini_type_var_is_vt (type))
331                         return OP_VMOVE;
332                 else
333                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
334         default:
335                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
336         }
337         return -1;
338 }
339
340 void
341 mono_print_bb (MonoBasicBlock *bb, const char *msg)
342 {
343         int i;
344         MonoInst *tree;
345         GString *str = g_string_new ("");
346
347         g_string_append_printf (str, "%s %d: [IN: ", msg, bb->block_num);
348         for (i = 0; i < bb->in_count; ++i)
349                 g_string_append_printf (str, " BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
350         g_string_append_printf (str, ", OUT: ");
351         for (i = 0; i < bb->out_count; ++i)
352                 g_string_append_printf (str, " BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
353         g_string_append_printf (str, " ]\n");
354
355         g_print ("%s", str->str);
356         g_string_free (str, TRUE);
357
358         for (tree = bb->code; tree; tree = tree->next)
359                 mono_print_ins_index (-1, tree);
360 }
361
362 void
363 mono_create_helper_signatures (void)
364 {
365         helper_sig_domain_get = mono_create_icall_signature ("ptr");
366         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
367         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
368         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
369         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
370         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
371 }
372
373 static MONO_NEVER_INLINE void
374 break_on_unverified (void)
375 {
376         if (mini_get_debug_options ()->break_on_unverified)
377                 G_BREAKPOINT ();
378 }
379
380 static MONO_NEVER_INLINE void
381 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
382 {
383         char *method_fname = mono_method_full_name (method, TRUE);
384         char *field_fname = mono_field_full_name (field);
385         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
386         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
387         g_free (method_fname);
388         g_free (field_fname);
389 }
390
391 static MONO_NEVER_INLINE void
392 inline_failure (MonoCompile *cfg, const char *msg)
393 {
394         if (cfg->verbose_level >= 2)
395                 printf ("inline failed: %s\n", msg);
396         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
397 }
398
399 static MONO_NEVER_INLINE void
400 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
401 {
402         if (cfg->verbose_level > 2)                                                                                     \
403                 printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), line);
404         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
405 }
406
407 static MONO_NEVER_INLINE void
408 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
409 {
410         cfg->exception_message = g_strdup_printf ("gsharedvt failed for method %s.%s.%s/%d opcode %s %s:%d", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), file, line);
411         if (cfg->verbose_level >= 2)
412                 printf ("%s\n", cfg->exception_message);
413         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
414 }
415
416 /*
417  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
418  * foo<T> (int i) { ldarg.0; box T; }
419  */
420 #define UNVERIFIED do { \
421         if (cfg->gsharedvt) { \
422                 if (cfg->verbose_level > 2)                                                                     \
423                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
424                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
425                 goto exception_exit;                                                                                    \
426         }                                                                                                                                       \
427         break_on_unverified ();                                                                                         \
428         goto unverified;                                                                                                        \
429 } while (0)
430
431 #define GET_BBLOCK(cfg,tblock,ip) do {  \
432                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
433                 if (!(tblock)) {        \
434                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
435             NEW_BBLOCK (cfg, (tblock)); \
436                         (tblock)->cil_code = (ip);      \
437                         ADD_BBLOCK (cfg, (tblock));     \
438                 } \
439         } while (0)
440
441 #if defined(TARGET_X86) || defined(TARGET_AMD64)
442 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
443                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
444                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
445                 (dest)->sreg1 = (sr1); \
446                 (dest)->sreg2 = (sr2); \
447                 (dest)->inst_imm = (imm); \
448                 (dest)->backend.shift_amount = (shift); \
449                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
450         } while (0)
451 #endif
452
453 /* Emit conversions so both operands of a binary opcode are of the same type */
454 static void
455 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
456 {
457         MonoInst *arg1 = *arg1_ref;
458         MonoInst *arg2 = *arg2_ref;
459
460         if (cfg->r4fp &&
461                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
462                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
463                 MonoInst *conv;
464
465                 /* Mixing r4/r8 is allowed by the spec */
466                 if (arg1->type == STACK_R4) {
467                         int dreg = alloc_freg (cfg);
468
469                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
470                         conv->type = STACK_R8;
471                         ins->sreg1 = dreg;
472                         *arg1_ref = conv;
473                 }
474                 if (arg2->type == STACK_R4) {
475                         int dreg = alloc_freg (cfg);
476
477                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
478                         conv->type = STACK_R8;
479                         ins->sreg2 = dreg;
480                         *arg2_ref = conv;
481                 }
482         }
483
484 #if SIZEOF_REGISTER == 8
485         /* FIXME: Need to add many more cases */
486         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
487                 MonoInst *widen;
488
489                 int dr = alloc_preg (cfg);
490                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
491                 (ins)->sreg2 = widen->dreg;
492         }
493 #endif
494 }
495
496 #define ADD_BINOP(op) do {      \
497                 MONO_INST_NEW (cfg, ins, (op)); \
498                 sp -= 2;        \
499                 ins->sreg1 = sp [0]->dreg;      \
500                 ins->sreg2 = sp [1]->dreg;      \
501                 type_from_op (cfg, ins, sp [0], sp [1]);        \
502                 CHECK_TYPE (ins);       \
503                 /* Have to insert a widening op */               \
504         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
505         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
506         MONO_ADD_INS ((cfg)->cbb, (ins)); \
507         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
508         } while (0)
509
510 #define ADD_UNOP(op) do {       \
511                 MONO_INST_NEW (cfg, ins, (op)); \
512                 sp--;   \
513                 ins->sreg1 = sp [0]->dreg;      \
514                 type_from_op (cfg, ins, sp [0], NULL);  \
515                 CHECK_TYPE (ins);       \
516         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
517         MONO_ADD_INS ((cfg)->cbb, (ins)); \
518                 *sp++ = mono_decompose_opcode (cfg, ins);       \
519         } while (0)
520
521 #define ADD_BINCOND(next_block) do {    \
522                 MonoInst *cmp;  \
523                 sp -= 2; \
524                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
525                 cmp->sreg1 = sp [0]->dreg;      \
526                 cmp->sreg2 = sp [1]->dreg;      \
527                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
528                 CHECK_TYPE (cmp);       \
529                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
530                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
531                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
532                 GET_BBLOCK (cfg, tblock, target);               \
533                 link_bblock (cfg, cfg->cbb, tblock);    \
534                 ins->inst_true_bb = tblock;     \
535                 if ((next_block)) {     \
536                         link_bblock (cfg, cfg->cbb, (next_block));      \
537                         ins->inst_false_bb = (next_block);      \
538                         start_new_bblock = 1;   \
539                 } else {        \
540                         GET_BBLOCK (cfg, tblock, ip);           \
541                         link_bblock (cfg, cfg->cbb, tblock);    \
542                         ins->inst_false_bb = tblock;    \
543                         start_new_bblock = 2;   \
544                 }       \
545                 if (sp != stack_start) {                                                                        \
546                     handle_stack_args (cfg, stack_start, sp - stack_start); \
547                         CHECK_UNVERIFIABLE (cfg); \
548                 } \
549         MONO_ADD_INS (cfg->cbb, cmp); \
550                 MONO_ADD_INS (cfg->cbb, ins);   \
551         } while (0)
552
553 /* *
554  * link_bblock: Links two basic blocks
555  *
556  * links two basic blocks in the control flow graph, the 'from'
557  * argument is the starting block and the 'to' argument is the block
558  * the control flow ends to after 'from'.
559  */
560 static void
561 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
562 {
563         MonoBasicBlock **newa;
564         int i, found;
565
566 #if 0
567         if (from->cil_code) {
568                 if (to->cil_code)
569                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
570                 else
571                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
572         } else {
573                 if (to->cil_code)
574                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
575                 else
576                         printf ("edge from entry to exit\n");
577         }
578 #endif
579
580         found = FALSE;
581         for (i = 0; i < from->out_count; ++i) {
582                 if (to == from->out_bb [i]) {
583                         found = TRUE;
584                         break;
585                 }
586         }
587         if (!found) {
588                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
589                 for (i = 0; i < from->out_count; ++i) {
590                         newa [i] = from->out_bb [i];
591                 }
592                 newa [i] = to;
593                 from->out_count++;
594                 from->out_bb = newa;
595         }
596
597         found = FALSE;
598         for (i = 0; i < to->in_count; ++i) {
599                 if (from == to->in_bb [i]) {
600                         found = TRUE;
601                         break;
602                 }
603         }
604         if (!found) {
605                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
606                 for (i = 0; i < to->in_count; ++i) {
607                         newa [i] = to->in_bb [i];
608                 }
609                 newa [i] = from;
610                 to->in_count++;
611                 to->in_bb = newa;
612         }
613 }
614
615 void
616 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
617 {
618         link_bblock (cfg, from, to);
619 }
620
621 /**
622  * mono_find_block_region:
623  *
624  *   We mark each basic block with a region ID. We use that to avoid BB
625  *   optimizations when blocks are in different regions.
626  *
627  * Returns:
628  *   A region token that encodes where this region is, and information
629  *   about the clause owner for this block.
630  *
631  *   The region encodes the try/catch/filter clause that owns this block
632  *   as well as the type.  -1 is a special value that represents a block
633  *   that is in none of try/catch/filter.
634  */
635 static int
636 mono_find_block_region (MonoCompile *cfg, int offset)
637 {
638         MonoMethodHeader *header = cfg->header;
639         MonoExceptionClause *clause;
640         int i;
641
642         for (i = 0; i < header->num_clauses; ++i) {
643                 clause = &header->clauses [i];
644                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
645                     (offset < (clause->handler_offset)))
646                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
647                            
648                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
649                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
650                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
651                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
652                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
653                         else
654                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
655                 }
656         }
657         for (i = 0; i < header->num_clauses; ++i) {
658                 clause = &header->clauses [i];
659
660                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
661                         return ((i + 1) << 8) | clause->flags;
662         }
663
664         return -1;
665 }
666
667 static gboolean
668 ip_in_finally_clause (MonoCompile *cfg, int offset)
669 {
670         MonoMethodHeader *header = cfg->header;
671         MonoExceptionClause *clause;
672         int i;
673
674         for (i = 0; i < header->num_clauses; ++i) {
675                 clause = &header->clauses [i];
676                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
677                         continue;
678
679                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
680                         return TRUE;
681         }
682         return FALSE;
683 }
684
685 static GList*
686 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
687 {
688         MonoMethodHeader *header = cfg->header;
689         MonoExceptionClause *clause;
690         int i;
691         GList *res = NULL;
692
693         for (i = 0; i < header->num_clauses; ++i) {
694                 clause = &header->clauses [i];
695                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
696                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
697                         if (clause->flags == type)
698                                 res = g_list_append (res, clause);
699                 }
700         }
701         return res;
702 }
703
704 static void
705 mono_create_spvar_for_region (MonoCompile *cfg, int region)
706 {
707         MonoInst *var;
708
709         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
710         if (var)
711                 return;
712
713         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
714         /* prevent it from being register allocated */
715         var->flags |= MONO_INST_VOLATILE;
716
717         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
718 }
719
720 MonoInst *
721 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
722 {
723         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
724 }
725
726 static MonoInst*
727 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
728 {
729         MonoInst *var;
730
731         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
732         if (var)
733                 return var;
734
735         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
736         /* prevent it from being register allocated */
737         var->flags |= MONO_INST_VOLATILE;
738
739         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
740
741         return var;
742 }
743
744 /*
745  * Returns the type used in the eval stack when @type is loaded.
746  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
747  */
748 void
749 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
750 {
751         MonoClass *klass;
752
753         type = mini_get_underlying_type (type);
754         inst->klass = klass = mono_class_from_mono_type (type);
755         if (type->byref) {
756                 inst->type = STACK_MP;
757                 return;
758         }
759
760 handle_enum:
761         switch (type->type) {
762         case MONO_TYPE_VOID:
763                 inst->type = STACK_INV;
764                 return;
765         case MONO_TYPE_I1:
766         case MONO_TYPE_U1:
767         case MONO_TYPE_I2:
768         case MONO_TYPE_U2:
769         case MONO_TYPE_I4:
770         case MONO_TYPE_U4:
771                 inst->type = STACK_I4;
772                 return;
773         case MONO_TYPE_I:
774         case MONO_TYPE_U:
775         case MONO_TYPE_PTR:
776         case MONO_TYPE_FNPTR:
777                 inst->type = STACK_PTR;
778                 return;
779         case MONO_TYPE_CLASS:
780         case MONO_TYPE_STRING:
781         case MONO_TYPE_OBJECT:
782         case MONO_TYPE_SZARRAY:
783         case MONO_TYPE_ARRAY:    
784                 inst->type = STACK_OBJ;
785                 return;
786         case MONO_TYPE_I8:
787         case MONO_TYPE_U8:
788                 inst->type = STACK_I8;
789                 return;
790         case MONO_TYPE_R4:
791                 inst->type = cfg->r4_stack_type;
792                 break;
793         case MONO_TYPE_R8:
794                 inst->type = STACK_R8;
795                 return;
796         case MONO_TYPE_VALUETYPE:
797                 if (type->data.klass->enumtype) {
798                         type = mono_class_enum_basetype (type->data.klass);
799                         goto handle_enum;
800                 } else {
801                         inst->klass = klass;
802                         inst->type = STACK_VTYPE;
803                         return;
804                 }
805         case MONO_TYPE_TYPEDBYREF:
806                 inst->klass = mono_defaults.typed_reference_class;
807                 inst->type = STACK_VTYPE;
808                 return;
809         case MONO_TYPE_GENERICINST:
810                 type = &type->data.generic_class->container_class->byval_arg;
811                 goto handle_enum;
812         case MONO_TYPE_VAR:
813         case MONO_TYPE_MVAR:
814                 g_assert (cfg->gshared);
815                 if (mini_is_gsharedvt_type (type)) {
816                         g_assert (cfg->gsharedvt);
817                         inst->type = STACK_VTYPE;
818                 } else {
819                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
820                 }
821                 return;
822         default:
823                 g_error ("unknown type 0x%02x in eval stack type", type->type);
824         }
825 }
826
827 /*
828  * The following tables are used to quickly validate the IL code in type_from_op ().
829  */
830 static const char
831 bin_num_table [STACK_MAX] [STACK_MAX] = {
832         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
834         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
835         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
836         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
837         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
838         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
839         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
840         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
841 };
842
843 static const char 
844 neg_table [] = {
845         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
846 };
847
848 /* reduce the size of this table */
849 static const char
850 bin_int_table [STACK_MAX] [STACK_MAX] = {
851         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
852         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
853         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
854         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
856         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
857         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
859 };
860
861 static const char
862 bin_comp_table [STACK_MAX] [STACK_MAX] = {
863 /*      Inv i  L  p  F  &  O  vt r4 */
864         {0},
865         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
866         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
867         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
868         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
869         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
870         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
871         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
872         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
873 };
874
875 /* reduce the size of this table */
876 static const char
877 shift_table [STACK_MAX] [STACK_MAX] = {
878         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
879         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
880         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
881         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
883         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
884         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
885         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
886 };
887
888 /*
889  * Tables to map from the non-specific opcode to the matching
890  * type-specific opcode.
891  */
892 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
893 static const guint16
894 binops_op_map [STACK_MAX] = {
895         0, OP_IADD-CEE_ADD, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD, 0, 0, OP_RADD-CEE_ADD
896 };
897
898 /* handles from CEE_NEG to CEE_CONV_U8 */
899 static const guint16
900 unops_op_map [STACK_MAX] = {
901         0, OP_INEG-CEE_NEG, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG, 0, 0, OP_RNEG-CEE_NEG
902 };
903
904 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
905 static const guint16
906 ovfops_op_map [STACK_MAX] = {
907         0, OP_ICONV_TO_U2-CEE_CONV_U2, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, 0, OP_RCONV_TO_U2-CEE_CONV_U2
908 };
909
910 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
911 static const guint16
912 ovf2ops_op_map [STACK_MAX] = {
913         0, OP_ICONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0, 0, OP_RCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
914 };
915
916 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
917 static const guint16
918 ovf3ops_op_map [STACK_MAX] = {
919         0, OP_ICONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0, 0, OP_RCONV_TO_OVF_I1-CEE_CONV_OVF_I1
920 };
921
922 /* handles from CEE_BEQ to CEE_BLT_UN */
923 static const guint16
924 beqops_op_map [STACK_MAX] = {
925         0, OP_IBEQ-CEE_BEQ, OP_LBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_FBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, 0, OP_FBEQ-CEE_BEQ
926 };
927
928 /* handles from CEE_CEQ to CEE_CLT_UN */
929 static const guint16
930 ceqops_op_map [STACK_MAX] = {
931         0, OP_ICEQ-OP_CEQ, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, 0, OP_RCEQ-OP_CEQ
932 };
933
934 /*
935  * Sets ins->type (the type on the eval stack) according to the
936  * type of the opcode and the arguments to it.
937  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
938  *
939  * FIXME: this function sets ins->type unconditionally in some cases, but
940  * it should set it to invalid for some types (a conv.x on an object)
941  */
942 static void
943 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
944 {
945         switch (ins->opcode) {
946         /* binops */
947         case CEE_ADD:
948         case CEE_SUB:
949         case CEE_MUL:
950         case CEE_DIV:
951         case CEE_REM:
952                 /* FIXME: check unverifiable args for STACK_MP */
953                 ins->type = bin_num_table [src1->type] [src2->type];
954                 ins->opcode += binops_op_map [ins->type];
955                 break;
956         case CEE_DIV_UN:
957         case CEE_REM_UN:
958         case CEE_AND:
959         case CEE_OR:
960         case CEE_XOR:
961                 ins->type = bin_int_table [src1->type] [src2->type];
962                 ins->opcode += binops_op_map [ins->type];
963                 break;
964         case CEE_SHL:
965         case CEE_SHR:
966         case CEE_SHR_UN:
967                 ins->type = shift_table [src1->type] [src2->type];
968                 ins->opcode += binops_op_map [ins->type];
969                 break;
970         case OP_COMPARE:
971         case OP_LCOMPARE:
972         case OP_ICOMPARE:
973                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
974                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
975                         ins->opcode = OP_LCOMPARE;
976                 else if (src1->type == STACK_R4)
977                         ins->opcode = OP_RCOMPARE;
978                 else if (src1->type == STACK_R8)
979                         ins->opcode = OP_FCOMPARE;
980                 else
981                         ins->opcode = OP_ICOMPARE;
982                 break;
983         case OP_ICOMPARE_IMM:
984                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
985                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
986                         ins->opcode = OP_LCOMPARE_IMM;          
987                 break;
988         case CEE_BEQ:
989         case CEE_BGE:
990         case CEE_BGT:
991         case CEE_BLE:
992         case CEE_BLT:
993         case CEE_BNE_UN:
994         case CEE_BGE_UN:
995         case CEE_BGT_UN:
996         case CEE_BLE_UN:
997         case CEE_BLT_UN:
998                 ins->opcode += beqops_op_map [src1->type];
999                 break;
1000         case OP_CEQ:
1001                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1002                 ins->opcode += ceqops_op_map [src1->type];
1003                 break;
1004         case OP_CGT:
1005         case OP_CGT_UN:
1006         case OP_CLT:
1007         case OP_CLT_UN:
1008                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1009                 ins->opcode += ceqops_op_map [src1->type];
1010                 break;
1011         /* unops */
1012         case CEE_NEG:
1013                 ins->type = neg_table [src1->type];
1014                 ins->opcode += unops_op_map [ins->type];
1015                 break;
1016         case CEE_NOT:
1017                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1018                         ins->type = src1->type;
1019                 else
1020                         ins->type = STACK_INV;
1021                 ins->opcode += unops_op_map [ins->type];
1022                 break;
1023         case CEE_CONV_I1:
1024         case CEE_CONV_I2:
1025         case CEE_CONV_I4:
1026         case CEE_CONV_U4:
1027                 ins->type = STACK_I4;
1028                 ins->opcode += unops_op_map [src1->type];
1029                 break;
1030         case CEE_CONV_R_UN:
1031                 ins->type = STACK_R8;
1032                 switch (src1->type) {
1033                 case STACK_I4:
1034                 case STACK_PTR:
1035                         ins->opcode = OP_ICONV_TO_R_UN;
1036                         break;
1037                 case STACK_I8:
1038                         ins->opcode = OP_LCONV_TO_R_UN; 
1039                         break;
1040                 }
1041                 break;
1042         case CEE_CONV_OVF_I1:
1043         case CEE_CONV_OVF_U1:
1044         case CEE_CONV_OVF_I2:
1045         case CEE_CONV_OVF_U2:
1046         case CEE_CONV_OVF_I4:
1047         case CEE_CONV_OVF_U4:
1048                 ins->type = STACK_I4;
1049                 ins->opcode += ovf3ops_op_map [src1->type];
1050                 break;
1051         case CEE_CONV_OVF_I_UN:
1052         case CEE_CONV_OVF_U_UN:
1053                 ins->type = STACK_PTR;
1054                 ins->opcode += ovf2ops_op_map [src1->type];
1055                 break;
1056         case CEE_CONV_OVF_I1_UN:
1057         case CEE_CONV_OVF_I2_UN:
1058         case CEE_CONV_OVF_I4_UN:
1059         case CEE_CONV_OVF_U1_UN:
1060         case CEE_CONV_OVF_U2_UN:
1061         case CEE_CONV_OVF_U4_UN:
1062                 ins->type = STACK_I4;
1063                 ins->opcode += ovf2ops_op_map [src1->type];
1064                 break;
1065         case CEE_CONV_U:
1066                 ins->type = STACK_PTR;
1067                 switch (src1->type) {
1068                 case STACK_I4:
1069                         ins->opcode = OP_ICONV_TO_U;
1070                         break;
1071                 case STACK_PTR:
1072                 case STACK_MP:
1073 #if SIZEOF_VOID_P == 8
1074                         ins->opcode = OP_LCONV_TO_U;
1075 #else
1076                         ins->opcode = OP_MOVE;
1077 #endif
1078                         break;
1079                 case STACK_I8:
1080                         ins->opcode = OP_LCONV_TO_U;
1081                         break;
1082                 case STACK_R8:
1083                         ins->opcode = OP_FCONV_TO_U;
1084                         break;
1085                 }
1086                 break;
1087         case CEE_CONV_I8:
1088         case CEE_CONV_U8:
1089                 ins->type = STACK_I8;
1090                 ins->opcode += unops_op_map [src1->type];
1091                 break;
1092         case CEE_CONV_OVF_I8:
1093         case CEE_CONV_OVF_U8:
1094                 ins->type = STACK_I8;
1095                 ins->opcode += ovf3ops_op_map [src1->type];
1096                 break;
1097         case CEE_CONV_OVF_U8_UN:
1098         case CEE_CONV_OVF_I8_UN:
1099                 ins->type = STACK_I8;
1100                 ins->opcode += ovf2ops_op_map [src1->type];
1101                 break;
1102         case CEE_CONV_R4:
1103                 ins->type = cfg->r4_stack_type;
1104                 ins->opcode += unops_op_map [src1->type];
1105                 break;
1106         case CEE_CONV_R8:
1107                 ins->type = STACK_R8;
1108                 ins->opcode += unops_op_map [src1->type];
1109                 break;
1110         case OP_CKFINITE:
1111                 ins->type = STACK_R8;           
1112                 break;
1113         case CEE_CONV_U2:
1114         case CEE_CONV_U1:
1115                 ins->type = STACK_I4;
1116                 ins->opcode += ovfops_op_map [src1->type];
1117                 break;
1118         case CEE_CONV_I:
1119         case CEE_CONV_OVF_I:
1120         case CEE_CONV_OVF_U:
1121                 ins->type = STACK_PTR;
1122                 ins->opcode += ovfops_op_map [src1->type];
1123                 break;
1124         case CEE_ADD_OVF:
1125         case CEE_ADD_OVF_UN:
1126         case CEE_MUL_OVF:
1127         case CEE_MUL_OVF_UN:
1128         case CEE_SUB_OVF:
1129         case CEE_SUB_OVF_UN:
1130                 ins->type = bin_num_table [src1->type] [src2->type];
1131                 ins->opcode += ovfops_op_map [src1->type];
1132                 if (ins->type == STACK_R8)
1133                         ins->type = STACK_INV;
1134                 break;
1135         case OP_LOAD_MEMBASE:
1136                 ins->type = STACK_PTR;
1137                 break;
1138         case OP_LOADI1_MEMBASE:
1139         case OP_LOADU1_MEMBASE:
1140         case OP_LOADI2_MEMBASE:
1141         case OP_LOADU2_MEMBASE:
1142         case OP_LOADI4_MEMBASE:
1143         case OP_LOADU4_MEMBASE:
1144                 ins->type = STACK_PTR;
1145                 break;
1146         case OP_LOADI8_MEMBASE:
1147                 ins->type = STACK_I8;
1148                 break;
1149         case OP_LOADR4_MEMBASE:
1150                 ins->type = cfg->r4_stack_type;
1151                 break;
1152         case OP_LOADR8_MEMBASE:
1153                 ins->type = STACK_R8;
1154                 break;
1155         default:
1156                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1157                 break;
1158         }
1159
1160         if (ins->type == STACK_MP)
1161                 ins->klass = mono_defaults.object_class;
1162 }
1163
1164 static MonoClass*
1165 ldind_to_type (int op)
1166 {
1167         switch (op) {
1168         case CEE_LDIND_I1: return mono_defaults.sbyte_class;
1169         case CEE_LDIND_U1: return mono_defaults.byte_class;
1170         case CEE_LDIND_I2: return mono_defaults.int16_class;
1171         case CEE_LDIND_U2: return mono_defaults.uint16_class;
1172         case CEE_LDIND_I4: return mono_defaults.int32_class;
1173         case CEE_LDIND_U4: return mono_defaults.uint32_class;
1174         case CEE_LDIND_I8: return mono_defaults.int64_class;
1175         case CEE_LDIND_I: return mono_defaults.int_class;
1176         case CEE_LDIND_R4: return mono_defaults.single_class;
1177         case CEE_LDIND_R8: return mono_defaults.double_class;
1178         case CEE_LDIND_REF:return mono_defaults.object_class; //FIXME we should try to return a more specific type
1179         default: g_error ("Unknown ldind type %d", op);
1180         }
1181 }
1182
1183 #if 0
1184
1185 static const char
1186 param_table [STACK_MAX] [STACK_MAX] = {
1187         {0},
1188 };
1189
1190 static int
1191 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1192 {
1193         int i;
1194
1195         if (sig->hasthis) {
1196                 switch (args->type) {
1197                 case STACK_I4:
1198                 case STACK_I8:
1199                 case STACK_R8:
1200                 case STACK_VTYPE:
1201                 case STACK_INV:
1202                         return 0;
1203                 }
1204                 args++;
1205         }
1206         for (i = 0; i < sig->param_count; ++i) {
1207                 switch (args [i].type) {
1208                 case STACK_INV:
1209                         return 0;
1210                 case STACK_MP:
1211                         if (!sig->params [i]->byref)
1212                                 return 0;
1213                         continue;
1214                 case STACK_OBJ:
1215                         if (sig->params [i]->byref)
1216                                 return 0;
1217                         switch (sig->params [i]->type) {
1218                         case MONO_TYPE_CLASS:
1219                         case MONO_TYPE_STRING:
1220                         case MONO_TYPE_OBJECT:
1221                         case MONO_TYPE_SZARRAY:
1222                         case MONO_TYPE_ARRAY:
1223                                 break;
1224                         default:
1225                                 return 0;
1226                         }
1227                         continue;
1228                 case STACK_R8:
1229                         if (sig->params [i]->byref)
1230                                 return 0;
1231                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1232                                 return 0;
1233                         continue;
1234                 case STACK_PTR:
1235                 case STACK_I4:
1236                 case STACK_I8:
1237                 case STACK_VTYPE:
1238                         break;
1239                 }
1240                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1241                         return 0;*/
1242         }
1243         return 1;
1244 }
1245 #endif
1246
1247 /*
1248  * When we need a pointer to the current domain many times in a method, we
1249  * call mono_domain_get() once and we store the result in a local variable.
1250  * This function returns the variable that represents the MonoDomain*.
1251  */
1252 inline static MonoInst *
1253 mono_get_domainvar (MonoCompile *cfg)
1254 {
1255         if (!cfg->domainvar)
1256                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1257         return cfg->domainvar;
1258 }
1259
1260 /*
1261  * The got_var contains the address of the Global Offset Table when AOT 
1262  * compiling.
1263  */
1264 MonoInst *
1265 mono_get_got_var (MonoCompile *cfg)
1266 {
1267         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1268                 return NULL;
1269         if (!cfg->got_var) {
1270                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1271         }
1272         return cfg->got_var;
1273 }
1274
1275 static void
1276 mono_create_rgctx_var (MonoCompile *cfg)
1277 {
1278         if (!cfg->rgctx_var) {
1279                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1280                 /* force the var to be stack allocated */
1281                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1282         }
1283 }
1284
1285 static MonoInst *
1286 mono_get_vtable_var (MonoCompile *cfg)
1287 {
1288         g_assert (cfg->gshared);
1289
1290         mono_create_rgctx_var (cfg);
1291
1292         return cfg->rgctx_var;
1293 }
1294
1295 static MonoType*
1296 type_from_stack_type (MonoInst *ins) {
1297         switch (ins->type) {
1298         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1299         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1300         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1301         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1302         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1303         case STACK_MP:
1304                 return &ins->klass->this_arg;
1305         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1306         case STACK_VTYPE: return &ins->klass->byval_arg;
1307         default:
1308                 g_error ("stack type %d to monotype not handled\n", ins->type);
1309         }
1310         return NULL;
1311 }
1312
1313 static G_GNUC_UNUSED int
1314 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1315 {
1316         t = mono_type_get_underlying_type (t);
1317         switch (t->type) {
1318         case MONO_TYPE_I1:
1319         case MONO_TYPE_U1:
1320         case MONO_TYPE_I2:
1321         case MONO_TYPE_U2:
1322         case MONO_TYPE_I4:
1323         case MONO_TYPE_U4:
1324                 return STACK_I4;
1325         case MONO_TYPE_I:
1326         case MONO_TYPE_U:
1327         case MONO_TYPE_PTR:
1328         case MONO_TYPE_FNPTR:
1329                 return STACK_PTR;
1330         case MONO_TYPE_CLASS:
1331         case MONO_TYPE_STRING:
1332         case MONO_TYPE_OBJECT:
1333         case MONO_TYPE_SZARRAY:
1334         case MONO_TYPE_ARRAY:    
1335                 return STACK_OBJ;
1336         case MONO_TYPE_I8:
1337         case MONO_TYPE_U8:
1338                 return STACK_I8;
1339         case MONO_TYPE_R4:
1340                 return cfg->r4_stack_type;
1341         case MONO_TYPE_R8:
1342                 return STACK_R8;
1343         case MONO_TYPE_VALUETYPE:
1344         case MONO_TYPE_TYPEDBYREF:
1345                 return STACK_VTYPE;
1346         case MONO_TYPE_GENERICINST:
1347                 if (mono_type_generic_inst_is_valuetype (t))
1348                         return STACK_VTYPE;
1349                 else
1350                         return STACK_OBJ;
1351                 break;
1352         default:
1353                 g_assert_not_reached ();
1354         }
1355
1356         return -1;
1357 }
1358
1359 static MonoClass*
1360 array_access_to_klass (int opcode)
1361 {
1362         switch (opcode) {
1363         case CEE_LDELEM_U1:
1364                 return mono_defaults.byte_class;
1365         case CEE_LDELEM_U2:
1366                 return mono_defaults.uint16_class;
1367         case CEE_LDELEM_I:
1368         case CEE_STELEM_I:
1369                 return mono_defaults.int_class;
1370         case CEE_LDELEM_I1:
1371         case CEE_STELEM_I1:
1372                 return mono_defaults.sbyte_class;
1373         case CEE_LDELEM_I2:
1374         case CEE_STELEM_I2:
1375                 return mono_defaults.int16_class;
1376         case CEE_LDELEM_I4:
1377         case CEE_STELEM_I4:
1378                 return mono_defaults.int32_class;
1379         case CEE_LDELEM_U4:
1380                 return mono_defaults.uint32_class;
1381         case CEE_LDELEM_I8:
1382         case CEE_STELEM_I8:
1383                 return mono_defaults.int64_class;
1384         case CEE_LDELEM_R4:
1385         case CEE_STELEM_R4:
1386                 return mono_defaults.single_class;
1387         case CEE_LDELEM_R8:
1388         case CEE_STELEM_R8:
1389                 return mono_defaults.double_class;
1390         case CEE_LDELEM_REF:
1391         case CEE_STELEM_REF:
1392                 return mono_defaults.object_class;
1393         default:
1394                 g_assert_not_reached ();
1395         }
1396         return NULL;
1397 }
1398
1399 /*
1400  * We try to share variables when possible
1401  */
1402 static MonoInst *
1403 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1404 {
1405         MonoInst *res;
1406         int pos, vnum;
1407
1408         /* inlining can result in deeper stacks */ 
1409         if (slot >= cfg->header->max_stack)
1410                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1411
1412         pos = ins->type - 1 + slot * STACK_MAX;
1413
1414         switch (ins->type) {
1415         case STACK_I4:
1416         case STACK_I8:
1417         case STACK_R8:
1418         case STACK_PTR:
1419         case STACK_MP:
1420         case STACK_OBJ:
1421                 if ((vnum = cfg->intvars [pos]))
1422                         return cfg->varinfo [vnum];
1423                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1424                 cfg->intvars [pos] = res->inst_c0;
1425                 break;
1426         default:
1427                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1428         }
1429         return res;
1430 }
1431
1432 static void
1433 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1434 {
1435         /* 
1436          * Don't use this if a generic_context is set, since that means AOT can't
1437          * look up the method using just the image+token.
1438          * table == 0 means this is a reference made from a wrapper.
1439          */
1440         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1441                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1442                 jump_info_token->image = image;
1443                 jump_info_token->token = token;
1444                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1445         }
1446 }
1447
1448 /*
1449  * This function is called to handle items that are left on the evaluation stack
1450  * at basic block boundaries. What happens is that we save the values to local variables
1451  * and we reload them later when first entering the target basic block (with the
1452  * handle_loaded_temps () function).
1453  * A single joint point will use the same variables (stored in the array bb->out_stack or
1454  * bb->in_stack, if the basic block is before or after the joint point).
1455  *
1456  * This function needs to be called _before_ emitting the last instruction of
1457  * the bb (i.e. before emitting a branch).
1458  * If the stack merge fails at a join point, cfg->unverifiable is set.
1459  */
1460 static void
1461 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1462 {
1463         int i, bindex;
1464         MonoBasicBlock *bb = cfg->cbb;
1465         MonoBasicBlock *outb;
1466         MonoInst *inst, **locals;
1467         gboolean found;
1468
1469         if (!count)
1470                 return;
1471         if (cfg->verbose_level > 3)
1472                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1473         if (!bb->out_scount) {
1474                 bb->out_scount = count;
1475                 //printf ("bblock %d has out:", bb->block_num);
1476                 found = FALSE;
1477                 for (i = 0; i < bb->out_count; ++i) {
1478                         outb = bb->out_bb [i];
1479                         /* exception handlers are linked, but they should not be considered for stack args */
1480                         if (outb->flags & BB_EXCEPTION_HANDLER)
1481                                 continue;
1482                         //printf (" %d", outb->block_num);
1483                         if (outb->in_stack) {
1484                                 found = TRUE;
1485                                 bb->out_stack = outb->in_stack;
1486                                 break;
1487                         }
1488                 }
1489                 //printf ("\n");
1490                 if (!found) {
1491                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1492                         for (i = 0; i < count; ++i) {
1493                                 /* 
1494                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1495                                  * stack slot and if they are of the same type.
1496                                  * This won't cause conflicts since if 'local' is used to 
1497                                  * store one of the values in the in_stack of a bblock, then
1498                                  * the same variable will be used for the same outgoing stack 
1499                                  * slot as well. 
1500                                  * This doesn't work when inlining methods, since the bblocks
1501                                  * in the inlined methods do not inherit their in_stack from
1502                                  * the bblock they are inlined to. See bug #58863 for an
1503                                  * example.
1504                                  */
1505                                 if (cfg->inlined_method)
1506                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1507                                 else
1508                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1509                         }
1510                 }
1511         }
1512
1513         for (i = 0; i < bb->out_count; ++i) {
1514                 outb = bb->out_bb [i];
1515                 /* exception handlers are linked, but they should not be considered for stack args */
1516                 if (outb->flags & BB_EXCEPTION_HANDLER)
1517                         continue;
1518                 if (outb->in_scount) {
1519                         if (outb->in_scount != bb->out_scount) {
1520                                 cfg->unverifiable = TRUE;
1521                                 return;
1522                         }
1523                         continue; /* check they are the same locals */
1524                 }
1525                 outb->in_scount = count;
1526                 outb->in_stack = bb->out_stack;
1527         }
1528
1529         locals = bb->out_stack;
1530         cfg->cbb = bb;
1531         for (i = 0; i < count; ++i) {
1532                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1533                 inst->cil_code = sp [i]->cil_code;
1534                 sp [i] = locals [i];
1535                 if (cfg->verbose_level > 3)
1536                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1537         }
1538
1539         /*
1540          * It is possible that the out bblocks already have in_stack assigned, and
1541          * the in_stacks differ. In this case, we will store to all the different 
1542          * in_stacks.
1543          */
1544
1545         found = TRUE;
1546         bindex = 0;
1547         while (found) {
1548                 /* Find a bblock which has a different in_stack */
1549                 found = FALSE;
1550                 while (bindex < bb->out_count) {
1551                         outb = bb->out_bb [bindex];
1552                         /* exception handlers are linked, but they should not be considered for stack args */
1553                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1554                                 bindex++;
1555                                 continue;
1556                         }
1557                         if (outb->in_stack != locals) {
1558                                 for (i = 0; i < count; ++i) {
1559                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1560                                         inst->cil_code = sp [i]->cil_code;
1561                                         sp [i] = locals [i];
1562                                         if (cfg->verbose_level > 3)
1563                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1564                                 }
1565                                 locals = outb->in_stack;
1566                                 found = TRUE;
1567                                 break;
1568                         }
1569                         bindex ++;
1570                 }
1571         }
1572 }
1573
1574 MonoInst*
1575 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1576 {
1577         MonoInst *ins;
1578
1579         if (cfg->compile_aot) {
1580                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1581         } else {
1582                 MonoJumpInfo ji;
1583                 gpointer target;
1584                 MonoError error;
1585
1586                 ji.type = patch_type;
1587                 ji.data.target = data;
1588                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1589                 mono_error_assert_ok (&error);
1590
1591                 EMIT_NEW_PCONST (cfg, ins, target);
1592         }
1593         return ins;
1594 }
1595
1596 static MonoInst*
1597 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1598 {
1599         int tls_offset = mono_tls_get_tls_offset (key);
1600
1601         if (cfg->compile_aot)
1602                 return NULL;
1603
1604         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1605                 MonoInst *ins;
1606                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1607                 ins->dreg = mono_alloc_preg (cfg);
1608                 ins->inst_offset = tls_offset;
1609                 return ins;
1610         }
1611         return NULL;
1612 }
1613
1614 static MonoInst*
1615 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1616 {
1617         int tls_offset = mono_tls_get_tls_offset (key);
1618
1619         if (cfg->compile_aot)
1620                 return NULL;
1621
1622         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1623                 MonoInst *ins;
1624                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1625                 ins->sreg1 = value->dreg;
1626                 ins->inst_offset = tls_offset;
1627                 return ins;
1628         }
1629         return NULL;
1630 }
1631
1632
1633 MonoInst*
1634 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1635 {
1636         MonoInst *fast_tls = NULL;
1637
1638         if (!mini_get_debug_options ()->use_fallback_tls)
1639                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1640
1641         if (fast_tls) {
1642                 MONO_ADD_INS (cfg->cbb, fast_tls);
1643                 return fast_tls;
1644         }
1645
1646         if (cfg->compile_aot) {
1647                 MonoInst *addr;
1648                 /*
1649                  * tls getters are critical pieces of code and we don't want to resolve them
1650                  * through the standard plt/tramp mechanism since we might expose ourselves
1651                  * to crashes and infinite recursions.
1652                  */
1653                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1654                 return mini_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1655         } else {
1656                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1657                 return mono_emit_jit_icall (cfg, getter, NULL);
1658         }
1659 }
1660
1661 static MonoInst*
1662 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1663 {
1664         MonoInst *fast_tls = NULL;
1665
1666         if (!mini_get_debug_options ()->use_fallback_tls)
1667                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1668
1669         if (fast_tls) {
1670                 MONO_ADD_INS (cfg->cbb, fast_tls);
1671                 return fast_tls;
1672         }
1673
1674         if (cfg->compile_aot) {
1675                 MonoInst *addr;
1676                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1677                 return mini_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1678         } else {
1679                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1680                 return mono_emit_jit_icall (cfg, setter, &value);
1681         }
1682 }
1683
1684 /*
1685  * emit_push_lmf:
1686  *
1687  *   Emit IR to push the current LMF onto the LMF stack.
1688  */
1689 static void
1690 emit_push_lmf (MonoCompile *cfg)
1691 {
1692         /*
1693          * Emit IR to push the LMF:
1694          * lmf_addr = <lmf_addr from tls>
1695          * lmf->lmf_addr = lmf_addr
1696          * lmf->prev_lmf = *lmf_addr
1697          * *lmf_addr = lmf
1698          */
1699         MonoInst *ins, *lmf_ins;
1700
1701         if (!cfg->lmf_ir)
1702                 return;
1703
1704         int lmf_reg, prev_lmf_reg;
1705         /*
1706          * Store lmf_addr in a variable, so it can be allocated to a global register.
1707          */
1708         if (!cfg->lmf_addr_var)
1709                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1710
1711 #ifdef HOST_WIN32
1712         ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1713         g_assert (ins);
1714         int jit_tls_dreg = ins->dreg;
1715
1716         lmf_reg = alloc_preg (cfg);
1717         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1718 #else
1719         lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1720         g_assert (lmf_ins);
1721 #endif
1722         lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1723
1724         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1725         lmf_reg = ins->dreg;
1726
1727         prev_lmf_reg = alloc_preg (cfg);
1728         /* Save previous_lmf */
1729         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1730         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1731         /* Set new lmf */
1732         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1733 }
1734
1735 /*
1736  * emit_pop_lmf:
1737  *
1738  *   Emit IR to pop the current LMF from the LMF stack.
1739  */
1740 static void
1741 emit_pop_lmf (MonoCompile *cfg)
1742 {
1743         int lmf_reg, lmf_addr_reg;
1744         MonoInst *ins;
1745
1746         if (!cfg->lmf_ir)
1747                 return;
1748
1749         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1750         lmf_reg = ins->dreg;
1751
1752         int prev_lmf_reg;
1753         /*
1754          * Emit IR to pop the LMF:
1755          * *(lmf->lmf_addr) = lmf->prev_lmf
1756          */
1757         /* This could be called before emit_push_lmf () */
1758         if (!cfg->lmf_addr_var)
1759                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1760         lmf_addr_reg = cfg->lmf_addr_var->dreg;
1761
1762         prev_lmf_reg = alloc_preg (cfg);
1763         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1764         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1765 }
1766
1767 static void
1768 emit_instrumentation_call (MonoCompile *cfg, void *func)
1769 {
1770         MonoInst *iargs [1];
1771
1772         /*
1773          * Avoid instrumenting inlined methods since it can
1774          * distort profiling results.
1775          */
1776         if (cfg->method != cfg->current_method)
1777                 return;
1778
1779         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1780                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1781                 mono_emit_jit_icall (cfg, func, iargs);
1782         }
1783 }
1784
1785 static int
1786 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1787 {
1788 handle_enum:
1789         type = mini_get_underlying_type (type);
1790         switch (type->type) {
1791         case MONO_TYPE_VOID:
1792                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1793         case MONO_TYPE_I1:
1794         case MONO_TYPE_U1:
1795         case MONO_TYPE_I2:
1796         case MONO_TYPE_U2:
1797         case MONO_TYPE_I4:
1798         case MONO_TYPE_U4:
1799                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1800         case MONO_TYPE_I:
1801         case MONO_TYPE_U:
1802         case MONO_TYPE_PTR:
1803         case MONO_TYPE_FNPTR:
1804                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1805         case MONO_TYPE_CLASS:
1806         case MONO_TYPE_STRING:
1807         case MONO_TYPE_OBJECT:
1808         case MONO_TYPE_SZARRAY:
1809         case MONO_TYPE_ARRAY:    
1810                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1811         case MONO_TYPE_I8:
1812         case MONO_TYPE_U8:
1813                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1814         case MONO_TYPE_R4:
1815                 if (cfg->r4fp)
1816                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1817                 else
1818                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1819         case MONO_TYPE_R8:
1820                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1821         case MONO_TYPE_VALUETYPE:
1822                 if (type->data.klass->enumtype) {
1823                         type = mono_class_enum_basetype (type->data.klass);
1824                         goto handle_enum;
1825                 } else
1826                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1827         case MONO_TYPE_TYPEDBYREF:
1828                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1829         case MONO_TYPE_GENERICINST:
1830                 type = &type->data.generic_class->container_class->byval_arg;
1831                 goto handle_enum;
1832         case MONO_TYPE_VAR:
1833         case MONO_TYPE_MVAR:
1834                 /* gsharedvt */
1835                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1836         default:
1837                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1838         }
1839         return -1;
1840 }
1841
1842 //XXX this ignores if t is byref
1843 #define MONO_TYPE_IS_PRIMITIVE_SCALAR(t) ((((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_U8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
1844
1845 /*
1846  * target_type_is_incompatible:
1847  * @cfg: MonoCompile context
1848  *
1849  * Check that the item @arg on the evaluation stack can be stored
1850  * in the target type (can be a local, or field, etc).
1851  * The cfg arg can be used to check if we need verification or just
1852  * validity checks.
1853  *
1854  * Returns: non-0 value if arg can't be stored on a target.
1855  */
1856 static int
1857 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1858 {
1859         MonoType *simple_type;
1860         MonoClass *klass;
1861
1862         if (target->byref) {
1863                 /* FIXME: check that the pointed to types match */
1864                 if (arg->type == STACK_MP) {
1865                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1866                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1867                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1868
1869                         /* if the target is native int& or same type */
1870                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
1871                                 return 0;
1872
1873                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
1874                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
1875                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
1876                                 return 0;
1877                         return 1;
1878                 }
1879                 if (arg->type == STACK_PTR)
1880                         return 0;
1881                 return 1;
1882         }
1883
1884         simple_type = mini_get_underlying_type (target);
1885         switch (simple_type->type) {
1886         case MONO_TYPE_VOID:
1887                 return 1;
1888         case MONO_TYPE_I1:
1889         case MONO_TYPE_U1:
1890         case MONO_TYPE_I2:
1891         case MONO_TYPE_U2:
1892         case MONO_TYPE_I4:
1893         case MONO_TYPE_U4:
1894                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
1895                         return 1;
1896                 return 0;
1897         case MONO_TYPE_PTR:
1898                 /* STACK_MP is needed when setting pinned locals */
1899                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1900                         return 1;
1901                 return 0;
1902         case MONO_TYPE_I:
1903         case MONO_TYPE_U:
1904         case MONO_TYPE_FNPTR:
1905                 /* 
1906                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
1907                  * in native int. (#688008).
1908                  */
1909                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1910                         return 1;
1911                 return 0;
1912         case MONO_TYPE_CLASS:
1913         case MONO_TYPE_STRING:
1914         case MONO_TYPE_OBJECT:
1915         case MONO_TYPE_SZARRAY:
1916         case MONO_TYPE_ARRAY:    
1917                 if (arg->type != STACK_OBJ)
1918                         return 1;
1919                 /* FIXME: check type compatibility */
1920                 return 0;
1921         case MONO_TYPE_I8:
1922         case MONO_TYPE_U8:
1923                 if (arg->type != STACK_I8)
1924                         return 1;
1925                 return 0;
1926         case MONO_TYPE_R4:
1927                 if (arg->type != cfg->r4_stack_type)
1928                         return 1;
1929                 return 0;
1930         case MONO_TYPE_R8:
1931                 if (arg->type != STACK_R8)
1932                         return 1;
1933                 return 0;
1934         case MONO_TYPE_VALUETYPE:
1935                 if (arg->type != STACK_VTYPE)
1936                         return 1;
1937                 klass = mono_class_from_mono_type (simple_type);
1938                 if (klass != arg->klass)
1939                         return 1;
1940                 return 0;
1941         case MONO_TYPE_TYPEDBYREF:
1942                 if (arg->type != STACK_VTYPE)
1943                         return 1;
1944                 klass = mono_class_from_mono_type (simple_type);
1945                 if (klass != arg->klass)
1946                         return 1;
1947                 return 0;
1948         case MONO_TYPE_GENERICINST:
1949                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
1950                         MonoClass *target_class;
1951                         if (arg->type != STACK_VTYPE)
1952                                 return 1;
1953                         klass = mono_class_from_mono_type (simple_type);
1954                         target_class = mono_class_from_mono_type (target);
1955                         /* The second cases is needed when doing partial sharing */
1956                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
1957                                 return 1;
1958                         return 0;
1959                 } else {
1960                         if (arg->type != STACK_OBJ)
1961                                 return 1;
1962                         /* FIXME: check type compatibility */
1963                         return 0;
1964                 }
1965         case MONO_TYPE_VAR:
1966         case MONO_TYPE_MVAR:
1967                 g_assert (cfg->gshared);
1968                 if (mini_type_var_is_vt (simple_type)) {
1969                         if (arg->type != STACK_VTYPE)
1970                                 return 1;
1971                 } else {
1972                         if (arg->type != STACK_OBJ)
1973                                 return 1;
1974                 }
1975                 return 0;
1976         default:
1977                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
1978         }
1979         return 1;
1980 }
1981
1982 /*
1983  * Prepare arguments for passing to a function call.
1984  * Return a non-zero value if the arguments can't be passed to the given
1985  * signature.
1986  * The type checks are not yet complete and some conversions may need
1987  * casts on 32 or 64 bit architectures.
1988  *
1989  * FIXME: implement this using target_type_is_incompatible ()
1990  */
1991 static int
1992 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
1993 {
1994         MonoType *simple_type;
1995         int i;
1996
1997         if (sig->hasthis) {
1998                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
1999                         return 1;
2000                 args++;
2001         }
2002         for (i = 0; i < sig->param_count; ++i) {
2003                 if (sig->params [i]->byref) {
2004                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2005                                 return 1;
2006                         continue;
2007                 }
2008                 simple_type = mini_get_underlying_type (sig->params [i]);
2009 handle_enum:
2010                 switch (simple_type->type) {
2011                 case MONO_TYPE_VOID:
2012                         return 1;
2013                         continue;
2014                 case MONO_TYPE_I1:
2015                 case MONO_TYPE_U1:
2016                 case MONO_TYPE_I2:
2017                 case MONO_TYPE_U2:
2018                 case MONO_TYPE_I4:
2019                 case MONO_TYPE_U4:
2020                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2021                                 return 1;
2022                         continue;
2023                 case MONO_TYPE_I:
2024                 case MONO_TYPE_U:
2025                 case MONO_TYPE_PTR:
2026                 case MONO_TYPE_FNPTR:
2027                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2028                                 return 1;
2029                         continue;
2030                 case MONO_TYPE_CLASS:
2031                 case MONO_TYPE_STRING:
2032                 case MONO_TYPE_OBJECT:
2033                 case MONO_TYPE_SZARRAY:
2034                 case MONO_TYPE_ARRAY:    
2035                         if (args [i]->type != STACK_OBJ)
2036                                 return 1;
2037                         continue;
2038                 case MONO_TYPE_I8:
2039                 case MONO_TYPE_U8:
2040                         if (args [i]->type != STACK_I8)
2041                                 return 1;
2042                         continue;
2043                 case MONO_TYPE_R4:
2044                         if (args [i]->type != cfg->r4_stack_type)
2045                                 return 1;
2046                         continue;
2047                 case MONO_TYPE_R8:
2048                         if (args [i]->type != STACK_R8)
2049                                 return 1;
2050                         continue;
2051                 case MONO_TYPE_VALUETYPE:
2052                         if (simple_type->data.klass->enumtype) {
2053                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2054                                 goto handle_enum;
2055                         }
2056                         if (args [i]->type != STACK_VTYPE)
2057                                 return 1;
2058                         continue;
2059                 case MONO_TYPE_TYPEDBYREF:
2060                         if (args [i]->type != STACK_VTYPE)
2061                                 return 1;
2062                         continue;
2063                 case MONO_TYPE_GENERICINST:
2064                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2065                         goto handle_enum;
2066                 case MONO_TYPE_VAR:
2067                 case MONO_TYPE_MVAR:
2068                         /* gsharedvt */
2069                         if (args [i]->type != STACK_VTYPE)
2070                                 return 1;
2071                         continue;
2072                 default:
2073                         g_error ("unknown type 0x%02x in check_call_signature",
2074                                  simple_type->type);
2075                 }
2076         }
2077         return 0;
2078 }
2079
2080 static int
2081 callvirt_to_call (int opcode)
2082 {
2083         switch (opcode) {
2084         case OP_CALL_MEMBASE:
2085                 return OP_CALL;
2086         case OP_VOIDCALL_MEMBASE:
2087                 return OP_VOIDCALL;
2088         case OP_FCALL_MEMBASE:
2089                 return OP_FCALL;
2090         case OP_RCALL_MEMBASE:
2091                 return OP_RCALL;
2092         case OP_VCALL_MEMBASE:
2093                 return OP_VCALL;
2094         case OP_LCALL_MEMBASE:
2095                 return OP_LCALL;
2096         default:
2097                 g_assert_not_reached ();
2098         }
2099
2100         return -1;
2101 }
2102
2103 static int
2104 callvirt_to_call_reg (int opcode)
2105 {
2106         switch (opcode) {
2107         case OP_CALL_MEMBASE:
2108                 return OP_CALL_REG;
2109         case OP_VOIDCALL_MEMBASE:
2110                 return OP_VOIDCALL_REG;
2111         case OP_FCALL_MEMBASE:
2112                 return OP_FCALL_REG;
2113         case OP_RCALL_MEMBASE:
2114                 return OP_RCALL_REG;
2115         case OP_VCALL_MEMBASE:
2116                 return OP_VCALL_REG;
2117         case OP_LCALL_MEMBASE:
2118                 return OP_LCALL_REG;
2119         default:
2120                 g_assert_not_reached ();
2121         }
2122
2123         return -1;
2124 }
2125
2126 /* Either METHOD or IMT_ARG needs to be set */
2127 static void
2128 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2129 {
2130         int method_reg;
2131
2132         if (COMPILE_LLVM (cfg)) {
2133                 if (imt_arg) {
2134                         method_reg = alloc_preg (cfg);
2135                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2136                 } else {
2137                         MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2138                         method_reg = ins->dreg;
2139                 }
2140
2141 #ifdef ENABLE_LLVM
2142                 call->imt_arg_reg = method_reg;
2143 #endif
2144                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2145                 return;
2146         }
2147
2148         if (imt_arg) {
2149                 method_reg = alloc_preg (cfg);
2150                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2151         } else {
2152                 MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2153                 method_reg = ins->dreg;
2154         }
2155
2156         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2157 }
2158
2159 static MonoJumpInfo *
2160 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2161 {
2162         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2163
2164         ji->ip.i = ip;
2165         ji->type = type;
2166         ji->data.target = target;
2167
2168         return ji;
2169 }
2170
2171 int
2172 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2173 {
2174         if (cfg->gshared)
2175                 return mono_class_check_context_used (klass);
2176         else
2177                 return 0;
2178 }
2179
2180 static int
2181 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2182 {
2183         if (cfg->gshared)
2184                 return mono_method_check_context_used (method);
2185         else
2186                 return 0;
2187 }
2188
2189 /*
2190  * check_method_sharing:
2191  *
2192  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2193  */
2194 static void
2195 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2196 {
2197         gboolean pass_vtable = FALSE;
2198         gboolean pass_mrgctx = FALSE;
2199
2200         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2201                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2202                 gboolean sharable = FALSE;
2203
2204                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2205                         sharable = TRUE;
2206
2207                 /*
2208                  * Pass vtable iff target method might
2209                  * be shared, which means that sharing
2210                  * is enabled for its class and its
2211                  * context is sharable (and it's not a
2212                  * generic method).
2213                  */
2214                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2215                         pass_vtable = TRUE;
2216         }
2217
2218         if (mini_method_get_context (cmethod) &&
2219                 mini_method_get_context (cmethod)->method_inst) {
2220                 g_assert (!pass_vtable);
2221
2222                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2223                         pass_mrgctx = TRUE;
2224                 } else {
2225                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2226                                 pass_mrgctx = TRUE;
2227                 }
2228         }
2229
2230         if (out_pass_vtable)
2231                 *out_pass_vtable = pass_vtable;
2232         if (out_pass_mrgctx)
2233                 *out_pass_mrgctx = pass_mrgctx;
2234 }
2235
2236 inline static MonoCallInst *
2237 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2238                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2239 {
2240         MonoType *sig_ret;
2241         MonoCallInst *call;
2242 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2243         int i;
2244 #endif
2245
2246         if (cfg->llvm_only)
2247                 tail = FALSE;
2248
2249         if (tail) {
2250                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2251
2252                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2253         } else
2254                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2255
2256         call->args = args;
2257         call->signature = sig;
2258         call->rgctx_reg = rgctx;
2259         sig_ret = mini_get_underlying_type (sig->ret);
2260
2261         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2262
2263         if (tail) {
2264                 if (mini_type_is_vtype (sig_ret)) {
2265                         call->vret_var = cfg->vret_addr;
2266                         //g_assert_not_reached ();
2267                 }
2268         } else if (mini_type_is_vtype (sig_ret)) {
2269                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2270                 MonoInst *loada;
2271
2272                 temp->backend.is_pinvoke = sig->pinvoke;
2273
2274                 /*
2275                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2276                  * address of return value to increase optimization opportunities.
2277                  * Before vtype decomposition, the dreg of the call ins itself represents the
2278                  * fact the call modifies the return value. After decomposition, the call will
2279                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2280                  * will be transformed into an LDADDR.
2281                  */
2282                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2283                 loada->dreg = alloc_preg (cfg);
2284                 loada->inst_p0 = temp;
2285                 /* We reference the call too since call->dreg could change during optimization */
2286                 loada->inst_p1 = call;
2287                 MONO_ADD_INS (cfg->cbb, loada);
2288
2289                 call->inst.dreg = temp->dreg;
2290
2291                 call->vret_var = loada;
2292         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2293                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2294
2295 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2296         if (COMPILE_SOFT_FLOAT (cfg)) {
2297                 /* 
2298                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2299                  * an icall, but that cannot be done during the call sequence since it would clobber
2300                  * the call registers + the stack. So we do it before emitting the call.
2301                  */
2302                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2303                         MonoType *t;
2304                         MonoInst *in = call->args [i];
2305
2306                         if (i >= sig->hasthis)
2307                                 t = sig->params [i - sig->hasthis];
2308                         else
2309                                 t = &mono_defaults.int_class->byval_arg;
2310                         t = mono_type_get_underlying_type (t);
2311
2312                         if (!t->byref && t->type == MONO_TYPE_R4) {
2313                                 MonoInst *iargs [1];
2314                                 MonoInst *conv;
2315
2316                                 iargs [0] = in;
2317                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2318
2319                                 /* The result will be in an int vreg */
2320                                 call->args [i] = conv;
2321                         }
2322                 }
2323         }
2324 #endif
2325
2326         call->need_unbox_trampoline = unbox_trampoline;
2327
2328 #ifdef ENABLE_LLVM
2329         if (COMPILE_LLVM (cfg))
2330                 mono_llvm_emit_call (cfg, call);
2331         else
2332                 mono_arch_emit_call (cfg, call);
2333 #else
2334         mono_arch_emit_call (cfg, call);
2335 #endif
2336
2337         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2338         cfg->flags |= MONO_CFG_HAS_CALLS;
2339         
2340         return call;
2341 }
2342
2343 static void
2344 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2345 {
2346         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2347         cfg->uses_rgctx_reg = TRUE;
2348         call->rgctx_reg = TRUE;
2349 #ifdef ENABLE_LLVM
2350         call->rgctx_arg_reg = rgctx_reg;
2351 #endif
2352 }       
2353
2354 MonoInst*
2355 mini_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2356 {
2357         MonoCallInst *call;
2358         MonoInst *ins;
2359         int rgctx_reg = -1;
2360         gboolean check_sp = FALSE;
2361
2362         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2363                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2364
2365                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2366                         check_sp = TRUE;
2367         }
2368
2369         if (rgctx_arg) {
2370                 rgctx_reg = mono_alloc_preg (cfg);
2371                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2372         }
2373
2374         if (check_sp) {
2375                 if (!cfg->stack_inbalance_var)
2376                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2377
2378                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2379                 ins->dreg = cfg->stack_inbalance_var->dreg;
2380                 MONO_ADD_INS (cfg->cbb, ins);
2381         }
2382
2383         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2384
2385         call->inst.sreg1 = addr->dreg;
2386
2387         if (imt_arg)
2388                 emit_imt_argument (cfg, call, NULL, imt_arg);
2389
2390         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2391
2392         if (check_sp) {
2393                 int sp_reg;
2394
2395                 sp_reg = mono_alloc_preg (cfg);
2396
2397                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2398                 ins->dreg = sp_reg;
2399                 MONO_ADD_INS (cfg->cbb, ins);
2400
2401                 /* Restore the stack so we don't crash when throwing the exception */
2402                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2403                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2404                 MONO_ADD_INS (cfg->cbb, ins);
2405
2406                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2407                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2408         }
2409
2410         if (rgctx_arg)
2411                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2412
2413         return (MonoInst*)call;
2414 }
2415
2416 static MonoInst*
2417 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2418
2419 static MonoInst*
2420 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2421                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2422 {
2423 #ifndef DISABLE_REMOTING
2424         gboolean might_be_remote = FALSE;
2425 #endif
2426         gboolean virtual_ = this_ins != NULL;
2427         gboolean enable_for_aot = TRUE;
2428         int context_used;
2429         MonoCallInst *call;
2430         MonoInst *call_target = NULL;
2431         int rgctx_reg = 0;
2432         gboolean need_unbox_trampoline;
2433
2434         if (!sig)
2435                 sig = mono_method_signature (method);
2436
2437         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2438                 g_assert_not_reached ();
2439
2440         if (rgctx_arg) {
2441                 rgctx_reg = mono_alloc_preg (cfg);
2442                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2443         }
2444
2445         if (method->string_ctor) {
2446                 /* Create the real signature */
2447                 /* FIXME: Cache these */
2448                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2449                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2450
2451                 sig = ctor_sig;
2452         }
2453
2454         context_used = mini_method_check_context_used (cfg, method);
2455
2456 #ifndef DISABLE_REMOTING
2457         might_be_remote = this_ins && sig->hasthis &&
2458                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2459                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2460
2461         if (might_be_remote && context_used) {
2462                 MonoInst *addr;
2463
2464                 g_assert (cfg->gshared);
2465
2466                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2467
2468                 return mini_emit_calli (cfg, sig, args, addr, NULL, NULL);
2469         }
2470 #endif
2471
2472         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2473                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2474
2475         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2476
2477         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2478
2479 #ifndef DISABLE_REMOTING
2480         if (might_be_remote)
2481                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2482         else
2483 #endif
2484                 call->method = method;
2485         call->inst.flags |= MONO_INST_HAS_METHOD;
2486         call->inst.inst_left = this_ins;
2487         call->tail_call = tail;
2488
2489         if (virtual_) {
2490                 int vtable_reg, slot_reg, this_reg;
2491                 int offset;
2492
2493                 this_reg = this_ins->dreg;
2494
2495                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2496                         MonoInst *dummy_use;
2497
2498                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2499
2500                         /* Make a call to delegate->invoke_impl */
2501                         call->inst.inst_basereg = this_reg;
2502                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2503                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2504
2505                         /* We must emit a dummy use here because the delegate trampoline will
2506                         replace the 'this' argument with the delegate target making this activation
2507                         no longer a root for the delegate.
2508                         This is an issue for delegates that target collectible code such as dynamic
2509                         methods of GC'able assemblies.
2510
2511                         For a test case look into #667921.
2512
2513                         FIXME: a dummy use is not the best way to do it as the local register allocator
2514                         will put it on a caller save register and spil it around the call. 
2515                         Ideally, we would either put it on a callee save register or only do the store part.  
2516                          */
2517                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2518
2519                         return (MonoInst*)call;
2520                 }
2521
2522                 if ((!cfg->compile_aot || enable_for_aot) && 
2523                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2524                          (MONO_METHOD_IS_FINAL (method) &&
2525                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2526                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2527                         /* 
2528                          * the method is not virtual, we just need to ensure this is not null
2529                          * and then we can call the method directly.
2530                          */
2531 #ifndef DISABLE_REMOTING
2532                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2533                                 /* 
2534                                  * The check above ensures method is not gshared, this is needed since
2535                                  * gshared methods can't have wrappers.
2536                                  */
2537                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2538                         }
2539 #endif
2540
2541                         if (!method->string_ctor)
2542                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2543
2544                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2545                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2546                         /*
2547                          * the method is virtual, but we can statically dispatch since either
2548                          * it's class or the method itself are sealed.
2549                          * But first we need to ensure it's not a null reference.
2550                          */
2551                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2552
2553                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2554                 } else if (call_target) {
2555                         vtable_reg = alloc_preg (cfg);
2556                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2557
2558                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2559                         call->inst.sreg1 = call_target->dreg;
2560                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2561                 } else {
2562                         vtable_reg = alloc_preg (cfg);
2563                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2564                         if (mono_class_is_interface (method->klass)) {
2565                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2566                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2567                                 slot_reg = vtable_reg;
2568                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2569                         } else {
2570                                 slot_reg = vtable_reg;
2571                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2572                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2573                                 if (imt_arg) {
2574                                         g_assert (mono_method_signature (method)->generic_param_count);
2575                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2576                                 }
2577                         }
2578
2579                         call->inst.sreg1 = slot_reg;
2580                         call->inst.inst_offset = offset;
2581                         call->is_virtual = TRUE;
2582                 }
2583         }
2584
2585         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2586
2587         if (rgctx_arg)
2588                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2589
2590         return (MonoInst*)call;
2591 }
2592
2593 MonoInst*
2594 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2595 {
2596         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2597 }
2598
2599 MonoInst*
2600 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2601                                            MonoInst **args)
2602 {
2603         MonoCallInst *call;
2604
2605         g_assert (sig);
2606
2607         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2608         call->fptr = func;
2609
2610         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2611
2612         return (MonoInst*)call;
2613 }
2614
2615 MonoInst*
2616 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2617 {
2618         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2619
2620         g_assert (info);
2621
2622         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2623 }
2624
2625 /*
2626  * mono_emit_abs_call:
2627  *
2628  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2629  */
2630 inline static MonoInst*
2631 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2632                                         MonoMethodSignature *sig, MonoInst **args)
2633 {
2634         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2635         MonoInst *ins;
2636
2637         /* 
2638          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2639          * handle it.
2640          */
2641         if (cfg->abs_patches == NULL)
2642                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2643         g_hash_table_insert (cfg->abs_patches, ji, ji);
2644         ins = mono_emit_native_call (cfg, ji, sig, args);
2645         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2646         return ins;
2647 }
2648
2649 static MonoMethodSignature*
2650 sig_to_rgctx_sig (MonoMethodSignature *sig)
2651 {
2652         // FIXME: memory allocation
2653         MonoMethodSignature *res;
2654         int i;
2655
2656         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2657         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2658         res->param_count = sig->param_count + 1;
2659         for (i = 0; i < sig->param_count; ++i)
2660                 res->params [i] = sig->params [i];
2661         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2662         return res;
2663 }
2664
2665 /* Make an indirect call to FSIG passing an additional argument */
2666 static MonoInst*
2667 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2668 {
2669         MonoMethodSignature *csig;
2670         MonoInst *args_buf [16];
2671         MonoInst **args;
2672         int i, pindex, tmp_reg;
2673
2674         /* Make a call with an rgctx/extra arg */
2675         if (fsig->param_count + 2 < 16)
2676                 args = args_buf;
2677         else
2678                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2679         pindex = 0;
2680         if (fsig->hasthis)
2681                 args [pindex ++] = orig_args [0];
2682         for (i = 0; i < fsig->param_count; ++i)
2683                 args [pindex ++] = orig_args [fsig->hasthis + i];
2684         tmp_reg = alloc_preg (cfg);
2685         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2686         csig = sig_to_rgctx_sig (fsig);
2687         return mini_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2688 }
2689
2690 /* Emit an indirect call to the function descriptor ADDR */
2691 static MonoInst*
2692 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2693 {
2694         int addr_reg, arg_reg;
2695         MonoInst *call_target;
2696
2697         g_assert (cfg->llvm_only);
2698
2699         /*
2700          * addr points to a <addr, arg> pair, load both of them, and
2701          * make a call to addr, passing arg as an extra arg.
2702          */
2703         addr_reg = alloc_preg (cfg);
2704         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2705         arg_reg = alloc_preg (cfg);
2706         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2707
2708         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2709 }
2710
2711 static gboolean
2712 direct_icalls_enabled (MonoCompile *cfg)
2713 {
2714         return FALSE;
2715
2716         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2717 #ifdef TARGET_AMD64
2718         if (cfg->compile_llvm && !cfg->llvm_only)
2719                 return FALSE;
2720 #endif
2721         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2722                 return FALSE;
2723         return TRUE;
2724 }
2725
2726 MonoInst*
2727 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2728 {
2729         /*
2730          * Call the jit icall without a wrapper if possible.
2731          * The wrapper is needed for the following reasons:
2732          * - to handle exceptions thrown using mono_raise_exceptions () from the
2733          *   icall function. The EH code needs the lmf frame pushed by the
2734          *   wrapper to be able to unwind back to managed code.
2735          * - to be able to do stack walks for asynchronously suspended
2736          *   threads when debugging.
2737          */
2738         if (info->no_raise && direct_icalls_enabled (cfg)) {
2739                 char *name;
2740                 int costs;
2741
2742                 if (!info->wrapper_method) {
2743                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2744                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2745                         g_free (name);
2746                         mono_memory_barrier ();
2747                 }
2748
2749                 /*
2750                  * Inline the wrapper method, which is basically a call to the C icall, and
2751                  * an exception check.
2752                  */
2753                 costs = inline_method (cfg, info->wrapper_method, NULL,
2754                                                            args, NULL, il_offset, TRUE);
2755                 g_assert (costs > 0);
2756                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2757
2758                 return args [0];
2759         } else {
2760                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2761         }
2762 }
2763  
2764 static MonoInst*
2765 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2766 {
2767         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2768                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2769                         int widen_op = -1;
2770
2771                         /* 
2772                          * Native code might return non register sized integers 
2773                          * without initializing the upper bits.
2774                          */
2775                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2776                         case OP_LOADI1_MEMBASE:
2777                                 widen_op = OP_ICONV_TO_I1;
2778                                 break;
2779                         case OP_LOADU1_MEMBASE:
2780                                 widen_op = OP_ICONV_TO_U1;
2781                                 break;
2782                         case OP_LOADI2_MEMBASE:
2783                                 widen_op = OP_ICONV_TO_I2;
2784                                 break;
2785                         case OP_LOADU2_MEMBASE:
2786                                 widen_op = OP_ICONV_TO_U2;
2787                                 break;
2788                         default:
2789                                 break;
2790                         }
2791
2792                         if (widen_op != -1) {
2793                                 int dreg = alloc_preg (cfg);
2794                                 MonoInst *widen;
2795
2796                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2797                                 widen->type = ins->type;
2798                                 ins = widen;
2799                         }
2800                 }
2801         }
2802
2803         return ins;
2804 }
2805
2806
2807 static void
2808 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2809 {
2810         MonoInst *args [16];
2811
2812         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2813         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2814
2815         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2816 }
2817
2818 MonoMethod*
2819 mini_get_memcpy_method (void)
2820 {
2821         static MonoMethod *memcpy_method = NULL;
2822         if (!memcpy_method) {
2823                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2824                 if (!memcpy_method)
2825                         g_error ("Old corlib found. Install a new one");
2826         }
2827         return memcpy_method;
2828 }
2829
2830 void
2831 mini_emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2832 {
2833         int card_table_shift_bits;
2834         gpointer card_table_mask;
2835         guint8 *card_table;
2836         MonoInst *dummy_use;
2837         int nursery_shift_bits;
2838         size_t nursery_size;
2839
2840         if (!cfg->gen_write_barriers)
2841                 return;
2842
2843         //method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1])
2844
2845         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2846
2847         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
2848
2849         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
2850                 MonoInst *wbarrier;
2851
2852                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
2853                 wbarrier->sreg1 = ptr->dreg;
2854                 wbarrier->sreg2 = value->dreg;
2855                 MONO_ADD_INS (cfg->cbb, wbarrier);
2856         } else if (card_table) {
2857                 int offset_reg = alloc_preg (cfg);
2858                 int card_reg;
2859                 MonoInst *ins;
2860
2861                 /*
2862                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
2863                  * collector case, so, for the serial collector, it might slightly slow down nursery
2864                  * collections. We also expect that the host system and the target system have the same card
2865                  * table configuration, which is the case if they have the same pointer size.
2866                  */
2867
2868                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
2869                 if (card_table_mask)
2870                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
2871
2872                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
2873                  * IMM's larger than 32bits.
2874                  */
2875                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
2876                 card_reg = ins->dreg;
2877
2878                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
2879                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
2880         } else {
2881                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
2882                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
2883         }
2884
2885         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
2886 }
2887
2888 MonoMethod*
2889 mini_get_memset_method (void)
2890 {
2891         static MonoMethod *memset_method = NULL;
2892         if (!memset_method) {
2893                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2894                 if (!memset_method)
2895                         g_error ("Old corlib found. Install a new one");
2896         }
2897         return memset_method;
2898 }
2899
2900 void
2901 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
2902 {
2903         MonoInst *iargs [3];
2904         int n;
2905         guint32 align;
2906         MonoMethod *memset_method;
2907         MonoInst *size_ins = NULL;
2908         MonoInst *bzero_ins = NULL;
2909         static MonoMethod *bzero_method;
2910
2911         /* FIXME: Optimize this for the case when dest is an LDADDR */
2912         mono_class_init (klass);
2913         if (mini_is_gsharedvt_klass (klass)) {
2914                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
2915                 bzero_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
2916                 if (!bzero_method)
2917                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
2918                 g_assert (bzero_method);
2919                 iargs [0] = dest;
2920                 iargs [1] = size_ins;
2921                 mini_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
2922                 return;
2923         }
2924
2925         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
2926
2927         n = mono_class_value_size (klass, &align);
2928
2929         if (n <= sizeof (gpointer) * 8) {
2930                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
2931         }
2932         else {
2933                 memset_method = mini_get_memset_method ();
2934                 iargs [0] = dest;
2935                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
2936                 EMIT_NEW_ICONST (cfg, iargs [2], n);
2937                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
2938         }
2939 }
2940
2941 /*
2942  * emit_get_rgctx:
2943  *
2944  *   Emit IR to return either the this pointer for instance method,
2945  * or the mrgctx for static methods.
2946  */
2947 static MonoInst*
2948 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
2949 {
2950         MonoInst *this_ins = NULL;
2951
2952         g_assert (cfg->gshared);
2953
2954         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
2955                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
2956                 !method->klass->valuetype)
2957                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
2958
2959         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
2960                 MonoInst *mrgctx_loc, *mrgctx_var;
2961
2962                 g_assert (!this_ins);
2963                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
2964
2965                 mrgctx_loc = mono_get_vtable_var (cfg);
2966                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2967
2968                 return mrgctx_var;
2969         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
2970                 MonoInst *mrgctx_loc, *mrgctx_var;
2971
2972                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
2973                 mrgctx_loc = mono_get_vtable_var (cfg);
2974                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2975
2976                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
2977
2978                 return mrgctx_var;
2979         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
2980                 MonoInst *vtable_loc, *vtable_var;
2981
2982                 g_assert (!this_ins);
2983
2984                 vtable_loc = mono_get_vtable_var (cfg);
2985                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
2986
2987                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
2988                         MonoInst *mrgctx_var = vtable_var;
2989                         int vtable_reg;
2990
2991                         vtable_reg = alloc_preg (cfg);
2992                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
2993                         vtable_var->type = STACK_PTR;
2994                 }
2995
2996                 return vtable_var;
2997         } else {
2998                 MonoInst *ins;
2999                 int vtable_reg;
3000         
3001                 vtable_reg = alloc_preg (cfg);
3002                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3003                 return ins;
3004         }
3005 }
3006
3007 static MonoJumpInfoRgctxEntry *
3008 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3009 {
3010         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3011         res->method = method;
3012         res->in_mrgctx = in_mrgctx;
3013         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3014         res->data->type = patch_type;
3015         res->data->data.target = patch_data;
3016         res->info_type = info_type;
3017
3018         return res;
3019 }
3020
3021 static inline MonoInst*
3022 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3023 {
3024         MonoInst *args [16];
3025         MonoInst *call;
3026
3027         // FIXME: No fastpath since the slot is not a compile time constant
3028         args [0] = rgctx;
3029         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3030         if (entry->in_mrgctx)
3031                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3032         else
3033                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3034         return call;
3035 #if 0
3036         /*
3037          * FIXME: This can be called during decompose, which is a problem since it creates
3038          * new bblocks.
3039          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3040          */
3041         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3042         gboolean mrgctx;
3043         MonoBasicBlock *is_null_bb, *end_bb;
3044         MonoInst *res, *ins, *call;
3045         MonoInst *args[16];
3046
3047         slot = mini_get_rgctx_entry_slot (entry);
3048
3049         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3050         index = MONO_RGCTX_SLOT_INDEX (slot);
3051         if (mrgctx)
3052                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3053         for (depth = 0; ; ++depth) {
3054                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3055
3056                 if (index < size - 1)
3057                         break;
3058                 index -= size - 1;
3059         }
3060
3061         NEW_BBLOCK (cfg, end_bb);
3062         NEW_BBLOCK (cfg, is_null_bb);
3063
3064         if (mrgctx) {
3065                 rgctx_reg = rgctx->dreg;
3066         } else {
3067                 rgctx_reg = alloc_preg (cfg);
3068
3069                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3070                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3071                 NEW_BBLOCK (cfg, is_null_bb);
3072
3073                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3074                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3075         }
3076
3077         for (i = 0; i < depth; ++i) {
3078                 int array_reg = alloc_preg (cfg);
3079
3080                 /* load ptr to next array */
3081                 if (mrgctx && i == 0)
3082                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3083                 else
3084                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3085                 rgctx_reg = array_reg;
3086                 /* is the ptr null? */
3087                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3088                 /* if yes, jump to actual trampoline */
3089                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3090         }
3091
3092         /* fetch slot */
3093         val_reg = alloc_preg (cfg);
3094         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3095         /* is the slot null? */
3096         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3097         /* if yes, jump to actual trampoline */
3098         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3099
3100         /* Fastpath */
3101         res_reg = alloc_preg (cfg);
3102         MONO_INST_NEW (cfg, ins, OP_MOVE);
3103         ins->dreg = res_reg;
3104         ins->sreg1 = val_reg;
3105         MONO_ADD_INS (cfg->cbb, ins);
3106         res = ins;
3107         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3108
3109         /* Slowpath */
3110         MONO_START_BB (cfg, is_null_bb);
3111         args [0] = rgctx;
3112         EMIT_NEW_ICONST (cfg, args [1], index);
3113         if (mrgctx)
3114                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3115         else
3116                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3117         MONO_INST_NEW (cfg, ins, OP_MOVE);
3118         ins->dreg = res_reg;
3119         ins->sreg1 = call->dreg;
3120         MONO_ADD_INS (cfg->cbb, ins);
3121         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3122
3123         MONO_START_BB (cfg, end_bb);
3124
3125         return res;
3126 #endif
3127 }
3128
3129 /*
3130  * emit_rgctx_fetch:
3131  *
3132  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3133  * given by RGCTX.
3134  */
3135 static inline MonoInst*
3136 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3137 {
3138         if (cfg->llvm_only)
3139                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3140         else
3141                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3142 }
3143
3144 MonoInst*
3145 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3146                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3147 {
3148         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3149         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3150
3151         return emit_rgctx_fetch (cfg, rgctx, entry);
3152 }
3153
3154 static MonoInst*
3155 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3156                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3157 {
3158         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3159         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3160
3161         return emit_rgctx_fetch (cfg, rgctx, entry);
3162 }
3163
3164 static MonoInst*
3165 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3166                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3167 {
3168         MonoJumpInfoGSharedVtCall *call_info;
3169         MonoJumpInfoRgctxEntry *entry;
3170         MonoInst *rgctx;
3171
3172         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3173         call_info->sig = sig;
3174         call_info->method = cmethod;
3175
3176         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3177         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3178
3179         return emit_rgctx_fetch (cfg, rgctx, entry);
3180 }
3181
3182 /*
3183  * emit_get_rgctx_virt_method:
3184  *
3185  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3186  */
3187 static MonoInst*
3188 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3189                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3190 {
3191         MonoJumpInfoVirtMethod *info;
3192         MonoJumpInfoRgctxEntry *entry;
3193         MonoInst *rgctx;
3194
3195         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3196         info->klass = klass;
3197         info->method = virt_method;
3198
3199         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3200         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3201
3202         return emit_rgctx_fetch (cfg, rgctx, entry);
3203 }
3204
3205 static MonoInst*
3206 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3207                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3208 {
3209         MonoJumpInfoRgctxEntry *entry;
3210         MonoInst *rgctx;
3211
3212         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3213         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3214
3215         return emit_rgctx_fetch (cfg, rgctx, entry);
3216 }
3217
3218 /*
3219  * emit_get_rgctx_method:
3220  *
3221  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3222  * normal constants, else emit a load from the rgctx.
3223  */
3224 static MonoInst*
3225 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3226                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3227 {
3228         if (!context_used) {
3229                 MonoInst *ins;
3230
3231                 switch (rgctx_type) {
3232                 case MONO_RGCTX_INFO_METHOD:
3233                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3234                         return ins;
3235                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3236                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3237                         return ins;
3238                 default:
3239                         g_assert_not_reached ();
3240                 }
3241         } else {
3242                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3243                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3244
3245                 return emit_rgctx_fetch (cfg, rgctx, entry);
3246         }
3247 }
3248
3249 static MonoInst*
3250 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3251                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3252 {
3253         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3254         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3255
3256         return emit_rgctx_fetch (cfg, rgctx, entry);
3257 }
3258
3259 static int
3260 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3261 {
3262         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3263         MonoRuntimeGenericContextInfoTemplate *template_;
3264         int i, idx;
3265
3266         g_assert (info);
3267
3268         for (i = 0; i < info->num_entries; ++i) {
3269                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3270
3271                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3272                         return i;
3273         }
3274
3275         if (info->num_entries == info->count_entries) {
3276                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3277                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3278
3279                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3280
3281                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3282                 info->entries = new_entries;
3283                 info->count_entries = new_count_entries;
3284         }
3285
3286         idx = info->num_entries;
3287         template_ = &info->entries [idx];
3288         template_->info_type = rgctx_type;
3289         template_->data = data;
3290
3291         info->num_entries ++;
3292
3293         return idx;
3294 }
3295
3296 /*
3297  * emit_get_gsharedvt_info:
3298  *
3299  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3300  */
3301 static MonoInst*
3302 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3303 {
3304         MonoInst *ins;
3305         int idx, dreg;
3306
3307         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3308         /* Load info->entries [idx] */
3309         dreg = alloc_preg (cfg);
3310         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3311
3312         return ins;
3313 }
3314
3315 MonoInst*
3316 mini_emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3317 {
3318         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3319 }
3320
3321 /*
3322  * On return the caller must check @klass for load errors.
3323  */
3324 static void
3325 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3326 {
3327         MonoInst *vtable_arg;
3328         int context_used;
3329
3330         context_used = mini_class_check_context_used (cfg, klass);
3331
3332         if (context_used) {
3333                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3334                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3335         } else {
3336                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3337
3338                 if (!vtable)
3339                         return;
3340                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3341         }
3342
3343         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3344                 MonoInst *ins;
3345
3346                 /*
3347                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3348                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3349                  */
3350                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3351                 ins->sreg1 = vtable_arg->dreg;
3352                 MONO_ADD_INS (cfg->cbb, ins);
3353         } else {
3354                 int inited_reg;
3355                 MonoBasicBlock *inited_bb;
3356                 MonoInst *args [16];
3357
3358                 inited_reg = alloc_ireg (cfg);
3359
3360                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3361
3362                 NEW_BBLOCK (cfg, inited_bb);
3363
3364                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3365                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3366
3367                 args [0] = vtable_arg;
3368                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3369
3370                 MONO_START_BB (cfg, inited_bb);
3371         }
3372 }
3373
3374 static void
3375 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3376 {
3377         MonoInst *ins;
3378
3379         if (cfg->gen_seq_points && cfg->method == method) {
3380                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3381                 if (nonempty_stack)
3382                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3383                 MONO_ADD_INS (cfg->cbb, ins);
3384         }
3385 }
3386
3387 void
3388 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3389 {
3390         if (mini_get_debug_options ()->better_cast_details) {
3391                 int vtable_reg = alloc_preg (cfg);
3392                 int klass_reg = alloc_preg (cfg);
3393                 MonoBasicBlock *is_null_bb = NULL;
3394                 MonoInst *tls_get;
3395                 int to_klass_reg, context_used;
3396
3397                 if (null_check) {
3398                         NEW_BBLOCK (cfg, is_null_bb);
3399
3400                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3401                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3402                 }
3403
3404                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3405                 if (!tls_get) {
3406                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3407                         exit (1);
3408                 }
3409
3410                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3411                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3412
3413                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3414
3415                 context_used = mini_class_check_context_used (cfg, klass);
3416                 if (context_used) {
3417                         MonoInst *class_ins;
3418
3419                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3420                         to_klass_reg = class_ins->dreg;
3421                 } else {
3422                         to_klass_reg = alloc_preg (cfg);
3423                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3424                 }
3425                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3426
3427                 if (null_check)
3428                         MONO_START_BB (cfg, is_null_bb);
3429         }
3430 }
3431
3432 void
3433 mini_reset_cast_details (MonoCompile *cfg)
3434 {
3435         /* Reset the variables holding the cast details */
3436         if (mini_get_debug_options ()->better_cast_details) {
3437                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3438                 /* It is enough to reset the from field */
3439                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3440         }
3441 }
3442
3443 /*
3444  * On return the caller must check @array_class for load errors
3445  */
3446 static void
3447 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3448 {
3449         int vtable_reg = alloc_preg (cfg);
3450         int context_used;
3451
3452         context_used = mini_class_check_context_used (cfg, array_class);
3453
3454         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3455
3456         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3457
3458         if (cfg->opt & MONO_OPT_SHARED) {
3459                 int class_reg = alloc_preg (cfg);
3460                 MonoInst *ins;
3461
3462                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3463                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3464                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3465         } else if (context_used) {
3466                 MonoInst *vtable_ins;
3467
3468                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3469                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3470         } else {
3471                 if (cfg->compile_aot) {
3472                         int vt_reg;
3473                         MonoVTable *vtable;
3474
3475                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3476                                 return;
3477                         vt_reg = alloc_preg (cfg);
3478                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3479                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3480                 } else {
3481                         MonoVTable *vtable;
3482                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3483                                 return;
3484                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3485                 }
3486         }
3487         
3488         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3489
3490         mini_reset_cast_details (cfg);
3491 }
3492
3493 /**
3494  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3495  * generic code is generated.
3496  */
3497 static MonoInst*
3498 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3499 {
3500         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3501
3502         if (context_used) {
3503                 MonoInst *rgctx, *addr;
3504
3505                 /* FIXME: What if the class is shared?  We might not
3506                    have to get the address of the method from the
3507                    RGCTX. */
3508                 addr = emit_get_rgctx_method (cfg, context_used, method,
3509                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3510                 if (cfg->llvm_only) {
3511                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3512                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3513                 } else {
3514                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3515
3516                         return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3517                 }
3518         } else {
3519                 gboolean pass_vtable, pass_mrgctx;
3520                 MonoInst *rgctx_arg = NULL;
3521
3522                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3523                 g_assert (!pass_mrgctx);
3524
3525                 if (pass_vtable) {
3526                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3527
3528                         g_assert (vtable);
3529                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3530                 }
3531
3532                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3533         }
3534 }
3535
3536 static MonoInst*
3537 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3538 {
3539         MonoInst *add;
3540         int obj_reg;
3541         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3542         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3543         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3544         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3545
3546         obj_reg = sp [0]->dreg;
3547         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3548         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3549
3550         /* FIXME: generics */
3551         g_assert (klass->rank == 0);
3552                         
3553         // Check rank == 0
3554         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3555         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3556
3557         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3558         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3559
3560         if (context_used) {
3561                 MonoInst *element_class;
3562
3563                 /* This assertion is from the unboxcast insn */
3564                 g_assert (klass->rank == 0);
3565
3566                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3567                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3568
3569                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3570                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3571         } else {
3572                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3573                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3574                 mini_reset_cast_details (cfg);
3575         }
3576
3577         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3578         MONO_ADD_INS (cfg->cbb, add);
3579         add->type = STACK_MP;
3580         add->klass = klass;
3581
3582         return add;
3583 }
3584
3585 static MonoInst*
3586 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3587 {
3588         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3589         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3590         MonoInst *ins;
3591         int dreg, addr_reg;
3592
3593         klass_inst = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3594
3595         /* obj */
3596         args [0] = obj;
3597
3598         /* klass */
3599         args [1] = klass_inst;
3600
3601         /* CASTCLASS */
3602         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3603
3604         NEW_BBLOCK (cfg, is_ref_bb);
3605         NEW_BBLOCK (cfg, is_nullable_bb);
3606         NEW_BBLOCK (cfg, end_bb);
3607         is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3608         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3609         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3610
3611         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3612         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3613
3614         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3615         addr_reg = alloc_dreg (cfg, STACK_MP);
3616
3617         /* Non-ref case */
3618         /* UNBOX */
3619         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3620         MONO_ADD_INS (cfg->cbb, addr);
3621
3622         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3623
3624         /* Ref case */
3625         MONO_START_BB (cfg, is_ref_bb);
3626
3627         /* Save the ref to a temporary */
3628         dreg = alloc_ireg (cfg);
3629         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3630         addr->dreg = addr_reg;
3631         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3632         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3633
3634         /* Nullable case */
3635         MONO_START_BB (cfg, is_nullable_bb);
3636
3637         {
3638                 MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3639                 MonoInst *unbox_call;
3640                 MonoMethodSignature *unbox_sig;
3641
3642                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3643                 unbox_sig->ret = &klass->byval_arg;
3644                 unbox_sig->param_count = 1;
3645                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3646
3647                 if (cfg->llvm_only)
3648                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3649                 else
3650                         unbox_call = mini_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3651
3652                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3653                 addr->dreg = addr_reg;
3654         }
3655
3656         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3657
3658         /* End */
3659         MONO_START_BB (cfg, end_bb);
3660
3661         /* LDOBJ */
3662         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3663
3664         return ins;
3665 }
3666
3667 /*
3668  * Returns NULL and set the cfg exception on error.
3669  */
3670 static MonoInst*
3671 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3672 {
3673         MonoInst *iargs [2];
3674         void *alloc_ftn;
3675
3676         if (context_used) {
3677                 MonoInst *data;
3678                 MonoRgctxInfoType rgctx_info;
3679                 MonoInst *iargs [2];
3680                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
3681
3682                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
3683
3684                 if (cfg->opt & MONO_OPT_SHARED)
3685                         rgctx_info = MONO_RGCTX_INFO_KLASS;
3686                 else
3687                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
3688                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
3689
3690                 if (cfg->opt & MONO_OPT_SHARED) {
3691                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3692                         iargs [1] = data;
3693                         alloc_ftn = ves_icall_object_new;
3694                 } else {
3695                         iargs [0] = data;
3696                         alloc_ftn = ves_icall_object_new_specific;
3697                 }
3698
3699                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
3700                         if (known_instance_size) {
3701                                 int size = mono_class_instance_size (klass);
3702                                 if (size < sizeof (MonoObject))
3703                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3704
3705                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
3706                         }
3707                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3708                 }
3709
3710                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3711         }
3712
3713         if (cfg->opt & MONO_OPT_SHARED) {
3714                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3715                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
3716
3717                 alloc_ftn = ves_icall_object_new;
3718         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
3719                 /* This happens often in argument checking code, eg. throw new FooException... */
3720                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
3721                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3722                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
3723         } else {
3724                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3725                 MonoMethod *managed_alloc = NULL;
3726                 gboolean pass_lw;
3727
3728                 if (!vtable) {
3729                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
3730                         cfg->exception_ptr = klass;
3731                         return NULL;
3732                 }
3733
3734                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
3735
3736                 if (managed_alloc) {
3737                         int size = mono_class_instance_size (klass);
3738                         if (size < sizeof (MonoObject))
3739                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3740
3741                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3742                         EMIT_NEW_ICONST (cfg, iargs [1], size);
3743                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3744                 }
3745                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3746                 if (pass_lw) {
3747                         guint32 lw = vtable->klass->instance_size;
3748                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3749                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
3750                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
3751                 }
3752                 else {
3753                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3754                 }
3755         }
3756
3757         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3758 }
3759         
3760 /*
3761  * Returns NULL and set the cfg exception on error.
3762  */     
3763 static MonoInst*
3764 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
3765 {
3766         MonoInst *alloc, *ins;
3767
3768         if (mono_class_is_nullable (klass)) {
3769                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3770
3771                 if (context_used) {
3772                         if (cfg->llvm_only && cfg->gsharedvt) {
3773                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3774                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3775                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3776                         } else {
3777                                 /* FIXME: What if the class is shared?  We might not
3778                                    have to get the method address from the RGCTX. */
3779                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3780                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3781                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3782
3783                                 return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3784                         }
3785                 } else {
3786                         gboolean pass_vtable, pass_mrgctx;
3787                         MonoInst *rgctx_arg = NULL;
3788
3789                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3790                         g_assert (!pass_mrgctx);
3791
3792                         if (pass_vtable) {
3793                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3794
3795                                 g_assert (vtable);
3796                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3797                         }
3798
3799                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3800                 }
3801         }
3802
3803         if (mini_is_gsharedvt_klass (klass)) {
3804                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3805                 MonoInst *res, *is_ref, *src_var, *addr;
3806                 int dreg;
3807
3808                 dreg = alloc_ireg (cfg);
3809
3810                 NEW_BBLOCK (cfg, is_ref_bb);
3811                 NEW_BBLOCK (cfg, is_nullable_bb);
3812                 NEW_BBLOCK (cfg, end_bb);
3813                 is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3814                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3815                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3816
3817                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3818                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3819
3820                 /* Non-ref case */
3821                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3822                 if (!alloc)
3823                         return NULL;
3824                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3825                 ins->opcode = OP_STOREV_MEMBASE;
3826
3827                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
3828                 res->type = STACK_OBJ;
3829                 res->klass = klass;
3830                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3831                 
3832                 /* Ref case */
3833                 MONO_START_BB (cfg, is_ref_bb);
3834
3835                 /* val is a vtype, so has to load the value manually */
3836                 src_var = get_vreg_to_inst (cfg, val->dreg);
3837                 if (!src_var)
3838                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
3839                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
3840                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
3841                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3842
3843                 /* Nullable case */
3844                 MONO_START_BB (cfg, is_nullable_bb);
3845
3846                 {
3847                         MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass,
3848                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
3849                         MonoInst *box_call;
3850                         MonoMethodSignature *box_sig;
3851
3852                         /*
3853                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
3854                          * construct that method at JIT time, so have to do things by hand.
3855                          */
3856                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3857                         box_sig->ret = &mono_defaults.object_class->byval_arg;
3858                         box_sig->param_count = 1;
3859                         box_sig->params [0] = &klass->byval_arg;
3860
3861                         if (cfg->llvm_only)
3862                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
3863                         else
3864                                 box_call = mini_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
3865                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
3866                         res->type = STACK_OBJ;
3867                         res->klass = klass;
3868                 }
3869
3870                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3871
3872                 MONO_START_BB (cfg, end_bb);
3873
3874                 return res;
3875         } else {
3876                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3877                 if (!alloc)
3878                         return NULL;
3879
3880                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3881                 return alloc;
3882         }
3883 }
3884
3885 static GHashTable* direct_icall_type_hash;
3886
3887 static gboolean
3888 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
3889 {
3890         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
3891         if (!direct_icalls_enabled (cfg))
3892                 return FALSE;
3893
3894         /*
3895          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
3896          * Whitelist a few icalls for now.
3897          */
3898         if (!direct_icall_type_hash) {
3899                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
3900
3901                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
3902                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
3903                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
3904                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
3905                 mono_memory_barrier ();
3906                 direct_icall_type_hash = h;
3907         }
3908
3909         if (cmethod->klass == mono_defaults.math_class)
3910                 return TRUE;
3911         /* No locking needed */
3912         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
3913                 return TRUE;
3914         return FALSE;
3915 }
3916
3917 static gboolean
3918 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
3919 {
3920         if (cmethod->klass == mono_defaults.systemtype_class) {
3921                 if (!strcmp (cmethod->name, "GetType"))
3922                         return TRUE;
3923         }
3924         return FALSE;
3925 }
3926
3927 static G_GNUC_UNUSED MonoInst*
3928 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
3929 {
3930         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
3931         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
3932         gboolean is_i4;
3933
3934         switch (enum_type->type) {
3935         case MONO_TYPE_I8:
3936         case MONO_TYPE_U8:
3937 #if SIZEOF_REGISTER == 8
3938         case MONO_TYPE_I:
3939         case MONO_TYPE_U:
3940 #endif
3941                 is_i4 = FALSE;
3942                 break;
3943         default:
3944                 is_i4 = TRUE;
3945                 break;
3946         }
3947
3948         {
3949                 MonoInst *load, *and_, *cmp, *ceq;
3950                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3951                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3952                 int dest_reg = alloc_ireg (cfg);
3953
3954                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
3955                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
3956                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
3957                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
3958
3959                 ceq->type = STACK_I4;
3960
3961                 if (!is_i4) {
3962                         load = mono_decompose_opcode (cfg, load);
3963                         and_ = mono_decompose_opcode (cfg, and_);
3964                         cmp = mono_decompose_opcode (cfg, cmp);
3965                         ceq = mono_decompose_opcode (cfg, ceq);
3966                 }
3967
3968                 return ceq;
3969         }
3970 }
3971
3972 /*
3973  * Returns NULL and set the cfg exception on error.
3974  */
3975 static G_GNUC_UNUSED MonoInst*
3976 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
3977 {
3978         MonoInst *ptr;
3979         int dreg;
3980         gpointer trampoline;
3981         MonoInst *obj, *method_ins, *tramp_ins;
3982         MonoDomain *domain;
3983         guint8 **code_slot;
3984
3985         if (virtual_ && !cfg->llvm_only) {
3986                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
3987                 g_assert (invoke);
3988
3989                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
3990                         return NULL;
3991         }
3992
3993         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
3994         if (!obj)
3995                 return NULL;
3996
3997         /* Inline the contents of mono_delegate_ctor */
3998
3999         /* Set target field */
4000         /* Optimize away setting of NULL target */
4001         if (!MONO_INS_IS_PCONST_NULL (target)) {
4002                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4003                 if (cfg->gen_write_barriers) {
4004                         dreg = alloc_preg (cfg);
4005                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4006                         mini_emit_write_barrier (cfg, ptr, target);
4007                 }
4008         }
4009
4010         /* Set method field */
4011         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4012         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4013
4014         /* 
4015          * To avoid looking up the compiled code belonging to the target method
4016          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4017          * store it, and we fill it after the method has been compiled.
4018          */
4019         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4020                 MonoInst *code_slot_ins;
4021
4022                 if (context_used) {
4023                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4024                 } else {
4025                         domain = mono_domain_get ();
4026                         mono_domain_lock (domain);
4027                         if (!domain_jit_info (domain)->method_code_hash)
4028                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4029                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4030                         if (!code_slot) {
4031                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4032                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4033                         }
4034                         mono_domain_unlock (domain);
4035
4036                         code_slot_ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4037                 }
4038                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4039         }
4040
4041         if (cfg->llvm_only) {
4042                 MonoInst *args [16];
4043
4044                 if (virtual_) {
4045                         args [0] = obj;
4046                         args [1] = target;
4047                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4048                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4049                 } else {
4050                         args [0] = obj;
4051                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4052                 }
4053
4054                 return obj;
4055         }
4056
4057         if (cfg->compile_aot) {
4058                 MonoDelegateClassMethodPair *del_tramp;
4059
4060                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4061                 del_tramp->klass = klass;
4062                 del_tramp->method = context_used ? NULL : method;
4063                 del_tramp->is_virtual = virtual_;
4064                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4065         } else {
4066                 if (virtual_)
4067                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4068                 else
4069                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4070                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4071         }
4072
4073         /* Set invoke_impl field */
4074         if (virtual_) {
4075                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4076         } else {
4077                 dreg = alloc_preg (cfg);
4078                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4079                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4080
4081                 dreg = alloc_preg (cfg);
4082                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4083                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4084         }
4085
4086         dreg = alloc_preg (cfg);
4087         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4088         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4089
4090         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4091
4092         return obj;
4093 }
4094
4095 static MonoInst*
4096 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4097 {
4098         MonoJitICallInfo *info;
4099
4100         /* Need to register the icall so it gets an icall wrapper */
4101         info = mono_get_array_new_va_icall (rank);
4102
4103         cfg->flags |= MONO_CFG_HAS_VARARGS;
4104
4105         /* mono_array_new_va () needs a vararg calling convention */
4106         cfg->exception_message = g_strdup ("array-new");
4107         cfg->disable_llvm = TRUE;
4108
4109         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4110         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4111 }
4112
4113 /*
4114  * handle_constrained_gsharedvt_call:
4115  *
4116  *   Handle constrained calls where the receiver is a gsharedvt type.
4117  * Return the instruction representing the call. Set the cfg exception on failure.
4118  */
4119 static MonoInst*
4120 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4121                                                                    gboolean *ref_emit_widen)
4122 {
4123         MonoInst *ins = NULL;
4124         gboolean emit_widen = *ref_emit_widen;
4125
4126         /*
4127          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4128          * This is hard to do with the current call code, since we would have to emit a branch and two different calls. So instead, we
4129          * pack the arguments into an array, and do the rest of the work in in an icall.
4130          */
4131         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4132                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret)) || mini_is_gsharedvt_type (fsig->ret)) &&
4133                 (fsig->param_count == 0 || (!fsig->hasthis && fsig->param_count == 1) || (fsig->param_count == 1 && (MONO_TYPE_IS_REFERENCE (fsig->params [0]) || fsig->params [0]->byref || mini_is_gsharedvt_type (fsig->params [0]))))) {
4134                 MonoInst *args [16];
4135
4136                 /*
4137                  * This case handles calls to
4138                  * - object:ToString()/Equals()/GetHashCode(),
4139                  * - System.IComparable<T>:CompareTo()
4140                  * - System.IEquatable<T>:Equals ()
4141                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4142                  */
4143
4144                 args [0] = sp [0];
4145                 if (mono_method_check_context_used (cmethod))
4146                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4147                 else
4148                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4149                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4150
4151                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4152                 if (fsig->hasthis && fsig->param_count) {
4153                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4154                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4155                         ins->dreg = alloc_preg (cfg);
4156                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4157                         MONO_ADD_INS (cfg->cbb, ins);
4158                         args [4] = ins;
4159
4160                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4161                                 int addr_reg, deref_arg_reg;
4162
4163                                 ins = mini_emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4164                                 deref_arg_reg = alloc_preg (cfg);
4165                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4166                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4167
4168                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4169                                 addr_reg = ins->dreg;
4170                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4171                         } else {
4172                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4173                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4174                         }
4175                 } else {
4176                         EMIT_NEW_ICONST (cfg, args [3], 0);
4177                         EMIT_NEW_ICONST (cfg, args [4], 0);
4178                 }
4179                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4180                 emit_widen = FALSE;
4181
4182                 if (mini_is_gsharedvt_type (fsig->ret)) {
4183                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4184                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4185                         MonoInst *add;
4186
4187                         /* Unbox */
4188                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4189                         MONO_ADD_INS (cfg->cbb, add);
4190                         /* Load value */
4191                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4192                         MONO_ADD_INS (cfg->cbb, ins);
4193                         /* ins represents the call result */
4194                 }
4195         } else {
4196                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4197         }
4198
4199         *ref_emit_widen = emit_widen;
4200
4201         return ins;
4202
4203  exception_exit:
4204         return NULL;
4205 }
4206
4207 static void
4208 mono_emit_load_got_addr (MonoCompile *cfg)
4209 {
4210         MonoInst *getaddr, *dummy_use;
4211
4212         if (!cfg->got_var || cfg->got_var_allocated)
4213                 return;
4214
4215         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4216         getaddr->cil_code = cfg->header->code;
4217         getaddr->dreg = cfg->got_var->dreg;
4218
4219         /* Add it to the start of the first bblock */
4220         if (cfg->bb_entry->code) {
4221                 getaddr->next = cfg->bb_entry->code;
4222                 cfg->bb_entry->code = getaddr;
4223         }
4224         else
4225                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4226
4227         cfg->got_var_allocated = TRUE;
4228
4229         /* 
4230          * Add a dummy use to keep the got_var alive, since real uses might
4231          * only be generated by the back ends.
4232          * Add it to end_bblock, so the variable's lifetime covers the whole
4233          * method.
4234          * It would be better to make the usage of the got var explicit in all
4235          * cases when the backend needs it (i.e. calls, throw etc.), so this
4236          * wouldn't be needed.
4237          */
4238         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4239         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4240 }
4241
4242 static int inline_limit;
4243 static gboolean inline_limit_inited;
4244
4245 static gboolean
4246 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4247 {
4248         MonoMethodHeaderSummary header;
4249         MonoVTable *vtable;
4250 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4251         MonoMethodSignature *sig = mono_method_signature (method);
4252         int i;
4253 #endif
4254
4255         if (cfg->disable_inline)
4256                 return FALSE;
4257         if (cfg->gsharedvt)
4258                 return FALSE;
4259
4260         if (cfg->inline_depth > 10)
4261                 return FALSE;
4262
4263         if (!mono_method_get_header_summary (method, &header))
4264                 return FALSE;
4265
4266         /*runtime, icall and pinvoke are checked by summary call*/
4267         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4268             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4269             (mono_class_is_marshalbyref (method->klass)) ||
4270             header.has_clauses)
4271                 return FALSE;
4272
4273         /* also consider num_locals? */
4274         /* Do the size check early to avoid creating vtables */
4275         if (!inline_limit_inited) {
4276                 char *inlinelimit;
4277                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4278                         inline_limit = atoi (inlinelimit);
4279                         g_free (inlinelimit);
4280                 } else
4281                         inline_limit = INLINE_LENGTH_LIMIT;
4282                 inline_limit_inited = TRUE;
4283         }
4284         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4285                 return FALSE;
4286
4287         /*
4288          * if we can initialize the class of the method right away, we do,
4289          * otherwise we don't allow inlining if the class needs initialization,
4290          * since it would mean inserting a call to mono_runtime_class_init()
4291          * inside the inlined code
4292          */
4293         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4294                 return FALSE;
4295
4296         if (!(cfg->opt & MONO_OPT_SHARED)) {
4297                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4298                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4299                         if (method->klass->has_cctor) {
4300                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4301                                 if (!vtable)
4302                                         return FALSE;
4303                                 if (!cfg->compile_aot) {
4304                                         MonoError error;
4305                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4306                                                 mono_error_cleanup (&error);
4307                                                 return FALSE;
4308                                         }
4309                                 }
4310                         }
4311                 } else if (mono_class_is_before_field_init (method->klass)) {
4312                         if (cfg->run_cctors && method->klass->has_cctor) {
4313                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4314                                 if (!method->klass->runtime_info)
4315                                         /* No vtable created yet */
4316                                         return FALSE;
4317                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4318                                 if (!vtable)
4319                                         return FALSE;
4320                                 /* This makes so that inline cannot trigger */
4321                                 /* .cctors: too many apps depend on them */
4322                                 /* running with a specific order... */
4323                                 if (! vtable->initialized)
4324                                         return FALSE;
4325                                 MonoError error;
4326                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4327                                         mono_error_cleanup (&error);
4328                                         return FALSE;
4329                                 }
4330                         }
4331                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4332                         if (!method->klass->runtime_info)
4333                                 /* No vtable created yet */
4334                                 return FALSE;
4335                         vtable = mono_class_vtable (cfg->domain, method->klass);
4336                         if (!vtable)
4337                                 return FALSE;
4338                         if (!vtable->initialized)
4339                                 return FALSE;
4340                 }
4341         } else {
4342                 /* 
4343                  * If we're compiling for shared code
4344                  * the cctor will need to be run at aot method load time, for example,
4345                  * or at the end of the compilation of the inlining method.
4346                  */
4347                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4348                         return FALSE;
4349         }
4350
4351 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4352         if (mono_arch_is_soft_float ()) {
4353                 /* FIXME: */
4354                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4355                         return FALSE;
4356                 for (i = 0; i < sig->param_count; ++i)
4357                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4358                                 return FALSE;
4359         }
4360 #endif
4361
4362         if (g_list_find (cfg->dont_inline, method))
4363                 return FALSE;
4364
4365         return TRUE;
4366 }
4367
4368 static gboolean
4369 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4370 {
4371         if (!cfg->compile_aot) {
4372                 g_assert (vtable);
4373                 if (vtable->initialized)
4374                         return FALSE;
4375         }
4376
4377         if (mono_class_is_before_field_init (klass)) {
4378                 if (cfg->method == method)
4379                         return FALSE;
4380         }
4381
4382         if (!mono_class_needs_cctor_run (klass, method))
4383                 return FALSE;
4384
4385         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4386                 /* The initialization is already done before the method is called */
4387                 return FALSE;
4388
4389         return TRUE;
4390 }
4391
4392 MonoInst*
4393 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4394 {
4395         MonoInst *ins;
4396         guint32 size;
4397         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4398         int context_used;
4399
4400         if (mini_is_gsharedvt_variable_klass (klass)) {
4401                 size = -1;
4402         } else {
4403                 mono_class_init (klass);
4404                 size = mono_class_array_element_size (klass);
4405         }
4406
4407         mult_reg = alloc_preg (cfg);
4408         array_reg = arr->dreg;
4409         index_reg = index->dreg;
4410
4411 #if SIZEOF_REGISTER == 8
4412         /* The array reg is 64 bits but the index reg is only 32 */
4413         if (COMPILE_LLVM (cfg)) {
4414                 /*
4415                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4416                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4417                  * of OP_X86_LEA for llvm.
4418                  */
4419                 index2_reg = index_reg;
4420         } else {
4421                 index2_reg = alloc_preg (cfg);
4422                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4423         }
4424 #else
4425         if (index->type == STACK_I8) {
4426                 index2_reg = alloc_preg (cfg);
4427                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4428         } else {
4429                 index2_reg = index_reg;
4430         }
4431 #endif
4432
4433         if (bcheck)
4434                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4435
4436 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4437         if (size == 1 || size == 2 || size == 4 || size == 8) {
4438                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4439
4440                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4441                 ins->klass = mono_class_get_element_class (klass);
4442                 ins->type = STACK_MP;
4443
4444                 return ins;
4445         }
4446 #endif          
4447
4448         add_reg = alloc_ireg_mp (cfg);
4449
4450         if (size == -1) {
4451                 MonoInst *rgctx_ins;
4452
4453                 /* gsharedvt */
4454                 g_assert (cfg->gshared);
4455                 context_used = mini_class_check_context_used (cfg, klass);
4456                 g_assert (context_used);
4457                 rgctx_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4458                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4459         } else {
4460                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4461         }
4462         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4463         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4464         ins->klass = mono_class_get_element_class (klass);
4465         ins->type = STACK_MP;
4466         MONO_ADD_INS (cfg->cbb, ins);
4467
4468         return ins;
4469 }
4470
4471 static MonoInst*
4472 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4473 {
4474         int bounds_reg = alloc_preg (cfg);
4475         int add_reg = alloc_ireg_mp (cfg);
4476         int mult_reg = alloc_preg (cfg);
4477         int mult2_reg = alloc_preg (cfg);
4478         int low1_reg = alloc_preg (cfg);
4479         int low2_reg = alloc_preg (cfg);
4480         int high1_reg = alloc_preg (cfg);
4481         int high2_reg = alloc_preg (cfg);
4482         int realidx1_reg = alloc_preg (cfg);
4483         int realidx2_reg = alloc_preg (cfg);
4484         int sum_reg = alloc_preg (cfg);
4485         int index1, index2, tmpreg;
4486         MonoInst *ins;
4487         guint32 size;
4488
4489         mono_class_init (klass);
4490         size = mono_class_array_element_size (klass);
4491
4492         index1 = index_ins1->dreg;
4493         index2 = index_ins2->dreg;
4494
4495 #if SIZEOF_REGISTER == 8
4496         /* The array reg is 64 bits but the index reg is only 32 */
4497         if (COMPILE_LLVM (cfg)) {
4498                 /* Not needed */
4499         } else {
4500                 tmpreg = alloc_preg (cfg);
4501                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4502                 index1 = tmpreg;
4503                 tmpreg = alloc_preg (cfg);
4504                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4505                 index2 = tmpreg;
4506         }
4507 #else
4508         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4509         tmpreg = -1;
4510 #endif
4511
4512         /* range checking */
4513         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4514                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4515
4516         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4517                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4518         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4519         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4520                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4521         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4522         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4523
4524         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4525                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4526         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4527         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4528                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4529         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4530         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4531
4532         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4533         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4534         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4535         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4536         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4537
4538         ins->type = STACK_MP;
4539         ins->klass = klass;
4540         MONO_ADD_INS (cfg->cbb, ins);
4541
4542         return ins;
4543 }
4544
4545 static MonoInst*
4546 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4547 {
4548         int rank;
4549         MonoInst *addr;
4550         MonoMethod *addr_method;
4551         int element_size;
4552         MonoClass *eclass = cmethod->klass->element_class;
4553
4554         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4555
4556         if (rank == 1)
4557                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4558
4559         /* emit_ldelema_2 depends on OP_LMUL */
4560         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4561                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4562         }
4563
4564         if (mini_is_gsharedvt_variable_klass (eclass))
4565                 element_size = 0;
4566         else
4567                 element_size = mono_class_array_element_size (eclass);
4568         addr_method = mono_marshal_get_array_address (rank, element_size);
4569         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4570
4571         return addr;
4572 }
4573
4574 static MonoBreakPolicy
4575 always_insert_breakpoint (MonoMethod *method)
4576 {
4577         return MONO_BREAK_POLICY_ALWAYS;
4578 }
4579
4580 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
4581
4582 /**
4583  * mono_set_break_policy:
4584  * \param policy_callback the new callback function
4585  *
4586  * Allow embedders to decide wherther to actually obey breakpoint instructions
4587  * (both break IL instructions and \c Debugger.Break method calls), for example
4588  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
4589  * untrusted or semi-trusted code.
4590  *
4591  * \p policy_callback will be called every time a break point instruction needs to
4592  * be inserted with the method argument being the method that calls \c Debugger.Break
4593  * or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
4594  * if it wants the breakpoint to not be effective in the given method.
4595  * \c MONO_BREAK_POLICY_ALWAYS is the default.
4596  */
4597 void
4598 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
4599 {
4600         if (policy_callback)
4601                 break_policy_func = policy_callback;
4602         else
4603                 break_policy_func = always_insert_breakpoint;
4604 }
4605
4606 static gboolean
4607 should_insert_brekpoint (MonoMethod *method) {
4608         switch (break_policy_func (method)) {
4609         case MONO_BREAK_POLICY_ALWAYS:
4610                 return TRUE;
4611         case MONO_BREAK_POLICY_NEVER:
4612                 return FALSE;
4613         case MONO_BREAK_POLICY_ON_DBG:
4614                 g_warning ("mdb no longer supported");
4615                 return FALSE;
4616         default:
4617                 g_warning ("Incorrect value returned from break policy callback");
4618                 return FALSE;
4619         }
4620 }
4621
4622 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4623 static MonoInst*
4624 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4625 {
4626         MonoInst *addr, *store, *load;
4627         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4628
4629         /* the bounds check is already done by the callers */
4630         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4631         if (is_set) {
4632                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4633                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4634                 if (mini_type_is_reference (&eklass->byval_arg))
4635                         mini_emit_write_barrier (cfg, addr, load);
4636         } else {
4637                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4638                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4639         }
4640         return store;
4641 }
4642
4643
4644 static gboolean
4645 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4646 {
4647         return mini_type_is_reference (&klass->byval_arg);
4648 }
4649
4650 static MonoInst*
4651 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4652 {
4653         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4654                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4655                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4656                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4657                 MonoInst *iargs [3];
4658
4659                 if (!helper->slot)
4660                         mono_class_setup_vtable (obj_array);
4661                 g_assert (helper->slot);
4662
4663                 if (sp [0]->type != STACK_OBJ)
4664                         return NULL;
4665                 if (sp [2]->type != STACK_OBJ)
4666                         return NULL;
4667
4668                 iargs [2] = sp [2];
4669                 iargs [1] = sp [1];
4670                 iargs [0] = sp [0];
4671
4672                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4673         } else {
4674                 MonoInst *ins;
4675
4676                 if (mini_is_gsharedvt_variable_klass (klass)) {
4677                         MonoInst *addr;
4678
4679                         // FIXME-VT: OP_ICONST optimization
4680                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4681                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4682                         ins->opcode = OP_STOREV_MEMBASE;
4683                 } else if (sp [1]->opcode == OP_ICONST) {
4684                         int array_reg = sp [0]->dreg;
4685                         int index_reg = sp [1]->dreg;
4686                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
4687
4688                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
4689                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
4690
4691                         if (safety_checks)
4692                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
4693                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
4694                 } else {
4695                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
4696                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4697                         if (generic_class_is_reference_type (cfg, klass))
4698                                 mini_emit_write_barrier (cfg, addr, sp [2]);
4699                 }
4700                 return ins;
4701         }
4702 }
4703
4704 static MonoInst*
4705 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4706 {
4707         MonoClass *eklass;
4708         
4709         if (is_set)
4710                 eklass = mono_class_from_mono_type (fsig->params [2]);
4711         else
4712                 eklass = mono_class_from_mono_type (fsig->ret);
4713
4714         if (is_set) {
4715                 return emit_array_store (cfg, eklass, args, FALSE);
4716         } else {
4717                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4718                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
4719                 return ins;
4720         }
4721 }
4722
4723 static gboolean
4724 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
4725 {
4726         uint32_t align;
4727         int param_size, return_size;
4728
4729         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
4730         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
4731
4732         if (cfg->verbose_level > 3)
4733                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
4734
4735         //Don't allow mixing reference types with value types
4736         if (param_klass->valuetype != return_klass->valuetype) {
4737                 if (cfg->verbose_level > 3)
4738                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
4739                 return FALSE;
4740         }
4741
4742         if (!param_klass->valuetype) {
4743                 if (cfg->verbose_level > 3)
4744                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
4745                 return TRUE;
4746         }
4747
4748         //That are blitable
4749         if (param_klass->has_references || return_klass->has_references)
4750                 return FALSE;
4751
4752         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
4753         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
4754                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
4755                         if (cfg->verbose_level > 3)
4756                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
4757                 return FALSE;
4758         }
4759
4760         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
4761                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
4762                 if (cfg->verbose_level > 3)
4763                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
4764                 return FALSE;
4765         }
4766
4767         param_size = mono_class_value_size (param_klass, &align);
4768         return_size = mono_class_value_size (return_klass, &align);
4769
4770         //We can do it if sizes match
4771         if (param_size == return_size) {
4772                 if (cfg->verbose_level > 3)
4773                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
4774                 return TRUE;
4775         }
4776
4777         //No simple way to handle struct if sizes don't match
4778         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
4779                 if (cfg->verbose_level > 3)
4780                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
4781                 return FALSE;
4782         }
4783
4784         /*
4785          * Same reg size category.
4786          * A quick note on why we don't require widening here.
4787          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
4788          *
4789          * Since the source value comes from a function argument, the JIT will already have
4790          * the value in a VREG and performed any widening needed before (say, when loading from a field).
4791          */
4792         if (param_size <= 4 && return_size <= 4) {
4793                 if (cfg->verbose_level > 3)
4794                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
4795                 return TRUE;
4796         }
4797
4798         return FALSE;
4799 }
4800
4801 static MonoInst*
4802 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
4803 {
4804         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
4805         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
4806
4807         if (mini_is_gsharedvt_variable_type (fsig->ret))
4808                 return NULL;
4809
4810         //Valuetypes that are semantically equivalent or numbers than can be widened to
4811         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
4812                 return args [0];
4813
4814         //Arrays of valuetypes that are semantically equivalent
4815         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
4816                 return args [0];
4817
4818         return NULL;
4819 }
4820
4821 static MonoInst*
4822 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4823 {
4824 #ifdef MONO_ARCH_SIMD_INTRINSICS
4825         MonoInst *ins = NULL;
4826
4827         if (cfg->opt & MONO_OPT_SIMD) {
4828                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
4829                 if (ins)
4830                         return ins;
4831         }
4832 #endif
4833
4834         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
4835 }
4836
4837 MonoInst*
4838 mini_emit_memory_barrier (MonoCompile *cfg, int kind)
4839 {
4840         MonoInst *ins = NULL;
4841         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
4842         MONO_ADD_INS (cfg->cbb, ins);
4843         ins->backend.memory_barrier_kind = kind;
4844
4845         return ins;
4846 }
4847
4848 static MonoInst*
4849 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4850 {
4851         MonoInst *ins = NULL;
4852         int opcode = 0;
4853
4854         /* The LLVM backend supports these intrinsics */
4855         if (cmethod->klass == mono_defaults.math_class) {
4856                 if (strcmp (cmethod->name, "Sin") == 0) {
4857                         opcode = OP_SIN;
4858                 } else if (strcmp (cmethod->name, "Cos") == 0) {
4859                         opcode = OP_COS;
4860                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
4861                         opcode = OP_SQRT;
4862                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
4863                         opcode = OP_ABS;
4864                 }
4865
4866                 if (opcode && fsig->param_count == 1) {
4867                         MONO_INST_NEW (cfg, ins, opcode);
4868                         ins->type = STACK_R8;
4869                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4870                         ins->sreg1 = args [0]->dreg;
4871                         MONO_ADD_INS (cfg->cbb, ins);
4872                 }
4873
4874                 opcode = 0;
4875                 if (cfg->opt & MONO_OPT_CMOV) {
4876                         if (strcmp (cmethod->name, "Min") == 0) {
4877                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4878                                         opcode = OP_IMIN;
4879                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4880                                         opcode = OP_IMIN_UN;
4881                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4882                                         opcode = OP_LMIN;
4883                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4884                                         opcode = OP_LMIN_UN;
4885                         } else if (strcmp (cmethod->name, "Max") == 0) {
4886                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4887                                         opcode = OP_IMAX;
4888                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4889                                         opcode = OP_IMAX_UN;
4890                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4891                                         opcode = OP_LMAX;
4892                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4893                                         opcode = OP_LMAX_UN;
4894                         }
4895                 }
4896
4897                 if (opcode && fsig->param_count == 2) {
4898                         MONO_INST_NEW (cfg, ins, opcode);
4899                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
4900                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4901                         ins->sreg1 = args [0]->dreg;
4902                         ins->sreg2 = args [1]->dreg;
4903                         MONO_ADD_INS (cfg->cbb, ins);
4904                 }
4905         }
4906
4907         return ins;
4908 }
4909
4910 static MonoInst*
4911 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4912 {
4913         if (cmethod->klass == mono_defaults.array_class) {
4914                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
4915                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
4916                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
4917                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
4918                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
4919                         return emit_array_unsafe_mov (cfg, fsig, args);
4920         }
4921
4922         return NULL;
4923 }
4924
4925 static MonoInst*
4926 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4927 {
4928         MonoInst *ins = NULL;
4929         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
4930
4931         if (cmethod->klass == mono_defaults.string_class) {
4932                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
4933                         int dreg = alloc_ireg (cfg);
4934                         int index_reg = alloc_preg (cfg);
4935                         int add_reg = alloc_preg (cfg);
4936
4937 #if SIZEOF_REGISTER == 8
4938                         if (COMPILE_LLVM (cfg)) {
4939                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
4940                         } else {
4941                                 /* The array reg is 64 bits but the index reg is only 32 */
4942                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
4943                         }
4944 #else
4945                         index_reg = args [1]->dreg;
4946 #endif  
4947                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
4948
4949 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4950                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
4951                         add_reg = ins->dreg;
4952                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4953                                                                    add_reg, 0);
4954 #else
4955                         int mult_reg = alloc_preg (cfg);
4956                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
4957                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
4958                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4959                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
4960 #endif
4961                         type_from_op (cfg, ins, NULL, NULL);
4962                         return ins;
4963                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
4964                         int dreg = alloc_ireg (cfg);
4965                         /* Decompose later to allow more optimizations */
4966                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
4967                         ins->type = STACK_I4;
4968                         ins->flags |= MONO_INST_FAULT;
4969                         cfg->cbb->has_array_access = TRUE;
4970                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
4971
4972                         return ins;
4973                 } else 
4974                         return NULL;
4975         } else if (cmethod->klass == mono_defaults.object_class) {
4976                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
4977                         int dreg = alloc_ireg_ref (cfg);
4978                         int vt_reg = alloc_preg (cfg);
4979                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4980                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
4981                         type_from_op (cfg, ins, NULL, NULL);
4982
4983                         return ins;
4984                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
4985                         int dreg = alloc_ireg (cfg);
4986                         int t1 = alloc_ireg (cfg);
4987         
4988                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
4989                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
4990                         ins->type = STACK_I4;
4991
4992                         return ins;
4993                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
4994                         MONO_INST_NEW (cfg, ins, OP_NOP);
4995                         MONO_ADD_INS (cfg->cbb, ins);
4996                         return ins;
4997                 } else
4998                         return NULL;
4999         } else if (cmethod->klass == mono_defaults.array_class) {
5000                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5001                         return emit_array_generic_access (cfg, fsig, args, FALSE);
5002                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5003                         return emit_array_generic_access (cfg, fsig, args, TRUE);
5004
5005 #ifndef MONO_BIG_ARRAYS
5006                 /*
5007                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
5008                  * Array methods.
5009                  */
5010                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
5011                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
5012                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
5013                         int dreg = alloc_ireg (cfg);
5014                         int bounds_reg = alloc_ireg_mp (cfg);
5015                         MonoBasicBlock *end_bb, *szarray_bb;
5016                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
5017
5018                         NEW_BBLOCK (cfg, end_bb);
5019                         NEW_BBLOCK (cfg, szarray_bb);
5020
5021                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
5022                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5023                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5024                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5025                         /* Non-szarray case */
5026                         if (get_length)
5027                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5028                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5029                         else
5030                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5031                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5032                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5033                         MONO_START_BB (cfg, szarray_bb);
5034                         /* Szarray case */
5035                         if (get_length)
5036                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5037                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5038                         else
5039                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5040                         MONO_START_BB (cfg, end_bb);
5041
5042                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5043                         ins->type = STACK_I4;
5044                         
5045                         return ins;
5046                 }
5047 #endif
5048
5049                 if (cmethod->name [0] != 'g')
5050                         return NULL;
5051
5052                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5053                         int dreg = alloc_ireg (cfg);
5054                         int vtable_reg = alloc_preg (cfg);
5055                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5056                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5057                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5058                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5059                         type_from_op (cfg, ins, NULL, NULL);
5060
5061                         return ins;
5062                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5063                         int dreg = alloc_ireg (cfg);
5064
5065                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5066                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5067                         type_from_op (cfg, ins, NULL, NULL);
5068
5069                         return ins;
5070                 } else
5071                         return NULL;
5072         } else if (cmethod->klass == runtime_helpers_class) {
5073                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5074                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5075                         return ins;
5076                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5077                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5078                         g_assert (ctx);
5079                         g_assert (ctx->method_inst);
5080                         g_assert (ctx->method_inst->type_argc == 1);
5081                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5082                         MonoClass *klass = mono_class_from_mono_type (t);
5083
5084                         ins = NULL;
5085
5086                         mono_class_init (klass);
5087                         if (MONO_TYPE_IS_REFERENCE (t))
5088                                 EMIT_NEW_ICONST (cfg, ins, 1);
5089                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5090                                 EMIT_NEW_ICONST (cfg, ins, 0);
5091                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5092                                 EMIT_NEW_ICONST (cfg, ins, 1);
5093                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5094                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5095                         else {
5096                                 g_assert (cfg->gshared);
5097
5098                                 int context_used = mini_class_check_context_used (cfg, klass);
5099
5100                                 /* This returns 1 or 2 */
5101                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5102                                 int dreg = alloc_ireg (cfg);
5103                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5104                         }
5105
5106                         return ins;
5107                 } else
5108                         return NULL;
5109         } else if (cmethod->klass == mono_defaults.monitor_class) {
5110                 gboolean is_enter = FALSE;
5111                 gboolean is_v4 = FALSE;
5112
5113                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5114                         is_enter = TRUE;
5115                         is_v4 = TRUE;
5116                 }
5117                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5118                         is_enter = TRUE;
5119
5120                 if (is_enter) {
5121                         /*
5122                          * To make async stack traces work, icalls which can block should have a wrapper.
5123                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5124                          */
5125                         MonoBasicBlock *end_bb;
5126
5127                         NEW_BBLOCK (cfg, end_bb);
5128
5129                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5130                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5131                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5132                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5133                         MONO_START_BB (cfg, end_bb);
5134                         return ins;
5135                 }
5136         } else if (cmethod->klass == mono_defaults.thread_class) {
5137                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5138                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5139                         MONO_ADD_INS (cfg->cbb, ins);
5140                         return ins;
5141                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5142                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5143                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5144                         guint32 opcode = 0;
5145                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5146
5147                         if (fsig->params [0]->type == MONO_TYPE_I1)
5148                                 opcode = OP_LOADI1_MEMBASE;
5149                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5150                                 opcode = OP_LOADU1_MEMBASE;
5151                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5152                                 opcode = OP_LOADI2_MEMBASE;
5153                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5154                                 opcode = OP_LOADU2_MEMBASE;
5155                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5156                                 opcode = OP_LOADI4_MEMBASE;
5157                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5158                                 opcode = OP_LOADU4_MEMBASE;
5159                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5160                                 opcode = OP_LOADI8_MEMBASE;
5161                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5162                                 opcode = OP_LOADR4_MEMBASE;
5163                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5164                                 opcode = OP_LOADR8_MEMBASE;
5165                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5166                                 opcode = OP_LOAD_MEMBASE;
5167
5168                         if (opcode) {
5169                                 MONO_INST_NEW (cfg, ins, opcode);
5170                                 ins->inst_basereg = args [0]->dreg;
5171                                 ins->inst_offset = 0;
5172                                 MONO_ADD_INS (cfg->cbb, ins);
5173
5174                                 switch (fsig->params [0]->type) {
5175                                 case MONO_TYPE_I1:
5176                                 case MONO_TYPE_U1:
5177                                 case MONO_TYPE_I2:
5178                                 case MONO_TYPE_U2:
5179                                 case MONO_TYPE_I4:
5180                                 case MONO_TYPE_U4:
5181                                         ins->dreg = mono_alloc_ireg (cfg);
5182                                         ins->type = STACK_I4;
5183                                         break;
5184                                 case MONO_TYPE_I8:
5185                                 case MONO_TYPE_U8:
5186                                         ins->dreg = mono_alloc_lreg (cfg);
5187                                         ins->type = STACK_I8;
5188                                         break;
5189                                 case MONO_TYPE_I:
5190                                 case MONO_TYPE_U:
5191                                         ins->dreg = mono_alloc_ireg (cfg);
5192 #if SIZEOF_REGISTER == 8
5193                                         ins->type = STACK_I8;
5194 #else
5195                                         ins->type = STACK_I4;
5196 #endif
5197                                         break;
5198                                 case MONO_TYPE_R4:
5199                                 case MONO_TYPE_R8:
5200                                         ins->dreg = mono_alloc_freg (cfg);
5201                                         ins->type = STACK_R8;
5202                                         break;
5203                                 default:
5204                                         g_assert (mini_type_is_reference (fsig->params [0]));
5205                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5206                                         ins->type = STACK_OBJ;
5207                                         break;
5208                                 }
5209
5210                                 if (opcode == OP_LOADI8_MEMBASE)
5211                                         ins = mono_decompose_opcode (cfg, ins);
5212
5213                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5214
5215                                 return ins;
5216                         }
5217                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5218                         guint32 opcode = 0;
5219                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5220
5221                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5222                                 opcode = OP_STOREI1_MEMBASE_REG;
5223                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5224                                 opcode = OP_STOREI2_MEMBASE_REG;
5225                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5226                                 opcode = OP_STOREI4_MEMBASE_REG;
5227                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5228                                 opcode = OP_STOREI8_MEMBASE_REG;
5229                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5230                                 opcode = OP_STORER4_MEMBASE_REG;
5231                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5232                                 opcode = OP_STORER8_MEMBASE_REG;
5233                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5234                                 opcode = OP_STORE_MEMBASE_REG;
5235
5236                         if (opcode) {
5237                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5238
5239                                 MONO_INST_NEW (cfg, ins, opcode);
5240                                 ins->sreg1 = args [1]->dreg;
5241                                 ins->inst_destbasereg = args [0]->dreg;
5242                                 ins->inst_offset = 0;
5243                                 MONO_ADD_INS (cfg->cbb, ins);
5244
5245                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5246                                         ins = mono_decompose_opcode (cfg, ins);
5247
5248                                 return ins;
5249                         }
5250                 }
5251         } else if (cmethod->klass->image == mono_defaults.corlib &&
5252                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5253                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5254                 ins = NULL;
5255
5256 #if SIZEOF_REGISTER == 8
5257                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5258                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5259                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5260                                 ins->dreg = mono_alloc_preg (cfg);
5261                                 ins->sreg1 = args [0]->dreg;
5262                                 ins->type = STACK_I8;
5263                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5264                                 MONO_ADD_INS (cfg->cbb, ins);
5265                         } else {
5266                                 MonoInst *load_ins;
5267
5268                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5269
5270                                 /* 64 bit reads are already atomic */
5271                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5272                                 load_ins->dreg = mono_alloc_preg (cfg);
5273                                 load_ins->inst_basereg = args [0]->dreg;
5274                                 load_ins->inst_offset = 0;
5275                                 load_ins->type = STACK_I8;
5276                                 MONO_ADD_INS (cfg->cbb, load_ins);
5277
5278                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5279
5280                                 ins = load_ins;
5281                         }
5282                 }
5283 #endif
5284
5285                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5286                         MonoInst *ins_iconst;
5287                         guint32 opcode = 0;
5288
5289                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5290                                 opcode = OP_ATOMIC_ADD_I4;
5291                                 cfg->has_atomic_add_i4 = TRUE;
5292                         }
5293 #if SIZEOF_REGISTER == 8
5294                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5295                                 opcode = OP_ATOMIC_ADD_I8;
5296 #endif
5297                         if (opcode) {
5298                                 if (!mono_arch_opcode_supported (opcode))
5299                                         return NULL;
5300                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5301                                 ins_iconst->inst_c0 = 1;
5302                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5303                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5304
5305                                 MONO_INST_NEW (cfg, ins, opcode);
5306                                 ins->dreg = mono_alloc_ireg (cfg);
5307                                 ins->inst_basereg = args [0]->dreg;
5308                                 ins->inst_offset = 0;
5309                                 ins->sreg2 = ins_iconst->dreg;
5310                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5311                                 MONO_ADD_INS (cfg->cbb, ins);
5312                         }
5313                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5314                         MonoInst *ins_iconst;
5315                         guint32 opcode = 0;
5316
5317                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5318                                 opcode = OP_ATOMIC_ADD_I4;
5319                                 cfg->has_atomic_add_i4 = TRUE;
5320                         }
5321 #if SIZEOF_REGISTER == 8
5322                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5323                                 opcode = OP_ATOMIC_ADD_I8;
5324 #endif
5325                         if (opcode) {
5326                                 if (!mono_arch_opcode_supported (opcode))
5327                                         return NULL;
5328                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5329                                 ins_iconst->inst_c0 = -1;
5330                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5331                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5332
5333                                 MONO_INST_NEW (cfg, ins, opcode);
5334                                 ins->dreg = mono_alloc_ireg (cfg);
5335                                 ins->inst_basereg = args [0]->dreg;
5336                                 ins->inst_offset = 0;
5337                                 ins->sreg2 = ins_iconst->dreg;
5338                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5339                                 MONO_ADD_INS (cfg->cbb, ins);
5340                         }
5341                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5342                         guint32 opcode = 0;
5343
5344                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5345                                 opcode = OP_ATOMIC_ADD_I4;
5346                                 cfg->has_atomic_add_i4 = TRUE;
5347                         }
5348 #if SIZEOF_REGISTER == 8
5349                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5350                                 opcode = OP_ATOMIC_ADD_I8;
5351 #endif
5352                         if (opcode) {
5353                                 if (!mono_arch_opcode_supported (opcode))
5354                                         return NULL;
5355                                 MONO_INST_NEW (cfg, ins, opcode);
5356                                 ins->dreg = mono_alloc_ireg (cfg);
5357                                 ins->inst_basereg = args [0]->dreg;
5358                                 ins->inst_offset = 0;
5359                                 ins->sreg2 = args [1]->dreg;
5360                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5361                                 MONO_ADD_INS (cfg->cbb, ins);
5362                         }
5363                 }
5364                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5365                         MonoInst *f2i = NULL, *i2f;
5366                         guint32 opcode, f2i_opcode, i2f_opcode;
5367                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5368                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5369
5370                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5371                             fsig->params [0]->type == MONO_TYPE_R4) {
5372                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5373                                 f2i_opcode = OP_MOVE_F_TO_I4;
5374                                 i2f_opcode = OP_MOVE_I4_TO_F;
5375                                 cfg->has_atomic_exchange_i4 = TRUE;
5376                         }
5377 #if SIZEOF_REGISTER == 8
5378                         else if (is_ref ||
5379                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5380                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5381                                  fsig->params [0]->type == MONO_TYPE_I) {
5382                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5383                                 f2i_opcode = OP_MOVE_F_TO_I8;
5384                                 i2f_opcode = OP_MOVE_I8_TO_F;
5385                         }
5386 #else
5387                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5388                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5389                                 cfg->has_atomic_exchange_i4 = TRUE;
5390                         }
5391 #endif
5392                         else
5393                                 return NULL;
5394
5395                         if (!mono_arch_opcode_supported (opcode))
5396                                 return NULL;
5397
5398                         if (is_float) {
5399                                 /* TODO: Decompose these opcodes instead of bailing here. */
5400                                 if (COMPILE_SOFT_FLOAT (cfg))
5401                                         return NULL;
5402
5403                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5404                                 f2i->dreg = mono_alloc_ireg (cfg);
5405                                 f2i->sreg1 = args [1]->dreg;
5406                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5407                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5408                                 MONO_ADD_INS (cfg->cbb, f2i);
5409                         }
5410
5411                         MONO_INST_NEW (cfg, ins, opcode);
5412                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5413                         ins->inst_basereg = args [0]->dreg;
5414                         ins->inst_offset = 0;
5415                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5416                         MONO_ADD_INS (cfg->cbb, ins);
5417
5418                         switch (fsig->params [0]->type) {
5419                         case MONO_TYPE_I4:
5420                                 ins->type = STACK_I4;
5421                                 break;
5422                         case MONO_TYPE_I8:
5423                                 ins->type = STACK_I8;
5424                                 break;
5425                         case MONO_TYPE_I:
5426 #if SIZEOF_REGISTER == 8
5427                                 ins->type = STACK_I8;
5428 #else
5429                                 ins->type = STACK_I4;
5430 #endif
5431                                 break;
5432                         case MONO_TYPE_R4:
5433                         case MONO_TYPE_R8:
5434                                 ins->type = STACK_R8;
5435                                 break;
5436                         default:
5437                                 g_assert (mini_type_is_reference (fsig->params [0]));
5438                                 ins->type = STACK_OBJ;
5439                                 break;
5440                         }
5441
5442                         if (is_float) {
5443                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5444                                 i2f->dreg = mono_alloc_freg (cfg);
5445                                 i2f->sreg1 = ins->dreg;
5446                                 i2f->type = STACK_R8;
5447                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5448                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5449                                 MONO_ADD_INS (cfg->cbb, i2f);
5450
5451                                 ins = i2f;
5452                         }
5453
5454                         if (cfg->gen_write_barriers && is_ref)
5455                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5456                 }
5457                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5458                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5459                         guint32 opcode, f2i_opcode, i2f_opcode;
5460                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5461                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5462
5463                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5464                             fsig->params [1]->type == MONO_TYPE_R4) {
5465                                 opcode = OP_ATOMIC_CAS_I4;
5466                                 f2i_opcode = OP_MOVE_F_TO_I4;
5467                                 i2f_opcode = OP_MOVE_I4_TO_F;
5468                                 cfg->has_atomic_cas_i4 = TRUE;
5469                         }
5470 #if SIZEOF_REGISTER == 8
5471                         else if (is_ref ||
5472                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5473                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5474                                  fsig->params [1]->type == MONO_TYPE_I) {
5475                                 opcode = OP_ATOMIC_CAS_I8;
5476                                 f2i_opcode = OP_MOVE_F_TO_I8;
5477                                 i2f_opcode = OP_MOVE_I8_TO_F;
5478                         }
5479 #else
5480                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5481                                 opcode = OP_ATOMIC_CAS_I4;
5482                                 cfg->has_atomic_cas_i4 = TRUE;
5483                         }
5484 #endif
5485                         else
5486                                 return NULL;
5487
5488                         if (!mono_arch_opcode_supported (opcode))
5489                                 return NULL;
5490
5491                         if (is_float) {
5492                                 /* TODO: Decompose these opcodes instead of bailing here. */
5493                                 if (COMPILE_SOFT_FLOAT (cfg))
5494                                         return NULL;
5495
5496                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5497                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5498                                 f2i_new->sreg1 = args [1]->dreg;
5499                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5500                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5501                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5502
5503                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5504                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5505                                 f2i_cmp->sreg1 = args [2]->dreg;
5506                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5507                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5508                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5509                         }
5510
5511                         MONO_INST_NEW (cfg, ins, opcode);
5512                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5513                         ins->sreg1 = args [0]->dreg;
5514                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5515                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5516                         MONO_ADD_INS (cfg->cbb, ins);
5517
5518                         switch (fsig->params [1]->type) {
5519                         case MONO_TYPE_I4:
5520                                 ins->type = STACK_I4;
5521                                 break;
5522                         case MONO_TYPE_I8:
5523                                 ins->type = STACK_I8;
5524                                 break;
5525                         case MONO_TYPE_I:
5526 #if SIZEOF_REGISTER == 8
5527                                 ins->type = STACK_I8;
5528 #else
5529                                 ins->type = STACK_I4;
5530 #endif
5531                                 break;
5532                         case MONO_TYPE_R4:
5533                                 ins->type = cfg->r4_stack_type;
5534                                 break;
5535                         case MONO_TYPE_R8:
5536                                 ins->type = STACK_R8;
5537                                 break;
5538                         default:
5539                                 g_assert (mini_type_is_reference (fsig->params [1]));
5540                                 ins->type = STACK_OBJ;
5541                                 break;
5542                         }
5543
5544                         if (is_float) {
5545                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5546                                 i2f->dreg = mono_alloc_freg (cfg);
5547                                 i2f->sreg1 = ins->dreg;
5548                                 i2f->type = STACK_R8;
5549                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5550                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5551                                 MONO_ADD_INS (cfg->cbb, i2f);
5552
5553                                 ins = i2f;
5554                         }
5555
5556                         if (cfg->gen_write_barriers && is_ref)
5557                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5558                 }
5559                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5560                          fsig->params [1]->type == MONO_TYPE_I4) {
5561                         MonoInst *cmp, *ceq;
5562
5563                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5564                                 return NULL;
5565
5566                         /* int32 r = CAS (location, value, comparand); */
5567                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5568                         ins->dreg = alloc_ireg (cfg);
5569                         ins->sreg1 = args [0]->dreg;
5570                         ins->sreg2 = args [1]->dreg;
5571                         ins->sreg3 = args [2]->dreg;
5572                         ins->type = STACK_I4;
5573                         MONO_ADD_INS (cfg->cbb, ins);
5574
5575                         /* bool result = r == comparand; */
5576                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5577                         cmp->sreg1 = ins->dreg;
5578                         cmp->sreg2 = args [2]->dreg;
5579                         cmp->type = STACK_I4;
5580                         MONO_ADD_INS (cfg->cbb, cmp);
5581
5582                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5583                         ceq->dreg = alloc_ireg (cfg);
5584                         ceq->type = STACK_I4;
5585                         MONO_ADD_INS (cfg->cbb, ceq);
5586
5587                         /* *success = result; */
5588                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5589
5590                         cfg->has_atomic_cas_i4 = TRUE;
5591                 }
5592                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5593                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5594
5595                 if (ins)
5596                         return ins;
5597         } else if (cmethod->klass->image == mono_defaults.corlib &&
5598                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5599                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5600                 ins = NULL;
5601
5602                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5603                         guint32 opcode = 0;
5604                         MonoType *t = fsig->params [0];
5605                         gboolean is_ref;
5606                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5607
5608                         g_assert (t->byref);
5609                         /* t is a byref type, so the reference check is more complicated */
5610                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5611                         if (t->type == MONO_TYPE_I1)
5612                                 opcode = OP_ATOMIC_LOAD_I1;
5613                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5614                                 opcode = OP_ATOMIC_LOAD_U1;
5615                         else if (t->type == MONO_TYPE_I2)
5616                                 opcode = OP_ATOMIC_LOAD_I2;
5617                         else if (t->type == MONO_TYPE_U2)
5618                                 opcode = OP_ATOMIC_LOAD_U2;
5619                         else if (t->type == MONO_TYPE_I4)
5620                                 opcode = OP_ATOMIC_LOAD_I4;
5621                         else if (t->type == MONO_TYPE_U4)
5622                                 opcode = OP_ATOMIC_LOAD_U4;
5623                         else if (t->type == MONO_TYPE_R4)
5624                                 opcode = OP_ATOMIC_LOAD_R4;
5625                         else if (t->type == MONO_TYPE_R8)
5626                                 opcode = OP_ATOMIC_LOAD_R8;
5627 #if SIZEOF_REGISTER == 8
5628                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5629                                 opcode = OP_ATOMIC_LOAD_I8;
5630                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5631                                 opcode = OP_ATOMIC_LOAD_U8;
5632 #else
5633                         else if (t->type == MONO_TYPE_I)
5634                                 opcode = OP_ATOMIC_LOAD_I4;
5635                         else if (is_ref || t->type == MONO_TYPE_U)
5636                                 opcode = OP_ATOMIC_LOAD_U4;
5637 #endif
5638
5639                         if (opcode) {
5640                                 if (!mono_arch_opcode_supported (opcode))
5641                                         return NULL;
5642
5643                                 MONO_INST_NEW (cfg, ins, opcode);
5644                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5645                                 ins->sreg1 = args [0]->dreg;
5646                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5647                                 MONO_ADD_INS (cfg->cbb, ins);
5648
5649                                 switch (t->type) {
5650                                 case MONO_TYPE_BOOLEAN:
5651                                 case MONO_TYPE_I1:
5652                                 case MONO_TYPE_U1:
5653                                 case MONO_TYPE_I2:
5654                                 case MONO_TYPE_U2:
5655                                 case MONO_TYPE_I4:
5656                                 case MONO_TYPE_U4:
5657                                         ins->type = STACK_I4;
5658                                         break;
5659                                 case MONO_TYPE_I8:
5660                                 case MONO_TYPE_U8:
5661                                         ins->type = STACK_I8;
5662                                         break;
5663                                 case MONO_TYPE_I:
5664                                 case MONO_TYPE_U:
5665 #if SIZEOF_REGISTER == 8
5666                                         ins->type = STACK_I8;
5667 #else
5668                                         ins->type = STACK_I4;
5669 #endif
5670                                         break;
5671                                 case MONO_TYPE_R4:
5672                                         ins->type = cfg->r4_stack_type;
5673                                         break;
5674                                 case MONO_TYPE_R8:
5675                                         ins->type = STACK_R8;
5676                                         break;
5677                                 default:
5678                                         g_assert (is_ref);
5679                                         ins->type = STACK_OBJ;
5680                                         break;
5681                                 }
5682                         }
5683                 }
5684
5685                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5686                         guint32 opcode = 0;
5687                         MonoType *t = fsig->params [0];
5688                         gboolean is_ref;
5689
5690                         g_assert (t->byref);
5691                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5692                         if (t->type == MONO_TYPE_I1)
5693                                 opcode = OP_ATOMIC_STORE_I1;
5694                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5695                                 opcode = OP_ATOMIC_STORE_U1;
5696                         else if (t->type == MONO_TYPE_I2)
5697                                 opcode = OP_ATOMIC_STORE_I2;
5698                         else if (t->type == MONO_TYPE_U2)
5699                                 opcode = OP_ATOMIC_STORE_U2;
5700                         else if (t->type == MONO_TYPE_I4)
5701                                 opcode = OP_ATOMIC_STORE_I4;
5702                         else if (t->type == MONO_TYPE_U4)
5703                                 opcode = OP_ATOMIC_STORE_U4;
5704                         else if (t->type == MONO_TYPE_R4)
5705                                 opcode = OP_ATOMIC_STORE_R4;
5706                         else if (t->type == MONO_TYPE_R8)
5707                                 opcode = OP_ATOMIC_STORE_R8;
5708 #if SIZEOF_REGISTER == 8
5709                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5710                                 opcode = OP_ATOMIC_STORE_I8;
5711                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5712                                 opcode = OP_ATOMIC_STORE_U8;
5713 #else
5714                         else if (t->type == MONO_TYPE_I)
5715                                 opcode = OP_ATOMIC_STORE_I4;
5716                         else if (is_ref || t->type == MONO_TYPE_U)
5717                                 opcode = OP_ATOMIC_STORE_U4;
5718 #endif
5719
5720                         if (opcode) {
5721                                 if (!mono_arch_opcode_supported (opcode))
5722                                         return NULL;
5723
5724                                 MONO_INST_NEW (cfg, ins, opcode);
5725                                 ins->dreg = args [0]->dreg;
5726                                 ins->sreg1 = args [1]->dreg;
5727                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5728                                 MONO_ADD_INS (cfg->cbb, ins);
5729
5730                                 if (cfg->gen_write_barriers && is_ref)
5731                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5732                         }
5733                 }
5734
5735                 if (ins)
5736                         return ins;
5737         } else if (cmethod->klass->image == mono_defaults.corlib &&
5738                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5739                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5740                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5741                         if (should_insert_brekpoint (cfg->method)) {
5742                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5743                         } else {
5744                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5745                                 MONO_ADD_INS (cfg->cbb, ins);
5746                         }
5747                         return ins;
5748                 }
5749         } else if (cmethod->klass->image == mono_defaults.corlib &&
5750                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5751                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5752                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5753 #ifdef TARGET_WIN32
5754                         EMIT_NEW_ICONST (cfg, ins, 1);
5755 #else
5756                         EMIT_NEW_ICONST (cfg, ins, 0);
5757 #endif
5758                 }
5759         } else if (cmethod->klass->image == mono_defaults.corlib &&
5760                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5761                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5762                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5763                         /* No stack walks are currently available, so implement this as an intrinsic */
5764                         MonoInst *assembly_ins;
5765
5766                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5767                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5768                         return ins;
5769                 }
5770         } else if (cmethod->klass->image == mono_defaults.corlib &&
5771                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5772                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5773                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5774                         /* No stack walks are currently available, so implement this as an intrinsic */
5775                         MonoInst *method_ins;
5776                         MonoMethod *declaring = cfg->method;
5777
5778                         /* This returns the declaring generic method */
5779                         if (declaring->is_inflated)
5780                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5781                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5782                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
5783                         cfg->no_inline = TRUE;
5784                         if (cfg->method != cfg->current_method)
5785                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
5786                         return ins;
5787                 }
5788         } else if (cmethod->klass == mono_defaults.math_class) {
5789                 /* 
5790                  * There is general branchless code for Min/Max, but it does not work for 
5791                  * all inputs:
5792                  * http://everything2.com/?node_id=1051618
5793                  */
5794         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
5795                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
5796                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
5797                 ins->dreg = alloc_preg (cfg);
5798                 ins->type = STACK_I4;
5799                 MONO_ADD_INS (cfg->cbb, ins);
5800                 return ins;
5801         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
5802                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
5803                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
5804                                 !strcmp (cmethod->klass->name, "Selector")) ||
5805                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
5806                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
5807                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
5808                                 !strcmp (cmethod->klass->name, "Selector"))
5809                            ) {
5810                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
5811                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
5812                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
5813                     cfg->compile_aot) {
5814                         MonoInst *pi;
5815                         MonoJumpInfoToken *ji;
5816                         char *s;
5817
5818                         if (args [0]->opcode == OP_GOT_ENTRY) {
5819                                 pi = (MonoInst *)args [0]->inst_p1;
5820                                 g_assert (pi->opcode == OP_PATCH_INFO);
5821                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
5822                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
5823                         } else {
5824                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
5825                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
5826                         }
5827
5828                         NULLIFY_INS (args [0]);
5829
5830                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
5831                         return_val_if_nok (&cfg->error, NULL);
5832
5833                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
5834                         ins->dreg = mono_alloc_ireg (cfg);
5835                         // FIXME: Leaks
5836                         ins->inst_p0 = s;
5837                         MONO_ADD_INS (cfg->cbb, ins);
5838                         return ins;
5839                 }
5840         }
5841
5842 #ifdef MONO_ARCH_SIMD_INTRINSICS
5843         if (cfg->opt & MONO_OPT_SIMD) {
5844                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5845                 if (ins)
5846                         return ins;
5847         }
5848 #endif
5849
5850         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5851         if (ins)
5852                 return ins;
5853
5854         if (COMPILE_LLVM (cfg)) {
5855                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
5856                 if (ins)
5857                         return ins;
5858         }
5859
5860         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
5861 }
5862
5863 /*
5864  * This entry point could be used later for arbitrary method
5865  * redirection.
5866  */
5867 inline static MonoInst*
5868 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
5869                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
5870 {
5871         if (method->klass == mono_defaults.string_class) {
5872                 /* managed string allocation support */
5873                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
5874                         MonoInst *iargs [2];
5875                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
5876                         MonoMethod *managed_alloc = NULL;
5877
5878                         g_assert (vtable); /*Should not fail since it System.String*/
5879 #ifndef MONO_CROSS_COMPILE
5880                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
5881 #endif
5882                         if (!managed_alloc)
5883                                 return NULL;
5884                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
5885                         iargs [1] = args [0];
5886                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
5887                 }
5888         }
5889         return NULL;
5890 }
5891
5892 static void
5893 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
5894 {
5895         MonoInst *store, *temp;
5896         int i;
5897
5898         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5899                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
5900
5901                 /*
5902                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
5903                  * would be different than the MonoInst's used to represent arguments, and
5904                  * the ldelema implementation can't deal with that.
5905                  * Solution: When ldelema is used on an inline argument, create a var for 
5906                  * it, emit ldelema on that var, and emit the saving code below in
5907                  * inline_method () if needed.
5908                  */
5909                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
5910                 cfg->args [i] = temp;
5911                 /* This uses cfg->args [i] which is set by the preceeding line */
5912                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
5913                 store->cil_code = sp [0]->cil_code;
5914                 sp++;
5915         }
5916 }
5917
5918 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
5919 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
5920
5921 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
5922 static gboolean
5923 check_inline_called_method_name_limit (MonoMethod *called_method)
5924 {
5925         int strncmp_result;
5926         static const char *limit = NULL;
5927         
5928         if (limit == NULL) {
5929                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
5930
5931                 if (limit_string != NULL)
5932                         limit = limit_string;
5933                 else
5934                         limit = "";
5935         }
5936
5937         if (limit [0] != '\0') {
5938                 char *called_method_name = mono_method_full_name (called_method, TRUE);
5939
5940                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
5941                 g_free (called_method_name);
5942         
5943                 //return (strncmp_result <= 0);
5944                 return (strncmp_result == 0);
5945         } else {
5946                 return TRUE;
5947         }
5948 }
5949 #endif
5950
5951 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
5952 static gboolean
5953 check_inline_caller_method_name_limit (MonoMethod *caller_method)
5954 {
5955         int strncmp_result;
5956         static const char *limit = NULL;
5957         
5958         if (limit == NULL) {
5959                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
5960                 if (limit_string != NULL) {
5961                         limit = limit_string;
5962                 } else {
5963                         limit = "";
5964                 }
5965         }
5966
5967         if (limit [0] != '\0') {
5968                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
5969
5970                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
5971                 g_free (caller_method_name);
5972         
5973                 //return (strncmp_result <= 0);
5974                 return (strncmp_result == 0);
5975         } else {
5976                 return TRUE;
5977         }
5978 }
5979 #endif
5980
5981 static void
5982 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5983 {
5984         static double r8_0 = 0.0;
5985         static float r4_0 = 0.0;
5986         MonoInst *ins;
5987         int t;
5988
5989         rtype = mini_get_underlying_type (rtype);
5990         t = rtype->type;
5991
5992         if (rtype->byref) {
5993                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5994         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5995                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5996         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5997                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
5998         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
5999                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
6000                 ins->type = STACK_R4;
6001                 ins->inst_p0 = (void*)&r4_0;
6002                 ins->dreg = dreg;
6003                 MONO_ADD_INS (cfg->cbb, ins);
6004         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6005                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6006                 ins->type = STACK_R8;
6007                 ins->inst_p0 = (void*)&r8_0;
6008                 ins->dreg = dreg;
6009                 MONO_ADD_INS (cfg->cbb, ins);
6010         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6011                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6012                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6013         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6014                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6015         } else {
6016                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6017         }
6018 }
6019
6020 static void
6021 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6022 {
6023         int t;
6024
6025         rtype = mini_get_underlying_type (rtype);
6026         t = rtype->type;
6027
6028         if (rtype->byref) {
6029                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6030         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6031                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6032         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6033                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6034         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6035                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6036         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6037                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6038         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6039                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6040                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6041         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6042                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6043         } else {
6044                 emit_init_rvar (cfg, dreg, rtype);
6045         }
6046 }
6047
6048 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6049 static void
6050 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6051 {
6052         MonoInst *var = cfg->locals [local];
6053         if (COMPILE_SOFT_FLOAT (cfg)) {
6054                 MonoInst *store;
6055                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6056                 emit_init_rvar (cfg, reg, type);
6057                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6058         } else {
6059                 if (init)
6060                         emit_init_rvar (cfg, var->dreg, type);
6061                 else
6062                         emit_dummy_init_rvar (cfg, var->dreg, type);
6063         }
6064 }
6065
6066 int
6067 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6068 {
6069         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6070 }
6071
6072 /*
6073  * inline_method:
6074  *
6075  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6076  */
6077 static int
6078 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6079                guchar *ip, guint real_offset, gboolean inline_always)
6080 {
6081         MonoError error;
6082         MonoInst *ins, *rvar = NULL;
6083         MonoMethodHeader *cheader;
6084         MonoBasicBlock *ebblock, *sbblock;
6085         int i, costs;
6086         MonoMethod *prev_inlined_method;
6087         MonoInst **prev_locals, **prev_args;
6088         MonoType **prev_arg_types;
6089         guint prev_real_offset;
6090         GHashTable *prev_cbb_hash;
6091         MonoBasicBlock **prev_cil_offset_to_bb;
6092         MonoBasicBlock *prev_cbb;
6093         const unsigned char *prev_ip;
6094         unsigned char *prev_cil_start;
6095         guint32 prev_cil_offset_to_bb_len;
6096         MonoMethod *prev_current_method;
6097         MonoGenericContext *prev_generic_context;
6098         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6099
6100         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6101
6102 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6103         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6104                 return 0;
6105 #endif
6106 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6107         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6108                 return 0;
6109 #endif
6110
6111         if (!fsig)
6112                 fsig = mono_method_signature (cmethod);
6113
6114         if (cfg->verbose_level > 2)
6115                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6116
6117         if (!cmethod->inline_info) {
6118                 cfg->stat_inlineable_methods++;
6119                 cmethod->inline_info = 1;
6120         }
6121
6122         /* allocate local variables */
6123         cheader = mono_method_get_header_checked (cmethod, &error);
6124         if (!cheader) {
6125                 if (inline_always) {
6126                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6127                         mono_error_move (&cfg->error, &error);
6128                 } else {
6129                         mono_error_cleanup (&error);
6130                 }
6131                 return 0;
6132         }
6133
6134         /*Must verify before creating locals as it can cause the JIT to assert.*/
6135         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6136                 mono_metadata_free_mh (cheader);
6137                 return 0;
6138         }
6139
6140         /* allocate space to store the return value */
6141         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6142                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6143         }
6144
6145         prev_locals = cfg->locals;
6146         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6147         for (i = 0; i < cheader->num_locals; ++i)
6148                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6149
6150         /* allocate start and end blocks */
6151         /* This is needed so if the inline is aborted, we can clean up */
6152         NEW_BBLOCK (cfg, sbblock);
6153         sbblock->real_offset = real_offset;
6154
6155         NEW_BBLOCK (cfg, ebblock);
6156         ebblock->block_num = cfg->num_bblocks++;
6157         ebblock->real_offset = real_offset;
6158
6159         prev_args = cfg->args;
6160         prev_arg_types = cfg->arg_types;
6161         prev_inlined_method = cfg->inlined_method;
6162         cfg->inlined_method = cmethod;
6163         cfg->ret_var_set = FALSE;
6164         cfg->inline_depth ++;
6165         prev_real_offset = cfg->real_offset;
6166         prev_cbb_hash = cfg->cbb_hash;
6167         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6168         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6169         prev_cil_start = cfg->cil_start;
6170         prev_ip = cfg->ip;
6171         prev_cbb = cfg->cbb;
6172         prev_current_method = cfg->current_method;
6173         prev_generic_context = cfg->generic_context;
6174         prev_ret_var_set = cfg->ret_var_set;
6175         prev_disable_inline = cfg->disable_inline;
6176
6177         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6178                 virtual_ = TRUE;
6179
6180         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6181
6182         ret_var_set = cfg->ret_var_set;
6183
6184         cfg->inlined_method = prev_inlined_method;
6185         cfg->real_offset = prev_real_offset;
6186         cfg->cbb_hash = prev_cbb_hash;
6187         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6188         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6189         cfg->cil_start = prev_cil_start;
6190         cfg->ip = prev_ip;
6191         cfg->locals = prev_locals;
6192         cfg->args = prev_args;
6193         cfg->arg_types = prev_arg_types;
6194         cfg->current_method = prev_current_method;
6195         cfg->generic_context = prev_generic_context;
6196         cfg->ret_var_set = prev_ret_var_set;
6197         cfg->disable_inline = prev_disable_inline;
6198         cfg->inline_depth --;
6199
6200         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6201                 if (cfg->verbose_level > 2)
6202                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6203
6204                 cfg->stat_inlined_methods++;
6205
6206                 /* always add some code to avoid block split failures */
6207                 MONO_INST_NEW (cfg, ins, OP_NOP);
6208                 MONO_ADD_INS (prev_cbb, ins);
6209
6210                 prev_cbb->next_bb = sbblock;
6211                 link_bblock (cfg, prev_cbb, sbblock);
6212
6213                 /* 
6214                  * Get rid of the begin and end bblocks if possible to aid local
6215                  * optimizations.
6216                  */
6217                 if (prev_cbb->out_count == 1)
6218                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6219
6220                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6221                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6222
6223                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6224                         MonoBasicBlock *prev = ebblock->in_bb [0];
6225
6226                         if (prev->next_bb == ebblock) {
6227                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6228                                 cfg->cbb = prev;
6229                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6230                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6231                                         cfg->cbb = prev_cbb;
6232                                 }
6233                         } else {
6234                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6235                                 cfg->cbb = ebblock;
6236                         }
6237                 } else {
6238                         /* 
6239                          * Its possible that the rvar is set in some prev bblock, but not in others.
6240                          * (#1835).
6241                          */
6242                         if (rvar) {
6243                                 MonoBasicBlock *bb;
6244
6245                                 for (i = 0; i < ebblock->in_count; ++i) {
6246                                         bb = ebblock->in_bb [i];
6247
6248                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6249                                                 cfg->cbb = bb;
6250
6251                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6252                                         }
6253                                 }
6254                         }
6255
6256                         cfg->cbb = ebblock;
6257                 }
6258
6259                 if (rvar) {
6260                         /*
6261                          * If the inlined method contains only a throw, then the ret var is not 
6262                          * set, so set it to a dummy value.
6263                          */
6264                         if (!ret_var_set)
6265                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6266
6267                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6268                         *sp++ = ins;
6269                 }
6270                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6271                 return costs + 1;
6272         } else {
6273                 if (cfg->verbose_level > 2)
6274                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6275                 cfg->exception_type = MONO_EXCEPTION_NONE;
6276
6277                 /* This gets rid of the newly added bblocks */
6278                 cfg->cbb = prev_cbb;
6279         }
6280         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6281         return 0;
6282 }
6283
6284 /*
6285  * Some of these comments may well be out-of-date.
6286  * Design decisions: we do a single pass over the IL code (and we do bblock 
6287  * splitting/merging in the few cases when it's required: a back jump to an IL
6288  * address that was not already seen as bblock starting point).
6289  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6290  * Complex operations are decomposed in simpler ones right away. We need to let the 
6291  * arch-specific code peek and poke inside this process somehow (except when the 
6292  * optimizations can take advantage of the full semantic info of coarse opcodes).
6293  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6294  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6295  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6296  * opcode with value bigger than OP_LAST.
6297  * At this point the IR can be handed over to an interpreter, a dumb code generator
6298  * or to the optimizing code generator that will translate it to SSA form.
6299  *
6300  * Profiling directed optimizations.
6301  * We may compile by default with few or no optimizations and instrument the code
6302  * or the user may indicate what methods to optimize the most either in a config file
6303  * or through repeated runs where the compiler applies offline the optimizations to 
6304  * each method and then decides if it was worth it.
6305  */
6306
6307 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6308 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6309 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6310 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6311 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6312 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6313 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6314 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6315
6316 /* offset from br.s -> br like opcodes */
6317 #define BIG_BRANCH_OFFSET 13
6318
6319 static gboolean
6320 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6321 {
6322         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6323
6324         return b == NULL || b == bb;
6325 }
6326
6327 static int
6328 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6329 {
6330         unsigned char *ip = start;
6331         unsigned char *target;
6332         int i;
6333         guint cli_addr;
6334         MonoBasicBlock *bblock;
6335         const MonoOpcode *opcode;
6336
6337         while (ip < end) {
6338                 cli_addr = ip - start;
6339                 i = mono_opcode_value ((const guint8 **)&ip, end);
6340                 if (i < 0)
6341                         UNVERIFIED;
6342                 opcode = &mono_opcodes [i];
6343                 switch (opcode->argument) {
6344                 case MonoInlineNone:
6345                         ip++; 
6346                         break;
6347                 case MonoInlineString:
6348                 case MonoInlineType:
6349                 case MonoInlineField:
6350                 case MonoInlineMethod:
6351                 case MonoInlineTok:
6352                 case MonoInlineSig:
6353                 case MonoShortInlineR:
6354                 case MonoInlineI:
6355                         ip += 5;
6356                         break;
6357                 case MonoInlineVar:
6358                         ip += 3;
6359                         break;
6360                 case MonoShortInlineVar:
6361                 case MonoShortInlineI:
6362                         ip += 2;
6363                         break;
6364                 case MonoShortInlineBrTarget:
6365                         target = start + cli_addr + 2 + (signed char)ip [1];
6366                         GET_BBLOCK (cfg, bblock, target);
6367                         ip += 2;
6368                         if (ip < end)
6369                                 GET_BBLOCK (cfg, bblock, ip);
6370                         break;
6371                 case MonoInlineBrTarget:
6372                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6373                         GET_BBLOCK (cfg, bblock, target);
6374                         ip += 5;
6375                         if (ip < end)
6376                                 GET_BBLOCK (cfg, bblock, ip);
6377                         break;
6378                 case MonoInlineSwitch: {
6379                         guint32 n = read32 (ip + 1);
6380                         guint32 j;
6381                         ip += 5;
6382                         cli_addr += 5 + 4 * n;
6383                         target = start + cli_addr;
6384                         GET_BBLOCK (cfg, bblock, target);
6385                         
6386                         for (j = 0; j < n; ++j) {
6387                                 target = start + cli_addr + (gint32)read32 (ip);
6388                                 GET_BBLOCK (cfg, bblock, target);
6389                                 ip += 4;
6390                         }
6391                         break;
6392                 }
6393                 case MonoInlineR:
6394                 case MonoInlineI8:
6395                         ip += 9;
6396                         break;
6397                 default:
6398                         g_assert_not_reached ();
6399                 }
6400
6401                 if (i == CEE_THROW) {
6402                         unsigned char *bb_start = ip - 1;
6403                         
6404                         /* Find the start of the bblock containing the throw */
6405                         bblock = NULL;
6406                         while ((bb_start >= start) && !bblock) {
6407                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6408                                 bb_start --;
6409                         }
6410                         if (bblock)
6411                                 bblock->out_of_line = 1;
6412                 }
6413         }
6414         return 0;
6415 unverified:
6416 exception_exit:
6417         *pos = ip;
6418         return 1;
6419 }
6420
6421 static inline MonoMethod *
6422 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6423 {
6424         MonoMethod *method;
6425
6426         error_init (error);
6427
6428         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6429                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6430                 if (context) {
6431                         method = mono_class_inflate_generic_method_checked (method, context, error);
6432                 }
6433         } else {
6434                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6435         }
6436
6437         return method;
6438 }
6439
6440 static inline MonoMethod *
6441 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6442 {
6443         MonoError error;
6444         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6445
6446         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6447                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6448                 method = NULL;
6449         }
6450
6451         if (!method && !cfg)
6452                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6453
6454         return method;
6455 }
6456
6457 MonoClass*
6458 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6459 {
6460         MonoError error;
6461         MonoClass *klass;
6462
6463         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6464                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6465                 if (context) {
6466                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6467                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6468                 }
6469         } else {
6470                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6471                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6472         }
6473         if (klass)
6474                 mono_class_init (klass);
6475         return klass;
6476 }
6477
6478 static inline MonoMethodSignature*
6479 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6480 {
6481         MonoMethodSignature *fsig;
6482
6483         error_init (error);
6484         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6485                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6486         } else {
6487                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6488                 return_val_if_nok (error, NULL);
6489         }
6490         if (context) {
6491                 fsig = mono_inflate_generic_signature(fsig, context, error);
6492         }
6493         return fsig;
6494 }
6495
6496 static MonoMethod*
6497 throw_exception (void)
6498 {
6499         static MonoMethod *method = NULL;
6500
6501         if (!method) {
6502                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6503                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6504         }
6505         g_assert (method);
6506         return method;
6507 }
6508
6509 static void
6510 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6511 {
6512         MonoMethod *thrower = throw_exception ();
6513         MonoInst *args [1];
6514
6515         EMIT_NEW_PCONST (cfg, args [0], ex);
6516         mono_emit_method_call (cfg, thrower, args, NULL);
6517 }
6518
6519 /*
6520  * Return the original method is a wrapper is specified. We can only access 
6521  * the custom attributes from the original method.
6522  */
6523 static MonoMethod*
6524 get_original_method (MonoMethod *method)
6525 {
6526         if (method->wrapper_type == MONO_WRAPPER_NONE)
6527                 return method;
6528
6529         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6530         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6531                 return NULL;
6532
6533         /* in other cases we need to find the original method */
6534         return mono_marshal_method_from_wrapper (method);
6535 }
6536
6537 static void
6538 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6539 {
6540         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6541         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6542         if (ex)
6543                 emit_throw_exception (cfg, ex);
6544 }
6545
6546 static void
6547 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6548 {
6549         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6550         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6551         if (ex)
6552                 emit_throw_exception (cfg, ex);
6553 }
6554
6555 /*
6556  * Check that the IL instructions at ip are the array initialization
6557  * sequence and return the pointer to the data and the size.
6558  */
6559 static const char*
6560 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6561 {
6562         /*
6563          * newarr[System.Int32]
6564          * dup
6565          * ldtoken field valuetype ...
6566          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6567          */
6568         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6569                 MonoError error;
6570                 guint32 token = read32 (ip + 7);
6571                 guint32 field_token = read32 (ip + 2);
6572                 guint32 field_index = field_token & 0xffffff;
6573                 guint32 rva;
6574                 const char *data_ptr;
6575                 int size = 0;
6576                 MonoMethod *cmethod;
6577                 MonoClass *dummy_class;
6578                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6579                 int dummy_align;
6580
6581                 if (!field) {
6582                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6583                         return NULL;
6584                 }
6585
6586                 *out_field_token = field_token;
6587
6588                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6589                 if (!cmethod)
6590                         return NULL;
6591                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6592                         return NULL;
6593                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6594                 case MONO_TYPE_I1:
6595                 case MONO_TYPE_U1:
6596                         size = 1; break;
6597                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6598 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6599                 case MONO_TYPE_I2:
6600                 case MONO_TYPE_U2:
6601                         size = 2; break;
6602                 case MONO_TYPE_I4:
6603                 case MONO_TYPE_U4:
6604                 case MONO_TYPE_R4:
6605                         size = 4; break;
6606                 case MONO_TYPE_R8:
6607                 case MONO_TYPE_I8:
6608                 case MONO_TYPE_U8:
6609                         size = 8; break;
6610 #endif
6611                 default:
6612                         return NULL;
6613                 }
6614                 size *= len;
6615                 if (size > mono_type_size (field->type, &dummy_align))
6616                     return NULL;
6617                 *out_size = size;
6618                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6619                 if (!image_is_dynamic (method->klass->image)) {
6620                         field_index = read32 (ip + 2) & 0xffffff;
6621                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6622                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6623                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6624                         /* for aot code we do the lookup on load */
6625                         if (aot && data_ptr)
6626                                 return (const char *)GUINT_TO_POINTER (rva);
6627                 } else {
6628                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6629                         g_assert (!aot);
6630                         data_ptr = mono_field_get_data (field);
6631                 }
6632                 return data_ptr;
6633         }
6634         return NULL;
6635 }
6636
6637 static void
6638 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6639 {
6640         MonoError error;
6641         char *method_fname = mono_method_full_name (method, TRUE);
6642         char *method_code;
6643         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6644
6645         if (!header) {
6646                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6647                 mono_error_cleanup (&error);
6648         } else if (header->code_size == 0)
6649                 method_code = g_strdup ("method body is empty.");
6650         else
6651                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6652         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6653         g_free (method_fname);
6654         g_free (method_code);
6655         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6656 }
6657
6658 static void
6659 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6660 {
6661         MonoInst *ins;
6662         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6663         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6664                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6665                 /* Optimize reg-reg moves away */
6666                 /* 
6667                  * Can't optimize other opcodes, since sp[0] might point to
6668                  * the last ins of a decomposed opcode.
6669                  */
6670                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6671         } else {
6672                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6673         }
6674 }
6675
6676 /*
6677  * ldloca inhibits many optimizations so try to get rid of it in common
6678  * cases.
6679  */
6680 static inline unsigned char *
6681 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6682 {
6683         int local, token;
6684         MonoClass *klass;
6685         MonoType *type;
6686
6687         if (size == 1) {
6688                 local = ip [1];
6689                 ip += 2;
6690         } else {
6691                 local = read16 (ip + 2);
6692                 ip += 4;
6693         }
6694         
6695         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6696                 /* From the INITOBJ case */
6697                 token = read32 (ip + 2);
6698                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6699                 CHECK_TYPELOAD (klass);
6700                 type = mini_get_underlying_type (&klass->byval_arg);
6701                 emit_init_local (cfg, local, type, TRUE);
6702                 return ip + 6;
6703         }
6704  exception_exit:
6705         return NULL;
6706 }
6707
6708 static MonoInst*
6709 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6710 {
6711         MonoInst *icall_args [16];
6712         MonoInst *call_target, *ins, *vtable_ins;
6713         int arg_reg, this_reg, vtable_reg;
6714         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6715         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6716         gboolean variant_iface = FALSE;
6717         guint32 slot;
6718         int offset;
6719         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6720
6721         /*
6722          * In llvm-only mode, vtables contain function descriptors instead of
6723          * method addresses/trampolines.
6724          */
6725         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6726
6727         if (is_iface)
6728                 slot = mono_method_get_imt_slot (cmethod);
6729         else
6730                 slot = mono_method_get_vtable_index (cmethod);
6731
6732         this_reg = sp [0]->dreg;
6733
6734         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6735                 variant_iface = TRUE;
6736
6737         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6738                 /*
6739                  * The simplest case, a normal virtual call.
6740                  */
6741                 int slot_reg = alloc_preg (cfg);
6742                 int addr_reg = alloc_preg (cfg);
6743                 int arg_reg = alloc_preg (cfg);
6744                 MonoBasicBlock *non_null_bb;
6745
6746                 vtable_reg = alloc_preg (cfg);
6747                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6748                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6749
6750                 /* Load the vtable slot, which contains a function descriptor. */
6751                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6752
6753                 NEW_BBLOCK (cfg, non_null_bb);
6754
6755                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6756                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6757                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6758
6759                 /* Slow path */
6760                 // FIXME: Make the wrapper use the preserveall cconv
6761                 // FIXME: Use one icall per slot for small slot numbers ?
6762                 icall_args [0] = vtable_ins;
6763                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6764                 /* Make the icall return the vtable slot value to save some code space */
6765                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6766                 ins->dreg = slot_reg;
6767                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6768
6769                 /* Fastpath */
6770                 MONO_START_BB (cfg, non_null_bb);
6771                 /* Load the address + arg from the vtable slot */
6772                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6773                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
6774
6775                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6776         }
6777
6778         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
6779                 /*
6780                  * A simple interface call
6781                  *
6782                  * We make a call through an imt slot to obtain the function descriptor we need to call.
6783                  * The imt slot contains a function descriptor for a runtime function + arg.
6784                  */
6785                 int slot_reg = alloc_preg (cfg);
6786                 int addr_reg = alloc_preg (cfg);
6787                 int arg_reg = alloc_preg (cfg);
6788                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6789
6790                 vtable_reg = alloc_preg (cfg);
6791                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6792                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6793
6794                 /*
6795                  * The slot is already initialized when the vtable is created so there is no need
6796                  * to check it here.
6797                  */
6798
6799                 /* Load the imt slot, which contains a function descriptor. */
6800                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6801
6802                 /* Load the address + arg of the imt thunk from the imt slot */
6803                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6804                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6805                 /*
6806                  * IMT thunks in llvm-only mode are C functions which take an info argument
6807                  * plus the imt method and return the ftndesc to call.
6808                  */
6809                 icall_args [0] = thunk_arg_ins;
6810                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6811                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6812                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6813
6814                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6815         }
6816
6817         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
6818                 /*
6819                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
6820                  * dynamically extended as more instantiations are discovered.
6821                  * This handles generic virtual methods both on classes and interfaces.
6822                  */
6823                 int slot_reg = alloc_preg (cfg);
6824                 int addr_reg = alloc_preg (cfg);
6825                 int arg_reg = alloc_preg (cfg);
6826                 int ftndesc_reg = alloc_preg (cfg);
6827                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6828                 MonoBasicBlock *slowpath_bb, *end_bb;
6829
6830                 NEW_BBLOCK (cfg, slowpath_bb);
6831                 NEW_BBLOCK (cfg, end_bb);
6832
6833                 vtable_reg = alloc_preg (cfg);
6834                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6835                 if (is_iface)
6836                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6837                 else
6838                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6839
6840                 /* Load the slot, which contains a function descriptor. */
6841                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6842
6843                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
6844                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
6845                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6846                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6847
6848                 /* Fastpath */
6849                 /* Same as with iface calls */
6850                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6851                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6852                 icall_args [0] = thunk_arg_ins;
6853                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6854                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6855                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6856                 ftndesc_ins->dreg = ftndesc_reg;
6857                 /*
6858                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
6859                  * they don't know about yet. Fall back to the slowpath in that case.
6860                  */
6861                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
6862                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6863
6864                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6865
6866                 /* Slowpath */
6867                 MONO_START_BB (cfg, slowpath_bb);
6868                 icall_args [0] = vtable_ins;
6869                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6870                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6871                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6872                 if (is_iface)
6873                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
6874                 else
6875                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
6876                 ftndesc_ins->dreg = ftndesc_reg;
6877                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6878
6879                 /* Common case */
6880                 MONO_START_BB (cfg, end_bb);
6881                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6882         }
6883
6884         /*
6885          * Non-optimized cases
6886          */
6887         icall_args [0] = sp [0];
6888         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6889
6890         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6891                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
6892
6893         arg_reg = alloc_preg (cfg);
6894         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
6895         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
6896
6897         g_assert (is_gsharedvt);
6898         if (is_iface)
6899                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
6900         else
6901                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
6902
6903         /*
6904          * Pass the extra argument even if the callee doesn't receive it, most
6905          * calling conventions allow this.
6906          */
6907         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6908 }
6909
6910 static gboolean
6911 is_exception_class (MonoClass *klass)
6912 {
6913         while (klass) {
6914                 if (klass == mono_defaults.exception_class)
6915                         return TRUE;
6916                 klass = klass->parent;
6917         }
6918         return FALSE;
6919 }
6920
6921 /*
6922  * is_jit_optimizer_disabled:
6923  *
6924  *   Determine whenever M's assembly has a DebuggableAttribute with the
6925  * IsJITOptimizerDisabled flag set.
6926  */
6927 static gboolean
6928 is_jit_optimizer_disabled (MonoMethod *m)
6929 {
6930         MonoError error;
6931         MonoAssembly *ass = m->klass->image->assembly;
6932         MonoCustomAttrInfo* attrs;
6933         MonoClass *klass;
6934         int i;
6935         gboolean val = FALSE;
6936
6937         g_assert (ass);
6938         if (ass->jit_optimizer_disabled_inited)
6939                 return ass->jit_optimizer_disabled;
6940
6941         klass = mono_class_try_get_debuggable_attribute_class ();
6942
6943         if (!klass) {
6944                 /* Linked away */
6945                 ass->jit_optimizer_disabled = FALSE;
6946                 mono_memory_barrier ();
6947                 ass->jit_optimizer_disabled_inited = TRUE;
6948                 return FALSE;
6949         }
6950
6951         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
6952         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6953         if (attrs) {
6954                 for (i = 0; i < attrs->num_attrs; ++i) {
6955                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
6956                         const gchar *p;
6957                         MonoMethodSignature *sig;
6958
6959                         if (!attr->ctor || attr->ctor->klass != klass)
6960                                 continue;
6961                         /* Decode the attribute. See reflection.c */
6962                         p = (const char*)attr->data;
6963                         g_assert (read16 (p) == 0x0001);
6964                         p += 2;
6965
6966                         // FIXME: Support named parameters
6967                         sig = mono_method_signature (attr->ctor);
6968                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
6969                                 continue;
6970                         /* Two boolean arguments */
6971                         p ++;
6972                         val = *p;
6973                 }
6974                 mono_custom_attrs_free (attrs);
6975         }
6976
6977         ass->jit_optimizer_disabled = val;
6978         mono_memory_barrier ();
6979         ass->jit_optimizer_disabled_inited = TRUE;
6980
6981         return val;
6982 }
6983
6984 static gboolean
6985 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
6986 {
6987         gboolean supported_tail_call;
6988         int i;
6989
6990         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
6991
6992         for (i = 0; i < fsig->param_count; ++i) {
6993                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
6994                         /* These can point to the current method's stack */
6995                         supported_tail_call = FALSE;
6996         }
6997         if (fsig->hasthis && cmethod->klass->valuetype)
6998                 /* this might point to the current method's stack */
6999                 supported_tail_call = FALSE;
7000         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7001                 supported_tail_call = FALSE;
7002         if (cfg->method->save_lmf)
7003                 supported_tail_call = FALSE;
7004         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7005                 supported_tail_call = FALSE;
7006         if (call_opcode != CEE_CALL)
7007                 supported_tail_call = FALSE;
7008
7009         /* Debugging support */
7010 #if 0
7011         if (supported_tail_call) {
7012                 if (!mono_debug_count ())
7013                         supported_tail_call = FALSE;
7014         }
7015 #endif
7016
7017         return supported_tail_call;
7018 }
7019
7020 /*
7021  * handle_ctor_call:
7022  *
7023  *   Handle calls made to ctors from NEWOBJ opcodes.
7024  */
7025 static void
7026 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7027                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7028 {
7029         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7030
7031         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7032                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7033                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7034                         mono_class_vtable (cfg->domain, cmethod->klass);
7035                         CHECK_TYPELOAD (cmethod->klass);
7036
7037                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7038                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7039                 } else {
7040                         if (context_used) {
7041                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7042                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7043                         } else {
7044                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7045
7046                                 CHECK_TYPELOAD (cmethod->klass);
7047                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7048                         }
7049                 }
7050         }
7051
7052         /* Avoid virtual calls to ctors if possible */
7053         if (mono_class_is_marshalbyref (cmethod->klass))
7054                 callvirt_this_arg = sp [0];
7055
7056         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7057                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7058                 CHECK_CFG_EXCEPTION;
7059         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7060                            mono_method_check_inlining (cfg, cmethod) &&
7061                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7062                 int costs;
7063
7064                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7065                         cfg->real_offset += 5;
7066
7067                         *inline_costs += costs - 5;
7068                 } else {
7069                         INLINE_FAILURE ("inline failure");
7070                         // FIXME-VT: Clean this up
7071                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7072                                 GSHAREDVT_FAILURE(*ip);
7073                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7074                 }
7075         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7076                 MonoInst *addr;
7077
7078                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7079
7080                 if (cfg->llvm_only) {
7081                         // FIXME: Avoid initializing vtable_arg
7082                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7083                 } else {
7084                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7085                 }
7086         } else if (context_used &&
7087                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7088                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7089                 MonoInst *cmethod_addr;
7090
7091                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7092
7093                 if (cfg->llvm_only) {
7094                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7095                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7096                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7097                 } else {
7098                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7099                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7100
7101                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7102                 }
7103         } else {
7104                 INLINE_FAILURE ("ctor call");
7105                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7106                                                                                   callvirt_this_arg, NULL, vtable_arg);
7107         }
7108  exception_exit:
7109         return;
7110 }
7111
7112 static void
7113 emit_setret (MonoCompile *cfg, MonoInst *val)
7114 {
7115         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7116         MonoInst *ins;
7117
7118         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7119                 MonoInst *ret_addr;
7120
7121                 if (!cfg->vret_addr) {
7122                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7123                 } else {
7124                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7125
7126                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7127                         ins->klass = mono_class_from_mono_type (ret_type);
7128                 }
7129         } else {
7130 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7131                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7132                         MonoInst *iargs [1];
7133                         MonoInst *conv;
7134
7135                         iargs [0] = val;
7136                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7137                         mono_arch_emit_setret (cfg, cfg->method, conv);
7138                 } else {
7139                         mono_arch_emit_setret (cfg, cfg->method, val);
7140                 }
7141 #else
7142                 mono_arch_emit_setret (cfg, cfg->method, val);
7143 #endif
7144         }
7145 }
7146
7147 /*
7148  * mono_method_to_ir:
7149  *
7150  * Translate the .net IL into linear IR.
7151  *
7152  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7153  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7154  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7155  * @inline_args: if not NULL, contains the arguments to the inline call
7156  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7157  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7158  *
7159  * This method is used to turn ECMA IL into Mono's internal Linear IR
7160  * reprensetation.  It is used both for entire methods, as well as
7161  * inlining existing methods.  In the former case, the @start_bblock,
7162  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7163  * inline_offset is set to zero.
7164  * 
7165  * Returns: the inline cost, or -1 if there was an error processing this method.
7166  */
7167 int
7168 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7169                    MonoInst *return_var, MonoInst **inline_args, 
7170                    guint inline_offset, gboolean is_virtual_call)
7171 {
7172         MonoError error;
7173         MonoInst *ins, **sp, **stack_start;
7174         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7175         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7176         MonoMethod *cmethod, *method_definition;
7177         MonoInst **arg_array;
7178         MonoMethodHeader *header;
7179         MonoImage *image;
7180         guint32 token, ins_flag;
7181         MonoClass *klass;
7182         MonoClass *constrained_class = NULL;
7183         unsigned char *ip, *end, *target, *err_pos;
7184         MonoMethodSignature *sig;
7185         MonoGenericContext *generic_context = NULL;
7186         MonoGenericContainer *generic_container = NULL;
7187         MonoType **param_types;
7188         int i, n, start_new_bblock, dreg;
7189         int num_calls = 0, inline_costs = 0;
7190         int breakpoint_id = 0;
7191         guint num_args;
7192         GSList *class_inits = NULL;
7193         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7194         int context_used;
7195         gboolean init_locals, seq_points, skip_dead_blocks;
7196         gboolean sym_seq_points = FALSE;
7197         MonoDebugMethodInfo *minfo;
7198         MonoBitSet *seq_point_locs = NULL;
7199         MonoBitSet *seq_point_set_locs = NULL;
7200
7201         cfg->disable_inline = is_jit_optimizer_disabled (method);
7202
7203         /* serialization and xdomain stuff may need access to private fields and methods */
7204         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7205         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7206         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7207         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7208         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7209         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7210
7211         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7212         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7213         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7214         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7215         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7216
7217         image = method->klass->image;
7218         header = mono_method_get_header_checked (method, &cfg->error);
7219         if (!header) {
7220                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7221                 goto exception_exit;
7222         } else {
7223                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7224         }
7225
7226         generic_container = mono_method_get_generic_container (method);
7227         sig = mono_method_signature (method);
7228         num_args = sig->hasthis + sig->param_count;
7229         ip = (unsigned char*)header->code;
7230         cfg->cil_start = ip;
7231         end = ip + header->code_size;
7232         cfg->stat_cil_code_size += header->code_size;
7233
7234         seq_points = cfg->gen_seq_points && cfg->method == method;
7235
7236         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7237                 /* We could hit a seq point before attaching to the JIT (#8338) */
7238                 seq_points = FALSE;
7239         }
7240
7241         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7242                 minfo = mono_debug_lookup_method (method);
7243                 if (minfo) {
7244                         MonoSymSeqPoint *sps;
7245                         int i, n_il_offsets;
7246
7247                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7248                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7249                         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);
7250                         sym_seq_points = TRUE;
7251                         for (i = 0; i < n_il_offsets; ++i) {
7252                                 if (sps [i].il_offset < header->code_size)
7253                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7254                         }
7255                         g_free (sps);
7256
7257                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7258                         if (asyncMethod) {
7259                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7260                                 {
7261                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7262                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7263                                 }
7264                                 mono_debug_free_method_async_debug_info (asyncMethod);
7265                         }
7266                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7267                         /* Methods without line number info like auto-generated property accessors */
7268                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7269                         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);
7270                         sym_seq_points = TRUE;
7271                 }
7272         }
7273
7274         /* 
7275          * Methods without init_locals set could cause asserts in various passes
7276          * (#497220). To work around this, we emit dummy initialization opcodes
7277          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7278          * on some platforms.
7279          */
7280         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7281                 init_locals = header->init_locals;
7282         else
7283                 init_locals = TRUE;
7284
7285         method_definition = method;
7286         while (method_definition->is_inflated) {
7287                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7288                 method_definition = imethod->declaring;
7289         }
7290
7291         /* SkipVerification is not allowed if core-clr is enabled */
7292         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7293                 dont_verify = TRUE;
7294                 dont_verify_stloc = TRUE;
7295         }
7296
7297         if (sig->is_inflated)
7298                 generic_context = mono_method_get_context (method);
7299         else if (generic_container)
7300                 generic_context = &generic_container->context;
7301         cfg->generic_context = generic_context;
7302
7303         if (!cfg->gshared)
7304                 g_assert (!sig->has_type_parameters);
7305
7306         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7307                 g_assert (method->is_inflated);
7308                 g_assert (mono_method_get_context (method)->method_inst);
7309         }
7310         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7311                 g_assert (sig->generic_param_count);
7312
7313         if (cfg->method == method) {
7314                 cfg->real_offset = 0;
7315         } else {
7316                 cfg->real_offset = inline_offset;
7317         }
7318
7319         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7320         cfg->cil_offset_to_bb_len = header->code_size;
7321
7322         cfg->current_method = method;
7323
7324         if (cfg->verbose_level > 2)
7325                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7326
7327         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7328         if (sig->hasthis)
7329                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7330         for (n = 0; n < sig->param_count; ++n)
7331                 param_types [n + sig->hasthis] = sig->params [n];
7332         cfg->arg_types = param_types;
7333
7334         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7335         if (cfg->method == method) {
7336
7337                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7338                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7339
7340                 /* ENTRY BLOCK */
7341                 NEW_BBLOCK (cfg, start_bblock);
7342                 cfg->bb_entry = start_bblock;
7343                 start_bblock->cil_code = NULL;
7344                 start_bblock->cil_length = 0;
7345
7346                 /* EXIT BLOCK */
7347                 NEW_BBLOCK (cfg, end_bblock);
7348                 cfg->bb_exit = end_bblock;
7349                 end_bblock->cil_code = NULL;
7350                 end_bblock->cil_length = 0;
7351                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7352                 g_assert (cfg->num_bblocks == 2);
7353
7354                 arg_array = cfg->args;
7355
7356                 if (header->num_clauses) {
7357                         cfg->spvars = g_hash_table_new (NULL, NULL);
7358                         cfg->exvars = g_hash_table_new (NULL, NULL);
7359                 }
7360                 /* handle exception clauses */
7361                 for (i = 0; i < header->num_clauses; ++i) {
7362                         MonoBasicBlock *try_bb;
7363                         MonoExceptionClause *clause = &header->clauses [i];
7364                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7365
7366                         try_bb->real_offset = clause->try_offset;
7367                         try_bb->try_start = TRUE;
7368                         try_bb->region = ((i + 1) << 8) | clause->flags;
7369                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7370                         tblock->real_offset = clause->handler_offset;
7371                         tblock->flags |= BB_EXCEPTION_HANDLER;
7372
7373                         /*
7374                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7375                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7376                          */
7377                         if (COMPILE_LLVM (cfg))
7378                                 link_bblock (cfg, try_bb, tblock);
7379
7380                         if (*(ip + clause->handler_offset) == CEE_POP)
7381                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7382
7383                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7384                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7385                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7386                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7387                                 MONO_ADD_INS (tblock, ins);
7388
7389                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7390                                         /* finally clauses already have a seq point */
7391                                         /* seq points for filter clauses are emitted below */
7392                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7393                                         MONO_ADD_INS (tblock, ins);
7394                                 }
7395
7396                                 /* todo: is a fault block unsafe to optimize? */
7397                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7398                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7399                         }
7400
7401                         /*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);
7402                           while (p < end) {
7403                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7404                           }*/
7405                         /* catch and filter blocks get the exception object on the stack */
7406                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7407                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7408
7409                                 /* mostly like handle_stack_args (), but just sets the input args */
7410                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7411                                 tblock->in_scount = 1;
7412                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7413                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7414
7415                                 cfg->cbb = tblock;
7416
7417 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7418                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7419                                 if (!cfg->compile_llvm) {
7420                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7421                                         ins->dreg = tblock->in_stack [0]->dreg;
7422                                         MONO_ADD_INS (tblock, ins);
7423                                 }
7424 #else
7425                                 MonoInst *dummy_use;
7426
7427                                 /* 
7428                                  * Add a dummy use for the exvar so its liveness info will be
7429                                  * correct.
7430                                  */
7431                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7432 #endif
7433
7434                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7435                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7436                                         MONO_ADD_INS (tblock, ins);
7437                                 }
7438                                 
7439                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7440                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7441                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7442                                         tblock->real_offset = clause->data.filter_offset;
7443                                         tblock->in_scount = 1;
7444                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7445                                         /* The filter block shares the exvar with the handler block */
7446                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7447                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7448                                         MONO_ADD_INS (tblock, ins);
7449                                 }
7450                         }
7451
7452                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7453                                         clause->data.catch_class &&
7454                                         cfg->gshared &&
7455                                         mono_class_check_context_used (clause->data.catch_class)) {
7456                                 /*
7457                                  * In shared generic code with catch
7458                                  * clauses containing type variables
7459                                  * the exception handling code has to
7460                                  * be able to get to the rgctx.
7461                                  * Therefore we have to make sure that
7462                                  * the vtable/mrgctx argument (for
7463                                  * static or generic methods) or the
7464                                  * "this" argument (for non-static
7465                                  * methods) are live.
7466                                  */
7467                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7468                                                 mini_method_get_context (method)->method_inst ||
7469                                                 method->klass->valuetype) {
7470                                         mono_get_vtable_var (cfg);
7471                                 } else {
7472                                         MonoInst *dummy_use;
7473
7474                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7475                                 }
7476                         }
7477                 }
7478         } else {
7479                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7480                 cfg->cbb = start_bblock;
7481                 cfg->args = arg_array;
7482                 mono_save_args (cfg, sig, inline_args);
7483         }
7484
7485         /* FIRST CODE BLOCK */
7486         NEW_BBLOCK (cfg, tblock);
7487         tblock->cil_code = ip;
7488         cfg->cbb = tblock;
7489         cfg->ip = ip;
7490
7491         ADD_BBLOCK (cfg, tblock);
7492
7493         if (cfg->method == method) {
7494                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7495                 if (breakpoint_id) {
7496                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7497                         MONO_ADD_INS (cfg->cbb, ins);
7498                 }
7499         }
7500
7501         /* we use a separate basic block for the initialization code */
7502         NEW_BBLOCK (cfg, init_localsbb);
7503         if (cfg->method == method)
7504                 cfg->bb_init = init_localsbb;
7505         init_localsbb->real_offset = cfg->real_offset;
7506         start_bblock->next_bb = init_localsbb;
7507         init_localsbb->next_bb = cfg->cbb;
7508         link_bblock (cfg, start_bblock, init_localsbb);
7509         link_bblock (cfg, init_localsbb, cfg->cbb);
7510                 
7511         cfg->cbb = init_localsbb;
7512
7513         if (cfg->gsharedvt && cfg->method == method) {
7514                 MonoGSharedVtMethodInfo *info;
7515                 MonoInst *var, *locals_var;
7516                 int dreg;
7517
7518                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7519                 info->method = cfg->method;
7520                 info->count_entries = 16;
7521                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7522                 cfg->gsharedvt_info = info;
7523
7524                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7525                 /* prevent it from being register allocated */
7526                 //var->flags |= MONO_INST_VOLATILE;
7527                 cfg->gsharedvt_info_var = var;
7528
7529                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7530                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7531
7532                 /* Allocate locals */
7533                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7534                 /* prevent it from being register allocated */
7535                 //locals_var->flags |= MONO_INST_VOLATILE;
7536                 cfg->gsharedvt_locals_var = locals_var;
7537
7538                 dreg = alloc_ireg (cfg);
7539                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7540
7541                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7542                 ins->dreg = locals_var->dreg;
7543                 ins->sreg1 = dreg;
7544                 MONO_ADD_INS (cfg->cbb, ins);
7545                 cfg->gsharedvt_locals_var_ins = ins;
7546                 
7547                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7548                 /*
7549                 if (init_locals)
7550                         ins->flags |= MONO_INST_INIT;
7551                 */
7552         }
7553
7554         if (mono_security_core_clr_enabled ()) {
7555                 /* check if this is native code, e.g. an icall or a p/invoke */
7556                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7557                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7558                         if (wrapped) {
7559                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7560                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7561
7562                                 /* if this ia a native call then it can only be JITted from platform code */
7563                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7564                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7565                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7566                                                         mono_get_exception_method_access ();
7567                                                 emit_throw_exception (cfg, ex);
7568                                         }
7569                                 }
7570                         }
7571                 }
7572         }
7573
7574         CHECK_CFG_EXCEPTION;
7575
7576         if (header->code_size == 0)
7577                 UNVERIFIED;
7578
7579         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7580                 ip = err_pos;
7581                 UNVERIFIED;
7582         }
7583
7584         if (cfg->method == method)
7585                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7586
7587         for (n = 0; n < header->num_locals; ++n) {
7588                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7589                         UNVERIFIED;
7590         }
7591         class_inits = NULL;
7592
7593         /* We force the vtable variable here for all shared methods
7594            for the possibility that they might show up in a stack
7595            trace where their exact instantiation is needed. */
7596         if (cfg->gshared && method == cfg->method) {
7597                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7598                                 mini_method_get_context (method)->method_inst ||
7599                                 method->klass->valuetype) {
7600                         mono_get_vtable_var (cfg);
7601                 } else {
7602                         /* FIXME: Is there a better way to do this?
7603                            We need the variable live for the duration
7604                            of the whole method. */
7605                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7606                 }
7607         }
7608
7609         /* add a check for this != NULL to inlined methods */
7610         if (is_virtual_call) {
7611                 MonoInst *arg_ins;
7612
7613                 NEW_ARGLOAD (cfg, arg_ins, 0);
7614                 MONO_ADD_INS (cfg->cbb, arg_ins);
7615                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7616         }
7617
7618         skip_dead_blocks = !dont_verify;
7619         if (skip_dead_blocks) {
7620                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7621                 CHECK_CFG_ERROR;
7622                 g_assert (bb);
7623         }
7624
7625         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7626         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7627
7628         ins_flag = 0;
7629         start_new_bblock = 0;
7630         while (ip < end) {
7631                 if (cfg->method == method)
7632                         cfg->real_offset = ip - header->code;
7633                 else
7634                         cfg->real_offset = inline_offset;
7635                 cfg->ip = ip;
7636
7637                 context_used = 0;
7638
7639                 if (start_new_bblock) {
7640                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7641                         if (start_new_bblock == 2) {
7642                                 g_assert (ip == tblock->cil_code);
7643                         } else {
7644                                 GET_BBLOCK (cfg, tblock, ip);
7645                         }
7646                         cfg->cbb->next_bb = tblock;
7647                         cfg->cbb = tblock;
7648                         start_new_bblock = 0;
7649                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7650                                 if (cfg->verbose_level > 3)
7651                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7652                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7653                                 *sp++ = ins;
7654                         }
7655                         if (class_inits)
7656                                 g_slist_free (class_inits);
7657                         class_inits = NULL;
7658                 } else {
7659                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7660                                 link_bblock (cfg, cfg->cbb, tblock);
7661                                 if (sp != stack_start) {
7662                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7663                                         sp = stack_start;
7664                                         CHECK_UNVERIFIABLE (cfg);
7665                                 }
7666                                 cfg->cbb->next_bb = tblock;
7667                                 cfg->cbb = tblock;
7668                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7669                                         if (cfg->verbose_level > 3)
7670                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7671                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7672                                         *sp++ = ins;
7673                                 }
7674                                 g_slist_free (class_inits);
7675                                 class_inits = NULL;
7676                         }
7677                 }
7678
7679                 if (skip_dead_blocks) {
7680                         int ip_offset = ip - header->code;
7681
7682                         if (ip_offset == bb->end)
7683                                 bb = bb->next;
7684
7685                         if (bb->dead) {
7686                                 int op_size = mono_opcode_size (ip, end);
7687                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7688
7689                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7690
7691                                 if (ip_offset + op_size == bb->end) {
7692                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7693                                         MONO_ADD_INS (cfg->cbb, ins);
7694                                         start_new_bblock = 1;
7695                                 }
7696
7697                                 ip += op_size;
7698                                 continue;
7699                         }
7700                 }
7701                 /*
7702                  * Sequence points are points where the debugger can place a breakpoint.
7703                  * Currently, we generate these automatically at points where the IL
7704                  * stack is empty.
7705                  */
7706                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7707                         /*
7708                          * Make methods interruptable at the beginning, and at the targets of
7709                          * backward branches.
7710                          * Also, do this at the start of every bblock in methods with clauses too,
7711                          * to be able to handle instructions with inprecise control flow like
7712                          * throw/endfinally.
7713                          * Backward branches are handled at the end of method-to-ir ().
7714                          */
7715                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7716                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7717
7718                         /* Avoid sequence points on empty IL like .volatile */
7719                         // FIXME: Enable this
7720                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7721                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7722                         if ((sp != stack_start) && !sym_seq_point)
7723                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7724                         MONO_ADD_INS (cfg->cbb, ins);
7725
7726                         if (sym_seq_points)
7727                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7728                 }
7729
7730                 cfg->cbb->real_offset = cfg->real_offset;
7731
7732                 if ((cfg->method == method) && cfg->coverage_info) {
7733                         guint32 cil_offset = ip - header->code;
7734                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7735
7736                         /* TODO: Use an increment here */
7737 #if defined(TARGET_X86)
7738                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
7739                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
7740                         ins->inst_imm = 1;
7741                         MONO_ADD_INS (cfg->cbb, ins);
7742 #else
7743                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
7744                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7745 #endif
7746                 }
7747
7748                 if (cfg->verbose_level > 3)
7749                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7750
7751                 switch (*ip) {
7752                 case CEE_NOP:
7753                         if (seq_points && !sym_seq_points && sp != stack_start) {
7754                                 /*
7755                                  * The C# compiler uses these nops to notify the JIT that it should
7756                                  * insert seq points.
7757                                  */
7758                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7759                                 MONO_ADD_INS (cfg->cbb, ins);
7760                         }
7761                         if (cfg->keep_cil_nops)
7762                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7763                         else
7764                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7765                         ip++;
7766                         MONO_ADD_INS (cfg->cbb, ins);
7767                         break;
7768                 case CEE_BREAK:
7769                         if (should_insert_brekpoint (cfg->method)) {
7770                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
7771                         } else {
7772                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7773                         }
7774                         ip++;
7775                         MONO_ADD_INS (cfg->cbb, ins);
7776                         break;
7777                 case CEE_LDARG_0:
7778                 case CEE_LDARG_1:
7779                 case CEE_LDARG_2:
7780                 case CEE_LDARG_3:
7781                         CHECK_STACK_OVF (1);
7782                         n = (*ip)-CEE_LDARG_0;
7783                         CHECK_ARG (n);
7784                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7785                         ip++;
7786                         *sp++ = ins;
7787                         break;
7788                 case CEE_LDLOC_0:
7789                 case CEE_LDLOC_1:
7790                 case CEE_LDLOC_2:
7791                 case CEE_LDLOC_3:
7792                         CHECK_STACK_OVF (1);
7793                         n = (*ip)-CEE_LDLOC_0;
7794                         CHECK_LOCAL (n);
7795                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7796                         ip++;
7797                         *sp++ = ins;
7798                         break;
7799                 case CEE_STLOC_0:
7800                 case CEE_STLOC_1:
7801                 case CEE_STLOC_2:
7802                 case CEE_STLOC_3: {
7803                         CHECK_STACK (1);
7804                         n = (*ip)-CEE_STLOC_0;
7805                         CHECK_LOCAL (n);
7806                         --sp;
7807                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
7808                                 UNVERIFIED;
7809                         emit_stloc_ir (cfg, sp, header, n);
7810                         ++ip;
7811                         inline_costs += 1;
7812                         break;
7813                         }
7814                 case CEE_LDARG_S:
7815                         CHECK_OPSIZE (2);
7816                         CHECK_STACK_OVF (1);
7817                         n = ip [1];
7818                         CHECK_ARG (n);
7819                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7820                         *sp++ = ins;
7821                         ip += 2;
7822                         break;
7823                 case CEE_LDARGA_S:
7824                         CHECK_OPSIZE (2);
7825                         CHECK_STACK_OVF (1);
7826                         n = ip [1];
7827                         CHECK_ARG (n);
7828                         NEW_ARGLOADA (cfg, ins, n);
7829                         MONO_ADD_INS (cfg->cbb, ins);
7830                         *sp++ = ins;
7831                         ip += 2;
7832                         break;
7833                 case CEE_STARG_S:
7834                         CHECK_OPSIZE (2);
7835                         CHECK_STACK (1);
7836                         --sp;
7837                         n = ip [1];
7838                         CHECK_ARG (n);
7839                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
7840                                 UNVERIFIED;
7841                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
7842                         ip += 2;
7843                         break;
7844                 case CEE_LDLOC_S:
7845                         CHECK_OPSIZE (2);
7846                         CHECK_STACK_OVF (1);
7847                         n = ip [1];
7848                         CHECK_LOCAL (n);
7849                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7850                         *sp++ = ins;
7851                         ip += 2;
7852                         break;
7853                 case CEE_LDLOCA_S: {
7854                         unsigned char *tmp_ip;
7855                         CHECK_OPSIZE (2);
7856                         CHECK_STACK_OVF (1);
7857                         CHECK_LOCAL (ip [1]);
7858
7859                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
7860                                 ip = tmp_ip;
7861                                 inline_costs += 1;
7862                                 break;
7863                         }
7864
7865                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
7866                         *sp++ = ins;
7867                         ip += 2;
7868                         break;
7869                 }
7870                 case CEE_STLOC_S:
7871                         CHECK_OPSIZE (2);
7872                         CHECK_STACK (1);
7873                         --sp;
7874                         CHECK_LOCAL (ip [1]);
7875                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
7876                                 UNVERIFIED;
7877                         emit_stloc_ir (cfg, sp, header, ip [1]);
7878                         ip += 2;
7879                         inline_costs += 1;
7880                         break;
7881                 case CEE_LDNULL:
7882                         CHECK_STACK_OVF (1);
7883                         EMIT_NEW_PCONST (cfg, ins, NULL);
7884                         ins->type = STACK_OBJ;
7885                         ++ip;
7886                         *sp++ = ins;
7887                         break;
7888                 case CEE_LDC_I4_M1:
7889                         CHECK_STACK_OVF (1);
7890                         EMIT_NEW_ICONST (cfg, ins, -1);
7891                         ++ip;
7892                         *sp++ = ins;
7893                         break;
7894                 case CEE_LDC_I4_0:
7895                 case CEE_LDC_I4_1:
7896                 case CEE_LDC_I4_2:
7897                 case CEE_LDC_I4_3:
7898                 case CEE_LDC_I4_4:
7899                 case CEE_LDC_I4_5:
7900                 case CEE_LDC_I4_6:
7901                 case CEE_LDC_I4_7:
7902                 case CEE_LDC_I4_8:
7903                         CHECK_STACK_OVF (1);
7904                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
7905                         ++ip;
7906                         *sp++ = ins;
7907                         break;
7908                 case CEE_LDC_I4_S:
7909                         CHECK_OPSIZE (2);
7910                         CHECK_STACK_OVF (1);
7911                         ++ip;
7912                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
7913                         ++ip;
7914                         *sp++ = ins;
7915                         break;
7916                 case CEE_LDC_I4:
7917                         CHECK_OPSIZE (5);
7918                         CHECK_STACK_OVF (1);
7919                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
7920                         ip += 5;
7921                         *sp++ = ins;
7922                         break;
7923                 case CEE_LDC_I8:
7924                         CHECK_OPSIZE (9);
7925                         CHECK_STACK_OVF (1);
7926                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
7927                         ins->type = STACK_I8;
7928                         ins->dreg = alloc_dreg (cfg, STACK_I8);
7929                         ++ip;
7930                         ins->inst_l = (gint64)read64 (ip);
7931                         MONO_ADD_INS (cfg->cbb, ins);
7932                         ip += 8;
7933                         *sp++ = ins;
7934                         break;
7935                 case CEE_LDC_R4: {
7936                         float *f;
7937                         gboolean use_aotconst = FALSE;
7938
7939 #ifdef TARGET_POWERPC
7940                         /* FIXME: Clean this up */
7941                         if (cfg->compile_aot)
7942                                 use_aotconst = TRUE;
7943 #endif
7944
7945                         /* FIXME: we should really allocate this only late in the compilation process */
7946                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
7947                         CHECK_OPSIZE (5);
7948                         CHECK_STACK_OVF (1);
7949
7950                         if (use_aotconst) {
7951                                 MonoInst *cons;
7952                                 int dreg;
7953
7954                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
7955
7956                                 dreg = alloc_freg (cfg);
7957                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
7958                                 ins->type = cfg->r4_stack_type;
7959                         } else {
7960                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
7961                                 ins->type = cfg->r4_stack_type;
7962                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
7963                                 ins->inst_p0 = f;
7964                                 MONO_ADD_INS (cfg->cbb, ins);
7965                         }
7966                         ++ip;
7967                         readr4 (ip, f);
7968                         ip += 4;
7969                         *sp++ = ins;                    
7970                         break;
7971                 }
7972                 case CEE_LDC_R8: {
7973                         double *d;
7974                         gboolean use_aotconst = FALSE;
7975
7976 #ifdef TARGET_POWERPC
7977                         /* FIXME: Clean this up */
7978                         if (cfg->compile_aot)
7979                                 use_aotconst = TRUE;
7980 #endif
7981
7982                         /* FIXME: we should really allocate this only late in the compilation process */
7983                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
7984                         CHECK_OPSIZE (9);
7985                         CHECK_STACK_OVF (1);
7986
7987                         if (use_aotconst) {
7988                                 MonoInst *cons;
7989                                 int dreg;
7990
7991                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
7992
7993                                 dreg = alloc_freg (cfg);
7994                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
7995                                 ins->type = STACK_R8;
7996                         } else {
7997                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7998                                 ins->type = STACK_R8;
7999                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8000                                 ins->inst_p0 = d;
8001                                 MONO_ADD_INS (cfg->cbb, ins);
8002                         }
8003                         ++ip;
8004                         readr8 (ip, d);
8005                         ip += 8;
8006                         *sp++ = ins;
8007                         break;
8008                 }
8009                 case CEE_DUP: {
8010                         MonoInst *temp, *store;
8011                         CHECK_STACK (1);
8012                         CHECK_STACK_OVF (1);
8013                         sp--;
8014                         ins = *sp;
8015
8016                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8017                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8018
8019                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8020                         *sp++ = ins;
8021
8022                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8023                         *sp++ = ins;
8024
8025                         ++ip;
8026                         inline_costs += 2;
8027                         break;
8028                 }
8029                 case CEE_POP:
8030                         CHECK_STACK (1);
8031                         ip++;
8032                         --sp;
8033
8034 #ifdef TARGET_X86
8035                         if (sp [0]->type == STACK_R8)
8036                                 /* we need to pop the value from the x86 FP stack */
8037                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8038 #endif
8039                         break;
8040                 case CEE_JMP: {
8041                         MonoCallInst *call;
8042                         MonoMethodSignature *fsig;
8043                         int i, n;
8044
8045                         INLINE_FAILURE ("jmp");
8046                         GSHAREDVT_FAILURE (*ip);
8047
8048                         CHECK_OPSIZE (5);
8049                         if (stack_start != sp)
8050                                 UNVERIFIED;
8051                         token = read32 (ip + 1);
8052                         /* FIXME: check the signature matches */
8053                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8054                         CHECK_CFG_ERROR;
8055  
8056                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8057                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8058
8059                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8060
8061                         fsig = mono_method_signature (cmethod);
8062                         n = fsig->param_count + fsig->hasthis;
8063                         if (cfg->llvm_only) {
8064                                 MonoInst **args;
8065
8066                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8067                                 for (i = 0; i < n; ++i)
8068                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8069                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8070                                 /*
8071                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8072                                  * have to emit a normal return since llvm expects it.
8073                                  */
8074                                 if (cfg->ret)
8075                                         emit_setret (cfg, ins);
8076                                 MONO_INST_NEW (cfg, ins, OP_BR);
8077                                 ins->inst_target_bb = end_bblock;
8078                                 MONO_ADD_INS (cfg->cbb, ins);
8079                                 link_bblock (cfg, cfg->cbb, end_bblock);
8080                                 ip += 5;
8081                                 break;
8082                         } else if (cfg->backend->have_op_tail_call) {
8083                                 /* Handle tail calls similarly to calls */
8084                                 DISABLE_AOT (cfg);
8085
8086                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8087                                 call->method = cmethod;
8088                                 call->tail_call = TRUE;
8089                                 call->signature = mono_method_signature (cmethod);
8090                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8091                                 call->inst.inst_p0 = cmethod;
8092                                 for (i = 0; i < n; ++i)
8093                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8094
8095                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8096                                         call->vret_var = cfg->vret_addr;
8097
8098                                 mono_arch_emit_call (cfg, call);
8099                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8100                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8101                         } else {
8102                                 for (i = 0; i < num_args; ++i)
8103                                         /* Prevent arguments from being optimized away */
8104                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8105
8106                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8107                                 ins = (MonoInst*)call;
8108                                 ins->inst_p0 = cmethod;
8109                                 MONO_ADD_INS (cfg->cbb, ins);
8110                         }
8111
8112                         ip += 5;
8113                         start_new_bblock = 1;
8114                         break;
8115                 }
8116                 case CEE_CALLI: {
8117                         MonoInst *addr;
8118                         MonoMethodSignature *fsig;
8119
8120                         CHECK_OPSIZE (5);
8121                         token = read32 (ip + 1);
8122
8123                         ins = NULL;
8124
8125                         //GSHAREDVT_FAILURE (*ip);
8126                         cmethod = NULL;
8127                         CHECK_STACK (1);
8128                         --sp;
8129                         addr = *sp;
8130                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8131                         CHECK_CFG_ERROR;
8132
8133                         if (method->dynamic && fsig->pinvoke) {
8134                                 MonoInst *args [3];
8135
8136                                 /*
8137                                  * This is a call through a function pointer using a pinvoke
8138                                  * signature. Have to create a wrapper and call that instead.
8139                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8140                                  * instead based on the signature.
8141                                  */
8142                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8143                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8144                                 args [2] = addr;
8145                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8146                         }
8147
8148                         n = fsig->param_count + fsig->hasthis;
8149
8150                         CHECK_STACK (n);
8151
8152                         //g_assert (!virtual_ || fsig->hasthis);
8153
8154                         sp -= n;
8155
8156                         inline_costs += 10 * num_calls++;
8157
8158                         /*
8159                          * Making generic calls out of gsharedvt methods.
8160                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8161                          * patching gshared method addresses into a gsharedvt method.
8162                          */
8163                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8164                                 /*
8165                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8166                                  */
8167                                 MonoInst *callee = addr;
8168
8169                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8170                                         /* Not tested */
8171                                         GSHAREDVT_FAILURE (*ip);
8172
8173                                 if (cfg->llvm_only)
8174                                         // FIXME:
8175                                         GSHAREDVT_FAILURE (*ip);
8176
8177                                 addr = emit_get_rgctx_sig (cfg, context_used,
8178                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8179                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8180                                 goto calli_end;
8181                         }
8182
8183                         /* Prevent inlining of methods with indirect calls */
8184                         INLINE_FAILURE ("indirect call");
8185
8186                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8187                                 MonoJumpInfoType info_type;
8188                                 gpointer info_data;
8189
8190                                 /*
8191                                  * Instead of emitting an indirect call, emit a direct call
8192                                  * with the contents of the aotconst as the patch info.
8193                                  */
8194                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8195                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8196                                         info_data = addr->inst_p0;
8197                                 } else {
8198                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8199                                         info_data = addr->inst_right->inst_left;
8200                                 }
8201
8202                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8203                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8204                                         NULLIFY_INS (addr);
8205                                         goto calli_end;
8206                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8207                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8208                                         NULLIFY_INS (addr);
8209                                         goto calli_end;
8210                                 }
8211                         }
8212                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8213
8214                         calli_end:
8215
8216                         /* End of call, INS should contain the result of the call, if any */
8217
8218                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8219                                 g_assert (ins);
8220                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8221                         }
8222
8223                         CHECK_CFG_EXCEPTION;
8224
8225                         ip += 5;
8226                         ins_flag = 0;
8227                         constrained_class = NULL;
8228                         break;
8229                 }
8230                 case CEE_CALL:
8231                 case CEE_CALLVIRT: {
8232                         MonoInst *addr = NULL;
8233                         MonoMethodSignature *fsig = NULL;
8234                         int array_rank = 0;
8235                         int virtual_ = *ip == CEE_CALLVIRT;
8236                         gboolean pass_imt_from_rgctx = FALSE;
8237                         MonoInst *imt_arg = NULL;
8238                         MonoInst *keep_this_alive = NULL;
8239                         gboolean pass_vtable = FALSE;
8240                         gboolean pass_mrgctx = FALSE;
8241                         MonoInst *vtable_arg = NULL;
8242                         gboolean check_this = FALSE;
8243                         gboolean supported_tail_call = FALSE;
8244                         gboolean tail_call = FALSE;
8245                         gboolean need_seq_point = FALSE;
8246                         guint32 call_opcode = *ip;
8247                         gboolean emit_widen = TRUE;
8248                         gboolean push_res = TRUE;
8249                         gboolean skip_ret = FALSE;
8250                         gboolean delegate_invoke = FALSE;
8251                         gboolean direct_icall = FALSE;
8252                         gboolean constrained_partial_call = FALSE;
8253                         MonoMethod *cil_method;
8254
8255                         CHECK_OPSIZE (5);
8256                         token = read32 (ip + 1);
8257
8258                         ins = NULL;
8259
8260                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8261                         CHECK_CFG_ERROR;
8262
8263                         cil_method = cmethod;
8264                                 
8265                         if (constrained_class) {
8266                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8267                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8268                                                 g_assert (!cmethod->klass->valuetype);
8269                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8270                                                         constrained_partial_call = TRUE;
8271                                         }
8272                                 }
8273
8274                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8275                                         if (cfg->verbose_level > 2)
8276                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8277                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8278                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8279                                                   cfg->gshared)) {
8280                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8281                                                 CHECK_CFG_ERROR;
8282                                         }
8283                                 } else {
8284                                         if (cfg->verbose_level > 2)
8285                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8286
8287                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8288                                                 /* 
8289                                                  * This is needed since get_method_constrained can't find 
8290                                                  * the method in klass representing a type var.
8291                                                  * The type var is guaranteed to be a reference type in this
8292                                                  * case.
8293                                                  */
8294                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8295                                                         g_assert (!cmethod->klass->valuetype);
8296                                         } else {
8297                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8298                                                 CHECK_CFG_ERROR;
8299                                         }
8300                                 }
8301
8302                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8303                                         /* Use the corresponding method from the base type to avoid boxing */
8304                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8305                                         g_assert (base_type);
8306                                         constrained_class = mono_class_from_mono_type (base_type);
8307                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8308                                         g_assert (cmethod);
8309                                 }
8310                         }
8311                                         
8312                         if (!dont_verify && !cfg->skip_visibility) {
8313                                 MonoMethod *target_method = cil_method;
8314                                 if (method->is_inflated) {
8315                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8316                                         CHECK_CFG_ERROR;
8317                                 }
8318                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8319                                         !mono_method_can_access_method (method, cil_method))
8320                                         emit_method_access_failure (cfg, method, cil_method);
8321                         }
8322
8323                         if (mono_security_core_clr_enabled ())
8324                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8325
8326                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8327                                 /* MS.NET seems to silently convert this to a callvirt */
8328                                 virtual_ = 1;
8329
8330                         {
8331                                 /*
8332                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8333                                  * converts to a callvirt.
8334                                  *
8335                                  * tests/bug-515884.il is an example of this behavior
8336                                  */
8337                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8338                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8339                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8340                                         virtual_ = 1;
8341                         }
8342
8343                         if (!cmethod->klass->inited)
8344                                 if (!mono_class_init (cmethod->klass))
8345                                         TYPE_LOAD_ERROR (cmethod->klass);
8346
8347                         fsig = mono_method_signature (cmethod);
8348                         if (!fsig)
8349                                 LOAD_ERROR;
8350                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8351                                 mini_class_is_system_array (cmethod->klass)) {
8352                                 array_rank = cmethod->klass->rank;
8353                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8354                                 direct_icall = TRUE;
8355                         } else if (fsig->pinvoke) {
8356                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8357                                 fsig = mono_method_signature (wrapper);
8358                         } else if (constrained_class) {
8359                         } else {
8360                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8361                                 CHECK_CFG_ERROR;
8362                         }
8363
8364                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8365                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8366
8367                         /* See code below */
8368                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8369                                 MonoBasicBlock *tbb;
8370
8371                                 GET_BBLOCK (cfg, tbb, ip + 5);
8372                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8373                                         /*
8374                                          * We want to extend the try block to cover the call, but we can't do it if the
8375                                          * call is made directly since its followed by an exception check.
8376                                          */
8377                                         direct_icall = FALSE;
8378                                 }
8379                         }
8380
8381                         mono_save_token_info (cfg, image, token, cil_method);
8382
8383                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8384                                 need_seq_point = TRUE;
8385
8386                         /* Don't support calls made using type arguments for now */
8387                         /*
8388                           if (cfg->gsharedvt) {
8389                           if (mini_is_gsharedvt_signature (fsig))
8390                           GSHAREDVT_FAILURE (*ip);
8391                           }
8392                         */
8393
8394                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8395                                 g_assert_not_reached ();
8396
8397                         n = fsig->param_count + fsig->hasthis;
8398
8399                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8400                                 UNVERIFIED;
8401
8402                         if (!cfg->gshared)
8403                                 g_assert (!mono_method_check_context_used (cmethod));
8404
8405                         CHECK_STACK (n);
8406
8407                         //g_assert (!virtual_ || fsig->hasthis);
8408
8409                         sp -= n;
8410
8411                         if (cmethod && cmethod->klass->image == mono_defaults.corlib && !strcmp (cmethod->klass->name, "ThrowHelper"))
8412                                 cfg->cbb->out_of_line = TRUE;
8413
8414                         /*
8415                          * We have the `constrained.' prefix opcode.
8416                          */
8417                         if (constrained_class) {
8418                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8419                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8420                                                 /* The 'Own method' case below */
8421                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8422                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8423                                         } else {
8424                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8425                                                 CHECK_CFG_EXCEPTION;
8426                                                 g_assert (ins);
8427                                                 goto call_end;
8428                                         }
8429                                 }
8430
8431                                 if (constrained_partial_call) {
8432                                         gboolean need_box = TRUE;
8433
8434                                         /*
8435                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8436                                          * called method is not known at compile time either. The called method could end up being
8437                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8438                                          * to box the receiver.
8439                                          * A simple solution would be to box always and make a normal virtual call, but that would
8440                                          * be bad performance wise.
8441                                          */
8442                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8443                                                 /*
8444                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8445                                                  */
8446                                                 need_box = FALSE;
8447                                         }
8448
8449                                         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)) {
8450                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8451                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8452                                                 ins->klass = constrained_class;
8453                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8454                                                 CHECK_CFG_EXCEPTION;
8455                                         } else if (need_box) {
8456                                                 MonoInst *box_type;
8457                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8458                                                 MonoInst *nonbox_call;
8459
8460                                                 /*
8461                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8462                                                  * if needed.
8463                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8464                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8465                                                  */
8466                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8467
8468                                                 NEW_BBLOCK (cfg, is_ref_bb);
8469                                                 NEW_BBLOCK (cfg, end_bb);
8470
8471                                                 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);
8472                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8473                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8474
8475                                                 /* Non-ref case */
8476                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8477
8478                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8479
8480                                                 /* Ref case */
8481                                                 MONO_START_BB (cfg, is_ref_bb);
8482                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8483                                                 ins->klass = constrained_class;
8484                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8485                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8486
8487                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8488
8489                                                 MONO_START_BB (cfg, end_bb);
8490                                                 cfg->cbb = end_bb;
8491
8492                                                 nonbox_call->dreg = ins->dreg;
8493                                                 goto call_end;
8494                                         } else {
8495                                                 g_assert (mono_class_is_interface (cmethod->klass));
8496                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8497                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8498                                                 goto call_end;
8499                                         }
8500                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8501                                         /*
8502                                          * The type parameter is instantiated as a valuetype,
8503                                          * but that type doesn't override the method we're
8504                                          * calling, so we need to box `this'.
8505                                          */
8506                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8507                                         ins->klass = constrained_class;
8508                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8509                                         CHECK_CFG_EXCEPTION;
8510                                 } else if (!constrained_class->valuetype) {
8511                                         int dreg = alloc_ireg_ref (cfg);
8512
8513                                         /*
8514                                          * The type parameter is instantiated as a reference
8515                                          * type.  We have a managed pointer on the stack, so
8516                                          * we need to dereference it here.
8517                                          */
8518                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8519                                         ins->type = STACK_OBJ;
8520                                         sp [0] = ins;
8521                                 } else {
8522                                         if (cmethod->klass->valuetype) {
8523                                                 /* Own method */
8524                                         } else {
8525                                                 /* Interface method */
8526                                                 int ioffset, slot;
8527
8528                                                 mono_class_setup_vtable (constrained_class);
8529                                                 CHECK_TYPELOAD (constrained_class);
8530                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8531                                                 if (ioffset == -1)
8532                                                         TYPE_LOAD_ERROR (constrained_class);
8533                                                 slot = mono_method_get_vtable_slot (cmethod);
8534                                                 if (slot == -1)
8535                                                         TYPE_LOAD_ERROR (cmethod->klass);
8536                                                 cmethod = constrained_class->vtable [ioffset + slot];
8537
8538                                                 if (cmethod->klass == mono_defaults.enum_class) {
8539                                                         /* Enum implements some interfaces, so treat this as the first case */
8540                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8541                                                         ins->klass = constrained_class;
8542                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8543                                                         CHECK_CFG_EXCEPTION;
8544                                                 }
8545                                         }
8546                                         virtual_ = 0;
8547                                 }
8548                                 constrained_class = NULL;
8549                         }
8550
8551                         if (check_call_signature (cfg, fsig, sp))
8552                                 UNVERIFIED;
8553
8554                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8555                                 delegate_invoke = TRUE;
8556
8557                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8558                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8559                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8560                                         emit_widen = FALSE;
8561                                 }
8562
8563                                 goto call_end;
8564                         }
8565
8566                         /* 
8567                          * If the callee is a shared method, then its static cctor
8568                          * might not get called after the call was patched.
8569                          */
8570                         if (cfg->gshared && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
8571                                 emit_class_init (cfg, cmethod->klass);
8572                                 CHECK_TYPELOAD (cmethod->klass);
8573                         }
8574
8575                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8576
8577                         if (cfg->gshared) {
8578                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8579
8580                                 context_used = mini_method_check_context_used (cfg, cmethod);
8581
8582                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8583                                         /* Generic method interface
8584                                            calls are resolved via a
8585                                            helper function and don't
8586                                            need an imt. */
8587                                         if (!cmethod_context || !cmethod_context->method_inst)
8588                                                 pass_imt_from_rgctx = TRUE;
8589                                 }
8590
8591                                 /*
8592                                  * If a shared method calls another
8593                                  * shared method then the caller must
8594                                  * have a generic sharing context
8595                                  * because the magic trampoline
8596                                  * requires it.  FIXME: We shouldn't
8597                                  * have to force the vtable/mrgctx
8598                                  * variable here.  Instead there
8599                                  * should be a flag in the cfg to
8600                                  * request a generic sharing context.
8601                                  */
8602                                 if (context_used &&
8603                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8604                                         mono_get_vtable_var (cfg);
8605                         }
8606
8607                         if (pass_vtable) {
8608                                 if (context_used) {
8609                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8610                                 } else {
8611                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8612
8613                                         CHECK_TYPELOAD (cmethod->klass);
8614                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8615                                 }
8616                         }
8617
8618                         if (pass_mrgctx) {
8619                                 g_assert (!vtable_arg);
8620
8621                                 if (!cfg->compile_aot) {
8622                                         /* 
8623                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8624                                          * for type load errors before.
8625                                          */
8626                                         mono_class_setup_vtable (cmethod->klass);
8627                                         CHECK_TYPELOAD (cmethod->klass);
8628                                 }
8629
8630                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8631
8632                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8633                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8634                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8635                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8636                                         if (virtual_)
8637                                                 check_this = TRUE;
8638                                         virtual_ = 0;
8639                                 }
8640                         }
8641
8642                         if (pass_imt_from_rgctx) {
8643                                 g_assert (!pass_vtable);
8644
8645                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8646                                         cmethod, MONO_RGCTX_INFO_METHOD);
8647                         }
8648
8649                         if (check_this)
8650                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8651
8652                         /* Calling virtual generic methods */
8653                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8654                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8655                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8656                             fsig->generic_param_count && 
8657                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8658                                 !cfg->llvm_only) {
8659                                 MonoInst *this_temp, *this_arg_temp, *store;
8660                                 MonoInst *iargs [4];
8661
8662                                 g_assert (fsig->is_inflated);
8663
8664                                 /* Prevent inlining of methods that contain indirect calls */
8665                                 INLINE_FAILURE ("virtual generic call");
8666
8667                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8668                                         GSHAREDVT_FAILURE (*ip);
8669
8670                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8671                                         g_assert (!imt_arg);
8672                                         if (!context_used)
8673                                                 g_assert (cmethod->is_inflated);
8674                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8675                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8676                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8677                                 } else {
8678                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8679                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8680                                         MONO_ADD_INS (cfg->cbb, store);
8681
8682                                         /* FIXME: This should be a managed pointer */
8683                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8684
8685                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8686                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8687                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8688                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8689                                         addr = mono_emit_jit_icall (cfg,
8690                                                                                                 mono_helper_compile_generic_method, iargs);
8691
8692                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8693
8694                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8695                                 }
8696
8697                                 goto call_end;
8698                         }
8699
8700                         /*
8701                          * Implement a workaround for the inherent races involved in locking:
8702                          * Monitor.Enter ()
8703                          * try {
8704                          * } finally {
8705                          *    Monitor.Exit ()
8706                          * }
8707                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8708                          * try block, the Exit () won't be executed, see:
8709                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8710                          * To work around this, we extend such try blocks to include the last x bytes
8711                          * of the Monitor.Enter () call.
8712                          */
8713                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8714                                 MonoBasicBlock *tbb;
8715
8716                                 GET_BBLOCK (cfg, tbb, ip + 5);
8717                                 /* 
8718                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8719                                  * from Monitor.Enter like ArgumentNullException.
8720                                  */
8721                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8722                                         /* Mark this bblock as needing to be extended */
8723                                         tbb->extend_try_block = TRUE;
8724                                 }
8725                         }
8726
8727                         /* Conversion to a JIT intrinsic */
8728                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8729                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8730                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8731                                         emit_widen = FALSE;
8732                                 }
8733                                 goto call_end;
8734                         }
8735                         CHECK_CFG_ERROR;
8736                         
8737                         /* Inlining */
8738                         if ((cfg->opt & MONO_OPT_INLINE) &&
8739                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8740                             mono_method_check_inlining (cfg, cmethod)) {
8741                                 int costs;
8742                                 gboolean always = FALSE;
8743
8744                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8745                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8746                                         /* Prevent inlining of methods that call wrappers */
8747                                         INLINE_FAILURE ("wrapper call");
8748                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8749                                         always = TRUE;
8750                                 }
8751
8752                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8753                                 if (costs) {
8754                                         cfg->real_offset += 5;
8755
8756                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8757                                                 /* *sp is already set by inline_method */
8758                                                 sp++;
8759                                                 push_res = FALSE;
8760                                         }
8761
8762                                         inline_costs += costs;
8763
8764                                         goto call_end;
8765                                 }
8766                         }
8767
8768                         /* Tail recursion elimination */
8769                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
8770                                 gboolean has_vtargs = FALSE;
8771                                 int i;
8772
8773                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8774                                 INLINE_FAILURE ("tail call");
8775
8776                                 /* keep it simple */
8777                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
8778                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
8779                                                 has_vtargs = TRUE;
8780                                 }
8781
8782                                 if (!has_vtargs) {
8783                                         if (need_seq_point) {
8784                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
8785                                                 need_seq_point = FALSE;
8786                                         }
8787                                         for (i = 0; i < n; ++i)
8788                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8789                                         MONO_INST_NEW (cfg, ins, OP_BR);
8790                                         MONO_ADD_INS (cfg->cbb, ins);
8791                                         tblock = start_bblock->out_bb [0];
8792                                         link_bblock (cfg, cfg->cbb, tblock);
8793                                         ins->inst_target_bb = tblock;
8794                                         start_new_bblock = 1;
8795
8796                                         /* skip the CEE_RET, too */
8797                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
8798                                                 skip_ret = TRUE;
8799                                         push_res = FALSE;
8800                                         goto call_end;
8801                                 }
8802                         }
8803
8804                         inline_costs += 10 * num_calls++;
8805
8806                         /*
8807                          * Synchronized wrappers.
8808                          * Its hard to determine where to replace a method with its synchronized
8809                          * wrapper without causing an infinite recursion. The current solution is
8810                          * to add the synchronized wrapper in the trampolines, and to
8811                          * change the called method to a dummy wrapper, and resolve that wrapper
8812                          * to the real method in mono_jit_compile_method ().
8813                          */
8814                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
8815                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
8816                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
8817                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
8818                         }
8819
8820                         /*
8821                          * Making generic calls out of gsharedvt methods.
8822                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8823                          * patching gshared method addresses into a gsharedvt method.
8824                          */
8825                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
8826                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
8827                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
8828                                 MonoRgctxInfoType info_type;
8829
8830                                 if (virtual_) {
8831                                         //if (mono_class_is_interface (cmethod->klass))
8832                                                 //GSHAREDVT_FAILURE (*ip);
8833                                         // disable for possible remoting calls
8834                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
8835                                                 GSHAREDVT_FAILURE (*ip);
8836                                         if (fsig->generic_param_count) {
8837                                                 /* virtual generic call */
8838                                                 g_assert (!imt_arg);
8839                                                 /* Same as the virtual generic case above */
8840                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8841                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8842                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
8843                                                 vtable_arg = NULL;
8844                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
8845                                                 /* This can happen when we call a fully instantiated iface method */
8846                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8847                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8848                                                 vtable_arg = NULL;
8849                                         }
8850                                 }
8851
8852                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
8853                                         keep_this_alive = sp [0];
8854
8855                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
8856                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
8857                                 else
8858                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
8859                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
8860
8861                                 if (cfg->llvm_only) {
8862                                         // FIXME: Avoid initializing vtable_arg
8863                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8864                                 } else {
8865                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8866                                 }
8867                                 goto call_end;
8868                         }
8869
8870                         /* Generic sharing */
8871
8872                         /*
8873                          * Use this if the callee is gsharedvt sharable too, since
8874                          * at runtime we might find an instantiation so the call cannot
8875                          * be patched (the 'no_patch' code path in mini-trampolines.c).
8876                          */
8877                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
8878                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8879                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
8880                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
8881                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
8882                                 INLINE_FAILURE ("gshared");
8883
8884                                 g_assert (cfg->gshared && cmethod);
8885                                 g_assert (!addr);
8886
8887                                 /*
8888                                  * We are compiling a call to a
8889                                  * generic method from shared code,
8890                                  * which means that we have to look up
8891                                  * the method in the rgctx and do an
8892                                  * indirect call.
8893                                  */
8894                                 if (fsig->hasthis)
8895                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8896
8897                                 if (cfg->llvm_only) {
8898                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
8899                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
8900                                         else
8901                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8902                                         // FIXME: Avoid initializing imt_arg/vtable_arg
8903                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8904                                 } else {
8905                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8906                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8907                                 }
8908                                 goto call_end;
8909                         }
8910
8911                         /* Direct calls to icalls */
8912                         if (direct_icall) {
8913                                 MonoMethod *wrapper;
8914                                 int costs;
8915
8916                                 /* Inline the wrapper */
8917                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8918
8919                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
8920                                 g_assert (costs > 0);
8921                                 cfg->real_offset += 5;
8922
8923                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8924                                         /* *sp is already set by inline_method */
8925                                         sp++;
8926                                         push_res = FALSE;
8927                                 }
8928
8929                                 inline_costs += costs;
8930
8931                                 goto call_end;
8932                         }
8933                                         
8934                         /* Array methods */
8935                         if (array_rank) {
8936                                 MonoInst *addr;
8937
8938                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
8939                                         MonoInst *val = sp [fsig->param_count];
8940
8941                                         if (val->type == STACK_OBJ) {
8942                                                 MonoInst *iargs [2];
8943
8944                                                 iargs [0] = sp [0];
8945                                                 iargs [1] = val;
8946                                                 
8947                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
8948                                         }
8949                                         
8950                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
8951                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
8952                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
8953                                                 mini_emit_write_barrier (cfg, addr, val);
8954                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
8955                                                 GSHAREDVT_FAILURE (*ip);
8956                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
8957                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8958
8959                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
8960                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
8961                                         if (!cmethod->klass->element_class->valuetype && !readonly)
8962                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
8963                                         CHECK_TYPELOAD (cmethod->klass);
8964                                         
8965                                         readonly = FALSE;
8966                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
8967                                         ins = addr;
8968                                 } else {
8969                                         g_assert_not_reached ();
8970                                 }
8971
8972                                 emit_widen = FALSE;
8973                                 goto call_end;
8974                         }
8975
8976                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
8977                         if (ins)
8978                                 goto call_end;
8979
8980                         /* Tail prefix / tail call optimization */
8981
8982                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
8983                         /* FIXME: runtime generic context pointer for jumps? */
8984                         /* FIXME: handle this for generic sharing eventually */
8985                         if ((ins_flag & MONO_INST_TAILCALL) &&
8986                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
8987                                 supported_tail_call = TRUE;
8988
8989                         if (supported_tail_call) {
8990                                 MonoCallInst *call;
8991
8992                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8993                                 INLINE_FAILURE ("tail call");
8994
8995                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
8996
8997                                 if (cfg->backend->have_op_tail_call) {
8998                                         /* Handle tail calls similarly to normal calls */
8999                                         tail_call = TRUE;
9000                                 } else {
9001                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9002
9003                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9004                                         call->tail_call = TRUE;
9005                                         call->method = cmethod;
9006                                         call->signature = mono_method_signature (cmethod);
9007
9008                                         /*
9009                                          * We implement tail calls by storing the actual arguments into the 
9010                                          * argument variables, then emitting a CEE_JMP.
9011                                          */
9012                                         for (i = 0; i < n; ++i) {
9013                                                 /* Prevent argument from being register allocated */
9014                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9015                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9016                                         }
9017                                         ins = (MonoInst*)call;
9018                                         ins->inst_p0 = cmethod;
9019                                         ins->inst_p1 = arg_array [0];
9020                                         MONO_ADD_INS (cfg->cbb, ins);
9021                                         link_bblock (cfg, cfg->cbb, end_bblock);
9022                                         start_new_bblock = 1;
9023
9024                                         // FIXME: Eliminate unreachable epilogs
9025
9026                                         /*
9027                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9028                                          * only reachable from this call.
9029                                          */
9030                                         GET_BBLOCK (cfg, tblock, ip + 5);
9031                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9032                                                 skip_ret = TRUE;
9033                                         push_res = FALSE;
9034
9035                                         goto call_end;
9036                                 }
9037                         }
9038
9039                         /*
9040                          * Virtual calls in llvm-only mode.
9041                          */
9042                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9043                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9044                                 goto call_end;
9045                         }
9046
9047                         /* Common call */
9048                         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) && !(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9049                                 INLINE_FAILURE ("call");
9050                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9051                                                                                           imt_arg, vtable_arg);
9052
9053                         if (tail_call && !cfg->llvm_only) {
9054                                 link_bblock (cfg, cfg->cbb, end_bblock);
9055                                 start_new_bblock = 1;
9056
9057                                 // FIXME: Eliminate unreachable epilogs
9058
9059                                 /*
9060                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9061                                  * only reachable from this call.
9062                                  */
9063                                 GET_BBLOCK (cfg, tblock, ip + 5);
9064                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9065                                         skip_ret = TRUE;
9066                                 push_res = FALSE;
9067                         }
9068
9069                         call_end:
9070
9071                         /* End of call, INS should contain the result of the call, if any */
9072
9073                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9074                                 g_assert (ins);
9075                                 if (emit_widen)
9076                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9077                                 else
9078                                         *sp++ = ins;
9079                         }
9080
9081                         if (keep_this_alive) {
9082                                 MonoInst *dummy_use;
9083
9084                                 /* See mono_emit_method_call_full () */
9085                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9086                         }
9087
9088                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9089                                 /*
9090                                  * Clang can convert these calls to tail calls which screw up the stack
9091                                  * walk. This happens even when the -fno-optimize-sibling-calls
9092                                  * option is passed to clang.
9093                                  * Work around this by emitting a dummy call.
9094                                  */
9095                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9096                         }
9097
9098                         CHECK_CFG_EXCEPTION;
9099
9100                         ip += 5;
9101                         if (skip_ret) {
9102                                 g_assert (*ip == CEE_RET);
9103                                 ip += 1;
9104                         }
9105                         ins_flag = 0;
9106                         constrained_class = NULL;
9107                         if (need_seq_point)
9108                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9109                         break;
9110                 }
9111                 case CEE_RET:
9112                         if (cfg->method != method) {
9113                                 /* return from inlined method */
9114                                 /* 
9115                                  * If in_count == 0, that means the ret is unreachable due to
9116                                  * being preceeded by a throw. In that case, inline_method () will
9117                                  * handle setting the return value 
9118                                  * (test case: test_0_inline_throw ()).
9119                                  */
9120                                 if (return_var && cfg->cbb->in_count) {
9121                                         MonoType *ret_type = mono_method_signature (method)->ret;
9122
9123                                         MonoInst *store;
9124                                         CHECK_STACK (1);
9125                                         --sp;
9126
9127                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9128                                                 UNVERIFIED;
9129
9130                                         //g_assert (returnvar != -1);
9131                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9132                                         cfg->ret_var_set = TRUE;
9133                                 } 
9134                         } else {
9135                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9136
9137                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9138                                         emit_pop_lmf (cfg);
9139
9140                                 if (cfg->ret) {
9141                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9142
9143                                         if (seq_points && !sym_seq_points) {
9144                                                 /* 
9145                                                  * Place a seq point here too even through the IL stack is not
9146                                                  * empty, so a step over on
9147                                                  * call <FOO>
9148                                                  * ret
9149                                                  * will work correctly.
9150                                                  */
9151                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9152                                                 MONO_ADD_INS (cfg->cbb, ins);
9153                                         }
9154
9155                                         g_assert (!return_var);
9156                                         CHECK_STACK (1);
9157                                         --sp;
9158
9159                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9160                                                 UNVERIFIED;
9161
9162                                         emit_setret (cfg, *sp);
9163                                 }
9164                         }
9165                         if (sp != stack_start)
9166                                 UNVERIFIED;
9167                         MONO_INST_NEW (cfg, ins, OP_BR);
9168                         ip++;
9169                         ins->inst_target_bb = end_bblock;
9170                         MONO_ADD_INS (cfg->cbb, ins);
9171                         link_bblock (cfg, cfg->cbb, end_bblock);
9172                         start_new_bblock = 1;
9173                         break;
9174                 case CEE_BR_S:
9175                         CHECK_OPSIZE (2);
9176                         MONO_INST_NEW (cfg, ins, OP_BR);
9177                         ip++;
9178                         target = ip + 1 + (signed char)(*ip);
9179                         ++ip;
9180                         GET_BBLOCK (cfg, tblock, target);
9181                         link_bblock (cfg, cfg->cbb, tblock);
9182                         ins->inst_target_bb = tblock;
9183                         if (sp != stack_start) {
9184                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9185                                 sp = stack_start;
9186                                 CHECK_UNVERIFIABLE (cfg);
9187                         }
9188                         MONO_ADD_INS (cfg->cbb, ins);
9189                         start_new_bblock = 1;
9190                         inline_costs += BRANCH_COST;
9191                         break;
9192                 case CEE_BEQ_S:
9193                 case CEE_BGE_S:
9194                 case CEE_BGT_S:
9195                 case CEE_BLE_S:
9196                 case CEE_BLT_S:
9197                 case CEE_BNE_UN_S:
9198                 case CEE_BGE_UN_S:
9199                 case CEE_BGT_UN_S:
9200                 case CEE_BLE_UN_S:
9201                 case CEE_BLT_UN_S:
9202                         CHECK_OPSIZE (2);
9203                         CHECK_STACK (2);
9204                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9205                         ip++;
9206                         target = ip + 1 + *(signed char*)ip;
9207                         ip++;
9208
9209                         ADD_BINCOND (NULL);
9210
9211                         sp = stack_start;
9212                         inline_costs += BRANCH_COST;
9213                         break;
9214                 case CEE_BR:
9215                         CHECK_OPSIZE (5);
9216                         MONO_INST_NEW (cfg, ins, OP_BR);
9217                         ip++;
9218
9219                         target = ip + 4 + (gint32)read32(ip);
9220                         ip += 4;
9221                         GET_BBLOCK (cfg, tblock, target);
9222                         link_bblock (cfg, cfg->cbb, tblock);
9223                         ins->inst_target_bb = tblock;
9224                         if (sp != stack_start) {
9225                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9226                                 sp = stack_start;
9227                                 CHECK_UNVERIFIABLE (cfg);
9228                         }
9229
9230                         MONO_ADD_INS (cfg->cbb, ins);
9231
9232                         start_new_bblock = 1;
9233                         inline_costs += BRANCH_COST;
9234                         break;
9235                 case CEE_BRFALSE_S:
9236                 case CEE_BRTRUE_S:
9237                 case CEE_BRFALSE:
9238                 case CEE_BRTRUE: {
9239                         MonoInst *cmp;
9240                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9241                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9242                         guint32 opsize = is_short ? 1 : 4;
9243
9244                         CHECK_OPSIZE (opsize);
9245                         CHECK_STACK (1);
9246                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9247                                 UNVERIFIED;
9248                         ip ++;
9249                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9250                         ip += opsize;
9251
9252                         sp--;
9253
9254                         GET_BBLOCK (cfg, tblock, target);
9255                         link_bblock (cfg, cfg->cbb, tblock);
9256                         GET_BBLOCK (cfg, tblock, ip);
9257                         link_bblock (cfg, cfg->cbb, tblock);
9258
9259                         if (sp != stack_start) {
9260                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9261                                 CHECK_UNVERIFIABLE (cfg);
9262                         }
9263
9264                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9265                         cmp->sreg1 = sp [0]->dreg;
9266                         type_from_op (cfg, cmp, sp [0], NULL);
9267                         CHECK_TYPE (cmp);
9268
9269 #if SIZEOF_REGISTER == 4
9270                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9271                                 /* Convert it to OP_LCOMPARE */
9272                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9273                                 ins->type = STACK_I8;
9274                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9275                                 ins->inst_l = 0;
9276                                 MONO_ADD_INS (cfg->cbb, ins);
9277                                 cmp->opcode = OP_LCOMPARE;
9278                                 cmp->sreg2 = ins->dreg;
9279                         }
9280 #endif
9281                         MONO_ADD_INS (cfg->cbb, cmp);
9282
9283                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9284                         type_from_op (cfg, ins, sp [0], NULL);
9285                         MONO_ADD_INS (cfg->cbb, ins);
9286                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9287                         GET_BBLOCK (cfg, tblock, target);
9288                         ins->inst_true_bb = tblock;
9289                         GET_BBLOCK (cfg, tblock, ip);
9290                         ins->inst_false_bb = tblock;
9291                         start_new_bblock = 2;
9292
9293                         sp = stack_start;
9294                         inline_costs += BRANCH_COST;
9295                         break;
9296                 }
9297                 case CEE_BEQ:
9298                 case CEE_BGE:
9299                 case CEE_BGT:
9300                 case CEE_BLE:
9301                 case CEE_BLT:
9302                 case CEE_BNE_UN:
9303                 case CEE_BGE_UN:
9304                 case CEE_BGT_UN:
9305                 case CEE_BLE_UN:
9306                 case CEE_BLT_UN:
9307                         CHECK_OPSIZE (5);
9308                         CHECK_STACK (2);
9309                         MONO_INST_NEW (cfg, ins, *ip);
9310                         ip++;
9311                         target = ip + 4 + (gint32)read32(ip);
9312                         ip += 4;
9313
9314                         ADD_BINCOND (NULL);
9315
9316                         sp = stack_start;
9317                         inline_costs += BRANCH_COST;
9318                         break;
9319                 case CEE_SWITCH: {
9320                         MonoInst *src1;
9321                         MonoBasicBlock **targets;
9322                         MonoBasicBlock *default_bblock;
9323                         MonoJumpInfoBBTable *table;
9324                         int offset_reg = alloc_preg (cfg);
9325                         int target_reg = alloc_preg (cfg);
9326                         int table_reg = alloc_preg (cfg);
9327                         int sum_reg = alloc_preg (cfg);
9328                         gboolean use_op_switch;
9329
9330                         CHECK_OPSIZE (5);
9331                         CHECK_STACK (1);
9332                         n = read32 (ip + 1);
9333                         --sp;
9334                         src1 = sp [0];
9335                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9336                                 UNVERIFIED;
9337
9338                         ip += 5;
9339                         CHECK_OPSIZE (n * sizeof (guint32));
9340                         target = ip + n * sizeof (guint32);
9341
9342                         GET_BBLOCK (cfg, default_bblock, target);
9343                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9344
9345                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9346                         for (i = 0; i < n; ++i) {
9347                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9348                                 targets [i] = tblock;
9349                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9350                                 ip += 4;
9351                         }
9352
9353                         if (sp != stack_start) {
9354                                 /* 
9355                                  * Link the current bb with the targets as well, so handle_stack_args
9356                                  * will set their in_stack correctly.
9357                                  */
9358                                 link_bblock (cfg, cfg->cbb, default_bblock);
9359                                 for (i = 0; i < n; ++i)
9360                                         link_bblock (cfg, cfg->cbb, targets [i]);
9361
9362                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9363                                 sp = stack_start;
9364                                 CHECK_UNVERIFIABLE (cfg);
9365
9366                                 /* Undo the links */
9367                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9368                                 for (i = 0; i < n; ++i)
9369                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9370                         }
9371
9372                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9373                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9374
9375                         for (i = 0; i < n; ++i)
9376                                 link_bblock (cfg, cfg->cbb, targets [i]);
9377
9378                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9379                         table->table = targets;
9380                         table->table_size = n;
9381
9382                         use_op_switch = FALSE;
9383 #ifdef TARGET_ARM
9384                         /* ARM implements SWITCH statements differently */
9385                         /* FIXME: Make it use the generic implementation */
9386                         if (!cfg->compile_aot)
9387                                 use_op_switch = TRUE;
9388 #endif
9389
9390                         if (COMPILE_LLVM (cfg))
9391                                 use_op_switch = TRUE;
9392
9393                         cfg->cbb->has_jump_table = 1;
9394
9395                         if (use_op_switch) {
9396                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9397                                 ins->sreg1 = src1->dreg;
9398                                 ins->inst_p0 = table;
9399                                 ins->inst_many_bb = targets;
9400                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9401                                 MONO_ADD_INS (cfg->cbb, ins);
9402                         } else {
9403                                 if (sizeof (gpointer) == 8)
9404                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9405                                 else
9406                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9407
9408 #if SIZEOF_REGISTER == 8
9409                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9410                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9411 #endif
9412
9413                                 if (cfg->compile_aot) {
9414                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9415                                 } else {
9416                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9417                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9418                                         ins->inst_p0 = table;
9419                                         ins->dreg = table_reg;
9420                                         MONO_ADD_INS (cfg->cbb, ins);
9421                                 }
9422
9423                                 /* FIXME: Use load_memindex */
9424                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9425                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9426                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9427                         }
9428                         start_new_bblock = 1;
9429                         inline_costs += (BRANCH_COST * 2);
9430                         break;
9431                 }
9432                 case CEE_LDIND_I1:
9433                 case CEE_LDIND_U1:
9434                 case CEE_LDIND_I2:
9435                 case CEE_LDIND_U2:
9436                 case CEE_LDIND_I4:
9437                 case CEE_LDIND_U4:
9438                 case CEE_LDIND_I8:
9439                 case CEE_LDIND_I:
9440                 case CEE_LDIND_R4:
9441                 case CEE_LDIND_R8:
9442                 case CEE_LDIND_REF:
9443                         CHECK_STACK (1);
9444                         --sp;
9445
9446                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9447                         *sp++ = ins;
9448                         ins_flag = 0;
9449                         ++ip;
9450                         break;
9451                 case CEE_STIND_REF:
9452                 case CEE_STIND_I1:
9453                 case CEE_STIND_I2:
9454                 case CEE_STIND_I4:
9455                 case CEE_STIND_I8:
9456                 case CEE_STIND_R4:
9457                 case CEE_STIND_R8:
9458                 case CEE_STIND_I:
9459                         CHECK_STACK (2);
9460                         sp -= 2;
9461
9462                         if (ins_flag & MONO_INST_VOLATILE) {
9463                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9464                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9465                         }
9466
9467                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9468                         ins->flags |= ins_flag;
9469                         ins_flag = 0;
9470
9471                         MONO_ADD_INS (cfg->cbb, ins);
9472
9473                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9474                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9475
9476                         inline_costs += 1;
9477                         ++ip;
9478                         break;
9479
9480                 case CEE_MUL:
9481                         CHECK_STACK (2);
9482
9483                         MONO_INST_NEW (cfg, ins, (*ip));
9484                         sp -= 2;
9485                         ins->sreg1 = sp [0]->dreg;
9486                         ins->sreg2 = sp [1]->dreg;
9487                         type_from_op (cfg, ins, sp [0], sp [1]);
9488                         CHECK_TYPE (ins);
9489                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9490
9491                         /* Use the immediate opcodes if possible */
9492                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9493                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9494                                 if (imm_opcode != -1) {
9495                                         ins->opcode = imm_opcode;
9496                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9497                                         ins->sreg2 = -1;
9498
9499                                         NULLIFY_INS (sp [1]);
9500                                 }
9501                         }
9502
9503                         MONO_ADD_INS ((cfg)->cbb, (ins));
9504
9505                         *sp++ = mono_decompose_opcode (cfg, ins);
9506                         ip++;
9507                         break;
9508                 case CEE_ADD:
9509                 case CEE_SUB:
9510                 case CEE_DIV:
9511                 case CEE_DIV_UN:
9512                 case CEE_REM:
9513                 case CEE_REM_UN:
9514                 case CEE_AND:
9515                 case CEE_OR:
9516                 case CEE_XOR:
9517                 case CEE_SHL:
9518                 case CEE_SHR:
9519                 case CEE_SHR_UN:
9520                         CHECK_STACK (2);
9521
9522                         MONO_INST_NEW (cfg, ins, (*ip));
9523                         sp -= 2;
9524                         ins->sreg1 = sp [0]->dreg;
9525                         ins->sreg2 = sp [1]->dreg;
9526                         type_from_op (cfg, ins, sp [0], sp [1]);
9527                         CHECK_TYPE (ins);
9528                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9529                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9530
9531                         /* FIXME: Pass opcode to is_inst_imm */
9532
9533                         /* Use the immediate opcodes if possible */
9534                         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)) {
9535                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9536                                 if (imm_opcode != -1) {
9537                                         ins->opcode = imm_opcode;
9538                                         if (sp [1]->opcode == OP_I8CONST) {
9539 #if SIZEOF_REGISTER == 8
9540                                                 ins->inst_imm = sp [1]->inst_l;
9541 #else
9542                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9543                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9544 #endif
9545                                         }
9546                                         else
9547                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9548                                         ins->sreg2 = -1;
9549
9550                                         /* Might be followed by an instruction added by add_widen_op */
9551                                         if (sp [1]->next == NULL)
9552                                                 NULLIFY_INS (sp [1]);
9553                                 }
9554                         }
9555                         MONO_ADD_INS ((cfg)->cbb, (ins));
9556
9557                         *sp++ = mono_decompose_opcode (cfg, ins);
9558                         ip++;
9559                         break;
9560                 case CEE_NEG:
9561                 case CEE_NOT:
9562                 case CEE_CONV_I1:
9563                 case CEE_CONV_I2:
9564                 case CEE_CONV_I4:
9565                 case CEE_CONV_R4:
9566                 case CEE_CONV_R8:
9567                 case CEE_CONV_U4:
9568                 case CEE_CONV_I8:
9569                 case CEE_CONV_U8:
9570                 case CEE_CONV_OVF_I8:
9571                 case CEE_CONV_OVF_U8:
9572                 case CEE_CONV_R_UN:
9573                         CHECK_STACK (1);
9574
9575                         /* Special case this earlier so we have long constants in the IR */
9576                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9577                                 int data = sp [-1]->inst_c0;
9578                                 sp [-1]->opcode = OP_I8CONST;
9579                                 sp [-1]->type = STACK_I8;
9580 #if SIZEOF_REGISTER == 8
9581                                 if ((*ip) == CEE_CONV_U8)
9582                                         sp [-1]->inst_c0 = (guint32)data;
9583                                 else
9584                                         sp [-1]->inst_c0 = data;
9585 #else
9586                                 sp [-1]->inst_ls_word = data;
9587                                 if ((*ip) == CEE_CONV_U8)
9588                                         sp [-1]->inst_ms_word = 0;
9589                                 else
9590                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9591 #endif
9592                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9593                         }
9594                         else {
9595                                 ADD_UNOP (*ip);
9596                         }
9597                         ip++;
9598                         break;
9599                 case CEE_CONV_OVF_I4:
9600                 case CEE_CONV_OVF_I1:
9601                 case CEE_CONV_OVF_I2:
9602                 case CEE_CONV_OVF_I:
9603                 case CEE_CONV_OVF_U:
9604                         CHECK_STACK (1);
9605
9606                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9607                                 ADD_UNOP (CEE_CONV_OVF_I8);
9608                                 ADD_UNOP (*ip);
9609                         } else {
9610                                 ADD_UNOP (*ip);
9611                         }
9612                         ip++;
9613                         break;
9614                 case CEE_CONV_OVF_U1:
9615                 case CEE_CONV_OVF_U2:
9616                 case CEE_CONV_OVF_U4:
9617                         CHECK_STACK (1);
9618
9619                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9620                                 ADD_UNOP (CEE_CONV_OVF_U8);
9621                                 ADD_UNOP (*ip);
9622                         } else {
9623                                 ADD_UNOP (*ip);
9624                         }
9625                         ip++;
9626                         break;
9627                 case CEE_CONV_OVF_I1_UN:
9628                 case CEE_CONV_OVF_I2_UN:
9629                 case CEE_CONV_OVF_I4_UN:
9630                 case CEE_CONV_OVF_I8_UN:
9631                 case CEE_CONV_OVF_U1_UN:
9632                 case CEE_CONV_OVF_U2_UN:
9633                 case CEE_CONV_OVF_U4_UN:
9634                 case CEE_CONV_OVF_U8_UN:
9635                 case CEE_CONV_OVF_I_UN:
9636                 case CEE_CONV_OVF_U_UN:
9637                 case CEE_CONV_U2:
9638                 case CEE_CONV_U1:
9639                 case CEE_CONV_I:
9640                 case CEE_CONV_U:
9641                         CHECK_STACK (1);
9642                         ADD_UNOP (*ip);
9643                         CHECK_CFG_EXCEPTION;
9644                         ip++;
9645                         break;
9646                 case CEE_ADD_OVF:
9647                 case CEE_ADD_OVF_UN:
9648                 case CEE_MUL_OVF:
9649                 case CEE_MUL_OVF_UN:
9650                 case CEE_SUB_OVF:
9651                 case CEE_SUB_OVF_UN:
9652                         CHECK_STACK (2);
9653                         ADD_BINOP (*ip);
9654                         ip++;
9655                         break;
9656                 case CEE_CPOBJ:
9657                         GSHAREDVT_FAILURE (*ip);
9658                         CHECK_OPSIZE (5);
9659                         CHECK_STACK (2);
9660                         token = read32 (ip + 1);
9661                         klass = mini_get_class (method, token, generic_context);
9662                         CHECK_TYPELOAD (klass);
9663                         sp -= 2;
9664                         mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9665                         ins_flag = 0;
9666                         ip += 5;
9667                         break;
9668                 case CEE_LDOBJ: {
9669                         int loc_index = -1;
9670                         int stloc_len = 0;
9671
9672                         CHECK_OPSIZE (5);
9673                         CHECK_STACK (1);
9674                         --sp;
9675                         token = read32 (ip + 1);
9676                         klass = mini_get_class (method, token, generic_context);
9677                         CHECK_TYPELOAD (klass);
9678
9679                         /* Optimize the common ldobj+stloc combination */
9680                         switch (ip [5]) {
9681                         case CEE_STLOC_S:
9682                                 loc_index = ip [6];
9683                                 stloc_len = 2;
9684                                 break;
9685                         case CEE_STLOC_0:
9686                         case CEE_STLOC_1:
9687                         case CEE_STLOC_2:
9688                         case CEE_STLOC_3:
9689                                 loc_index = ip [5] - CEE_STLOC_0;
9690                                 stloc_len = 1;
9691                                 break;
9692                         default:
9693                                 break;
9694                         }
9695
9696                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9697                                 CHECK_LOCAL (loc_index);
9698
9699                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9700                                 ins->dreg = cfg->locals [loc_index]->dreg;
9701                                 ins->flags |= ins_flag;
9702                                 ip += 5;
9703                                 ip += stloc_len;
9704                                 if (ins_flag & MONO_INST_VOLATILE) {
9705                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9706                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9707                                 }
9708                                 ins_flag = 0;
9709                                 break;
9710                         }
9711
9712                         /* Optimize the ldobj+stobj combination */
9713                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token)) {
9714                                 CHECK_STACK (1);
9715
9716                                 sp --;
9717
9718                                 mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9719
9720                                 ip += 5 + 5;
9721                                 ins_flag = 0;
9722                                 break;
9723                         }
9724
9725                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9726                         *sp++ = ins;
9727
9728                         ip += 5;
9729                         ins_flag = 0;
9730                         inline_costs += 1;
9731                         break;
9732                 }
9733                 case CEE_LDSTR:
9734                         CHECK_STACK_OVF (1);
9735                         CHECK_OPSIZE (5);
9736                         n = read32 (ip + 1);
9737
9738                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9739                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9740                                 ins->type = STACK_OBJ;
9741                                 *sp = ins;
9742                         }
9743                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9744                                 MonoInst *iargs [1];
9745                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9746
9747                                 if (cfg->compile_aot)
9748                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9749                                 else
9750                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
9751                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
9752                         } else {
9753                                 if (cfg->opt & MONO_OPT_SHARED) {
9754                                         MonoInst *iargs [3];
9755
9756                                         if (cfg->compile_aot) {
9757                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
9758                                         }
9759                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
9760                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
9761                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
9762                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
9763                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9764                                         CHECK_CFG_ERROR;
9765                                 } else {
9766                                         if (cfg->cbb->out_of_line) {
9767                                                 MonoInst *iargs [2];
9768
9769                                                 if (image == mono_defaults.corlib) {
9770                                                         /* 
9771                                                          * Avoid relocations in AOT and save some space by using a 
9772                                                          * version of helper_ldstr specialized to mscorlib.
9773                                                          */
9774                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
9775                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
9776                                                 } else {
9777                                                         /* Avoid creating the string object */
9778                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
9779                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
9780                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
9781                                                 }
9782                                         } 
9783                                         else
9784                                         if (cfg->compile_aot) {
9785                                                 NEW_LDSTRCONST (cfg, ins, image, n);
9786                                                 *sp = ins;
9787                                                 MONO_ADD_INS (cfg->cbb, ins);
9788                                         } 
9789                                         else {
9790                                                 NEW_PCONST (cfg, ins, NULL);
9791                                                 ins->type = STACK_OBJ;
9792                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9793                                                 CHECK_CFG_ERROR;
9794                                                 
9795                                                 if (!ins->inst_p0)
9796                                                         OUT_OF_MEMORY_FAILURE;
9797
9798                                                 *sp = ins;
9799                                                 MONO_ADD_INS (cfg->cbb, ins);
9800                                         }
9801                                 }
9802                         }
9803
9804                         sp++;
9805                         ip += 5;
9806                         break;
9807                 case CEE_NEWOBJ: {
9808                         MonoInst *iargs [2];
9809                         MonoMethodSignature *fsig;
9810                         MonoInst this_ins;
9811                         MonoInst *alloc;
9812                         MonoInst *vtable_arg = NULL;
9813
9814                         CHECK_OPSIZE (5);
9815                         token = read32 (ip + 1);
9816                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9817                         CHECK_CFG_ERROR;
9818
9819                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9820                         CHECK_CFG_ERROR;
9821
9822                         mono_save_token_info (cfg, image, token, cmethod);
9823
9824                         if (!mono_class_init (cmethod->klass))
9825                                 TYPE_LOAD_ERROR (cmethod->klass);
9826
9827                         context_used = mini_method_check_context_used (cfg, cmethod);
9828
9829                         if (mono_security_core_clr_enabled ())
9830                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
9831
9832                         if (cfg->gshared && cmethod && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
9833                                 emit_class_init (cfg, cmethod->klass);
9834                                 CHECK_TYPELOAD (cmethod->klass);
9835                         }
9836
9837                         /*
9838                         if (cfg->gsharedvt) {
9839                                 if (mini_is_gsharedvt_variable_signature (sig))
9840                                         GSHAREDVT_FAILURE (*ip);
9841                         }
9842                         */
9843
9844                         n = fsig->param_count;
9845                         CHECK_STACK (n);
9846
9847                         /* 
9848                          * Generate smaller code for the common newobj <exception> instruction in
9849                          * argument checking code.
9850                          */
9851                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
9852                                 is_exception_class (cmethod->klass) && n <= 2 &&
9853                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
9854                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
9855                                 MonoInst *iargs [3];
9856
9857                                 sp -= n;
9858
9859                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
9860                                 switch (n) {
9861                                 case 0:
9862                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
9863                                         break;
9864                                 case 1:
9865                                         iargs [1] = sp [0];
9866                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
9867                                         break;
9868                                 case 2:
9869                                         iargs [1] = sp [0];
9870                                         iargs [2] = sp [1];
9871                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
9872                                         break;
9873                                 default:
9874                                         g_assert_not_reached ();
9875                                 }
9876
9877                                 ip += 5;
9878                                 inline_costs += 5;
9879                                 break;
9880                         }
9881
9882                         /* move the args to allow room for 'this' in the first position */
9883                         while (n--) {
9884                                 --sp;
9885                                 sp [1] = sp [0];
9886                         }
9887
9888                         /* check_call_signature () requires sp[0] to be set */
9889                         this_ins.type = STACK_OBJ;
9890                         sp [0] = &this_ins;
9891                         if (check_call_signature (cfg, fsig, sp))
9892                                 UNVERIFIED;
9893
9894                         iargs [0] = NULL;
9895
9896                         if (mini_class_is_system_array (cmethod->klass)) {
9897                                 *sp = emit_get_rgctx_method (cfg, context_used,
9898                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9899
9900                                 /* Avoid varargs in the common case */
9901                                 if (fsig->param_count == 1)
9902                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
9903                                 else if (fsig->param_count == 2)
9904                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
9905                                 else if (fsig->param_count == 3)
9906                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
9907                                 else if (fsig->param_count == 4)
9908                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
9909                                 else
9910                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
9911                         } else if (cmethod->string_ctor) {
9912                                 g_assert (!context_used);
9913                                 g_assert (!vtable_arg);
9914                                 /* we simply pass a null pointer */
9915                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
9916                                 /* now call the string ctor */
9917                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
9918                         } else {
9919                                 if (cmethod->klass->valuetype) {
9920                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
9921                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
9922                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
9923
9924                                         alloc = NULL;
9925
9926                                         /* 
9927                                          * The code generated by mini_emit_virtual_call () expects
9928                                          * iargs [0] to be a boxed instance, but luckily the vcall
9929                                          * will be transformed into a normal call there.
9930                                          */
9931                                 } else if (context_used) {
9932                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
9933                                         *sp = alloc;
9934                                 } else {
9935                                         MonoVTable *vtable = NULL;
9936
9937                                         if (!cfg->compile_aot)
9938                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
9939                                         CHECK_TYPELOAD (cmethod->klass);
9940
9941                                         /*
9942                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
9943                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
9944                                          * As a workaround, we call class cctors before allocating objects.
9945                                          */
9946                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
9947                                                 emit_class_init (cfg, cmethod->klass);
9948                                                 if (cfg->verbose_level > 2)
9949                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
9950                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
9951                                         }
9952
9953                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
9954                                         *sp = alloc;
9955                                 }
9956                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
9957
9958                                 if (alloc)
9959                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
9960
9961                                 /* Now call the actual ctor */
9962                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
9963                                 CHECK_CFG_EXCEPTION;
9964                         }
9965
9966                         if (alloc == NULL) {
9967                                 /* Valuetype */
9968                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
9969                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
9970                                 *sp++= ins;
9971                         } else {
9972                                 *sp++ = alloc;
9973                         }
9974                         
9975                         ip += 5;
9976                         inline_costs += 5;
9977                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
9978                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9979                         break;
9980                 }
9981                 case CEE_CASTCLASS:
9982                 case CEE_ISINST: {
9983                         CHECK_STACK (1);
9984                         --sp;
9985                         CHECK_OPSIZE (5);
9986                         token = read32 (ip + 1);
9987                         klass = mini_get_class (method, token, generic_context);
9988                         CHECK_TYPELOAD (klass);
9989                         if (sp [0]->type != STACK_OBJ)
9990                                 UNVERIFIED;
9991
9992                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
9993                         ins->dreg = alloc_preg (cfg);
9994                         ins->sreg1 = (*sp)->dreg;
9995                         ins->klass = klass;
9996                         ins->type = STACK_OBJ;
9997                         MONO_ADD_INS (cfg->cbb, ins);
9998
9999                         CHECK_CFG_EXCEPTION;
10000                         *sp++ = ins;
10001                         ip += 5;
10002
10003                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10004                         break;
10005                 }
10006                 case CEE_UNBOX_ANY: {
10007                         MonoInst *res, *addr;
10008
10009                         CHECK_STACK (1);
10010                         --sp;
10011                         CHECK_OPSIZE (5);
10012                         token = read32 (ip + 1);
10013                         klass = mini_get_class (method, token, generic_context);
10014                         CHECK_TYPELOAD (klass);
10015
10016                         mono_save_token_info (cfg, image, token, klass);
10017
10018                         context_used = mini_class_check_context_used (cfg, klass);
10019
10020                         if (mini_is_gsharedvt_klass (klass)) {
10021                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10022                                 inline_costs += 2;
10023                         } else if (generic_class_is_reference_type (cfg, klass)) {
10024                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10025                                         EMIT_NEW_PCONST (cfg, res, NULL);
10026                                         res->type = STACK_OBJ;
10027                                 } else {
10028                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10029                                         res->dreg = alloc_preg (cfg);
10030                                         res->sreg1 = (*sp)->dreg;
10031                                         res->klass = klass;
10032                                         res->type = STACK_OBJ;
10033                                         MONO_ADD_INS (cfg->cbb, res);
10034                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10035                                 }
10036                         } else if (mono_class_is_nullable (klass)) {
10037                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10038                         } else {
10039                                 addr = handle_unbox (cfg, klass, sp, context_used);
10040                                 /* LDOBJ */
10041                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10042                                 res = ins;
10043                                 inline_costs += 2;
10044                         }
10045
10046                         *sp ++ = res;
10047                         ip += 5;
10048                         break;
10049                 }
10050                 case CEE_BOX: {
10051                         MonoInst *val;
10052                         MonoClass *enum_class;
10053                         MonoMethod *has_flag;
10054
10055                         CHECK_STACK (1);
10056                         --sp;
10057                         val = *sp;
10058                         CHECK_OPSIZE (5);
10059                         token = read32 (ip + 1);
10060                         klass = mini_get_class (method, token, generic_context);
10061                         CHECK_TYPELOAD (klass);
10062
10063                         mono_save_token_info (cfg, image, token, klass);
10064
10065                         context_used = mini_class_check_context_used (cfg, klass);
10066
10067                         if (generic_class_is_reference_type (cfg, klass)) {
10068                                 *sp++ = val;
10069                                 ip += 5;
10070                                 break;
10071                         }
10072
10073                         if (klass == mono_defaults.void_class)
10074                                 UNVERIFIED;
10075                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10076                                 UNVERIFIED;
10077                         /* frequent check in generic code: box (struct), brtrue */
10078
10079                         /*
10080                          * Look for:
10081                          *
10082                          *   <push int/long ptr>
10083                          *   <push int/long>
10084                          *   box MyFlags
10085                          *   constrained. MyFlags
10086                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10087                          *
10088                          * If we find this sequence and the operand types on box and constrained
10089                          * are equal, we can emit a specialized instruction sequence instead of
10090                          * the very slow HasFlag () call.
10091                          */
10092                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10093                             /* Cheap checks first. */
10094                             ip + 5 + 6 + 5 < end &&
10095                             ip [5] == CEE_PREFIX1 &&
10096                             ip [6] == CEE_CONSTRAINED_ &&
10097                             ip [11] == CEE_CALLVIRT &&
10098                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10099                             mono_class_is_enum (klass) &&
10100                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10101                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10102                             has_flag->klass == mono_defaults.enum_class &&
10103                             !strcmp (has_flag->name, "HasFlag") &&
10104                             has_flag->signature->hasthis &&
10105                             has_flag->signature->param_count == 1) {
10106                                 CHECK_TYPELOAD (enum_class);
10107
10108                                 if (enum_class == klass) {
10109                                         MonoInst *enum_this, *enum_flag;
10110
10111                                         ip += 5 + 6 + 5;
10112                                         --sp;
10113
10114                                         enum_this = sp [0];
10115                                         enum_flag = sp [1];
10116
10117                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10118                                         break;
10119                                 }
10120                         }
10121
10122                         // FIXME: LLVM can't handle the inconsistent bb linking
10123                         if (!mono_class_is_nullable (klass) &&
10124                                 !mini_is_gsharedvt_klass (klass) &&
10125                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10126                                 (ip [5] == CEE_BRTRUE || 
10127                                  ip [5] == CEE_BRTRUE_S ||
10128                                  ip [5] == CEE_BRFALSE ||
10129                                  ip [5] == CEE_BRFALSE_S)) {
10130                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10131                                 int dreg;
10132                                 MonoBasicBlock *true_bb, *false_bb;
10133
10134                                 ip += 5;
10135
10136                                 if (cfg->verbose_level > 3) {
10137                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10138                                         printf ("<box+brtrue opt>\n");
10139                                 }
10140
10141                                 switch (*ip) {
10142                                 case CEE_BRTRUE_S:
10143                                 case CEE_BRFALSE_S:
10144                                         CHECK_OPSIZE (2);
10145                                         ip++;
10146                                         target = ip + 1 + (signed char)(*ip);
10147                                         ip++;
10148                                         break;
10149                                 case CEE_BRTRUE:
10150                                 case CEE_BRFALSE:
10151                                         CHECK_OPSIZE (5);
10152                                         ip++;
10153                                         target = ip + 4 + (gint)(read32 (ip));
10154                                         ip += 4;
10155                                         break;
10156                                 default:
10157                                         g_assert_not_reached ();
10158                                 }
10159
10160                                 /* 
10161                                  * We need to link both bblocks, since it is needed for handling stack
10162                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10163                                  * Branching to only one of them would lead to inconsistencies, so
10164                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10165                                  */
10166                                 GET_BBLOCK (cfg, true_bb, target);
10167                                 GET_BBLOCK (cfg, false_bb, ip);
10168
10169                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10170                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10171
10172                                 if (sp != stack_start) {
10173                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10174                                         sp = stack_start;
10175                                         CHECK_UNVERIFIABLE (cfg);
10176                                 }
10177
10178                                 if (COMPILE_LLVM (cfg)) {
10179                                         dreg = alloc_ireg (cfg);
10180                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10181                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10182
10183                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10184                                 } else {
10185                                         /* The JIT can't eliminate the iconst+compare */
10186                                         MONO_INST_NEW (cfg, ins, OP_BR);
10187                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10188                                         MONO_ADD_INS (cfg->cbb, ins);
10189                                 }
10190
10191                                 start_new_bblock = 1;
10192                                 break;
10193                         }
10194
10195                         *sp++ = handle_box (cfg, val, klass, context_used);
10196
10197                         CHECK_CFG_EXCEPTION;
10198                         ip += 5;
10199                         inline_costs += 1;
10200                         break;
10201                 }
10202                 case CEE_UNBOX: {
10203                         CHECK_STACK (1);
10204                         --sp;
10205                         CHECK_OPSIZE (5);
10206                         token = read32 (ip + 1);
10207                         klass = mini_get_class (method, token, generic_context);
10208                         CHECK_TYPELOAD (klass);
10209
10210                         mono_save_token_info (cfg, image, token, klass);
10211
10212                         context_used = mini_class_check_context_used (cfg, klass);
10213
10214                         if (mono_class_is_nullable (klass)) {
10215                                 MonoInst *val;
10216
10217                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10218                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10219
10220                                 *sp++= ins;
10221                         } else {
10222                                 ins = handle_unbox (cfg, klass, sp, context_used);
10223                                 *sp++ = ins;
10224                         }
10225                         ip += 5;
10226                         inline_costs += 2;
10227                         break;
10228                 }
10229                 case CEE_LDFLD:
10230                 case CEE_LDFLDA:
10231                 case CEE_STFLD:
10232                 case CEE_LDSFLD:
10233                 case CEE_LDSFLDA:
10234                 case CEE_STSFLD: {
10235                         MonoClassField *field;
10236 #ifndef DISABLE_REMOTING
10237                         int costs;
10238 #endif
10239                         guint foffset;
10240                         gboolean is_instance;
10241                         int op;
10242                         gpointer addr = NULL;
10243                         gboolean is_special_static;
10244                         MonoType *ftype;
10245                         MonoInst *store_val = NULL;
10246                         MonoInst *thread_ins;
10247
10248                         op = *ip;
10249                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10250                         if (is_instance) {
10251                                 if (op == CEE_STFLD) {
10252                                         CHECK_STACK (2);
10253                                         sp -= 2;
10254                                         store_val = sp [1];
10255                                 } else {
10256                                         CHECK_STACK (1);
10257                                         --sp;
10258                                 }
10259                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10260                                         UNVERIFIED;
10261                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10262                                         UNVERIFIED;
10263                         } else {
10264                                 if (op == CEE_STSFLD) {
10265                                         CHECK_STACK (1);
10266                                         sp--;
10267                                         store_val = sp [0];
10268                                 }
10269                         }
10270
10271                         CHECK_OPSIZE (5);
10272                         token = read32 (ip + 1);
10273                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10274                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10275                                 klass = field->parent;
10276                         }
10277                         else {
10278                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10279                                 CHECK_CFG_ERROR;
10280                         }
10281                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10282                                 FIELD_ACCESS_FAILURE (method, field);
10283                         mono_class_init (klass);
10284
10285                         /* if the class is Critical then transparent code cannot access it's fields */
10286                         if (!is_instance && mono_security_core_clr_enabled ())
10287                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10288
10289                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10290                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10291                         if (mono_security_core_clr_enabled ())
10292                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10293                         */
10294
10295                         ftype = mono_field_get_type (field);
10296
10297                         /*
10298                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10299                          * the static case.
10300                          */
10301                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10302                                 switch (op) {
10303                                 case CEE_LDFLD:
10304                                         op = CEE_LDSFLD;
10305                                         break;
10306                                 case CEE_STFLD:
10307                                         op = CEE_STSFLD;
10308                                         break;
10309                                 case CEE_LDFLDA:
10310                                         op = CEE_LDSFLDA;
10311                                         break;
10312                                 default:
10313                                         g_assert_not_reached ();
10314                                 }
10315                                 is_instance = FALSE;
10316                         }
10317
10318                         context_used = mini_class_check_context_used (cfg, klass);
10319
10320                         /* INSTANCE CASE */
10321
10322                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10323                         if (op == CEE_STFLD) {
10324                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10325                                         UNVERIFIED;
10326 #ifndef DISABLE_REMOTING
10327                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10328                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10329                                         MonoInst *iargs [5];
10330
10331                                         GSHAREDVT_FAILURE (op);
10332
10333                                         iargs [0] = sp [0];
10334                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10335                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10336                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10337                                                     field->offset);
10338                                         iargs [4] = sp [1];
10339
10340                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10341                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10342                                                                                            iargs, ip, cfg->real_offset, TRUE);
10343                                                 CHECK_CFG_EXCEPTION;
10344                                                 g_assert (costs > 0);
10345                                                       
10346                                                 cfg->real_offset += 5;
10347
10348                                                 inline_costs += costs;
10349                                         } else {
10350                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10351                                         }
10352                                 } else
10353 #endif
10354                                 {
10355                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10356
10357                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10358
10359                                         if (ins_flag & MONO_INST_VOLATILE) {
10360                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10361                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10362                                         }
10363
10364                                         if (mini_is_gsharedvt_klass (klass)) {
10365                                                 MonoInst *offset_ins;
10366
10367                                                 context_used = mini_class_check_context_used (cfg, klass);
10368
10369                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10370                                                 /* The value is offset by 1 */
10371                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10372                                                 dreg = alloc_ireg_mp (cfg);
10373                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10374                                                 wbarrier_ptr_ins = ins;
10375                                                 /* The decomposition will call mini_emit_memory_copy () which will emit a wbarrier if needed */
10376                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10377                                         } else {
10378                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10379                                         }
10380                                         if (sp [0]->opcode != OP_LDADDR)
10381                                                 store->flags |= MONO_INST_FAULT;
10382
10383                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10384                                                 if (mini_is_gsharedvt_klass (klass)) {
10385                                                         g_assert (wbarrier_ptr_ins);
10386                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10387                                                 } else {
10388                                                         /* insert call to write barrier */
10389                                                         MonoInst *ptr;
10390                                                         int dreg;
10391
10392                                                         dreg = alloc_ireg_mp (cfg);
10393                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10394                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10395                                                 }
10396                                         }
10397
10398                                         store->flags |= ins_flag;
10399                                 }
10400                                 ins_flag = 0;
10401                                 ip += 5;
10402                                 break;
10403                         }
10404
10405 #ifndef DISABLE_REMOTING
10406                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10407                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10408                                 MonoInst *iargs [4];
10409
10410                                 GSHAREDVT_FAILURE (op);
10411
10412                                 iargs [0] = sp [0];
10413                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10414                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10415                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10416                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10417                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10418                                                                                    iargs, ip, cfg->real_offset, TRUE);
10419                                         CHECK_CFG_EXCEPTION;
10420                                         g_assert (costs > 0);
10421                                                       
10422                                         cfg->real_offset += 5;
10423
10424                                         *sp++ = iargs [0];
10425
10426                                         inline_costs += costs;
10427                                 } else {
10428                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10429                                         *sp++ = ins;
10430                                 }
10431                         } else 
10432 #endif
10433                         if (is_instance) {
10434                                 if (sp [0]->type == STACK_VTYPE) {
10435                                         MonoInst *var;
10436
10437                                         /* Have to compute the address of the variable */
10438
10439                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10440                                         if (!var)
10441                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10442                                         else
10443                                                 g_assert (var->klass == klass);
10444                                         
10445                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10446                                         sp [0] = ins;
10447                                 }
10448
10449                                 if (op == CEE_LDFLDA) {
10450                                         if (sp [0]->type == STACK_OBJ) {
10451                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10452                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10453                                         }
10454
10455                                         dreg = alloc_ireg_mp (cfg);
10456
10457                                         if (mini_is_gsharedvt_klass (klass)) {
10458                                                 MonoInst *offset_ins;
10459
10460                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10461                                                 /* The value is offset by 1 */
10462                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10463                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10464                                         } else {
10465                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10466                                         }
10467                                         ins->klass = mono_class_from_mono_type (field->type);
10468                                         ins->type = STACK_MP;
10469                                         *sp++ = ins;
10470                                 } else {
10471                                         MonoInst *load;
10472
10473                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10474
10475                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10476                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10477                                                 if (ins) {
10478                                                         *sp++ = ins;
10479                                                         ins_flag = 0;
10480                                                         ip += 5;
10481                                                         break;
10482                                                 }
10483                                         }
10484
10485                                         MonoInst *field_add_inst = sp [0];
10486                                         if (mini_is_gsharedvt_klass (klass)) {
10487                                                 MonoInst *offset_ins;
10488
10489                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10490                                                 /* The value is offset by 1 */
10491                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10492                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10493                                                 foffset = 0;
10494                                         }
10495
10496                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10497
10498                                         if (sp [0]->opcode != OP_LDADDR)
10499                                                 load->flags |= MONO_INST_FAULT;
10500                                         *sp++ = load;
10501                                 }
10502                         }
10503
10504                         if (is_instance) {
10505                                 ins_flag = 0;
10506                                 ip += 5;
10507                                 break;
10508                         }
10509
10510                         /* STATIC CASE */
10511                         context_used = mini_class_check_context_used (cfg, klass);
10512
10513                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10514                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10515                                 CHECK_CFG_ERROR;
10516                         }
10517
10518                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10519                          * to be called here.
10520                          */
10521                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10522                                 mono_class_vtable (cfg->domain, klass);
10523                                 CHECK_TYPELOAD (klass);
10524                         }
10525                         mono_domain_lock (cfg->domain);
10526                         if (cfg->domain->special_static_fields)
10527                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10528                         mono_domain_unlock (cfg->domain);
10529
10530                         is_special_static = mono_class_field_is_special_static (field);
10531
10532                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10533                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10534                         else
10535                                 thread_ins = NULL;
10536
10537                         /* Generate IR to compute the field address */
10538                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10539                                 /*
10540                                  * Fast access to TLS data
10541                                  * Inline version of get_thread_static_data () in
10542                                  * threads.c.
10543                                  */
10544                                 guint32 offset;
10545                                 int idx, static_data_reg, array_reg, dreg;
10546
10547                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10548                                         GSHAREDVT_FAILURE (op);
10549
10550                                 static_data_reg = alloc_ireg (cfg);
10551                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10552
10553                                 if (cfg->compile_aot) {
10554                                         int offset_reg, offset2_reg, idx_reg;
10555
10556                                         /* For TLS variables, this will return the TLS offset */
10557                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10558                                         offset_reg = ins->dreg;
10559                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10560                                         idx_reg = alloc_ireg (cfg);
10561                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10562                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10563                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10564                                         array_reg = alloc_ireg (cfg);
10565                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10566                                         offset2_reg = alloc_ireg (cfg);
10567                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10568                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10569                                         dreg = alloc_ireg (cfg);
10570                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10571                                 } else {
10572                                         offset = (gsize)addr & 0x7fffffff;
10573                                         idx = offset & 0x3f;
10574
10575                                         array_reg = alloc_ireg (cfg);
10576                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10577                                         dreg = alloc_ireg (cfg);
10578                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10579                                 }
10580                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10581                                         (cfg->compile_aot && is_special_static) ||
10582                                         (context_used && is_special_static)) {
10583                                 MonoInst *iargs [2];
10584
10585                                 g_assert (field->parent);
10586                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10587                                 if (context_used) {
10588                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10589                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10590                                 } else {
10591                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10592                                 }
10593                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10594                         } else if (context_used) {
10595                                 MonoInst *static_data;
10596
10597                                 /*
10598                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10599                                         method->klass->name_space, method->klass->name, method->name,
10600                                         depth, field->offset);
10601                                 */
10602
10603                                 if (mono_class_needs_cctor_run (klass, method))
10604                                         emit_class_init (cfg, klass);
10605
10606                                 /*
10607                                  * The pointer we're computing here is
10608                                  *
10609                                  *   super_info.static_data + field->offset
10610                                  */
10611                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10612                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10613
10614                                 if (mini_is_gsharedvt_klass (klass)) {
10615                                         MonoInst *offset_ins;
10616
10617                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10618                                         /* The value is offset by 1 */
10619                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10620                                         dreg = alloc_ireg_mp (cfg);
10621                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10622                                 } else if (field->offset == 0) {
10623                                         ins = static_data;
10624                                 } else {
10625                                         int addr_reg = mono_alloc_preg (cfg);
10626                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10627                                 }
10628                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10629                                 MonoInst *iargs [2];
10630
10631                                 g_assert (field->parent);
10632                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10633                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10634                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10635                         } else {
10636                                 MonoVTable *vtable = NULL;
10637
10638                                 if (!cfg->compile_aot)
10639                                         vtable = mono_class_vtable (cfg->domain, klass);
10640                                 CHECK_TYPELOAD (klass);
10641
10642                                 if (!addr) {
10643                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10644                                                 if (!(g_slist_find (class_inits, klass))) {
10645                                                         emit_class_init (cfg, klass);
10646                                                         if (cfg->verbose_level > 2)
10647                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10648                                                         class_inits = g_slist_prepend (class_inits, klass);
10649                                                 }
10650                                         } else {
10651                                                 if (cfg->run_cctors) {
10652                                                         /* This makes so that inline cannot trigger */
10653                                                         /* .cctors: too many apps depend on them */
10654                                                         /* running with a specific order... */
10655                                                         g_assert (vtable);
10656                                                         if (! vtable->initialized)
10657                                                                 INLINE_FAILURE ("class init");
10658                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10659                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10660                                                                 goto exception_exit;
10661                                                         }
10662                                                 }
10663                                         }
10664                                         if (cfg->compile_aot)
10665                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10666                                         else {
10667                                                 g_assert (vtable);
10668                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10669                                                 g_assert (addr);
10670                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10671                                         }
10672                                 } else {
10673                                         MonoInst *iargs [1];
10674                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10675                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10676                                 }
10677                         }
10678
10679                         /* Generate IR to do the actual load/store operation */
10680
10681                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10682                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10683                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10684                         }
10685
10686                         if (op == CEE_LDSFLDA) {
10687                                 ins->klass = mono_class_from_mono_type (ftype);
10688                                 ins->type = STACK_PTR;
10689                                 *sp++ = ins;
10690                         } else if (op == CEE_STSFLD) {
10691                                 MonoInst *store;
10692
10693                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10694                                 store->flags |= ins_flag;
10695                         } else {
10696                                 gboolean is_const = FALSE;
10697                                 MonoVTable *vtable = NULL;
10698                                 gpointer addr = NULL;
10699
10700                                 if (!context_used) {
10701                                         vtable = mono_class_vtable (cfg->domain, klass);
10702                                         CHECK_TYPELOAD (klass);
10703                                 }
10704                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10705                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10706                                         int ro_type = ftype->type;
10707                                         if (!addr)
10708                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10709                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10710                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10711                                         }
10712
10713                                         GSHAREDVT_FAILURE (op);
10714
10715                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10716                                         is_const = TRUE;
10717                                         switch (ro_type) {
10718                                         case MONO_TYPE_BOOLEAN:
10719                                         case MONO_TYPE_U1:
10720                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10721                                                 sp++;
10722                                                 break;
10723                                         case MONO_TYPE_I1:
10724                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10725                                                 sp++;
10726                                                 break;                                          
10727                                         case MONO_TYPE_CHAR:
10728                                         case MONO_TYPE_U2:
10729                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10730                                                 sp++;
10731                                                 break;
10732                                         case MONO_TYPE_I2:
10733                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10734                                                 sp++;
10735                                                 break;
10736                                                 break;
10737                                         case MONO_TYPE_I4:
10738                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
10739                                                 sp++;
10740                                                 break;                                          
10741                                         case MONO_TYPE_U4:
10742                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
10743                                                 sp++;
10744                                                 break;
10745                                         case MONO_TYPE_I:
10746                                         case MONO_TYPE_U:
10747                                         case MONO_TYPE_PTR:
10748                                         case MONO_TYPE_FNPTR:
10749                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10750                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
10751                                                 sp++;
10752                                                 break;
10753                                         case MONO_TYPE_STRING:
10754                                         case MONO_TYPE_OBJECT:
10755                                         case MONO_TYPE_CLASS:
10756                                         case MONO_TYPE_SZARRAY:
10757                                         case MONO_TYPE_ARRAY:
10758                                                 if (!mono_gc_is_moving ()) {
10759                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10760                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
10761                                                         sp++;
10762                                                 } else {
10763                                                         is_const = FALSE;
10764                                                 }
10765                                                 break;
10766                                         case MONO_TYPE_I8:
10767                                         case MONO_TYPE_U8:
10768                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
10769                                                 sp++;
10770                                                 break;
10771                                         case MONO_TYPE_R4:
10772                                         case MONO_TYPE_R8:
10773                                         case MONO_TYPE_VALUETYPE:
10774                                         default:
10775                                                 is_const = FALSE;
10776                                                 break;
10777                                         }
10778                                 }
10779
10780                                 if (!is_const) {
10781                                         MonoInst *load;
10782
10783                                         CHECK_STACK_OVF (1);
10784
10785                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
10786                                         load->flags |= ins_flag;
10787                                         ins_flag = 0;
10788                                         *sp++ = load;
10789                                 }
10790                         }
10791
10792                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10793                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10794                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10795                         }
10796
10797                         ins_flag = 0;
10798                         ip += 5;
10799                         break;
10800                 }
10801                 case CEE_STOBJ:
10802                         CHECK_STACK (2);
10803                         sp -= 2;
10804                         CHECK_OPSIZE (5);
10805                         token = read32 (ip + 1);
10806                         klass = mini_get_class (method, token, generic_context);
10807                         CHECK_TYPELOAD (klass);
10808
10809                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
10810                         mini_emit_memory_store (cfg, &klass->byval_arg, sp [0], sp [1], ins_flag);
10811                         ins_flag = 0;
10812                         ip += 5;
10813                         inline_costs += 1;
10814                         break;
10815
10816                         /*
10817                          * Array opcodes
10818                          */
10819                 case CEE_NEWARR: {
10820                         MonoInst *len_ins;
10821                         const char *data_ptr;
10822                         int data_size = 0;
10823                         guint32 field_token;
10824
10825                         CHECK_STACK (1);
10826                         --sp;
10827
10828                         CHECK_OPSIZE (5);
10829                         token = read32 (ip + 1);
10830
10831                         klass = mini_get_class (method, token, generic_context);
10832                         CHECK_TYPELOAD (klass);
10833                         if (klass->byval_arg.type == MONO_TYPE_VOID)
10834                                 UNVERIFIED;
10835
10836                         context_used = mini_class_check_context_used (cfg, klass);
10837
10838                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
10839                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
10840                                 ins->sreg1 = sp [0]->dreg;
10841                                 ins->type = STACK_I4;
10842                                 ins->dreg = alloc_ireg (cfg);
10843                                 MONO_ADD_INS (cfg->cbb, ins);
10844                                 *sp = mono_decompose_opcode (cfg, ins);
10845                         }
10846
10847                         if (context_used) {
10848                                 MonoInst *args [3];
10849                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10850                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
10851
10852                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
10853
10854                                 /* vtable */
10855                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
10856                                         array_class, MONO_RGCTX_INFO_VTABLE);
10857                                 /* array len */
10858                                 args [1] = sp [0];
10859
10860                                 if (managed_alloc)
10861                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
10862                                 else
10863                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
10864                         } else {
10865                                 if (cfg->opt & MONO_OPT_SHARED) {
10866                                         /* Decompose now to avoid problems with references to the domainvar */
10867                                         MonoInst *iargs [3];
10868
10869                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10870                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10871                                         iargs [2] = sp [0];
10872
10873                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
10874                                 } else {
10875                                         /* Decompose later since it is needed by abcrem */
10876                                         MonoClass *array_type = mono_array_class_get (klass, 1);
10877                                         mono_class_vtable (cfg->domain, array_type);
10878                                         CHECK_TYPELOAD (array_type);
10879
10880                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
10881                                         ins->dreg = alloc_ireg_ref (cfg);
10882                                         ins->sreg1 = sp [0]->dreg;
10883                                         ins->inst_newa_class = klass;
10884                                         ins->type = STACK_OBJ;
10885                                         ins->klass = array_type;
10886                                         MONO_ADD_INS (cfg->cbb, ins);
10887                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10888                                         cfg->cbb->has_array_access = TRUE;
10889
10890                                         /* Needed so mono_emit_load_get_addr () gets called */
10891                                         mono_get_got_var (cfg);
10892                                 }
10893                         }
10894
10895                         len_ins = sp [0];
10896                         ip += 5;
10897                         *sp++ = ins;
10898                         inline_costs += 1;
10899
10900                         /* 
10901                          * we inline/optimize the initialization sequence if possible.
10902                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
10903                          * for small sizes open code the memcpy
10904                          * ensure the rva field is big enough
10905                          */
10906                         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))) {
10907                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
10908                                 MonoInst *iargs [3];
10909                                 int add_reg = alloc_ireg_mp (cfg);
10910
10911                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
10912                                 if (cfg->compile_aot) {
10913                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
10914                                 } else {
10915                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
10916                                 }
10917                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
10918                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
10919                                 ip += 11;
10920                         }
10921
10922                         break;
10923                 }
10924                 case CEE_LDLEN:
10925                         CHECK_STACK (1);
10926                         --sp;
10927                         if (sp [0]->type != STACK_OBJ)
10928                                 UNVERIFIED;
10929
10930                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
10931                         ins->dreg = alloc_preg (cfg);
10932                         ins->sreg1 = sp [0]->dreg;
10933                         ins->type = STACK_I4;
10934                         /* This flag will be inherited by the decomposition */
10935                         ins->flags |= MONO_INST_FAULT;
10936                         MONO_ADD_INS (cfg->cbb, ins);
10937                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10938                         cfg->cbb->has_array_access = TRUE;
10939                         ip ++;
10940                         *sp++ = ins;
10941                         break;
10942                 case CEE_LDELEMA:
10943                         CHECK_STACK (2);
10944                         sp -= 2;
10945                         CHECK_OPSIZE (5);
10946                         if (sp [0]->type != STACK_OBJ)
10947                                 UNVERIFIED;
10948
10949                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
10950
10951                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
10952                         CHECK_TYPELOAD (klass);
10953                         /* we need to make sure that this array is exactly the type it needs
10954                          * to be for correctness. the wrappers are lax with their usage
10955                          * so we need to ignore them here
10956                          */
10957                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
10958                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10959                                 mini_emit_check_array_type (cfg, sp [0], array_class);
10960                                 CHECK_TYPELOAD (array_class);
10961                         }
10962
10963                         readonly = FALSE;
10964                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
10965                         *sp++ = ins;
10966                         ip += 5;
10967                         break;
10968                 case CEE_LDELEM:
10969                 case CEE_LDELEM_I1:
10970                 case CEE_LDELEM_U1:
10971                 case CEE_LDELEM_I2:
10972                 case CEE_LDELEM_U2:
10973                 case CEE_LDELEM_I4:
10974                 case CEE_LDELEM_U4:
10975                 case CEE_LDELEM_I8:
10976                 case CEE_LDELEM_I:
10977                 case CEE_LDELEM_R4:
10978                 case CEE_LDELEM_R8:
10979                 case CEE_LDELEM_REF: {
10980                         MonoInst *addr;
10981
10982                         CHECK_STACK (2);
10983                         sp -= 2;
10984
10985                         if (*ip == CEE_LDELEM) {
10986                                 CHECK_OPSIZE (5);
10987                                 token = read32 (ip + 1);
10988                                 klass = mini_get_class (method, token, generic_context);
10989                                 CHECK_TYPELOAD (klass);
10990                                 mono_class_init (klass);
10991                         }
10992                         else
10993                                 klass = array_access_to_klass (*ip);
10994
10995                         if (sp [0]->type != STACK_OBJ)
10996                                 UNVERIFIED;
10997
10998                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
10999
11000                         if (mini_is_gsharedvt_variable_klass (klass)) {
11001                                 // FIXME-VT: OP_ICONST optimization
11002                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11003                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11004                                 ins->opcode = OP_LOADV_MEMBASE;
11005                         } else if (sp [1]->opcode == OP_ICONST) {
11006                                 int array_reg = sp [0]->dreg;
11007                                 int index_reg = sp [1]->dreg;
11008                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11009
11010                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11011                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11012
11013                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11014                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11015                         } else {
11016                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11017                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11018                         }
11019                         *sp++ = ins;
11020                         if (*ip == CEE_LDELEM)
11021                                 ip += 5;
11022                         else
11023                                 ++ip;
11024                         break;
11025                 }
11026                 case CEE_STELEM_I:
11027                 case CEE_STELEM_I1:
11028                 case CEE_STELEM_I2:
11029                 case CEE_STELEM_I4:
11030                 case CEE_STELEM_I8:
11031                 case CEE_STELEM_R4:
11032                 case CEE_STELEM_R8:
11033                 case CEE_STELEM_REF:
11034                 case CEE_STELEM: {
11035                         CHECK_STACK (3);
11036                         sp -= 3;
11037
11038                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11039
11040                         if (*ip == CEE_STELEM) {
11041                                 CHECK_OPSIZE (5);
11042                                 token = read32 (ip + 1);
11043                                 klass = mini_get_class (method, token, generic_context);
11044                                 CHECK_TYPELOAD (klass);
11045                                 mono_class_init (klass);
11046                         }
11047                         else
11048                                 klass = array_access_to_klass (*ip);
11049
11050                         if (sp [0]->type != STACK_OBJ)
11051                                 UNVERIFIED;
11052
11053                         emit_array_store (cfg, klass, sp, TRUE);
11054
11055                         if (*ip == CEE_STELEM)
11056                                 ip += 5;
11057                         else
11058                                 ++ip;
11059                         inline_costs += 1;
11060                         break;
11061                 }
11062                 case CEE_CKFINITE: {
11063                         CHECK_STACK (1);
11064                         --sp;
11065
11066                         if (cfg->llvm_only) {
11067                                 MonoInst *iargs [1];
11068
11069                                 iargs [0] = sp [0];
11070                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11071                         } else  {
11072                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11073                                 ins->sreg1 = sp [0]->dreg;
11074                                 ins->dreg = alloc_freg (cfg);
11075                                 ins->type = STACK_R8;
11076                                 MONO_ADD_INS (cfg->cbb, ins);
11077
11078                                 *sp++ = mono_decompose_opcode (cfg, ins);
11079                         }
11080
11081                         ++ip;
11082                         break;
11083                 }
11084                 case CEE_REFANYVAL: {
11085                         MonoInst *src_var, *src;
11086
11087                         int klass_reg = alloc_preg (cfg);
11088                         int dreg = alloc_preg (cfg);
11089
11090                         GSHAREDVT_FAILURE (*ip);
11091
11092                         CHECK_STACK (1);
11093                         MONO_INST_NEW (cfg, ins, *ip);
11094                         --sp;
11095                         CHECK_OPSIZE (5);
11096                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11097                         CHECK_TYPELOAD (klass);
11098
11099                         context_used = mini_class_check_context_used (cfg, klass);
11100
11101                         // FIXME:
11102                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11103                         if (!src_var)
11104                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11105                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11106                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11107
11108                         if (context_used) {
11109                                 MonoInst *klass_ins;
11110
11111                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11112                                                 klass, MONO_RGCTX_INFO_KLASS);
11113
11114                                 // FIXME:
11115                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11116                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11117                         } else {
11118                                 mini_emit_class_check (cfg, klass_reg, klass);
11119                         }
11120                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11121                         ins->type = STACK_MP;
11122                         ins->klass = klass;
11123                         *sp++ = ins;
11124                         ip += 5;
11125                         break;
11126                 }
11127                 case CEE_MKREFANY: {
11128                         MonoInst *loc, *addr;
11129
11130                         GSHAREDVT_FAILURE (*ip);
11131
11132                         CHECK_STACK (1);
11133                         MONO_INST_NEW (cfg, ins, *ip);
11134                         --sp;
11135                         CHECK_OPSIZE (5);
11136                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11137                         CHECK_TYPELOAD (klass);
11138
11139                         context_used = mini_class_check_context_used (cfg, klass);
11140
11141                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11142                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11143
11144                         if (context_used) {
11145                                 MonoInst *const_ins;
11146                                 int type_reg = alloc_preg (cfg);
11147
11148                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11149                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11150                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11151                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11152                         } else {
11153                                 int const_reg = alloc_preg (cfg);
11154                                 int type_reg = alloc_preg (cfg);
11155
11156                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11157                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11158                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11159                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11160                         }
11161                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11162
11163                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11164                         ins->type = STACK_VTYPE;
11165                         ins->klass = mono_defaults.typed_reference_class;
11166                         *sp++ = ins;
11167                         ip += 5;
11168                         break;
11169                 }
11170                 case CEE_LDTOKEN: {
11171                         gpointer handle;
11172                         MonoClass *handle_class;
11173
11174                         CHECK_STACK_OVF (1);
11175
11176                         CHECK_OPSIZE (5);
11177                         n = read32 (ip + 1);
11178
11179                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11180                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11181                                 handle = mono_method_get_wrapper_data (method, n);
11182                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11183                                 if (handle_class == mono_defaults.typehandle_class)
11184                                         handle = &((MonoClass*)handle)->byval_arg;
11185                         }
11186                         else {
11187                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11188                                 CHECK_CFG_ERROR;
11189                         }
11190                         if (!handle)
11191                                 LOAD_ERROR;
11192                         mono_class_init (handle_class);
11193                         if (cfg->gshared) {
11194                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11195                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11196                                         /* This case handles ldtoken
11197                                            of an open type, like for
11198                                            typeof(Gen<>). */
11199                                         context_used = 0;
11200                                 } else if (handle_class == mono_defaults.typehandle_class) {
11201                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11202                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11203                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11204                                 else if (handle_class == mono_defaults.methodhandle_class)
11205                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11206                                 else
11207                                         g_assert_not_reached ();
11208                         }
11209
11210                         if ((cfg->opt & MONO_OPT_SHARED) &&
11211                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11212                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11213                                 MonoInst *addr, *vtvar, *iargs [3];
11214                                 int method_context_used;
11215
11216                                 method_context_used = mini_method_check_context_used (cfg, method);
11217
11218                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11219
11220                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11221                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11222                                 if (method_context_used) {
11223                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11224                                                 method, MONO_RGCTX_INFO_METHOD);
11225                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11226                                 } else {
11227                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11228                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11229                                 }
11230                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11231
11232                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11233
11234                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11235                         } else {
11236                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11237                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11238                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11239                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11240                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11241                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11242
11243                                         mono_class_init (tclass);
11244                                         if (context_used) {
11245                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11246                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11247                                         } else if (cfg->compile_aot) {
11248                                                 if (method->wrapper_type) {
11249                                                         error_init (&error); //got to do it since there are multiple conditionals below
11250                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11251                                                                 /* Special case for static synchronized wrappers */
11252                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11253                                                         } else {
11254                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11255                                                                 /* FIXME: n is not a normal token */
11256                                                                 DISABLE_AOT (cfg);
11257                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11258                                                         }
11259                                                 } else {
11260                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11261                                                 }
11262                                         } else {
11263                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11264                                                 CHECK_CFG_ERROR;
11265                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11266                                         }
11267                                         ins->type = STACK_OBJ;
11268                                         ins->klass = cmethod->klass;
11269                                         ip += 5;
11270                                 } else {
11271                                         MonoInst *addr, *vtvar;
11272
11273                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11274
11275                                         if (context_used) {
11276                                                 if (handle_class == mono_defaults.typehandle_class) {
11277                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11278                                                                         mono_class_from_mono_type ((MonoType *)handle),
11279                                                                         MONO_RGCTX_INFO_TYPE);
11280                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11281                                                         ins = emit_get_rgctx_method (cfg, context_used,
11282                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11283                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11284                                                         ins = emit_get_rgctx_field (cfg, context_used,
11285                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11286                                                 } else {
11287                                                         g_assert_not_reached ();
11288                                                 }
11289                                         } else if (cfg->compile_aot) {
11290                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11291                                         } else {
11292                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11293                                         }
11294                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11295                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11296                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11297                                 }
11298                         }
11299
11300                         *sp++ = ins;
11301                         ip += 5;
11302                         break;
11303                 }
11304                 case CEE_THROW:
11305                         CHECK_STACK (1);
11306                         if (sp [-1]->type != STACK_OBJ)
11307                                 UNVERIFIED;
11308
11309                         MONO_INST_NEW (cfg, ins, OP_THROW);
11310                         --sp;
11311                         ins->sreg1 = sp [0]->dreg;
11312                         ip++;
11313                         cfg->cbb->out_of_line = TRUE;
11314                         MONO_ADD_INS (cfg->cbb, ins);
11315                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11316                         MONO_ADD_INS (cfg->cbb, ins);
11317                         sp = stack_start;
11318                         
11319                         link_bblock (cfg, cfg->cbb, end_bblock);
11320                         start_new_bblock = 1;
11321                         /* This can complicate code generation for llvm since the return value might not be defined */
11322                         if (COMPILE_LLVM (cfg))
11323                                 INLINE_FAILURE ("throw");
11324                         break;
11325                 case CEE_ENDFINALLY:
11326                         if (!ip_in_finally_clause (cfg, ip - header->code))
11327                                 UNVERIFIED;
11328                         /* mono_save_seq_point_info () depends on this */
11329                         if (sp != stack_start)
11330                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11331                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11332                         MONO_ADD_INS (cfg->cbb, ins);
11333                         ip++;
11334                         start_new_bblock = 1;
11335
11336                         /*
11337                          * Control will leave the method so empty the stack, otherwise
11338                          * the next basic block will start with a nonempty stack.
11339                          */
11340                         while (sp != stack_start) {
11341                                 sp--;
11342                         }
11343                         break;
11344                 case CEE_LEAVE:
11345                 case CEE_LEAVE_S: {
11346                         GList *handlers;
11347
11348                         if (*ip == CEE_LEAVE) {
11349                                 CHECK_OPSIZE (5);
11350                                 target = ip + 5 + (gint32)read32(ip + 1);
11351                         } else {
11352                                 CHECK_OPSIZE (2);
11353                                 target = ip + 2 + (signed char)(ip [1]);
11354                         }
11355
11356                         /* empty the stack */
11357                         while (sp != stack_start) {
11358                                 sp--;
11359                         }
11360
11361                         /* 
11362                          * If this leave statement is in a catch block, check for a
11363                          * pending exception, and rethrow it if necessary.
11364                          * We avoid doing this in runtime invoke wrappers, since those are called
11365                          * by native code which excepts the wrapper to catch all exceptions.
11366                          */
11367                         for (i = 0; i < header->num_clauses; ++i) {
11368                                 MonoExceptionClause *clause = &header->clauses [i];
11369
11370                                 /* 
11371                                  * Use <= in the final comparison to handle clauses with multiple
11372                                  * leave statements, like in bug #78024.
11373                                  * The ordering of the exception clauses guarantees that we find the
11374                                  * innermost clause.
11375                                  */
11376                                 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) {
11377                                         MonoInst *exc_ins;
11378                                         MonoBasicBlock *dont_throw;
11379
11380                                         /*
11381                                           MonoInst *load;
11382
11383                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11384                                         */
11385
11386                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11387
11388                                         NEW_BBLOCK (cfg, dont_throw);
11389
11390                                         /*
11391                                          * Currently, we always rethrow the abort exception, despite the 
11392                                          * fact that this is not correct. See thread6.cs for an example. 
11393                                          * But propagating the abort exception is more important than 
11394                                          * getting the sematics right.
11395                                          */
11396                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11397                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11398                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11399
11400                                         MONO_START_BB (cfg, dont_throw);
11401                                 }
11402                         }
11403
11404 #ifdef ENABLE_LLVM
11405                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11406 #endif
11407
11408                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11409                                 GList *tmp;
11410                                 MonoExceptionClause *clause;
11411
11412                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11413                                         clause = (MonoExceptionClause *)tmp->data;
11414                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11415                                         g_assert (tblock);
11416                                         link_bblock (cfg, cfg->cbb, tblock);
11417                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11418                                         ins->inst_target_bb = tblock;
11419                                         ins->inst_eh_block = clause;
11420                                         MONO_ADD_INS (cfg->cbb, ins);
11421                                         cfg->cbb->has_call_handler = 1;
11422                                         if (COMPILE_LLVM (cfg)) {
11423                                                 MonoBasicBlock *target_bb;
11424
11425                                                 /* 
11426                                                  * Link the finally bblock with the target, since it will
11427                                                  * conceptually branch there.
11428                                                  */
11429                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11430                                                 GET_BBLOCK (cfg, target_bb, target);
11431                                                 link_bblock (cfg, tblock, target_bb);
11432                                         }
11433                                 }
11434                                 g_list_free (handlers);
11435                         } 
11436
11437                         MONO_INST_NEW (cfg, ins, OP_BR);
11438                         MONO_ADD_INS (cfg->cbb, ins);
11439                         GET_BBLOCK (cfg, tblock, target);
11440                         link_bblock (cfg, cfg->cbb, tblock);
11441                         ins->inst_target_bb = tblock;
11442
11443                         start_new_bblock = 1;
11444
11445                         if (*ip == CEE_LEAVE)
11446                                 ip += 5;
11447                         else
11448                                 ip += 2;
11449
11450                         break;
11451                 }
11452
11453                         /*
11454                          * Mono specific opcodes
11455                          */
11456                 case MONO_CUSTOM_PREFIX: {
11457
11458                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11459
11460                         CHECK_OPSIZE (2);
11461                         switch (ip [1]) {
11462                         case CEE_MONO_ICALL: {
11463                                 gpointer func;
11464                                 MonoJitICallInfo *info;
11465
11466                                 token = read32 (ip + 2);
11467                                 func = mono_method_get_wrapper_data (method, token);
11468                                 info = mono_find_jit_icall_by_addr (func);
11469                                 if (!info)
11470                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11471                                 g_assert (info);
11472
11473                                 CHECK_STACK (info->sig->param_count);
11474                                 sp -= info->sig->param_count;
11475
11476                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11477                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11478                                         *sp++ = ins;
11479
11480                                 ip += 6;
11481                                 inline_costs += 10 * num_calls++;
11482
11483                                 break;
11484                         }
11485                         case CEE_MONO_LDPTR_CARD_TABLE:
11486                         case CEE_MONO_LDPTR_NURSERY_START:
11487                         case CEE_MONO_LDPTR_NURSERY_BITS:
11488                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11489                                 CHECK_STACK_OVF (1);
11490
11491                                 switch (ip [1]) {
11492                                         case CEE_MONO_LDPTR_CARD_TABLE:
11493                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11494                                                 break;
11495                                         case CEE_MONO_LDPTR_NURSERY_START:
11496                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11497                                                 break;
11498                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11499                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11500                                                 break;
11501                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11502                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11503                                                 break;
11504                                 }
11505
11506                                 *sp++ = ins;
11507                                 ip += 2;
11508                                 inline_costs += 10 * num_calls++;
11509                                 break;
11510                         }
11511                         case CEE_MONO_LDPTR: {
11512                                 gpointer ptr;
11513
11514                                 CHECK_STACK_OVF (1);
11515                                 CHECK_OPSIZE (6);
11516                                 token = read32 (ip + 2);
11517
11518                                 ptr = mono_method_get_wrapper_data (method, token);
11519                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11520                                 *sp++ = ins;
11521                                 ip += 6;
11522                                 inline_costs += 10 * num_calls++;
11523                                 /* Can't embed random pointers into AOT code */
11524                                 DISABLE_AOT (cfg);
11525                                 break;
11526                         }
11527                         case CEE_MONO_JIT_ICALL_ADDR: {
11528                                 MonoJitICallInfo *callinfo;
11529                                 gpointer ptr;
11530
11531                                 CHECK_STACK_OVF (1);
11532                                 CHECK_OPSIZE (6);
11533                                 token = read32 (ip + 2);
11534
11535                                 ptr = mono_method_get_wrapper_data (method, token);
11536                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11537                                 g_assert (callinfo);
11538                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11539                                 *sp++ = ins;
11540                                 ip += 6;
11541                                 inline_costs += 10 * num_calls++;
11542                                 break;
11543                         }
11544                         case CEE_MONO_ICALL_ADDR: {
11545                                 MonoMethod *cmethod;
11546                                 gpointer ptr;
11547
11548                                 CHECK_STACK_OVF (1);
11549                                 CHECK_OPSIZE (6);
11550                                 token = read32 (ip + 2);
11551
11552                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11553
11554                                 if (cfg->compile_aot) {
11555                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11556                                                 /*
11557                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11558                                                  * before the call, its not needed when using direct pinvoke.
11559                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11560                                                  * on platforms which don't support dlopen ().
11561                                                  */
11562                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11563                                         } else {
11564                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11565                                         }
11566                                 } else {
11567                                         ptr = mono_lookup_internal_call (cmethod);
11568                                         g_assert (ptr);
11569                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11570                                 }
11571                                 *sp++ = ins;
11572                                 ip += 6;
11573                                 break;
11574                         }
11575                         case CEE_MONO_VTADDR: {
11576                                 MonoInst *src_var, *src;
11577
11578                                 CHECK_STACK (1);
11579                                 --sp;
11580
11581                                 // FIXME:
11582                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11583                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11584                                 *sp++ = src;
11585                                 ip += 2;
11586                                 break;
11587                         }
11588                         case CEE_MONO_NEWOBJ: {
11589                                 MonoInst *iargs [2];
11590
11591                                 CHECK_STACK_OVF (1);
11592                                 CHECK_OPSIZE (6);
11593                                 token = read32 (ip + 2);
11594                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11595                                 mono_class_init (klass);
11596                                 NEW_DOMAINCONST (cfg, iargs [0]);
11597                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11598                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11599                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11600                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11601                                 ip += 6;
11602                                 inline_costs += 10 * num_calls++;
11603                                 break;
11604                         }
11605                         case CEE_MONO_OBJADDR:
11606                                 CHECK_STACK (1);
11607                                 --sp;
11608                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11609                                 ins->dreg = alloc_ireg_mp (cfg);
11610                                 ins->sreg1 = sp [0]->dreg;
11611                                 ins->type = STACK_MP;
11612                                 MONO_ADD_INS (cfg->cbb, ins);
11613                                 *sp++ = ins;
11614                                 ip += 2;
11615                                 break;
11616                         case CEE_MONO_LDNATIVEOBJ:
11617                                 /*
11618                                  * Similar to LDOBJ, but instead load the unmanaged 
11619                                  * representation of the vtype to the stack.
11620                                  */
11621                                 CHECK_STACK (1);
11622                                 CHECK_OPSIZE (6);
11623                                 --sp;
11624                                 token = read32 (ip + 2);
11625                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11626                                 g_assert (klass->valuetype);
11627                                 mono_class_init (klass);
11628
11629                                 {
11630                                         MonoInst *src, *dest, *temp;
11631
11632                                         src = sp [0];
11633                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11634                                         temp->backend.is_pinvoke = 1;
11635                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11636                                         mini_emit_memory_copy (cfg, dest, src, klass, TRUE, 0);
11637
11638                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11639                                         dest->type = STACK_VTYPE;
11640                                         dest->klass = klass;
11641
11642                                         *sp ++ = dest;
11643                                         ip += 6;
11644                                 }
11645                                 break;
11646                         case CEE_MONO_RETOBJ: {
11647                                 /*
11648                                  * Same as RET, but return the native representation of a vtype
11649                                  * to the caller.
11650                                  */
11651                                 g_assert (cfg->ret);
11652                                 g_assert (mono_method_signature (method)->pinvoke); 
11653                                 CHECK_STACK (1);
11654                                 --sp;
11655                                 
11656                                 CHECK_OPSIZE (6);
11657                                 token = read32 (ip + 2);    
11658                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11659
11660                                 if (!cfg->vret_addr) {
11661                                         g_assert (cfg->ret_var_is_local);
11662
11663                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11664                                 } else {
11665                                         EMIT_NEW_RETLOADA (cfg, ins);
11666                                 }
11667                                 mini_emit_memory_copy (cfg, ins, sp [0], klass, TRUE, 0);
11668                                 
11669                                 if (sp != stack_start)
11670                                         UNVERIFIED;
11671                                 
11672                                 MONO_INST_NEW (cfg, ins, OP_BR);
11673                                 ins->inst_target_bb = end_bblock;
11674                                 MONO_ADD_INS (cfg->cbb, ins);
11675                                 link_bblock (cfg, cfg->cbb, end_bblock);
11676                                 start_new_bblock = 1;
11677                                 ip += 6;
11678                                 break;
11679                         }
11680                         case CEE_MONO_SAVE_LMF:
11681                         case CEE_MONO_RESTORE_LMF:
11682                                 ip += 2;
11683                                 break;
11684                         case CEE_MONO_CLASSCONST:
11685                                 CHECK_STACK_OVF (1);
11686                                 CHECK_OPSIZE (6);
11687                                 token = read32 (ip + 2);
11688                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11689                                 *sp++ = ins;
11690                                 ip += 6;
11691                                 inline_costs += 10 * num_calls++;
11692                                 break;
11693                         case CEE_MONO_NOT_TAKEN:
11694                                 cfg->cbb->out_of_line = TRUE;
11695                                 ip += 2;
11696                                 break;
11697                         case CEE_MONO_TLS: {
11698                                 MonoTlsKey key;
11699
11700                                 CHECK_STACK_OVF (1);
11701                                 CHECK_OPSIZE (6);
11702                                 key = (MonoTlsKey)read32 (ip + 2);
11703                                 g_assert (key < TLS_KEY_NUM);
11704
11705                                 ins = mono_create_tls_get (cfg, key);
11706                                 g_assert (ins);
11707                                 ins->type = STACK_PTR;
11708                                 *sp++ = ins;
11709                                 ip += 6;
11710                                 break;
11711                         }
11712                         case CEE_MONO_DYN_CALL: {
11713                                 MonoCallInst *call;
11714
11715                                 /* It would be easier to call a trampoline, but that would put an
11716                                  * extra frame on the stack, confusing exception handling. So
11717                                  * implement it inline using an opcode for now.
11718                                  */
11719
11720                                 if (!cfg->dyn_call_var) {
11721                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11722                                         /* prevent it from being register allocated */
11723                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11724                                 }
11725
11726                                 /* Has to use a call inst since it local regalloc expects it */
11727                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11728                                 ins = (MonoInst*)call;
11729                                 sp -= 2;
11730                                 ins->sreg1 = sp [0]->dreg;
11731                                 ins->sreg2 = sp [1]->dreg;
11732                                 MONO_ADD_INS (cfg->cbb, ins);
11733
11734                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11735
11736                                 ip += 2;
11737                                 inline_costs += 10 * num_calls++;
11738
11739                                 break;
11740                         }
11741                         case CEE_MONO_MEMORY_BARRIER: {
11742                                 CHECK_OPSIZE (6);
11743                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
11744                                 ip += 6;
11745                                 break;
11746                         }
11747                         case CEE_MONO_ATOMIC_STORE_I4: {
11748                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
11749
11750                                 CHECK_OPSIZE (6);
11751                                 CHECK_STACK (2);
11752                                 sp -= 2;
11753
11754                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
11755                                 ins->dreg = sp [0]->dreg;
11756                                 ins->sreg1 = sp [1]->dreg;
11757                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
11758                                 MONO_ADD_INS (cfg->cbb, ins);
11759
11760                                 ip += 6;
11761                                 break;
11762                         }
11763                         case CEE_MONO_JIT_ATTACH: {
11764                                 MonoInst *args [16], *domain_ins;
11765                                 MonoInst *ad_ins, *jit_tls_ins;
11766                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
11767
11768                                 g_assert (!mono_threads_is_coop_enabled ());
11769
11770                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11771
11772                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11773                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11774
11775                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
11776                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
11777
11778                                 if (ad_ins && jit_tls_ins) {
11779                                         NEW_BBLOCK (cfg, next_bb);
11780                                         NEW_BBLOCK (cfg, call_bb);
11781
11782                                         if (cfg->compile_aot) {
11783                                                 /* AOT code is only used in the root domain */
11784                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
11785                                         } else {
11786                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
11787                                         }
11788                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
11789                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
11790
11791                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
11792                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
11793
11794                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
11795                                         MONO_START_BB (cfg, call_bb);
11796                                 }
11797
11798                                 /* AOT code is only used in the root domain */
11799                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
11800                                 if (cfg->compile_aot) {
11801                                         MonoInst *addr;
11802
11803                                         /*
11804                                          * This is called on unattached threads, so it cannot go through the trampoline
11805                                          * infrastructure. Use an indirect call through a got slot initialized at load time
11806                                          * instead.
11807                                          */
11808                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
11809                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
11810                                 } else {
11811                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
11812                                 }
11813                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11814
11815                                 if (next_bb)
11816                                         MONO_START_BB (cfg, next_bb);
11817
11818                                 ip += 2;
11819                                 break;
11820                         }
11821                         case CEE_MONO_JIT_DETACH: {
11822                                 MonoInst *args [16];
11823
11824                                 /* Restore the original domain */
11825                                 dreg = alloc_ireg (cfg);
11826                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
11827                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
11828                                 ip += 2;
11829                                 break;
11830                         }
11831                         case CEE_MONO_CALLI_EXTRA_ARG: {
11832                                 MonoInst *addr;
11833                                 MonoMethodSignature *fsig;
11834                                 MonoInst *arg;
11835
11836                                 /*
11837                                  * This is the same as CEE_CALLI, but passes an additional argument
11838                                  * to the called method in llvmonly mode.
11839                                  * This is only used by delegate invoke wrappers to call the
11840                                  * actual delegate method.
11841                                  */
11842                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
11843
11844                                 CHECK_OPSIZE (6);
11845                                 token = read32 (ip + 2);
11846
11847                                 ins = NULL;
11848
11849                                 cmethod = NULL;
11850                                 CHECK_STACK (1);
11851                                 --sp;
11852                                 addr = *sp;
11853                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
11854                                 CHECK_CFG_ERROR;
11855
11856                                 if (cfg->llvm_only)
11857                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
11858
11859                                 n = fsig->param_count + fsig->hasthis + 1;
11860
11861                                 CHECK_STACK (n);
11862
11863                                 sp -= n;
11864                                 arg = sp [n - 1];
11865
11866                                 if (cfg->llvm_only) {
11867                                         /*
11868                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
11869                                          * cconv. This is set by mono_init_delegate ().
11870                                          */
11871                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
11872                                                 MonoInst *callee = addr;
11873                                                 MonoInst *call, *localloc_ins;
11874                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11875                                                 int low_bit_reg = alloc_preg (cfg);
11876
11877                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11878                                                 NEW_BBLOCK (cfg, end_bb);
11879
11880                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11881                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11882                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11883
11884                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
11885                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11886                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11887                                                 /*
11888                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
11889                                                  */
11890                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11891                                                 ins->dreg = alloc_preg (cfg);
11892                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11893                                                 MONO_ADD_INS (cfg->cbb, ins);
11894                                                 localloc_ins = ins;
11895                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11896                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11897                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11898
11899                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11900                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11901
11902                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
11903                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11904                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11905                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11906                                                 ins->dreg = call->dreg;
11907
11908                                                 MONO_START_BB (cfg, end_bb);
11909                                         } else {
11910                                                 /* Caller uses a normal calling conv */
11911
11912                                                 MonoInst *callee = addr;
11913                                                 MonoInst *call, *localloc_ins;
11914                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11915                                                 int low_bit_reg = alloc_preg (cfg);
11916
11917                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11918                                                 NEW_BBLOCK (cfg, end_bb);
11919
11920                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11921                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11922                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11923
11924                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
11925                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
11926                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11927                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
11928                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
11929                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
11930                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
11931                                                 MONO_ADD_INS (cfg->cbb, addr);
11932                                                 /*
11933                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
11934                                                  */
11935                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
11936                                                 ins->dreg = alloc_preg (cfg);
11937                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
11938                                                 MONO_ADD_INS (cfg->cbb, ins);
11939                                                 localloc_ins = ins;
11940                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
11941                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
11942                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
11943
11944                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
11945                                                 ins->dreg = call->dreg;
11946                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
11947
11948                                                 MONO_START_BB (cfg, end_bb);
11949                                         }
11950                                 } else {
11951                                         /* Same as CEE_CALLI */
11952                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
11953                                                 /*
11954                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
11955                                                  */
11956                                                 MonoInst *callee = addr;
11957
11958                                                 addr = emit_get_rgctx_sig (cfg, context_used,
11959                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
11960                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
11961                                         } else {
11962                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
11963                                         }
11964                                 }
11965
11966                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
11967                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
11968
11969                                 CHECK_CFG_EXCEPTION;
11970
11971                                 ip += 6;
11972                                 ins_flag = 0;
11973                                 constrained_class = NULL;
11974                                 break;
11975                         }
11976                         case CEE_MONO_LDDOMAIN:
11977                                 CHECK_STACK_OVF (1);
11978                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
11979                                 ip += 2;
11980                                 *sp++ = ins;
11981                                 break;
11982                         case CEE_MONO_GET_LAST_ERROR:
11983                                 CHECK_OPSIZE (2);
11984                                 CHECK_STACK_OVF (1);
11985
11986                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
11987                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
11988                                 ins->type = STACK_I4;
11989                                 MONO_ADD_INS (cfg->cbb, ins);
11990
11991                                 ip += 2;
11992                                 *sp++ = ins;
11993                                 break;
11994                         case CEE_MONO_GET_RGCTX_ARG:
11995                                 CHECK_OPSIZE (2);
11996                                 CHECK_STACK_OVF (1);
11997
11998                                 mono_create_rgctx_var (cfg);
11999
12000                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12001                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12002                                 ins->sreg1 = cfg->rgctx_var->dreg;
12003                                 ins->type = STACK_PTR;
12004                                 MONO_ADD_INS (cfg->cbb, ins);
12005
12006                                 ip += 2;
12007                                 *sp++ = ins;
12008                                 break;
12009                         default:
12010                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12011                                 break;
12012                         }
12013                         break;
12014                 }
12015
12016                 case CEE_PREFIX1: {
12017                         CHECK_OPSIZE (2);
12018                         switch (ip [1]) {
12019                         case CEE_ARGLIST: {
12020                                 /* somewhat similar to LDTOKEN */
12021                                 MonoInst *addr, *vtvar;
12022                                 CHECK_STACK_OVF (1);
12023                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12024
12025                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12026                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12027
12028                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12029                                 ins->type = STACK_VTYPE;
12030                                 ins->klass = mono_defaults.argumenthandle_class;
12031                                 *sp++ = ins;
12032                                 ip += 2;
12033                                 break;
12034                         }
12035                         case CEE_CEQ:
12036                         case CEE_CGT:
12037                         case CEE_CGT_UN:
12038                         case CEE_CLT:
12039                         case CEE_CLT_UN: {
12040                                 MonoInst *cmp, *arg1, *arg2;
12041
12042                                 CHECK_STACK (2);
12043                                 sp -= 2;
12044                                 arg1 = sp [0];
12045                                 arg2 = sp [1];
12046
12047                                 /*
12048                                  * The following transforms:
12049                                  *    CEE_CEQ    into OP_CEQ
12050                                  *    CEE_CGT    into OP_CGT
12051                                  *    CEE_CGT_UN into OP_CGT_UN
12052                                  *    CEE_CLT    into OP_CLT
12053                                  *    CEE_CLT_UN into OP_CLT_UN
12054                                  */
12055                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12056
12057                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12058                                 cmp->sreg1 = arg1->dreg;
12059                                 cmp->sreg2 = arg2->dreg;
12060                                 type_from_op (cfg, cmp, arg1, arg2);
12061                                 CHECK_TYPE (cmp);
12062                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12063                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12064                                         cmp->opcode = OP_LCOMPARE;
12065                                 else if (arg1->type == STACK_R4)
12066                                         cmp->opcode = OP_RCOMPARE;
12067                                 else if (arg1->type == STACK_R8)
12068                                         cmp->opcode = OP_FCOMPARE;
12069                                 else
12070                                         cmp->opcode = OP_ICOMPARE;
12071                                 MONO_ADD_INS (cfg->cbb, cmp);
12072                                 ins->type = STACK_I4;
12073                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12074                                 type_from_op (cfg, ins, arg1, arg2);
12075
12076                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12077                                         /*
12078                                          * The backends expect the fceq opcodes to do the
12079                                          * comparison too.
12080                                          */
12081                                         ins->sreg1 = cmp->sreg1;
12082                                         ins->sreg2 = cmp->sreg2;
12083                                         NULLIFY_INS (cmp);
12084                                 }
12085                                 MONO_ADD_INS (cfg->cbb, ins);
12086                                 *sp++ = ins;
12087                                 ip += 2;
12088                                 break;
12089                         }
12090                         case CEE_LDFTN: {
12091                                 MonoInst *argconst;
12092                                 MonoMethod *cil_method;
12093
12094                                 CHECK_STACK_OVF (1);
12095                                 CHECK_OPSIZE (6);
12096                                 n = read32 (ip + 2);
12097                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12098                                 CHECK_CFG_ERROR;
12099
12100                                 mono_class_init (cmethod->klass);
12101
12102                                 mono_save_token_info (cfg, image, n, cmethod);
12103
12104                                 context_used = mini_method_check_context_used (cfg, cmethod);
12105
12106                                 cil_method = cmethod;
12107                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12108                                         emit_method_access_failure (cfg, method, cil_method);
12109
12110                                 if (mono_security_core_clr_enabled ())
12111                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12112
12113                                 /* 
12114                                  * Optimize the common case of ldftn+delegate creation
12115                                  */
12116                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12117                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12118                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12119                                                 MonoInst *target_ins, *handle_ins;
12120                                                 MonoMethod *invoke;
12121                                                 int invoke_context_used;
12122
12123                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12124                                                 if (!invoke || !mono_method_signature (invoke))
12125                                                         LOAD_ERROR;
12126
12127                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12128
12129                                                 target_ins = sp [-1];
12130
12131                                                 if (mono_security_core_clr_enabled ())
12132                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12133
12134                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12135                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12136                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12137                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12138                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12139                                                         }
12140                                                 }
12141
12142                                                 /* FIXME: SGEN support */
12143                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12144                                                         ip += 6;
12145                                                         if (cfg->verbose_level > 3)
12146                                                                 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));
12147                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12148                                                                 sp --;
12149                                                                 *sp = handle_ins;
12150                                                                 CHECK_CFG_EXCEPTION;
12151                                                                 ip += 5;
12152                                                                 sp ++;
12153                                                                 break;
12154                                                         }
12155                                                         ip -= 6;
12156                                                 }
12157                                         }
12158                                 }
12159
12160                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12161                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12162                                 *sp++ = ins;
12163                                 
12164                                 ip += 6;
12165                                 inline_costs += 10 * num_calls++;
12166                                 break;
12167                         }
12168                         case CEE_LDVIRTFTN: {
12169                                 MonoInst *args [2];
12170
12171                                 CHECK_STACK (1);
12172                                 CHECK_OPSIZE (6);
12173                                 n = read32 (ip + 2);
12174                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12175                                 CHECK_CFG_ERROR;
12176
12177                                 mono_class_init (cmethod->klass);
12178  
12179                                 context_used = mini_method_check_context_used (cfg, cmethod);
12180
12181                                 if (mono_security_core_clr_enabled ())
12182                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12183
12184                                 /*
12185                                  * Optimize the common case of ldvirtftn+delegate creation
12186                                  */
12187                                 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)) {
12188                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12189                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12190                                                 MonoInst *target_ins, *handle_ins;
12191                                                 MonoMethod *invoke;
12192                                                 int invoke_context_used;
12193                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12194
12195                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12196                                                 if (!invoke || !mono_method_signature (invoke))
12197                                                         LOAD_ERROR;
12198
12199                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12200
12201                                                 target_ins = sp [-1];
12202
12203                                                 if (mono_security_core_clr_enabled ())
12204                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12205
12206                                                 /* FIXME: SGEN support */
12207                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12208                                                         ip += 6;
12209                                                         if (cfg->verbose_level > 3)
12210                                                                 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));
12211                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12212                                                                 sp -= 2;
12213                                                                 *sp = handle_ins;
12214                                                                 CHECK_CFG_EXCEPTION;
12215                                                                 ip += 5;
12216                                                                 sp ++;
12217                                                                 break;
12218                                                         }
12219                                                         ip -= 6;
12220                                                 }
12221                                         }
12222                                 }
12223
12224                                 --sp;
12225                                 args [0] = *sp;
12226
12227                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12228                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12229
12230                                 if (context_used)
12231                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12232                                 else
12233                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12234
12235                                 ip += 6;
12236                                 inline_costs += 10 * num_calls++;
12237                                 break;
12238                         }
12239                         case CEE_LDARG:
12240                                 CHECK_STACK_OVF (1);
12241                                 CHECK_OPSIZE (4);
12242                                 n = read16 (ip + 2);
12243                                 CHECK_ARG (n);
12244                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12245                                 *sp++ = ins;
12246                                 ip += 4;
12247                                 break;
12248                         case CEE_LDARGA:
12249                                 CHECK_STACK_OVF (1);
12250                                 CHECK_OPSIZE (4);
12251                                 n = read16 (ip + 2);
12252                                 CHECK_ARG (n);
12253                                 NEW_ARGLOADA (cfg, ins, n);
12254                                 MONO_ADD_INS (cfg->cbb, ins);
12255                                 *sp++ = ins;
12256                                 ip += 4;
12257                                 break;
12258                         case CEE_STARG:
12259                                 CHECK_STACK (1);
12260                                 --sp;
12261                                 CHECK_OPSIZE (4);
12262                                 n = read16 (ip + 2);
12263                                 CHECK_ARG (n);
12264                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12265                                         UNVERIFIED;
12266                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12267                                 ip += 4;
12268                                 break;
12269                         case CEE_LDLOC:
12270                                 CHECK_STACK_OVF (1);
12271                                 CHECK_OPSIZE (4);
12272                                 n = read16 (ip + 2);
12273                                 CHECK_LOCAL (n);
12274                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12275                                 *sp++ = ins;
12276                                 ip += 4;
12277                                 break;
12278                         case CEE_LDLOCA: {
12279                                 unsigned char *tmp_ip;
12280                                 CHECK_STACK_OVF (1);
12281                                 CHECK_OPSIZE (4);
12282                                 n = read16 (ip + 2);
12283                                 CHECK_LOCAL (n);
12284
12285                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12286                                         ip = tmp_ip;
12287                                         inline_costs += 1;
12288                                         break;
12289                                 }                       
12290                                 
12291                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12292                                 *sp++ = ins;
12293                                 ip += 4;
12294                                 break;
12295                         }
12296                         case CEE_STLOC:
12297                                 CHECK_STACK (1);
12298                                 --sp;
12299                                 CHECK_OPSIZE (4);
12300                                 n = read16 (ip + 2);
12301                                 CHECK_LOCAL (n);
12302                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12303                                         UNVERIFIED;
12304                                 emit_stloc_ir (cfg, sp, header, n);
12305                                 ip += 4;
12306                                 inline_costs += 1;
12307                                 break;
12308                         case CEE_LOCALLOC: {
12309                                 CHECK_STACK (1);
12310                                 MonoBasicBlock *non_zero_bb, *end_bb;
12311                                 int alloc_ptr = alloc_preg (cfg);
12312                                 --sp;
12313                                 if (sp != stack_start) 
12314                                         UNVERIFIED;
12315                                 if (cfg->method != method) 
12316                                         /* 
12317                                          * Inlining this into a loop in a parent could lead to 
12318                                          * stack overflows which is different behavior than the
12319                                          * non-inlined case, thus disable inlining in this case.
12320                                          */
12321                                         INLINE_FAILURE("localloc");
12322
12323                                 NEW_BBLOCK (cfg, non_zero_bb);
12324                                 NEW_BBLOCK (cfg, end_bb);
12325
12326                                 /* if size != zero */
12327                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12328                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12329
12330                                 //size is zero, so result is NULL
12331                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12332                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12333
12334                                 MONO_START_BB (cfg, non_zero_bb);
12335                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12336                                 ins->dreg = alloc_ptr;
12337                                 ins->sreg1 = sp [0]->dreg;
12338                                 ins->type = STACK_PTR;
12339                                 MONO_ADD_INS (cfg->cbb, ins);
12340
12341                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12342                                 if (init_locals)
12343                                         ins->flags |= MONO_INST_INIT;
12344
12345                                 MONO_START_BB (cfg, end_bb);
12346                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12347                                 ins->type = STACK_PTR;
12348
12349                                 *sp++ = ins;
12350                                 ip += 2;
12351                                 break;
12352                         }
12353                         case CEE_ENDFILTER: {
12354                                 MonoExceptionClause *clause, *nearest;
12355                                 int cc;
12356
12357                                 CHECK_STACK (1);
12358                                 --sp;
12359                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12360                                         UNVERIFIED;
12361                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12362                                 ins->sreg1 = (*sp)->dreg;
12363                                 MONO_ADD_INS (cfg->cbb, ins);
12364                                 start_new_bblock = 1;
12365                                 ip += 2;
12366
12367                                 nearest = NULL;
12368                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12369                                         clause = &header->clauses [cc];
12370                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12371                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12372                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12373                                                 nearest = clause;
12374                                 }
12375                                 g_assert (nearest);
12376                                 if ((ip - header->code) != nearest->handler_offset)
12377                                         UNVERIFIED;
12378
12379                                 break;
12380                         }
12381                         case CEE_UNALIGNED_:
12382                                 ins_flag |= MONO_INST_UNALIGNED;
12383                                 /* FIXME: record alignment? we can assume 1 for now */
12384                                 CHECK_OPSIZE (3);
12385                                 ip += 3;
12386                                 break;
12387                         case CEE_VOLATILE_:
12388                                 ins_flag |= MONO_INST_VOLATILE;
12389                                 ip += 2;
12390                                 break;
12391                         case CEE_TAIL_:
12392                                 ins_flag   |= MONO_INST_TAILCALL;
12393                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12394                                 /* Can't inline tail calls at this time */
12395                                 inline_costs += 100000;
12396                                 ip += 2;
12397                                 break;
12398                         case CEE_INITOBJ:
12399                                 CHECK_STACK (1);
12400                                 --sp;
12401                                 CHECK_OPSIZE (6);
12402                                 token = read32 (ip + 2);
12403                                 klass = mini_get_class (method, token, generic_context);
12404                                 CHECK_TYPELOAD (klass);
12405                                 if (generic_class_is_reference_type (cfg, klass))
12406                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12407                                 else
12408                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12409                                 ip += 6;
12410                                 inline_costs += 1;
12411                                 break;
12412                         case CEE_CONSTRAINED_:
12413                                 CHECK_OPSIZE (6);
12414                                 token = read32 (ip + 2);
12415                                 constrained_class = mini_get_class (method, token, generic_context);
12416                                 CHECK_TYPELOAD (constrained_class);
12417                                 ip += 6;
12418                                 break;
12419                         case CEE_CPBLK:
12420                                 CHECK_STACK (3);
12421                                 sp -= 3;
12422                                 mini_emit_memory_copy_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12423                                 ip += 2;
12424                                 ins_flag = 0;
12425                                 inline_costs += 1;
12426                                 break;
12427                         case CEE_INITBLK:
12428                                 CHECK_STACK (3);
12429                                 sp -= 3;
12430                                 mini_emit_memory_init_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12431                                 ip += 2;
12432                                 ins_flag = 0;
12433                                 inline_costs += 1;
12434                                 break;
12435                         case CEE_NO_:
12436                                 CHECK_OPSIZE (3);
12437                                 if (ip [2] & 0x1)
12438                                         ins_flag |= MONO_INST_NOTYPECHECK;
12439                                 if (ip [2] & 0x2)
12440                                         ins_flag |= MONO_INST_NORANGECHECK;
12441                                 /* we ignore the no-nullcheck for now since we
12442                                  * really do it explicitly only when doing callvirt->call
12443                                  */
12444                                 ip += 3;
12445                                 break;
12446                         case CEE_RETHROW: {
12447                                 MonoInst *load;
12448                                 int handler_offset = -1;
12449
12450                                 for (i = 0; i < header->num_clauses; ++i) {
12451                                         MonoExceptionClause *clause = &header->clauses [i];
12452                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12453                                                 handler_offset = clause->handler_offset;
12454                                                 break;
12455                                         }
12456                                 }
12457
12458                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12459
12460                                 if (handler_offset == -1)
12461                                         UNVERIFIED;
12462
12463                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12464                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12465                                 ins->sreg1 = load->dreg;
12466                                 MONO_ADD_INS (cfg->cbb, ins);
12467
12468                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12469                                 MONO_ADD_INS (cfg->cbb, ins);
12470
12471                                 sp = stack_start;
12472                                 link_bblock (cfg, cfg->cbb, end_bblock);
12473                                 start_new_bblock = 1;
12474                                 ip += 2;
12475                                 break;
12476                         }
12477                         case CEE_SIZEOF: {
12478                                 guint32 val;
12479                                 int ialign;
12480
12481                                 CHECK_STACK_OVF (1);
12482                                 CHECK_OPSIZE (6);
12483                                 token = read32 (ip + 2);
12484                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12485                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12486                                         CHECK_CFG_ERROR;
12487
12488                                         val = mono_type_size (type, &ialign);
12489                                 } else {
12490                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12491                                         CHECK_TYPELOAD (klass);
12492
12493                                         val = mono_type_size (&klass->byval_arg, &ialign);
12494
12495                                         if (mini_is_gsharedvt_klass (klass))
12496                                                 GSHAREDVT_FAILURE (*ip);
12497                                 }
12498                                 EMIT_NEW_ICONST (cfg, ins, val);
12499                                 *sp++= ins;
12500                                 ip += 6;
12501                                 break;
12502                         }
12503                         case CEE_REFANYTYPE: {
12504                                 MonoInst *src_var, *src;
12505
12506                                 GSHAREDVT_FAILURE (*ip);
12507
12508                                 CHECK_STACK (1);
12509                                 --sp;
12510
12511                                 // FIXME:
12512                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12513                                 if (!src_var)
12514                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12515                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12516                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12517                                 *sp++ = ins;
12518                                 ip += 2;
12519                                 break;
12520                         }
12521                         case CEE_READONLY_:
12522                                 readonly = TRUE;
12523                                 ip += 2;
12524                                 break;
12525
12526                         case CEE_UNUSED56:
12527                         case CEE_UNUSED57:
12528                         case CEE_UNUSED70:
12529                         case CEE_UNUSED:
12530                         case CEE_UNUSED99:
12531                                 UNVERIFIED;
12532                                 
12533                         default:
12534                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12535                                 UNVERIFIED;
12536                         }
12537                         break;
12538                 }
12539                 case CEE_UNUSED58:
12540                 case CEE_UNUSED1:
12541                         UNVERIFIED;
12542
12543                 default:
12544                         g_warning ("opcode 0x%02x not handled", *ip);
12545                         UNVERIFIED;
12546                 }
12547         }
12548         if (start_new_bblock != 1)
12549                 UNVERIFIED;
12550
12551         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12552         if (cfg->cbb->next_bb) {
12553                 /* This could already be set because of inlining, #693905 */
12554                 MonoBasicBlock *bb = cfg->cbb;
12555
12556                 while (bb->next_bb)
12557                         bb = bb->next_bb;
12558                 bb->next_bb = end_bblock;
12559         } else {
12560                 cfg->cbb->next_bb = end_bblock;
12561         }
12562
12563         if (cfg->method == method && cfg->domainvar) {
12564                 MonoInst *store;
12565                 MonoInst *get_domain;
12566
12567                 cfg->cbb = init_localsbb;
12568
12569                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12570                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12571                 MONO_ADD_INS (cfg->cbb, store);
12572         }
12573
12574 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12575         if (cfg->compile_aot)
12576                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12577                 mono_get_got_var (cfg);
12578 #endif
12579
12580         if (cfg->method == method && cfg->got_var)
12581                 mono_emit_load_got_addr (cfg);
12582
12583         if (init_localsbb) {
12584                 cfg->cbb = init_localsbb;
12585                 cfg->ip = NULL;
12586                 for (i = 0; i < header->num_locals; ++i) {
12587                         emit_init_local (cfg, i, header->locals [i], init_locals);
12588                 }
12589         }
12590
12591         if (cfg->init_ref_vars && cfg->method == method) {
12592                 /* Emit initialization for ref vars */
12593                 // FIXME: Avoid duplication initialization for IL locals.
12594                 for (i = 0; i < cfg->num_varinfo; ++i) {
12595                         MonoInst *ins = cfg->varinfo [i];
12596
12597                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12598                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12599                 }
12600         }
12601
12602         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12603                 cfg->cbb = init_localsbb;
12604                 emit_push_lmf (cfg);
12605         }
12606
12607         cfg->cbb = init_localsbb;
12608         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12609
12610         if (seq_points) {
12611                 MonoBasicBlock *bb;
12612
12613                 /*
12614                  * Make seq points at backward branch targets interruptable.
12615                  */
12616                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12617                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12618                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12619         }
12620
12621         /* Add a sequence point for method entry/exit events */
12622         if (seq_points && cfg->gen_sdb_seq_points) {
12623                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12624                 MONO_ADD_INS (init_localsbb, ins);
12625                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12626                 MONO_ADD_INS (cfg->bb_exit, ins);
12627         }
12628
12629         /*
12630          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12631          * the code they refer to was dead (#11880).
12632          */
12633         if (sym_seq_points) {
12634                 for (i = 0; i < header->code_size; ++i) {
12635                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12636                                 MonoInst *ins;
12637
12638                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12639                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12640                         }
12641                 }
12642         }
12643
12644         cfg->ip = NULL;
12645
12646         if (cfg->method == method) {
12647                 MonoBasicBlock *bb;
12648                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12649                         if (bb == cfg->bb_init)
12650                                 bb->region = -1;
12651                         else
12652                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12653                         if (cfg->spvars)
12654                                 mono_create_spvar_for_region (cfg, bb->region);
12655                         if (cfg->verbose_level > 2)
12656                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12657                 }
12658         } else {
12659                 MonoBasicBlock *bb;
12660                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12661                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12662                         bb->real_offset = inline_offset;
12663                 }
12664         }
12665
12666         if (inline_costs < 0) {
12667                 char *mname;
12668
12669                 /* Method is too large */
12670                 mname = mono_method_full_name (method, TRUE);
12671                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12672                 g_free (mname);
12673         }
12674
12675         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12676                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12677
12678         goto cleanup;
12679
12680 mono_error_exit:
12681         g_assert (!mono_error_ok (&cfg->error));
12682         goto cleanup;
12683  
12684  exception_exit:
12685         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12686         goto cleanup;
12687
12688  unverified:
12689         set_exception_type_from_invalid_il (cfg, method, ip);
12690         goto cleanup;
12691
12692  cleanup:
12693         g_slist_free (class_inits);
12694         mono_basic_block_free (original_bb);
12695         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12696         if (cfg->exception_type)
12697                 return -1;
12698         else
12699                 return inline_costs;
12700 }
12701
12702 static int
12703 store_membase_reg_to_store_membase_imm (int opcode)
12704 {
12705         switch (opcode) {
12706         case OP_STORE_MEMBASE_REG:
12707                 return OP_STORE_MEMBASE_IMM;
12708         case OP_STOREI1_MEMBASE_REG:
12709                 return OP_STOREI1_MEMBASE_IMM;
12710         case OP_STOREI2_MEMBASE_REG:
12711                 return OP_STOREI2_MEMBASE_IMM;
12712         case OP_STOREI4_MEMBASE_REG:
12713                 return OP_STOREI4_MEMBASE_IMM;
12714         case OP_STOREI8_MEMBASE_REG:
12715                 return OP_STOREI8_MEMBASE_IMM;
12716         default:
12717                 g_assert_not_reached ();
12718         }
12719
12720         return -1;
12721 }               
12722
12723 int
12724 mono_op_to_op_imm (int opcode)
12725 {
12726         switch (opcode) {
12727         case OP_IADD:
12728                 return OP_IADD_IMM;
12729         case OP_ISUB:
12730                 return OP_ISUB_IMM;
12731         case OP_IDIV:
12732                 return OP_IDIV_IMM;
12733         case OP_IDIV_UN:
12734                 return OP_IDIV_UN_IMM;
12735         case OP_IREM:
12736                 return OP_IREM_IMM;
12737         case OP_IREM_UN:
12738                 return OP_IREM_UN_IMM;
12739         case OP_IMUL:
12740                 return OP_IMUL_IMM;
12741         case OP_IAND:
12742                 return OP_IAND_IMM;
12743         case OP_IOR:
12744                 return OP_IOR_IMM;
12745         case OP_IXOR:
12746                 return OP_IXOR_IMM;
12747         case OP_ISHL:
12748                 return OP_ISHL_IMM;
12749         case OP_ISHR:
12750                 return OP_ISHR_IMM;
12751         case OP_ISHR_UN:
12752                 return OP_ISHR_UN_IMM;
12753
12754         case OP_LADD:
12755                 return OP_LADD_IMM;
12756         case OP_LSUB:
12757                 return OP_LSUB_IMM;
12758         case OP_LAND:
12759                 return OP_LAND_IMM;
12760         case OP_LOR:
12761                 return OP_LOR_IMM;
12762         case OP_LXOR:
12763                 return OP_LXOR_IMM;
12764         case OP_LSHL:
12765                 return OP_LSHL_IMM;
12766         case OP_LSHR:
12767                 return OP_LSHR_IMM;
12768         case OP_LSHR_UN:
12769                 return OP_LSHR_UN_IMM;
12770 #if SIZEOF_REGISTER == 8
12771         case OP_LREM:
12772                 return OP_LREM_IMM;
12773 #endif
12774
12775         case OP_COMPARE:
12776                 return OP_COMPARE_IMM;
12777         case OP_ICOMPARE:
12778                 return OP_ICOMPARE_IMM;
12779         case OP_LCOMPARE:
12780                 return OP_LCOMPARE_IMM;
12781
12782         case OP_STORE_MEMBASE_REG:
12783                 return OP_STORE_MEMBASE_IMM;
12784         case OP_STOREI1_MEMBASE_REG:
12785                 return OP_STOREI1_MEMBASE_IMM;
12786         case OP_STOREI2_MEMBASE_REG:
12787                 return OP_STOREI2_MEMBASE_IMM;
12788         case OP_STOREI4_MEMBASE_REG:
12789                 return OP_STOREI4_MEMBASE_IMM;
12790
12791 #if defined(TARGET_X86) || defined (TARGET_AMD64)
12792         case OP_X86_PUSH:
12793                 return OP_X86_PUSH_IMM;
12794         case OP_X86_COMPARE_MEMBASE_REG:
12795                 return OP_X86_COMPARE_MEMBASE_IMM;
12796 #endif
12797 #if defined(TARGET_AMD64)
12798         case OP_AMD64_ICOMPARE_MEMBASE_REG:
12799                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
12800 #endif
12801         case OP_VOIDCALL_REG:
12802                 return OP_VOIDCALL;
12803         case OP_CALL_REG:
12804                 return OP_CALL;
12805         case OP_LCALL_REG:
12806                 return OP_LCALL;
12807         case OP_FCALL_REG:
12808                 return OP_FCALL;
12809         case OP_LOCALLOC:
12810                 return OP_LOCALLOC_IMM;
12811         }
12812
12813         return -1;
12814 }
12815
12816 static int
12817 ldind_to_load_membase (int opcode)
12818 {
12819         switch (opcode) {
12820         case CEE_LDIND_I1:
12821                 return OP_LOADI1_MEMBASE;
12822         case CEE_LDIND_U1:
12823                 return OP_LOADU1_MEMBASE;
12824         case CEE_LDIND_I2:
12825                 return OP_LOADI2_MEMBASE;
12826         case CEE_LDIND_U2:
12827                 return OP_LOADU2_MEMBASE;
12828         case CEE_LDIND_I4:
12829                 return OP_LOADI4_MEMBASE;
12830         case CEE_LDIND_U4:
12831                 return OP_LOADU4_MEMBASE;
12832         case CEE_LDIND_I:
12833                 return OP_LOAD_MEMBASE;
12834         case CEE_LDIND_REF:
12835                 return OP_LOAD_MEMBASE;
12836         case CEE_LDIND_I8:
12837                 return OP_LOADI8_MEMBASE;
12838         case CEE_LDIND_R4:
12839                 return OP_LOADR4_MEMBASE;
12840         case CEE_LDIND_R8:
12841                 return OP_LOADR8_MEMBASE;
12842         default:
12843                 g_assert_not_reached ();
12844         }
12845
12846         return -1;
12847 }
12848
12849 static int
12850 stind_to_store_membase (int opcode)
12851 {
12852         switch (opcode) {
12853         case CEE_STIND_I1:
12854                 return OP_STOREI1_MEMBASE_REG;
12855         case CEE_STIND_I2:
12856                 return OP_STOREI2_MEMBASE_REG;
12857         case CEE_STIND_I4:
12858                 return OP_STOREI4_MEMBASE_REG;
12859         case CEE_STIND_I:
12860         case CEE_STIND_REF:
12861                 return OP_STORE_MEMBASE_REG;
12862         case CEE_STIND_I8:
12863                 return OP_STOREI8_MEMBASE_REG;
12864         case CEE_STIND_R4:
12865                 return OP_STORER4_MEMBASE_REG;
12866         case CEE_STIND_R8:
12867                 return OP_STORER8_MEMBASE_REG;
12868         default:
12869                 g_assert_not_reached ();
12870         }
12871
12872         return -1;
12873 }
12874
12875 int
12876 mono_load_membase_to_load_mem (int opcode)
12877 {
12878         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
12879 #if defined(TARGET_X86) || defined(TARGET_AMD64)
12880         switch (opcode) {
12881         case OP_LOAD_MEMBASE:
12882                 return OP_LOAD_MEM;
12883         case OP_LOADU1_MEMBASE:
12884                 return OP_LOADU1_MEM;
12885         case OP_LOADU2_MEMBASE:
12886                 return OP_LOADU2_MEM;
12887         case OP_LOADI4_MEMBASE:
12888                 return OP_LOADI4_MEM;
12889         case OP_LOADU4_MEMBASE:
12890                 return OP_LOADU4_MEM;
12891 #if SIZEOF_REGISTER == 8
12892         case OP_LOADI8_MEMBASE:
12893                 return OP_LOADI8_MEM;
12894 #endif
12895         }
12896 #endif
12897
12898         return -1;
12899 }
12900
12901 static inline int
12902 op_to_op_dest_membase (int store_opcode, int opcode)
12903 {
12904 #if defined(TARGET_X86)
12905         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
12906                 return -1;
12907
12908         switch (opcode) {
12909         case OP_IADD:
12910                 return OP_X86_ADD_MEMBASE_REG;
12911         case OP_ISUB:
12912                 return OP_X86_SUB_MEMBASE_REG;
12913         case OP_IAND:
12914                 return OP_X86_AND_MEMBASE_REG;
12915         case OP_IOR:
12916                 return OP_X86_OR_MEMBASE_REG;
12917         case OP_IXOR:
12918                 return OP_X86_XOR_MEMBASE_REG;
12919         case OP_ADD_IMM:
12920         case OP_IADD_IMM:
12921                 return OP_X86_ADD_MEMBASE_IMM;
12922         case OP_SUB_IMM:
12923         case OP_ISUB_IMM:
12924                 return OP_X86_SUB_MEMBASE_IMM;
12925         case OP_AND_IMM:
12926         case OP_IAND_IMM:
12927                 return OP_X86_AND_MEMBASE_IMM;
12928         case OP_OR_IMM:
12929         case OP_IOR_IMM:
12930                 return OP_X86_OR_MEMBASE_IMM;
12931         case OP_XOR_IMM:
12932         case OP_IXOR_IMM:
12933                 return OP_X86_XOR_MEMBASE_IMM;
12934         case OP_MOVE:
12935                 return OP_NOP;
12936         }
12937 #endif
12938
12939 #if defined(TARGET_AMD64)
12940         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
12941                 return -1;
12942
12943         switch (opcode) {
12944         case OP_IADD:
12945                 return OP_X86_ADD_MEMBASE_REG;
12946         case OP_ISUB:
12947                 return OP_X86_SUB_MEMBASE_REG;
12948         case OP_IAND:
12949                 return OP_X86_AND_MEMBASE_REG;
12950         case OP_IOR:
12951                 return OP_X86_OR_MEMBASE_REG;
12952         case OP_IXOR:
12953                 return OP_X86_XOR_MEMBASE_REG;
12954         case OP_IADD_IMM:
12955                 return OP_X86_ADD_MEMBASE_IMM;
12956         case OP_ISUB_IMM:
12957                 return OP_X86_SUB_MEMBASE_IMM;
12958         case OP_IAND_IMM:
12959                 return OP_X86_AND_MEMBASE_IMM;
12960         case OP_IOR_IMM:
12961                 return OP_X86_OR_MEMBASE_IMM;
12962         case OP_IXOR_IMM:
12963                 return OP_X86_XOR_MEMBASE_IMM;
12964         case OP_LADD:
12965                 return OP_AMD64_ADD_MEMBASE_REG;
12966         case OP_LSUB:
12967                 return OP_AMD64_SUB_MEMBASE_REG;
12968         case OP_LAND:
12969                 return OP_AMD64_AND_MEMBASE_REG;
12970         case OP_LOR:
12971                 return OP_AMD64_OR_MEMBASE_REG;
12972         case OP_LXOR:
12973                 return OP_AMD64_XOR_MEMBASE_REG;
12974         case OP_ADD_IMM:
12975         case OP_LADD_IMM:
12976                 return OP_AMD64_ADD_MEMBASE_IMM;
12977         case OP_SUB_IMM:
12978         case OP_LSUB_IMM:
12979                 return OP_AMD64_SUB_MEMBASE_IMM;
12980         case OP_AND_IMM:
12981         case OP_LAND_IMM:
12982                 return OP_AMD64_AND_MEMBASE_IMM;
12983         case OP_OR_IMM:
12984         case OP_LOR_IMM:
12985                 return OP_AMD64_OR_MEMBASE_IMM;
12986         case OP_XOR_IMM:
12987         case OP_LXOR_IMM:
12988                 return OP_AMD64_XOR_MEMBASE_IMM;
12989         case OP_MOVE:
12990                 return OP_NOP;
12991         }
12992 #endif
12993
12994         return -1;
12995 }
12996
12997 static inline int
12998 op_to_op_store_membase (int store_opcode, int opcode)
12999 {
13000 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13001         switch (opcode) {
13002         case OP_ICEQ:
13003                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13004                         return OP_X86_SETEQ_MEMBASE;
13005         case OP_CNE:
13006                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13007                         return OP_X86_SETNE_MEMBASE;
13008         }
13009 #endif
13010
13011         return -1;
13012 }
13013
13014 static inline int
13015 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13016 {
13017 #ifdef TARGET_X86
13018         /* FIXME: This has sign extension issues */
13019         /*
13020         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13021                 return OP_X86_COMPARE_MEMBASE8_IMM;
13022         */
13023
13024         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13025                 return -1;
13026
13027         switch (opcode) {
13028         case OP_X86_PUSH:
13029                 return OP_X86_PUSH_MEMBASE;
13030         case OP_COMPARE_IMM:
13031         case OP_ICOMPARE_IMM:
13032                 return OP_X86_COMPARE_MEMBASE_IMM;
13033         case OP_COMPARE:
13034         case OP_ICOMPARE:
13035                 return OP_X86_COMPARE_MEMBASE_REG;
13036         }
13037 #endif
13038
13039 #ifdef TARGET_AMD64
13040         /* FIXME: This has sign extension issues */
13041         /*
13042         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13043                 return OP_X86_COMPARE_MEMBASE8_IMM;
13044         */
13045
13046         switch (opcode) {
13047         case OP_X86_PUSH:
13048                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13049                         return OP_X86_PUSH_MEMBASE;
13050                 break;
13051                 /* FIXME: This only works for 32 bit immediates
13052         case OP_COMPARE_IMM:
13053         case OP_LCOMPARE_IMM:
13054                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13055                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13056                 */
13057         case OP_ICOMPARE_IMM:
13058                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13059                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13060                 break;
13061         case OP_COMPARE:
13062         case OP_LCOMPARE:
13063                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13064                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13065                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13066                         return OP_AMD64_COMPARE_MEMBASE_REG;
13067                 break;
13068         case OP_ICOMPARE:
13069                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13070                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13071                 break;
13072         }
13073 #endif
13074
13075         return -1;
13076 }
13077
13078 static inline int
13079 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13080 {
13081 #ifdef TARGET_X86
13082         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13083                 return -1;
13084         
13085         switch (opcode) {
13086         case OP_COMPARE:
13087         case OP_ICOMPARE:
13088                 return OP_X86_COMPARE_REG_MEMBASE;
13089         case OP_IADD:
13090                 return OP_X86_ADD_REG_MEMBASE;
13091         case OP_ISUB:
13092                 return OP_X86_SUB_REG_MEMBASE;
13093         case OP_IAND:
13094                 return OP_X86_AND_REG_MEMBASE;
13095         case OP_IOR:
13096                 return OP_X86_OR_REG_MEMBASE;
13097         case OP_IXOR:
13098                 return OP_X86_XOR_REG_MEMBASE;
13099         }
13100 #endif
13101
13102 #ifdef TARGET_AMD64
13103         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13104                 switch (opcode) {
13105                 case OP_ICOMPARE:
13106                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13107                 case OP_IADD:
13108                         return OP_X86_ADD_REG_MEMBASE;
13109                 case OP_ISUB:
13110                         return OP_X86_SUB_REG_MEMBASE;
13111                 case OP_IAND:
13112                         return OP_X86_AND_REG_MEMBASE;
13113                 case OP_IOR:
13114                         return OP_X86_OR_REG_MEMBASE;
13115                 case OP_IXOR:
13116                         return OP_X86_XOR_REG_MEMBASE;
13117                 }
13118         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13119                 switch (opcode) {
13120                 case OP_COMPARE:
13121                 case OP_LCOMPARE:
13122                         return OP_AMD64_COMPARE_REG_MEMBASE;
13123                 case OP_LADD:
13124                         return OP_AMD64_ADD_REG_MEMBASE;
13125                 case OP_LSUB:
13126                         return OP_AMD64_SUB_REG_MEMBASE;
13127                 case OP_LAND:
13128                         return OP_AMD64_AND_REG_MEMBASE;
13129                 case OP_LOR:
13130                         return OP_AMD64_OR_REG_MEMBASE;
13131                 case OP_LXOR:
13132                         return OP_AMD64_XOR_REG_MEMBASE;
13133                 }
13134         }
13135 #endif
13136
13137         return -1;
13138 }
13139
13140 int
13141 mono_op_to_op_imm_noemul (int opcode)
13142 {
13143         switch (opcode) {
13144 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13145         case OP_LSHR:
13146         case OP_LSHL:
13147         case OP_LSHR_UN:
13148                 return -1;
13149 #endif
13150 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13151         case OP_IDIV:
13152         case OP_IDIV_UN:
13153         case OP_IREM:
13154         case OP_IREM_UN:
13155                 return -1;
13156 #endif
13157 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13158         case OP_IMUL:
13159                 return -1;
13160 #endif
13161         default:
13162                 return mono_op_to_op_imm (opcode);
13163         }
13164 }
13165
13166 /**
13167  * mono_handle_global_vregs:
13168  *
13169  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13170  * for them.
13171  */
13172 void
13173 mono_handle_global_vregs (MonoCompile *cfg)
13174 {
13175         gint32 *vreg_to_bb;
13176         MonoBasicBlock *bb;
13177         int i, pos;
13178
13179         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13180
13181 #ifdef MONO_ARCH_SIMD_INTRINSICS
13182         if (cfg->uses_simd_intrinsics)
13183                 mono_simd_simplify_indirection (cfg);
13184 #endif
13185
13186         /* Find local vregs used in more than one bb */
13187         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13188                 MonoInst *ins = bb->code;       
13189                 int block_num = bb->block_num;
13190
13191                 if (cfg->verbose_level > 2)
13192                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13193
13194                 cfg->cbb = bb;
13195                 for (; ins; ins = ins->next) {
13196                         const char *spec = INS_INFO (ins->opcode);
13197                         int regtype = 0, regindex;
13198                         gint32 prev_bb;
13199
13200                         if (G_UNLIKELY (cfg->verbose_level > 2))
13201                                 mono_print_ins (ins);
13202
13203                         g_assert (ins->opcode >= MONO_CEE_LAST);
13204
13205                         for (regindex = 0; regindex < 4; regindex ++) {
13206                                 int vreg = 0;
13207
13208                                 if (regindex == 0) {
13209                                         regtype = spec [MONO_INST_DEST];
13210                                         if (regtype == ' ')
13211                                                 continue;
13212                                         vreg = ins->dreg;
13213                                 } else if (regindex == 1) {
13214                                         regtype = spec [MONO_INST_SRC1];
13215                                         if (regtype == ' ')
13216                                                 continue;
13217                                         vreg = ins->sreg1;
13218                                 } else if (regindex == 2) {
13219                                         regtype = spec [MONO_INST_SRC2];
13220                                         if (regtype == ' ')
13221                                                 continue;
13222                                         vreg = ins->sreg2;
13223                                 } else if (regindex == 3) {
13224                                         regtype = spec [MONO_INST_SRC3];
13225                                         if (regtype == ' ')
13226                                                 continue;
13227                                         vreg = ins->sreg3;
13228                                 }
13229
13230 #if SIZEOF_REGISTER == 4
13231                                 /* In the LLVM case, the long opcodes are not decomposed */
13232                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13233                                         /*
13234                                          * Since some instructions reference the original long vreg,
13235                                          * and some reference the two component vregs, it is quite hard
13236                                          * to determine when it needs to be global. So be conservative.
13237                                          */
13238                                         if (!get_vreg_to_inst (cfg, vreg)) {
13239                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13240
13241                                                 if (cfg->verbose_level > 2)
13242                                                         printf ("LONG VREG R%d made global.\n", vreg);
13243                                         }
13244
13245                                         /*
13246                                          * Make the component vregs volatile since the optimizations can
13247                                          * get confused otherwise.
13248                                          */
13249                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13250                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13251                                 }
13252 #endif
13253
13254                                 g_assert (vreg != -1);
13255
13256                                 prev_bb = vreg_to_bb [vreg];
13257                                 if (prev_bb == 0) {
13258                                         /* 0 is a valid block num */
13259                                         vreg_to_bb [vreg] = block_num + 1;
13260                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13261                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13262                                                 continue;
13263
13264                                         if (!get_vreg_to_inst (cfg, vreg)) {
13265                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13266                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13267
13268                                                 switch (regtype) {
13269                                                 case 'i':
13270                                                         if (vreg_is_ref (cfg, vreg))
13271                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13272                                                         else
13273                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13274                                                         break;
13275                                                 case 'l':
13276                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13277                                                         break;
13278                                                 case 'f':
13279                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13280                                                         break;
13281                                                 case 'v':
13282                                                 case 'x':
13283                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13284                                                         break;
13285                                                 default:
13286                                                         g_assert_not_reached ();
13287                                                 }
13288                                         }
13289
13290                                         /* Flag as having been used in more than one bb */
13291                                         vreg_to_bb [vreg] = -1;
13292                                 }
13293                         }
13294                 }
13295         }
13296
13297         /* If a variable is used in only one bblock, convert it into a local vreg */
13298         for (i = 0; i < cfg->num_varinfo; i++) {
13299                 MonoInst *var = cfg->varinfo [i];
13300                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13301
13302                 switch (var->type) {
13303                 case STACK_I4:
13304                 case STACK_OBJ:
13305                 case STACK_PTR:
13306                 case STACK_MP:
13307                 case STACK_VTYPE:
13308 #if SIZEOF_REGISTER == 8
13309                 case STACK_I8:
13310 #endif
13311 #if !defined(TARGET_X86)
13312                 /* Enabling this screws up the fp stack on x86 */
13313                 case STACK_R8:
13314 #endif
13315                         if (mono_arch_is_soft_float ())
13316                                 break;
13317
13318                         /*
13319                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13320                                 break;
13321                         */
13322
13323                         /* Arguments are implicitly global */
13324                         /* Putting R4 vars into registers doesn't work currently */
13325                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13326                         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) {
13327                                 /* 
13328                                  * Make that the variable's liveness interval doesn't contain a call, since
13329                                  * that would cause the lvreg to be spilled, making the whole optimization
13330                                  * useless.
13331                                  */
13332                                 /* This is too slow for JIT compilation */
13333 #if 0
13334                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13335                                         MonoInst *ins;
13336                                         int def_index, call_index, ins_index;
13337                                         gboolean spilled = FALSE;
13338
13339                                         def_index = -1;
13340                                         call_index = -1;
13341                                         ins_index = 0;
13342                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13343                                                 const char *spec = INS_INFO (ins->opcode);
13344
13345                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13346                                                         def_index = ins_index;
13347
13348                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13349                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13350                                                         if (call_index > def_index) {
13351                                                                 spilled = TRUE;
13352                                                                 break;
13353                                                         }
13354                                                 }
13355
13356                                                 if (MONO_IS_CALL (ins))
13357                                                         call_index = ins_index;
13358
13359                                                 ins_index ++;
13360                                         }
13361
13362                                         if (spilled)
13363                                                 break;
13364                                 }
13365 #endif
13366
13367                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13368                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13369                                 var->flags |= MONO_INST_IS_DEAD;
13370                                 cfg->vreg_to_inst [var->dreg] = NULL;
13371                         }
13372                         break;
13373                 }
13374         }
13375
13376         /* 
13377          * Compress the varinfo and vars tables so the liveness computation is faster and
13378          * takes up less space.
13379          */
13380         pos = 0;
13381         for (i = 0; i < cfg->num_varinfo; ++i) {
13382                 MonoInst *var = cfg->varinfo [i];
13383                 if (pos < i && cfg->locals_start == i)
13384                         cfg->locals_start = pos;
13385                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13386                         if (pos < i) {
13387                                 cfg->varinfo [pos] = cfg->varinfo [i];
13388                                 cfg->varinfo [pos]->inst_c0 = pos;
13389                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13390                                 cfg->vars [pos].idx = pos;
13391 #if SIZEOF_REGISTER == 4
13392                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13393                                         /* Modify the two component vars too */
13394                                         MonoInst *var1;
13395
13396                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13397                                         var1->inst_c0 = pos;
13398                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13399                                         var1->inst_c0 = pos;
13400                                 }
13401 #endif
13402                         }
13403                         pos ++;
13404                 }
13405         }
13406         cfg->num_varinfo = pos;
13407         if (cfg->locals_start > cfg->num_varinfo)
13408                 cfg->locals_start = cfg->num_varinfo;
13409 }
13410
13411 /*
13412  * mono_allocate_gsharedvt_vars:
13413  *
13414  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13415  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13416  */
13417 void
13418 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13419 {
13420         int i;
13421
13422         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13423
13424         for (i = 0; i < cfg->num_varinfo; ++i) {
13425                 MonoInst *ins = cfg->varinfo [i];
13426                 int idx;
13427
13428                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13429                         if (i >= cfg->locals_start) {
13430                                 /* Local */
13431                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13432                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13433                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13434                                 ins->inst_imm = idx;
13435                         } else {
13436                                 /* Arg */
13437                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13438                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13439                         }
13440                 }
13441         }
13442 }
13443
13444 /**
13445  * mono_spill_global_vars:
13446  *
13447  *   Generate spill code for variables which are not allocated to registers, 
13448  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13449  * code is generated which could be optimized by the local optimization passes.
13450  */
13451 void
13452 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13453 {
13454         MonoBasicBlock *bb;
13455         char spec2 [16];
13456         int orig_next_vreg;
13457         guint32 *vreg_to_lvreg;
13458         guint32 *lvregs;
13459         guint32 i, lvregs_len, lvregs_size;
13460         gboolean dest_has_lvreg = FALSE;
13461         MonoStackType stacktypes [128];
13462         MonoInst **live_range_start, **live_range_end;
13463         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13464
13465         *need_local_opts = FALSE;
13466
13467         memset (spec2, 0, sizeof (spec2));
13468
13469         /* FIXME: Move this function to mini.c */
13470         stacktypes ['i'] = STACK_PTR;
13471         stacktypes ['l'] = STACK_I8;
13472         stacktypes ['f'] = STACK_R8;
13473 #ifdef MONO_ARCH_SIMD_INTRINSICS
13474         stacktypes ['x'] = STACK_VTYPE;
13475 #endif
13476
13477 #if SIZEOF_REGISTER == 4
13478         /* Create MonoInsts for longs */
13479         for (i = 0; i < cfg->num_varinfo; i++) {
13480                 MonoInst *ins = cfg->varinfo [i];
13481
13482                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13483                         switch (ins->type) {
13484                         case STACK_R8:
13485                         case STACK_I8: {
13486                                 MonoInst *tree;
13487
13488                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13489                                         break;
13490
13491                                 g_assert (ins->opcode == OP_REGOFFSET);
13492
13493                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13494                                 g_assert (tree);
13495                                 tree->opcode = OP_REGOFFSET;
13496                                 tree->inst_basereg = ins->inst_basereg;
13497                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13498
13499                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13500                                 g_assert (tree);
13501                                 tree->opcode = OP_REGOFFSET;
13502                                 tree->inst_basereg = ins->inst_basereg;
13503                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13504                                 break;
13505                         }
13506                         default:
13507                                 break;
13508                         }
13509                 }
13510         }
13511 #endif
13512
13513         if (cfg->compute_gc_maps) {
13514                 /* registers need liveness info even for !non refs */
13515                 for (i = 0; i < cfg->num_varinfo; i++) {
13516                         MonoInst *ins = cfg->varinfo [i];
13517
13518                         if (ins->opcode == OP_REGVAR)
13519                                 ins->flags |= MONO_INST_GC_TRACK;
13520                 }
13521         }
13522                 
13523         /* FIXME: widening and truncation */
13524
13525         /*
13526          * As an optimization, when a variable allocated to the stack is first loaded into 
13527          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13528          * the variable again.
13529          */
13530         orig_next_vreg = cfg->next_vreg;
13531         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13532         lvregs_size = 1024;
13533         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13534         lvregs_len = 0;
13535
13536         /* 
13537          * These arrays contain the first and last instructions accessing a given
13538          * variable.
13539          * Since we emit bblocks in the same order we process them here, and we
13540          * don't split live ranges, these will precisely describe the live range of
13541          * the variable, i.e. the instruction range where a valid value can be found
13542          * in the variables location.
13543          * The live range is computed using the liveness info computed by the liveness pass.
13544          * We can't use vmv->range, since that is an abstract live range, and we need
13545          * one which is instruction precise.
13546          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13547          */
13548         /* FIXME: Only do this if debugging info is requested */
13549         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13550         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13551         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13552         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13553         
13554         /* Add spill loads/stores */
13555         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13556                 MonoInst *ins;
13557
13558                 if (cfg->verbose_level > 2)
13559                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13560
13561                 /* Clear vreg_to_lvreg array */
13562                 for (i = 0; i < lvregs_len; i++)
13563                         vreg_to_lvreg [lvregs [i]] = 0;
13564                 lvregs_len = 0;
13565
13566                 cfg->cbb = bb;
13567                 MONO_BB_FOR_EACH_INS (bb, ins) {
13568                         const char *spec = INS_INFO (ins->opcode);
13569                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13570                         gboolean store, no_lvreg;
13571                         int sregs [MONO_MAX_SRC_REGS];
13572
13573                         if (G_UNLIKELY (cfg->verbose_level > 2))
13574                                 mono_print_ins (ins);
13575
13576                         if (ins->opcode == OP_NOP)
13577                                 continue;
13578
13579                         /* 
13580                          * We handle LDADDR here as well, since it can only be decomposed
13581                          * when variable addresses are known.
13582                          */
13583                         if (ins->opcode == OP_LDADDR) {
13584                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13585
13586                                 if (var->opcode == OP_VTARG_ADDR) {
13587                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13588                                         MonoInst *vtaddr = var->inst_left;
13589                                         if (vtaddr->opcode == OP_REGVAR) {
13590                                                 ins->opcode = OP_MOVE;
13591                                                 ins->sreg1 = vtaddr->dreg;
13592                                         }
13593                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13594                                                 ins->opcode = OP_LOAD_MEMBASE;
13595                                                 ins->inst_basereg = vtaddr->inst_basereg;
13596                                                 ins->inst_offset = vtaddr->inst_offset;
13597                                         } else
13598                                                 NOT_IMPLEMENTED;
13599                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13600                                         /* gsharedvt arg passed by ref */
13601                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13602
13603                                         ins->opcode = OP_LOAD_MEMBASE;
13604                                         ins->inst_basereg = var->inst_basereg;
13605                                         ins->inst_offset = var->inst_offset;
13606                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13607                                         MonoInst *load, *load2, *load3;
13608                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13609                                         int reg1, reg2, reg3;
13610                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13611                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13612
13613                                         /*
13614                                          * gsharedvt local.
13615                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13616                                          */
13617
13618                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13619
13620                                         g_assert (info_var);
13621                                         g_assert (locals_var);
13622
13623                                         /* Mark the instruction used to compute the locals var as used */
13624                                         cfg->gsharedvt_locals_var_ins = NULL;
13625
13626                                         /* Load the offset */
13627                                         if (info_var->opcode == OP_REGOFFSET) {
13628                                                 reg1 = alloc_ireg (cfg);
13629                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13630                                         } else if (info_var->opcode == OP_REGVAR) {
13631                                                 load = NULL;
13632                                                 reg1 = info_var->dreg;
13633                                         } else {
13634                                                 g_assert_not_reached ();
13635                                         }
13636                                         reg2 = alloc_ireg (cfg);
13637                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13638                                         /* Load the locals area address */
13639                                         reg3 = alloc_ireg (cfg);
13640                                         if (locals_var->opcode == OP_REGOFFSET) {
13641                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13642                                         } else if (locals_var->opcode == OP_REGVAR) {
13643                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13644                                         } else {
13645                                                 g_assert_not_reached ();
13646                                         }
13647                                         /* Compute the address */
13648                                         ins->opcode = OP_PADD;
13649                                         ins->sreg1 = reg3;
13650                                         ins->sreg2 = reg2;
13651
13652                                         mono_bblock_insert_before_ins (bb, ins, load3);
13653                                         mono_bblock_insert_before_ins (bb, load3, load2);
13654                                         if (load)
13655                                                 mono_bblock_insert_before_ins (bb, load2, load);
13656                                 } else {
13657                                         g_assert (var->opcode == OP_REGOFFSET);
13658
13659                                         ins->opcode = OP_ADD_IMM;
13660                                         ins->sreg1 = var->inst_basereg;
13661                                         ins->inst_imm = var->inst_offset;
13662                                 }
13663
13664                                 *need_local_opts = TRUE;
13665                                 spec = INS_INFO (ins->opcode);
13666                         }
13667
13668                         if (ins->opcode < MONO_CEE_LAST) {
13669                                 mono_print_ins (ins);
13670                                 g_assert_not_reached ();
13671                         }
13672
13673                         /*
13674                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13675                          * src register.
13676                          * FIXME:
13677                          */
13678                         if (MONO_IS_STORE_MEMBASE (ins)) {
13679                                 tmp_reg = ins->dreg;
13680                                 ins->dreg = ins->sreg2;
13681                                 ins->sreg2 = tmp_reg;
13682                                 store = TRUE;
13683
13684                                 spec2 [MONO_INST_DEST] = ' ';
13685                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13686                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13687                                 spec2 [MONO_INST_SRC3] = ' ';
13688                                 spec = spec2;
13689                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13690                                 g_assert_not_reached ();
13691                         else
13692                                 store = FALSE;
13693                         no_lvreg = FALSE;
13694
13695                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13696                                 printf ("\t %.3s %d", spec, ins->dreg);
13697                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13698                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13699                                         printf (" %d", sregs [srcindex]);
13700                                 printf ("\n");
13701                         }
13702
13703                         /***************/
13704                         /*    DREG     */
13705                         /***************/
13706                         regtype = spec [MONO_INST_DEST];
13707                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13708                         prev_dreg = -1;
13709
13710                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13711                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13712                                 MonoInst *store_ins;
13713                                 int store_opcode;
13714                                 MonoInst *def_ins = ins;
13715                                 int dreg = ins->dreg; /* The original vreg */
13716
13717                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13718
13719                                 if (var->opcode == OP_REGVAR) {
13720                                         ins->dreg = var->dreg;
13721                                 } 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)) {
13722                                         /* 
13723                                          * Instead of emitting a load+store, use a _membase opcode.
13724                                          */
13725                                         g_assert (var->opcode == OP_REGOFFSET);
13726                                         if (ins->opcode == OP_MOVE) {
13727                                                 NULLIFY_INS (ins);
13728                                                 def_ins = NULL;
13729                                         } else {
13730                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13731                                                 ins->inst_basereg = var->inst_basereg;
13732                                                 ins->inst_offset = var->inst_offset;
13733                                                 ins->dreg = -1;
13734                                         }
13735                                         spec = INS_INFO (ins->opcode);
13736                                 } else {
13737                                         guint32 lvreg;
13738
13739                                         g_assert (var->opcode == OP_REGOFFSET);
13740
13741                                         prev_dreg = ins->dreg;
13742
13743                                         /* Invalidate any previous lvreg for this vreg */
13744                                         vreg_to_lvreg [ins->dreg] = 0;
13745
13746                                         lvreg = 0;
13747
13748                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
13749                                                 regtype = 'l';
13750                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
13751                                         }
13752
13753                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
13754
13755 #if SIZEOF_REGISTER != 8
13756                                         if (regtype == 'l') {
13757                                                 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));
13758                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13759                                                 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));
13760                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13761                                                 def_ins = store_ins;
13762                                         }
13763                                         else
13764 #endif
13765                                         {
13766                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
13767
13768                                                 /* Try to fuse the store into the instruction itself */
13769                                                 /* FIXME: Add more instructions */
13770                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
13771                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
13772                                                         ins->inst_imm = ins->inst_c0;
13773                                                         ins->inst_destbasereg = var->inst_basereg;
13774                                                         ins->inst_offset = var->inst_offset;
13775                                                         spec = INS_INFO (ins->opcode);
13776                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
13777                                                         ins->opcode = store_opcode;
13778                                                         ins->inst_destbasereg = var->inst_basereg;
13779                                                         ins->inst_offset = var->inst_offset;
13780
13781                                                         no_lvreg = TRUE;
13782
13783                                                         tmp_reg = ins->dreg;
13784                                                         ins->dreg = ins->sreg2;
13785                                                         ins->sreg2 = tmp_reg;
13786                                                         store = TRUE;
13787
13788                                                         spec2 [MONO_INST_DEST] = ' ';
13789                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13790                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13791                                                         spec2 [MONO_INST_SRC3] = ' ';
13792                                                         spec = spec2;
13793                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
13794                                                         // FIXME: The backends expect the base reg to be in inst_basereg
13795                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
13796                                                         ins->dreg = -1;
13797                                                         ins->inst_basereg = var->inst_basereg;
13798                                                         ins->inst_offset = var->inst_offset;
13799                                                         spec = INS_INFO (ins->opcode);
13800                                                 } else {
13801                                                         /* printf ("INS: "); mono_print_ins (ins); */
13802                                                         /* Create a store instruction */
13803                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
13804
13805                                                         /* Insert it after the instruction */
13806                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
13807
13808                                                         def_ins = store_ins;
13809
13810                                                         /* 
13811                                                          * We can't assign ins->dreg to var->dreg here, since the
13812                                                          * sregs could use it. So set a flag, and do it after
13813                                                          * the sregs.
13814                                                          */
13815                                                         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)))
13816                                                                 dest_has_lvreg = TRUE;
13817                                                 }
13818                                         }
13819                                 }
13820
13821                                 if (def_ins && !live_range_start [dreg]) {
13822                                         live_range_start [dreg] = def_ins;
13823                                         live_range_start_bb [dreg] = bb;
13824                                 }
13825
13826                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
13827                                         MonoInst *tmp;
13828
13829                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
13830                                         tmp->inst_c1 = dreg;
13831                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
13832                                 }
13833                         }
13834
13835                         /************/
13836                         /*  SREGS   */
13837                         /************/
13838                         num_sregs = mono_inst_get_src_registers (ins, sregs);
13839                         for (srcindex = 0; srcindex < 3; ++srcindex) {
13840                                 regtype = spec [MONO_INST_SRC1 + srcindex];
13841                                 sreg = sregs [srcindex];
13842
13843                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
13844                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
13845                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
13846                                         MonoInst *use_ins = ins;
13847                                         MonoInst *load_ins;
13848                                         guint32 load_opcode;
13849
13850                                         if (var->opcode == OP_REGVAR) {
13851                                                 sregs [srcindex] = var->dreg;
13852                                                 //mono_inst_set_src_registers (ins, sregs);
13853                                                 live_range_end [sreg] = use_ins;
13854                                                 live_range_end_bb [sreg] = bb;
13855
13856                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13857                                                         MonoInst *tmp;
13858
13859                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13860                                                         /* var->dreg is a hreg */
13861                                                         tmp->inst_c1 = sreg;
13862                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
13863                                                 }
13864
13865                                                 continue;
13866                                         }
13867
13868                                         g_assert (var->opcode == OP_REGOFFSET);
13869                                                 
13870                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
13871
13872                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
13873
13874                                         if (vreg_to_lvreg [sreg]) {
13875                                                 g_assert (vreg_to_lvreg [sreg] != -1);
13876
13877                                                 /* The variable is already loaded to an lvreg */
13878                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13879                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
13880                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
13881                                                 //mono_inst_set_src_registers (ins, sregs);
13882                                                 continue;
13883                                         }
13884
13885                                         /* Try to fuse the load into the instruction */
13886                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
13887                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
13888                                                 sregs [0] = var->inst_basereg;
13889                                                 //mono_inst_set_src_registers (ins, sregs);
13890                                                 ins->inst_offset = var->inst_offset;
13891                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
13892                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
13893                                                 sregs [1] = var->inst_basereg;
13894                                                 //mono_inst_set_src_registers (ins, sregs);
13895                                                 ins->inst_offset = var->inst_offset;
13896                                         } else {
13897                                                 if (MONO_IS_REAL_MOVE (ins)) {
13898                                                         ins->opcode = OP_NOP;
13899                                                         sreg = ins->dreg;
13900                                                 } else {
13901                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
13902
13903                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
13904
13905                                                         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) {
13906                                                                 if (var->dreg == prev_dreg) {
13907                                                                         /*
13908                                                                          * sreg refers to the value loaded by the load
13909                                                                          * emitted below, but we need to use ins->dreg
13910                                                                          * since it refers to the store emitted earlier.
13911                                                                          */
13912                                                                         sreg = ins->dreg;
13913                                                                 }
13914                                                                 g_assert (sreg != -1);
13915                                                                 vreg_to_lvreg [var->dreg] = sreg;
13916                                                                 if (lvregs_len >= lvregs_size) {
13917                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13918                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13919                                                                         lvregs = new_lvregs;
13920                                                                         lvregs_size *= 2;
13921                                                                 }
13922                                                                 lvregs [lvregs_len ++] = var->dreg;
13923                                                         }
13924                                                 }
13925
13926                                                 sregs [srcindex] = sreg;
13927                                                 //mono_inst_set_src_registers (ins, sregs);
13928
13929 #if SIZEOF_REGISTER != 8
13930                                                 if (regtype == 'l') {
13931                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
13932                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13933                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
13934                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13935                                                         use_ins = load_ins;
13936                                                 }
13937                                                 else
13938 #endif
13939                                                 {
13940 #if SIZEOF_REGISTER == 4
13941                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
13942 #endif
13943                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
13944                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
13945                                                         use_ins = load_ins;
13946                                                 }
13947                                         }
13948
13949                                         if (var->dreg < orig_next_vreg) {
13950                                                 live_range_end [var->dreg] = use_ins;
13951                                                 live_range_end_bb [var->dreg] = bb;
13952                                         }
13953
13954                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13955                                                 MonoInst *tmp;
13956
13957                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13958                                                 tmp->inst_c1 = var->dreg;
13959                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
13960                                         }
13961                                 }
13962                         }
13963                         mono_inst_set_src_registers (ins, sregs);
13964
13965                         if (dest_has_lvreg) {
13966                                 g_assert (ins->dreg != -1);
13967                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
13968                                 if (lvregs_len >= lvregs_size) {
13969                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
13970                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
13971                                         lvregs = new_lvregs;
13972                                         lvregs_size *= 2;
13973                                 }
13974                                 lvregs [lvregs_len ++] = prev_dreg;
13975                                 dest_has_lvreg = FALSE;
13976                         }
13977
13978                         if (store) {
13979                                 tmp_reg = ins->dreg;
13980                                 ins->dreg = ins->sreg2;
13981                                 ins->sreg2 = tmp_reg;
13982                         }
13983
13984                         if (MONO_IS_CALL (ins)) {
13985                                 /* Clear vreg_to_lvreg array */
13986                                 for (i = 0; i < lvregs_len; i++)
13987                                         vreg_to_lvreg [lvregs [i]] = 0;
13988                                 lvregs_len = 0;
13989                         } else if (ins->opcode == OP_NOP) {
13990                                 ins->dreg = -1;
13991                                 MONO_INST_NULLIFY_SREGS (ins);
13992                         }
13993
13994                         if (cfg->verbose_level > 2)
13995                                 mono_print_ins_index (1, ins);
13996                 }
13997
13998                 /* Extend the live range based on the liveness info */
13999                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14000                         for (i = 0; i < cfg->num_varinfo; i ++) {
14001                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14002
14003                                 if (vreg_is_volatile (cfg, vi->vreg))
14004                                         /* The liveness info is incomplete */
14005                                         continue;
14006
14007                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14008                                         /* Live from at least the first ins of this bb */
14009                                         live_range_start [vi->vreg] = bb->code;
14010                                         live_range_start_bb [vi->vreg] = bb;
14011                                 }
14012
14013                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14014                                         /* Live at least until the last ins of this bb */
14015                                         live_range_end [vi->vreg] = bb->last_ins;
14016                                         live_range_end_bb [vi->vreg] = bb;
14017                                 }
14018                         }
14019                 }
14020         }
14021         
14022         /*
14023          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14024          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14025          */
14026         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14027                 for (i = 0; i < cfg->num_varinfo; ++i) {
14028                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14029                         MonoInst *ins;
14030
14031                         if (live_range_start [vreg]) {
14032                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14033                                 ins->inst_c0 = i;
14034                                 ins->inst_c1 = vreg;
14035                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14036                         }
14037                         if (live_range_end [vreg]) {
14038                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14039                                 ins->inst_c0 = i;
14040                                 ins->inst_c1 = vreg;
14041                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14042                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14043                                 else
14044                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14045                         }
14046                 }
14047         }
14048
14049         if (cfg->gsharedvt_locals_var_ins) {
14050                 /* Nullify if unused */
14051                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14052                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14053         }
14054
14055         g_free (live_range_start);
14056         g_free (live_range_end);
14057         g_free (live_range_start_bb);
14058         g_free (live_range_end_bb);
14059 }
14060
14061
14062 /**
14063  * FIXME:
14064  * - use 'iadd' instead of 'int_add'
14065  * - handling ovf opcodes: decompose in method_to_ir.
14066  * - unify iregs/fregs
14067  *   -> partly done, the missing parts are:
14068  *   - a more complete unification would involve unifying the hregs as well, so
14069  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14070  *     would no longer map to the machine hregs, so the code generators would need to
14071  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14072  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14073  *     fp/non-fp branches speeds it up by about 15%.
14074  * - use sext/zext opcodes instead of shifts
14075  * - add OP_ICALL
14076  * - get rid of TEMPLOADs if possible and use vregs instead
14077  * - clean up usage of OP_P/OP_ opcodes
14078  * - cleanup usage of DUMMY_USE
14079  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14080  *   stack
14081  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14082  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14083  * - make sure handle_stack_args () is called before the branch is emitted
14084  * - when the new IR is done, get rid of all unused stuff
14085  * - COMPARE/BEQ as separate instructions or unify them ?
14086  *   - keeping them separate allows specialized compare instructions like
14087  *     compare_imm, compare_membase
14088  *   - most back ends unify fp compare+branch, fp compare+ceq
14089  * - integrate mono_save_args into inline_method
14090  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14091  * - handle long shift opts on 32 bit platforms somehow: they require 
14092  *   3 sregs (2 for arg1 and 1 for arg2)
14093  * - make byref a 'normal' type.
14094  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14095  *   variable if needed.
14096  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14097  *   like inline_method.
14098  * - remove inlining restrictions
14099  * - fix LNEG and enable cfold of INEG
14100  * - generalize x86 optimizations like ldelema as a peephole optimization
14101  * - add store_mem_imm for amd64
14102  * - optimize the loading of the interruption flag in the managed->native wrappers
14103  * - avoid special handling of OP_NOP in passes
14104  * - move code inserting instructions into one function/macro.
14105  * - try a coalescing phase after liveness analysis
14106  * - add float -> vreg conversion + local optimizations on !x86
14107  * - figure out how to handle decomposed branches during optimizations, ie.
14108  *   compare+branch, op_jump_table+op_br etc.
14109  * - promote RuntimeXHandles to vregs
14110  * - vtype cleanups:
14111  *   - add a NEW_VARLOADA_VREG macro
14112  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14113  *   accessing vtype fields.
14114  * - get rid of I8CONST on 64 bit platforms
14115  * - dealing with the increase in code size due to branches created during opcode
14116  *   decomposition:
14117  *   - use extended basic blocks
14118  *     - all parts of the JIT
14119  *     - handle_global_vregs () && local regalloc
14120  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14121  * - sources of increase in code size:
14122  *   - vtypes
14123  *   - long compares
14124  *   - isinst and castclass
14125  *   - lvregs not allocated to global registers even if used multiple times
14126  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14127  *   meaningful.
14128  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14129  * - add all micro optimizations from the old JIT
14130  * - put tree optimizations into the deadce pass
14131  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14132  *   specific function.
14133  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14134  *   fcompare + branchCC.
14135  * - create a helper function for allocating a stack slot, taking into account 
14136  *   MONO_CFG_HAS_SPILLUP.
14137  * - merge r68207.
14138  * - optimize mono_regstate2_alloc_int/float.
14139  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14140  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14141  *   parts of the tree could be separated by other instructions, killing the tree
14142  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14143  *   instructions if the result of the load is used multiple times ?
14144  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14145  * - LAST MERGE: 108395.
14146  * - when returning vtypes in registers, generate IR and append it to the end of the
14147  *   last bb instead of doing it in the epilog.
14148  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14149  */
14150
14151 /*
14152
14153 NOTES
14154 -----
14155
14156 - When to decompose opcodes:
14157   - earlier: this makes some optimizations hard to implement, since the low level IR
14158   no longer contains the neccessary information. But it is easier to do.
14159   - later: harder to implement, enables more optimizations.
14160 - Branches inside bblocks:
14161   - created when decomposing complex opcodes. 
14162     - branches to another bblock: harmless, but not tracked by the branch 
14163       optimizations, so need to branch to a label at the start of the bblock.
14164     - branches to inside the same bblock: very problematic, trips up the local
14165       reg allocator. Can be fixed by spitting the current bblock, but that is a
14166       complex operation, since some local vregs can become global vregs etc.
14167 - Local/global vregs:
14168   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14169     local register allocator.
14170   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14171     structure, created by mono_create_var (). Assigned to hregs or the stack by
14172     the global register allocator.
14173 - When to do optimizations like alu->alu_imm:
14174   - earlier -> saves work later on since the IR will be smaller/simpler
14175   - later -> can work on more instructions
14176 - Handling of valuetypes:
14177   - When a vtype is pushed on the stack, a new temporary is created, an 
14178     instruction computing its address (LDADDR) is emitted and pushed on
14179     the stack. Need to optimize cases when the vtype is used immediately as in
14180     argument passing, stloc etc.
14181 - Instead of the to_end stuff in the old JIT, simply call the function handling
14182   the values on the stack before emitting the last instruction of the bb.
14183 */
14184
14185 #else /* !DISABLE_JIT */
14186
14187 void
14188 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
14189 {
14190 }
14191
14192 #endif /* !DISABLE_JIT */