Merge pull request #2431 from alexanderkyte/tests_with_excludes
[mono.git] / mono / mini / mini-trampolines.c
1 /*
2  * (C) 2003 Ximian, Inc.
3  * (C) 2003-2011 Novell, Inc.
4  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
5  */
6 #include <config.h>
7 #include <glib.h>
8
9 #include <mono/metadata/appdomain.h>
10 #include <mono/metadata/metadata-internals.h>
11 #include <mono/metadata/marshal.h>
12 #include <mono/metadata/tabledefs.h>
13 #include <mono/utils/mono-counters.h>
14 #include <mono/utils/mono-error-internals.h>
15 #include <mono/utils/mono-membar.h>
16 #include <mono/utils/mono-compiler.h>
17
18 #include "mini.h"
19
20 /*
21  * Address of the trampoline code.  This is used by the debugger to check
22  * whether a method is a trampoline.
23  */
24 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
25
26 static GHashTable *rgctx_lazy_fetch_trampoline_hash;
27 static GHashTable *rgctx_lazy_fetch_trampoline_hash_addr;
28 static guint32 trampoline_calls, jit_trampolines, unbox_trampolines, static_rgctx_trampolines;
29
30 #define mono_trampolines_lock() mono_os_mutex_lock (&trampolines_mutex)
31 #define mono_trampolines_unlock() mono_os_mutex_unlock (&trampolines_mutex)
32 static mono_mutex_t trampolines_mutex;
33
34 #ifdef MONO_ARCH_GSHARED_SUPPORTED
35
36 typedef struct {
37         MonoMethod *m;
38         gpointer addr;
39 } RgctxTrampInfo;
40
41 static gint
42 rgctx_tramp_info_equal (gconstpointer ka, gconstpointer kb)
43 {
44         const RgctxTrampInfo *i1 = (const RgctxTrampInfo *)ka;
45         const RgctxTrampInfo *i2 = (const RgctxTrampInfo *)kb;
46
47         if (i1->m == i2->m && i1->addr == i2->addr)
48                 return 1;
49         else
50                 return 0;
51 }
52
53 static guint
54 rgctx_tramp_info_hash (gconstpointer data)
55 {
56         const RgctxTrampInfo *info = (const RgctxTrampInfo *)data;
57
58         return GPOINTER_TO_UINT (info->m) ^ GPOINTER_TO_UINT (info->addr);
59 }
60
61 /**
62  * mono_create_static_rgctx_trampoline:
63  * @m: the mono method to create a trampoline for
64  * @addr: the address to jump to (where the compiled code for M lives)
65  *
66  * Creates a static rgctx trampoline for M which branches to ADDR which should
67  * point to the compiled code of M.
68  *
69  * Static rgctx trampolines are used when a shared generic method which doesn't
70  * have a this argument is called indirectly, ie. from code which can't pass in
71  * the rgctx argument. The trampoline sets the rgctx argument and jumps to the
72  * methods code. These trampolines are similar to the unbox trampolines, they
73  * perform the same task as the static rgctx wrappers, but they are smaller/faster,
74  * and can be made to work with full AOT.
75  *
76  * On PPC addr should be an ftnptr and the return value is an ftnptr too.
77  *
78  * Returns the generated static rgctx trampoline.
79  */
80 gpointer
81 mono_create_static_rgctx_trampoline (MonoMethod *m, gpointer addr)
82 {
83         gpointer ctx;
84         gpointer res;
85         MonoDomain *domain;
86         RgctxTrampInfo tmp_info;
87         RgctxTrampInfo *info;
88
89 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
90         g_assert (((gpointer*)addr) [2] == 0);
91 #endif
92
93         ctx = mini_method_get_rgctx (m);
94
95         domain = mono_domain_get ();
96
97         /* 
98          * In the AOT case, addr might point to either the method, or to an unbox trampoline,
99          * so make the hash keyed on the m+addr pair.
100          */
101         mono_domain_lock (domain);
102         if (!domain_jit_info (domain)->static_rgctx_trampoline_hash)
103                 domain_jit_info (domain)->static_rgctx_trampoline_hash = g_hash_table_new (rgctx_tramp_info_hash, rgctx_tramp_info_equal);
104         tmp_info.m = m;
105         tmp_info.addr = addr;
106         res = g_hash_table_lookup (domain_jit_info (domain)->static_rgctx_trampoline_hash,
107                                                            &tmp_info);
108         mono_domain_unlock (domain);
109         if (res)
110                 return res;
111
112         if (mono_aot_only)
113                 res = mono_aot_get_static_rgctx_trampoline (ctx, addr);
114         else
115                 res = mono_arch_get_static_rgctx_trampoline (m, (MonoMethodRuntimeGenericContext *)ctx, addr);
116
117         mono_domain_lock (domain);
118         /* Duplicates inserted while we didn't hold the lock are OK */
119         info = (RgctxTrampInfo *)mono_domain_alloc (domain, sizeof (RgctxTrampInfo));
120         info->m = m;
121         info->addr = addr;
122         g_hash_table_insert (domain_jit_info (domain)->static_rgctx_trampoline_hash, info, res);
123         mono_domain_unlock (domain);
124
125         static_rgctx_trampolines ++;
126
127         return res;
128 }
129 #else
130 gpointer
131 mono_create_static_rgctx_trampoline (MonoMethod *m, gpointer addr)
132 {
133        /* 
134         * This shouldn't happen as all arches which support generic sharing support
135         * static rgctx trampolines as well.
136         */
137        g_assert_not_reached ();
138 }
139 #endif
140
141 #if 0
142 #define DEBUG_IMT(stmt) do { stmt; } while (0)
143 #else
144 #define DEBUG_IMT(stmt) do { } while (0)
145 #endif
146
147 /*
148  * mini_resolve_imt_method:
149  *
150  *   Resolve the actual method called when making an IMT call through VTABLE_SLOT with IMT_METHOD as the interface method.
151  *
152  * Either IMPL_METHOD or OUT_AOT_ADDR will be set on return.
153  */
154 gpointer*
155 mini_resolve_imt_method (MonoVTable *vt, gpointer *vtable_slot, MonoMethod *imt_method, MonoMethod **impl_method, gpointer *out_aot_addr, gboolean *out_need_rgctx_tramp, MonoMethod **variant_iface)
156 {
157         MonoMethod *impl = NULL, *generic_virtual = NULL;
158         gboolean lookup_aot, variance_used = FALSE, need_rgctx_tramp = FALSE;
159         gpointer addr;
160         guint8 *aot_addr = NULL;
161         int displacement = vtable_slot - ((gpointer*)vt);
162         int interface_offset;
163         int imt_slot = MONO_IMT_SIZE + displacement;
164
165         g_assert (imt_slot < MONO_IMT_SIZE);
166
167         /* This has to be variance aware since imt_method can be from an interface that vt->klass doesn't directly implement */
168         interface_offset = mono_class_interface_offset_with_variance (vt->klass, imt_method->klass, &variance_used);
169         if (interface_offset < 0)
170                 g_error ("%s doesn't implement interface %s\n", mono_type_get_name_full (&vt->klass->byval_arg, MONO_TYPE_NAME_FORMAT_IL), mono_type_get_name_full (&imt_method->klass->byval_arg, MONO_TYPE_NAME_FORMAT_IL));
171
172         *variant_iface = NULL;
173         if (imt_method->is_inflated && ((MonoMethodInflated*)imt_method)->context.method_inst) {
174                 /* Generic virtual method */
175                 generic_virtual = imt_method;
176                 need_rgctx_tramp = TRUE;
177         } else if (variance_used && mono_class_has_variant_generic_params (imt_method->klass)) {
178                 *variant_iface = imt_method;
179         }
180
181         addr = NULL;
182         /* We can only use the AOT compiled code if we don't require further processing */
183         lookup_aot = !generic_virtual & !variant_iface;
184
185         if (!mono_llvm_only)
186                 mono_vtable_build_imt_slot (vt, mono_method_get_imt_slot (imt_method));
187
188         if (imt_method->is_inflated && ((MonoMethodInflated*)imt_method)->context.method_inst) {
189                 MonoError error;
190                 MonoGenericContext context = { NULL, NULL };
191
192                 /*
193                  * Generic virtual method, imt_method contains the inflated interface
194                  * method, need to get the inflated impl method.
195                  */
196                 /* imt_method->slot might not be set */
197                 impl = mono_class_get_vtable_entry (vt->klass, interface_offset + mono_method_get_declaring_generic_method (imt_method)->slot);
198
199                 if (impl->klass->generic_class)
200                         context.class_inst = impl->klass->generic_class->context.class_inst;
201                 context.method_inst = ((MonoMethodInflated*)imt_method)->context.method_inst;
202                 impl = mono_class_inflate_generic_method_checked (impl, &context, &error);
203                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
204         } else {
205                 /* Avoid loading metadata or creating a generic vtable if possible */
206                 if (lookup_aot && !vt->klass->valuetype)
207                         aot_addr = (guint8 *)mono_aot_get_method_from_vt_slot (mono_domain_get (), vt, interface_offset + mono_method_get_vtable_slot (imt_method));
208                 else
209                         aot_addr = NULL;
210                 if (aot_addr)
211                         impl = NULL;
212                 else
213                         impl = mono_class_get_vtable_entry (vt->klass, interface_offset + mono_method_get_vtable_slot (imt_method));
214         }
215
216         if (impl && mono_method_needs_static_rgctx_invoke (impl, FALSE))
217                 need_rgctx_tramp = TRUE;
218         if (impl && impl->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
219                 WrapperInfo *info = mono_marshal_get_wrapper_info (impl);
220
221                 if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER)
222                         need_rgctx_tramp = TRUE;
223         }
224         *impl_method = impl;
225         *out_need_rgctx_tramp = need_rgctx_tramp;
226         *out_aot_addr = aot_addr;
227
228         DEBUG_IMT (printf ("mono_convert_imt_slot_to_vtable_slot: method = %s.%s.%s, imt_method = %s.%s.%s\n",
229                                            method->klass->name_space, method->klass->name, method->name,
230                                            imt_method->klass->name_space, imt_method->klass->name, imt_method->name));
231
232         if (vt->imt_collisions_bitmap & (1 << imt_slot)) {
233                 int slot = mono_method_get_vtable_index (imt_method);
234                 int vtable_offset;
235
236                 g_assert (slot != -1);
237                 vtable_offset = interface_offset + slot;
238                 vtable_slot = & (vt->vtable [vtable_offset]);
239                 DEBUG_IMT (printf ("mono_convert_imt_slot_to_vtable_slot: slot %p[%d] is in the IMT, and colliding becomes %p[%d] (interface_offset = %d, method->slot = %d)\n", slot, imt_slot, vtable_slot, vtable_offset, interface_offset, imt_method->slot));
240                 return vtable_slot;
241         } else {
242                 DEBUG_IMT (printf ("mono_convert_imt_slot_to_vtable_slot: slot %p[%d] is in the IMT, but not colliding\n", slot, imt_slot));
243                 return vtable_slot;
244         }
245 }
246
247 /*
248  * This is a super-ugly hack to fix bug #616463.
249  *
250  * The problem is that we don't always set is_generic for generic
251  * method definitions.  See the comment at the end of
252  * mono_class_inflate_generic_method_full_checked() in class.c.
253  */
254 static gboolean
255 is_generic_method_definition (MonoMethod *m)
256 {
257         MonoGenericContext *context;
258         if (m->is_generic)
259                 return TRUE;
260         if (!m->is_inflated)
261                 return FALSE;
262
263         context = mono_method_get_context (m);
264         if (!context->method_inst)
265                 return FALSE;
266         if (context->method_inst == mono_method_get_generic_container (((MonoMethodInflated*)m)->declaring)->context.method_inst)
267                 return TRUE;
268         return FALSE;
269 }
270
271 gboolean
272 mini_jit_info_is_gsharedvt (MonoJitInfo *ji)
273 {
274         if (ji && ji->has_generic_jit_info && (mono_jit_info_get_generic_sharing_context (ji)->is_gsharedvt))
275                 return TRUE;
276         else
277                 return FALSE;
278 }
279
280 /**
281  * mini_add_method_trampoline:
282  * @m: 
283  * @compiled_method:
284  * @add_static_rgctx_tramp: adds a static rgctx trampoline
285  * @add_unbox_tramp: adds an unboxing trampoline
286  *
287  * Add static rgctx/gsharedvt_in/unbox trampolines to
288  * M/COMPILED_METHOD if needed.
289  *
290  * Returns the trampoline address, or COMPILED_METHOD if no trampoline
291  * is needed.
292  */
293 gpointer
294 mini_add_method_trampoline (MonoMethod *m, gpointer compiled_method, gboolean add_static_rgctx_tramp, gboolean add_unbox_tramp)
295 {
296         gpointer addr = compiled_method;
297         gboolean callee_gsharedvt, callee_array_helper;
298         MonoMethod *jmethod = NULL;
299         MonoJitInfo *ji;
300
301         // FIXME: This loads information from AOT (perf problem)
302         ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
303         callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
304
305         callee_array_helper = FALSE;
306         if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
307                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
308
309                 /*
310                  * generic array helpers.
311                  * Have to replace the wrappers with the original generic instances.
312                  */
313                 if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
314                         callee_array_helper = TRUE;
315                         m = info->d.generic_array_helper.method;
316                 }
317         } else if (m->wrapper_type == MONO_WRAPPER_UNKNOWN) {
318                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
319
320                 /* Same for synchronized inner wrappers */
321                 if (info && info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
322                         m = info->d.synchronized_inner.method;
323                 }
324         }
325
326         if (callee_gsharedvt)
327                 g_assert (m->is_inflated);
328
329         addr = compiled_method;
330
331         if (add_unbox_tramp) {
332                 /*
333                  * The unbox trampolines call the method directly, so need to add
334                  * an rgctx tramp before them.
335                  */
336                 if (mono_aot_only) {
337                         addr = mono_aot_get_unbox_trampoline (m);
338                 } else {
339                         unbox_trampolines ++;
340                         addr = mono_arch_get_unbox_trampoline (m, addr);
341                 }
342         }
343
344         if (ji && !ji->is_trampoline)
345                 jmethod = jinfo_get_method (ji);
346         if (callee_gsharedvt && mini_is_gsharedvt_variable_signature (mono_method_signature (jmethod))) {
347                 MonoMethodSignature *sig, *gsig;
348
349                 /* Here m is a generic instance, while ji->method is the gsharedvt method implementing it */
350
351                 /* Call from normal/gshared code to gsharedvt code with variable signature */
352                 sig = mono_method_signature (m);
353                 gsig = mono_method_signature (jmethod);
354
355                 addr = mini_get_gsharedvt_wrapper (TRUE, addr, sig, gsig, -1, FALSE);
356
357                 if (mono_llvm_only)
358                         g_assert_not_reached ();
359                 //printf ("IN: %s\n", mono_method_full_name (m, TRUE));
360         }
361
362         if (callee_array_helper) {
363                 add_static_rgctx_tramp = FALSE;
364                 /* FIXME: ji->from_aot is not set for llvm methods */
365                 if (ji && (ji->from_aot || mono_aot_only)) {
366                         /* In AOT mode, compiled_method points to one of the InternalArray methods in Array. */
367                         if (!mono_llvm_only && mono_method_needs_static_rgctx_invoke (jinfo_get_method (ji), TRUE))
368                                 add_static_rgctx_tramp = TRUE;
369                 }
370         }
371
372         if (mono_llvm_only)
373                 add_static_rgctx_tramp = FALSE;
374
375         if (add_static_rgctx_tramp)
376                 addr = mono_create_static_rgctx_trampoline (m, addr);
377
378         return addr;
379 }
380
381 /*
382  * mini_create_llvmonly_ftndesc:
383  *
384  *   Create a function descriptor of the form <addr, arg>, which
385  * represents a callee ADDR with ARG as the last argument.
386  * This is used for:
387  * - generic sharing (ARG is the rgctx)
388  * - gsharedvt signature wrappers (ARG is a function descriptor)
389  */
390 MonoFtnDesc*
391 mini_create_llvmonly_ftndesc (MonoDomain *domain, gpointer addr, gpointer arg)
392 {
393         MonoFtnDesc *ftndesc = (MonoFtnDesc*)mono_domain_alloc0 (mono_domain_get (), 2 * sizeof (gpointer));
394         ftndesc->addr = addr;
395         ftndesc->arg = arg;
396
397         return ftndesc;
398 }
399
400 /**
401  * mini_add_method_wrappers_llvmonly:
402  *
403  *   Add unbox/gsharedvt wrappers around COMPILED_METHOD if needed. Return the wrapper address or COMPILED_METHOD
404  * if no wrapper is needed. Set OUT_ARG to the rgctx/extra argument needed to be passed to the returned method.
405  */
406 gpointer
407 mini_add_method_wrappers_llvmonly (MonoMethod *m, gpointer compiled_method, gboolean caller_gsharedvt, gboolean add_unbox_tramp, gpointer *out_arg)
408 {
409         gpointer addr;
410         gboolean callee_gsharedvt, callee_array_helper;
411         MonoMethod *jmethod = NULL;
412         MonoJitInfo *ji;
413
414         // FIXME: This loads information from AOT (perf problem)
415         ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
416         callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
417
418         callee_array_helper = FALSE;
419         if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
420                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
421
422                 /*
423                  * generic array helpers.
424                  * Have to replace the wrappers with the original generic instances.
425                  */
426                 if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
427                         callee_array_helper = TRUE;
428                         m = info->d.generic_array_helper.method;
429                 }
430         } else if (m->wrapper_type == MONO_WRAPPER_UNKNOWN) {
431                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
432
433                 /* Same for synchronized inner wrappers */
434                 if (info && info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
435                         m = info->d.synchronized_inner.method;
436                 }
437         }
438
439         if (callee_gsharedvt)
440                 g_assert (m->is_inflated);
441
442         addr = compiled_method;
443
444         if (add_unbox_tramp) {
445                 /* 
446                  * The unbox trampolines call the method directly, so need to add
447                  * an rgctx tramp before them.
448                  */
449                 if (mono_aot_only) {
450                         addr = mono_aot_get_unbox_trampoline (m);
451                 } else {
452                         unbox_trampolines ++;
453                         addr = mono_arch_get_unbox_trampoline (m, addr);
454                 }
455         }
456
457         g_assert (mono_llvm_only);
458         g_assert (out_arg);
459
460         if (ji && !ji->is_trampoline)
461                 jmethod = jinfo_get_method (ji);
462
463         if (callee_gsharedvt)
464                 callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jmethod));
465
466         if (!caller_gsharedvt && callee_gsharedvt) {
467                 MonoMethodSignature *sig, *gsig;
468                 gpointer wrapper_addr;
469
470                 /* Here m is a generic instance, while ji->method is the gsharedvt method implementing it */
471
472                 /* Call from normal/gshared code to gsharedvt code with variable signature */
473                 sig = mono_method_signature (m);
474                 gsig = mono_method_signature (jmethod);
475
476                 wrapper_addr = mini_get_gsharedvt_wrapper (TRUE, addr, sig, gsig, -1, FALSE);
477
478                 /*
479                  * This is a gsharedvt in wrapper, it gets passed a ftndesc for the gsharedvt method as an argument.
480                  */
481                 *out_arg = mini_create_llvmonly_ftndesc (mono_domain_get (), addr, mini_method_get_rgctx (m));
482                 addr = wrapper_addr;
483                 //printf ("IN: %s\n", mono_method_full_name (m, TRUE));
484         }
485
486         if (!(*out_arg) && mono_method_needs_static_rgctx_invoke (m, FALSE))
487                 *out_arg = mini_method_get_rgctx (m);
488
489         if (caller_gsharedvt && !callee_gsharedvt) {
490                 /*
491                  * The callee uses the gsharedvt calling convention, have to add an out wrapper.
492                  */
493                 gpointer out_wrapper = mini_get_gsharedvt_wrapper (FALSE, NULL, mono_method_signature (m), NULL, -1, FALSE);
494                 MonoFtnDesc *out_wrapper_arg = mini_create_llvmonly_ftndesc (mono_domain_get (), addr, *out_arg);
495
496                 addr = out_wrapper;
497                 *out_arg = out_wrapper_arg;
498         }
499
500         return addr;
501 }
502
503 /**
504  * common_call_trampoline:
505  *
506  *   The code to handle normal, virtual, and interface method calls and jumps, both
507  * from JITted and LLVM compiled code.
508  */
509 static gpointer
510 common_call_trampoline_inner (mgreg_t *regs, guint8 *code, MonoMethod *m, MonoVTable *vt, gpointer *vtable_slot)
511 {
512         gpointer addr, compiled_method;
513         gboolean generic_shared = FALSE;
514         gboolean need_unbox_tramp = FALSE;
515         gboolean need_rgctx_tramp = FALSE;
516         MonoMethod *declaring = NULL;
517         MonoMethod *generic_virtual = NULL, *variant_iface = NULL;
518         int context_used;
519         gboolean imt_call, virtual_;
520         gpointer *orig_vtable_slot, *vtable_slot_to_patch = NULL;
521         MonoJitInfo *ji = NULL;
522
523         virtual_ = vt && (gpointer)vtable_slot > (gpointer)vt;
524         imt_call = vt && (gpointer)vtable_slot < (gpointer)vt;
525
526         /*
527          * rgctx trampolines are needed when the call is indirect so the caller can't pass
528          * the rgctx argument needed by the callee.
529          */
530         if (virtual_ && m)
531                 need_rgctx_tramp = mono_method_needs_static_rgctx_invoke (m, FALSE);
532
533         orig_vtable_slot = vtable_slot;
534         vtable_slot_to_patch = vtable_slot;
535
536         /* IMT call */
537         if (imt_call) {
538                 MonoMethod *imt_method = NULL, *impl_method = NULL;
539                 MonoObject *this_arg;
540
541                 g_assert (vtable_slot);
542
543                 imt_method = mono_arch_find_imt_method (regs, code);
544                 this_arg = (MonoObject *)mono_arch_get_this_arg_from_call (regs, code);
545
546                 if (mono_object_is_transparent_proxy (this_arg)) {
547                         /* Use the slow path for now */
548                     m = mono_object_get_virtual_method (this_arg, imt_method);
549                         vtable_slot_to_patch = NULL;
550                 } else {
551                         if (imt_method->is_inflated && ((MonoMethodInflated*)imt_method)->context.method_inst) {
552                                 /* Generic virtual method */
553                                 generic_virtual = imt_method;
554                                 need_rgctx_tramp = TRUE;
555                         }
556
557                         vtable_slot = mini_resolve_imt_method (vt, vtable_slot, imt_method, &impl_method, &addr, &need_rgctx_tramp, &variant_iface);
558                         /* This is the vcall slot which gets called through the IMT thunk */
559                         vtable_slot_to_patch = vtable_slot;
560
561                         if (addr) {
562                                 /*
563                                  * We found AOT compiled code for the method, skip the rest.
564                                  */
565                                 if (mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot))
566                                         *vtable_slot = addr;
567
568                                 return mono_create_ftnptr (mono_domain_get (), addr);
569                         }
570
571                         m = impl_method;
572                 }
573         }
574
575         /*
576          * The virtual check is needed because is_generic_method_definition (m) could
577          * return TRUE for methods used in IMT calls too.
578          */
579         if (virtual_ && is_generic_method_definition (m)) {
580                 MonoError error;
581                 MonoGenericContext context = { NULL, NULL };
582                 MonoMethod *declaring;
583
584                 if (m->is_inflated)
585                         declaring = mono_method_get_declaring_generic_method (m);
586                 else
587                         declaring = m;
588
589                 if (m->klass->generic_class)
590                         context.class_inst = m->klass->generic_class->context.class_inst;
591                 else
592                         g_assert (!m->klass->generic_container);
593
594                 generic_virtual = mono_arch_find_imt_method (regs, code);
595                 g_assert (generic_virtual);
596                 g_assert (generic_virtual->is_inflated);
597                 context.method_inst = ((MonoMethodInflated*)generic_virtual)->context.method_inst;
598
599                 m = mono_class_inflate_generic_method_checked (declaring, &context, &error);
600                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
601                 /* FIXME: only do this if the method is sharable */
602                 need_rgctx_tramp = TRUE;
603         } else if ((context_used = mono_method_check_context_used (m))) {
604                 MonoClass *klass = NULL;
605                 MonoMethod *actual_method = NULL;
606                 MonoVTable *vt = NULL;
607                 MonoGenericInst *method_inst = NULL;
608
609                 vtable_slot = NULL;
610                 generic_shared = TRUE;
611
612                 g_assert (code);
613
614                 /*
615                  * The caller is gshared code, compute the actual method to call from M and this/rgctx.
616                  */
617                 if (m->is_inflated && mono_method_get_context (m)->method_inst) {
618                         MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext*)mono_arch_find_static_call_vtable (regs, code);
619
620                         klass = mrgctx->class_vtable->klass;
621                         method_inst = mrgctx->method_inst;
622                 } else if ((m->flags & METHOD_ATTRIBUTE_STATIC) || m->klass->valuetype) {
623                         MonoVTable *vtable = mono_arch_find_static_call_vtable (regs, code);
624
625                         klass = vtable->klass;
626                 } else {
627                         MonoObject *this_argument = (MonoObject *)mono_arch_get_this_arg_from_call (regs, code);
628
629                         vt = this_argument->vtable;
630                         vtable_slot = orig_vtable_slot;
631
632                         g_assert (this_argument->vtable->klass->inited);
633
634                         if (!vtable_slot) {
635                                 mono_class_setup_supertypes (this_argument->vtable->klass);
636                                 klass = this_argument->vtable->klass->supertypes [m->klass->idepth - 1];
637                         }
638                 }
639
640                 g_assert (vtable_slot || klass);
641
642                 if (vtable_slot) {
643                         int displacement = vtable_slot - ((gpointer*)vt);
644
645                         g_assert_not_reached ();
646
647                         g_assert (displacement > 0);
648
649                         actual_method = vt->klass->vtable [displacement];
650                 }
651
652                 if (method_inst || m->wrapper_type) {
653                         MonoError error;
654                         MonoGenericContext context = { NULL, NULL };
655
656                         if (m->is_inflated)
657                                 declaring = mono_method_get_declaring_generic_method (m);
658                         else
659                                 declaring = m;
660
661                         if (klass->generic_class)
662                                 context.class_inst = klass->generic_class->context.class_inst;
663                         else if (klass->generic_container)
664                                 context.class_inst = klass->generic_container->context.class_inst;
665                         context.method_inst = method_inst;
666
667                         actual_method = mono_class_inflate_generic_method_checked (declaring, &context, &error);
668                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
669                 } else {
670                         actual_method = mono_class_get_method_generic (klass, m);
671                 }
672
673                 g_assert (klass);
674                 g_assert (actual_method);
675                 g_assert (actual_method->klass == klass);
676
677                 if (actual_method->is_inflated)
678                         declaring = mono_method_get_declaring_generic_method (actual_method);
679                 else
680                         declaring = NULL;
681
682                 m = actual_method;
683         }
684
685         if (m->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
686                 m = mono_marshal_get_synchronized_wrapper (m);
687                 need_rgctx_tramp = FALSE;
688         }
689
690         /* Calls made through delegates on platforms without delegate trampolines */
691         if (!code && mono_method_needs_static_rgctx_invoke (m, FALSE))
692                 need_rgctx_tramp = TRUE;
693
694         addr = compiled_method = mono_compile_method (m);
695         g_assert (addr);
696
697         if (generic_virtual || variant_iface) {
698                 if (vt->klass->valuetype) /*FIXME is this required variant iface?*/
699                         need_unbox_tramp = TRUE;
700         } else if (orig_vtable_slot) {
701                 if (m->klass->valuetype)
702                         need_unbox_tramp = TRUE;
703         }
704
705         addr = mini_add_method_trampoline (m, compiled_method, need_rgctx_tramp, need_unbox_tramp);
706
707         if (generic_virtual || variant_iface) {
708                 MonoMethod *target = generic_virtual ? generic_virtual : variant_iface;
709
710                 vtable_slot = orig_vtable_slot;
711                 g_assert (vtable_slot);
712
713                 mono_method_add_generic_virtual_invocation (mono_domain_get (), 
714                                                                                                         vt, vtable_slot,
715                                                                                                         target, addr);
716
717                 return addr;
718         }
719
720         /* the method was jumped to */
721         if (!code) {
722                 MonoDomain *domain = mono_domain_get ();
723
724                 /* Patch the got entries pointing to this method */
725                 /* 
726                  * We do this here instead of in mono_codegen () to cover the case when m
727                  * was loaded from an aot image.
728                  */
729                 if (domain_jit_info (domain)->jump_target_got_slot_hash) {
730                         GSList *list, *tmp;
731
732                         mono_domain_lock (domain);
733                         list = (GSList *)g_hash_table_lookup (domain_jit_info (domain)->jump_target_got_slot_hash, m);
734                         if (list) {
735                                 for (tmp = list; tmp; tmp = tmp->next) {
736                                         gpointer *got_slot = (gpointer *)tmp->data;
737                                         *got_slot = addr;
738                                 }
739                                 g_hash_table_remove (domain_jit_info (domain)->jump_target_got_slot_hash, m);
740                                 g_slist_free (list);
741                         }
742                         mono_domain_unlock (domain);
743                 }
744
745                 return addr;
746         }
747
748         vtable_slot = orig_vtable_slot;
749
750         if (vtable_slot) {
751                 if (vtable_slot_to_patch && (mono_aot_is_got_entry (code, (guint8*)vtable_slot_to_patch) || mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot_to_patch))) {
752                         g_assert (*vtable_slot_to_patch);
753                         *vtable_slot_to_patch = mono_get_addr_from_ftnptr (addr);
754                 }
755         } else {
756                 guint8 *plt_entry = mono_aot_get_plt_entry (code);
757                 gboolean no_patch = FALSE;
758                 MonoJitInfo *target_ji;
759
760                 if (plt_entry) {
761                         if (generic_shared) {
762                                 target_ji =
763                                         mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
764                                 if (!ji)
765                                         ji = mini_jit_info_table_find (mono_domain_get (), (char*)code, NULL);
766
767                                 if (ji && target_ji && generic_shared && ji->has_generic_jit_info && !target_ji->has_generic_jit_info) {
768                                         no_patch = TRUE;
769                                 }
770                         }
771                         if (!no_patch)
772                                 mono_aot_patch_plt_entry (code, plt_entry, NULL, regs, (guint8 *)addr);
773                 } else {
774                         if (generic_shared) {
775                                 if (m->wrapper_type != MONO_WRAPPER_NONE)
776                                         m = mono_marshal_method_from_wrapper (m);
777                                 //g_assert (mono_method_is_generic_sharable (m, FALSE));
778                         }
779
780                         /* Patch calling code */
781                         target_ji =
782                                 mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
783                         if (!ji)
784                                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)code, NULL);
785
786                         if (ji && target_ji && generic_shared && ji->has_generic_jit_info && !target_ji->has_generic_jit_info) {
787                                 /* 
788                                  * Can't patch the call as the caller is gshared, but the callee is not. Happens when
789                                  * generic sharing fails.
790                                  * FIXME: Performance problem.
791                                  */
792                                 no_patch = TRUE;
793                         }
794
795                         if (!no_patch && mono_method_same_domain (ji, target_ji))
796                                 mono_arch_patch_callsite ((guint8 *)ji->code_start, code, (guint8 *)addr);
797                 }
798         }
799
800         return addr;
801 }
802
803 static gpointer
804 common_call_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, MonoVTable *vt, gpointer *vtable_slot)
805 {
806         gpointer res;
807         MONO_PREPARE_RESET_BLOCKING;
808         res = common_call_trampoline_inner (regs, code, m, vt, vtable_slot);
809         MONO_FINISH_RESET_BLOCKING;
810         return res;
811 }
812
813 /**
814  * mono_magic_trampoline:
815  *
816  * This trampoline handles normal calls from JITted code.
817  */
818 gpointer
819 mono_magic_trampoline (mgreg_t *regs, guint8 *code, gpointer arg, guint8* tramp)
820 {
821         trampoline_calls ++;
822
823         return common_call_trampoline (regs, code, (MonoMethod *)arg, NULL, NULL);
824 }
825
826 /**
827  * mono_vcall_trampoline:
828  *
829  * This trampoline handles virtual calls.
830  */
831 static gpointer
832 mono_vcall_trampoline (mgreg_t *regs, guint8 *code, int slot, guint8 *tramp)
833 {
834         MonoObject *this_arg;
835         MonoVTable *vt;
836         gpointer *vtable_slot;
837         MonoMethod *m;
838         gpointer addr;
839
840         trampoline_calls ++;
841
842         /*
843          * We need to obtain the following pieces of information:
844          * - the method which needs to be compiled.
845          * - the vtable slot.
846          * We use one vtable trampoline per vtable slot index, so we need only the vtable,
847          * the other two can be computed from the vtable + the slot index.
848          */
849
850         /*
851          * Obtain the vtable from the 'this' arg.
852          */
853         this_arg = (MonoObject *)mono_arch_get_this_arg_from_call (regs, code);
854         g_assert (this_arg);
855
856         vt = this_arg->vtable;
857
858         if (slot >= 0) {
859                 /* Normal virtual call */
860                 vtable_slot = &(vt->vtable [slot]);
861
862                 /* Avoid loading metadata or creating a generic vtable if possible */
863                 addr = mono_aot_get_method_from_vt_slot (mono_domain_get (), vt, slot);
864                 if (addr && !vt->klass->valuetype) {
865                         if (mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot))
866                                 *vtable_slot = addr;
867
868                         return mono_create_ftnptr (mono_domain_get (), addr);
869                 }
870
871                 /*
872                  * Bug #616463 (see
873                  * is_generic_method_definition() above) also
874                  * goes away if we do a
875                  * mono_class_setup_vtable (vt->klass) here,
876                  * because we then inflate the method
877                  * correctly, put it in the cache, and the
878                  * "wrong" inflation invocation still looks up
879                  * the correctly inflated method.
880                  *
881                  * The hack above seems more stable and
882                  * trustworthy.
883                  */
884                 m = mono_class_get_vtable_entry (vt->klass, slot);
885         } else {
886                 /* IMT call */
887                 vtable_slot = &(((gpointer*)vt) [slot]);
888
889                 m = NULL;
890         }
891
892         return common_call_trampoline (regs, code, m, vt, vtable_slot);
893 }
894
895 #ifndef DISABLE_REMOTING
896 gpointer
897 mono_generic_virtual_remoting_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, guint8 *tramp)
898 {
899         MonoError error;
900         MonoGenericContext context = { NULL, NULL };
901         MonoMethod *imt_method, *declaring;
902         gpointer addr;
903
904         trampoline_calls ++;
905
906         g_assert (m->is_generic);
907
908         if (m->is_inflated)
909                 declaring = mono_method_get_declaring_generic_method (m);
910         else
911                 declaring = m;
912
913         if (m->klass->generic_class)
914                 context.class_inst = m->klass->generic_class->context.class_inst;
915         else
916                 g_assert (!m->klass->generic_container);
917
918         imt_method = mono_arch_find_imt_method (regs, code);
919         if (imt_method->is_inflated)
920                 context.method_inst = ((MonoMethodInflated*)imt_method)->context.method_inst;
921         m = mono_class_inflate_generic_method_checked (declaring, &context, &error);
922         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */;
923         m = mono_marshal_get_remoting_invoke_with_check (m);
924
925         addr = mono_compile_method (m);
926         g_assert (addr);
927
928         return addr;
929 }
930 #endif
931
932 /**
933  * mono_aot_trampoline:
934  *
935  * This trampoline handles calls made from AOT code. We try to bypass the 
936  * normal JIT compilation logic to avoid loading the metadata for the method.
937  */
938 #ifdef MONO_ARCH_AOT_SUPPORTED
939 gpointer
940 mono_aot_trampoline (mgreg_t *regs, guint8 *code, guint8 *token_info, 
941                                          guint8* tramp)
942 {
943         MonoImage *image;
944         guint32 token;
945         MonoMethod *method = NULL;
946         gpointer addr;
947         guint8 *plt_entry;
948
949         trampoline_calls ++;
950
951         image = (MonoImage *)*(gpointer*)(gpointer)token_info;
952         token_info += sizeof (gpointer);
953         token = *(guint32*)(gpointer)token_info;
954
955         addr = mono_aot_get_method_from_token (mono_domain_get (), image, token);
956         if (!addr) {
957                 MonoError error;
958                 method = mono_get_method_checked (image, token, NULL, NULL, &error);
959                 if (!method)
960                         g_error ("Could not load AOT trampoline due to %s", mono_error_get_message (&error));
961
962                 /* Use the generic code */
963                 return mono_magic_trampoline (regs, code, method, tramp);
964         }
965
966         addr = mono_create_ftnptr (mono_domain_get (), addr);
967
968         /* This is a normal call through a PLT entry */
969         plt_entry = mono_aot_get_plt_entry (code);
970         g_assert (plt_entry);
971
972         mono_aot_patch_plt_entry (code, plt_entry, NULL, regs, (guint8 *)addr);
973
974         return addr;
975 }
976
977 /*
978  * mono_aot_plt_trampoline:
979  *
980  *   This trampoline handles calls made from AOT code through the PLT table.
981  */
982 gpointer
983 mono_aot_plt_trampoline (mgreg_t *regs, guint8 *code, guint8 *aot_module, 
984                                                  guint8* tramp)
985 {
986         guint32 plt_info_offset = mono_aot_get_plt_info_offset (regs, code);
987         gpointer res;
988
989         trampoline_calls ++;
990
991         res = mono_aot_plt_resolve (aot_module, plt_info_offset, code);
992         if (!res) {
993                 if (mono_loader_get_last_error ())
994                         mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
995                 // FIXME: Error handling (how ?)
996                 g_assert (res);
997         }
998
999         return res;
1000 }
1001 #endif
1002
1003 static gpointer
1004 mono_rgctx_lazy_fetch_trampoline (mgreg_t *regs, guint8 *code, gpointer data, guint8 *tramp)
1005 {
1006         static gboolean inited = FALSE;
1007         static int num_lookups = 0;
1008         guint32 slot = GPOINTER_TO_UINT (data);
1009         mgreg_t *r = (mgreg_t*)regs;
1010         gpointer arg = (gpointer)(gssize)r [MONO_ARCH_VTABLE_REG];
1011         guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
1012         gboolean mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
1013
1014         trampoline_calls ++;
1015
1016         if (!inited) {
1017                 mono_counters_register ("RGCTX unmanaged lookups", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_lookups);
1018                 inited = TRUE;
1019         }
1020
1021         num_lookups++;
1022
1023         if (mrgctx)
1024                 return mono_method_fill_runtime_generic_context ((MonoMethodRuntimeGenericContext *)arg, index);
1025         else
1026                 return mono_class_fill_runtime_generic_context ((MonoVTable *)arg, index);
1027 }
1028
1029 /*
1030  * Precompute data to speed up mono_delegate_trampoline ().
1031  * METHOD might be NULL.
1032  */
1033 static MonoDelegateTrampInfo*
1034 create_delegate_trampoline_data (MonoDomain *domain, MonoClass *klass, MonoMethod *method)
1035 {
1036         MonoDelegateTrampInfo *tramp_data;
1037         MonoMethod *invoke;
1038         MonoError err;
1039
1040         // Precompute the delegate invoke impl and pass it to the delegate trampoline
1041         invoke = mono_get_delegate_invoke (klass);
1042         g_assert (invoke);
1043
1044         tramp_data = (MonoDelegateTrampInfo *)mono_domain_alloc0 (domain, sizeof (MonoDelegateTrampInfo));
1045         tramp_data->invoke = invoke;
1046         tramp_data->invoke_sig = mono_method_signature (invoke);
1047         tramp_data->impl_this = mono_arch_get_delegate_invoke_impl (mono_method_signature (invoke), TRUE);
1048         tramp_data->impl_nothis = mono_arch_get_delegate_invoke_impl (mono_method_signature (invoke), FALSE);
1049         tramp_data->method = method;
1050         if (method) {
1051                 mono_error_init (&err);
1052                 tramp_data->sig = mono_method_signature_checked (method, &err);
1053                 tramp_data->need_rgctx_tramp = mono_method_needs_static_rgctx_invoke (method, FALSE);
1054         }
1055
1056         return tramp_data;
1057 }
1058
1059 /**
1060  * mono_delegate_trampoline:
1061  *
1062  *   This trampoline handles calls made to Delegate:Invoke ().
1063  * This is called once the first time a delegate is invoked, so it must be fast.
1064  */
1065 gpointer
1066 mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *arg, guint8* tramp)
1067 {
1068         MonoDomain *domain = mono_domain_get ();
1069         MonoDelegate *delegate;
1070         MonoJitInfo *ji;
1071         MonoMethod *m;
1072         MonoMethod *method = NULL;
1073         gboolean multicast, callvirt = FALSE, closed_over_null = FALSE;
1074         gboolean need_rgctx_tramp = FALSE;
1075         gboolean need_unbox_tramp = FALSE;
1076         gboolean enable_caching = TRUE;
1077         MonoDelegateTrampInfo *tramp_info = (MonoDelegateTrampInfo*)arg;
1078         MonoMethod *invoke = tramp_info->invoke;
1079         guint8 *impl_this = (guint8 *)tramp_info->impl_this;
1080         guint8 *impl_nothis = (guint8 *)tramp_info->impl_nothis;
1081         MonoError err;
1082         MonoMethodSignature *sig;
1083         gpointer addr, compiled_method;
1084         gboolean is_remote = FALSE;
1085
1086         trampoline_calls ++;
1087
1088         /* Obtain the delegate object according to the calling convention */
1089         delegate = (MonoDelegate *)mono_arch_get_this_arg_from_call (regs, code);
1090         g_assert (mono_class_has_parent (mono_object_class (delegate), mono_defaults.multicastdelegate_class));
1091
1092         if (delegate->method) {
1093                 method = delegate->method;
1094
1095                 /*
1096                  * delegate->method_ptr == NULL means the delegate was initialized by 
1097                  * mini_delegate_ctor, while != NULL means it is initialized by 
1098                  * mono_delegate_ctor_with_method (). In both cases, we need to add wrappers
1099                  * (ctor_with_method () does this, but it doesn't store the wrapper back into
1100                  * delegate->method).
1101                  */
1102 #ifndef DISABLE_REMOTING
1103                 if (delegate->target && delegate->target->vtable->klass == mono_defaults.transparent_proxy_class) {
1104                         is_remote = TRUE;
1105 #ifndef DISABLE_COM
1106                         if (((MonoTransparentProxy *)delegate->target)->remote_class->proxy_class != mono_class_get_com_object_class () &&
1107                            !mono_class_is_com_object (((MonoTransparentProxy *)delegate->target)->remote_class->proxy_class))
1108 #endif
1109                                 method = mono_marshal_get_remoting_invoke (method);
1110                 }
1111 #endif
1112                 if (!is_remote) {
1113                         sig = tramp_info->sig;
1114                         if (!(sig && method == tramp_info->method)) {
1115                                 mono_error_init (&err);
1116                                 sig = mono_method_signature_checked (method, &err);
1117                                 if (!sig)
1118                                         mono_error_raise_exception (&err);
1119                         }
1120
1121                         if (sig->hasthis && method->klass->valuetype) {
1122                                 gboolean need_unbox = TRUE;
1123
1124                                 if (tramp_info->invoke_sig->param_count > sig->param_count && tramp_info->invoke_sig->params [0]->byref)
1125                                         need_unbox = FALSE;
1126
1127                                 if (need_unbox) {
1128                                         if (mono_aot_only)
1129                                                 need_unbox_tramp = TRUE;
1130                                         else
1131                                                 method = mono_marshal_get_unbox_wrapper (method);
1132                                 }
1133                         }
1134                 }
1135         // If "delegate->method_ptr" is null mono_get_addr_from_ftnptr will fail if
1136         // ftnptrs are being used.  "method" would end up null on archtitectures without
1137         // ftnptrs so we can just skip this.
1138         } else if (delegate->method_ptr) {
1139                 ji = mono_jit_info_table_find (domain, (char *)mono_get_addr_from_ftnptr (delegate->method_ptr));
1140                 if (ji)
1141                         method = jinfo_get_method (ji);
1142         }
1143
1144         if (method) {
1145                 sig = tramp_info->sig;
1146                 if (!(sig && method == tramp_info->method)) {
1147                         mono_error_init (&err);
1148                         sig = mono_method_signature_checked (method, &err);
1149                         if (!sig)
1150                                 mono_error_raise_exception (&err);
1151                 }
1152
1153                 callvirt = !delegate->target && sig->hasthis;
1154                 if (callvirt)
1155                         closed_over_null = tramp_info->invoke_sig->param_count == sig->param_count;
1156
1157                 if (callvirt && !closed_over_null) {
1158                         /*
1159                          * The delegate needs to make a virtual call to the target method using its
1160                          * first argument as the receiver. This is hard to support in full-aot, so
1161                          * optimize it in some cases if possible.
1162                          * If the target method is not virtual or is in a sealed class,
1163                          * the vcall will call it directly.
1164                          * If the call doesn't return a valuetype, then the vcall uses the same calling
1165                          * convention as a normal call.
1166                          */
1167                         if (((method->klass->flags & TYPE_ATTRIBUTE_SEALED) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) && !MONO_TYPE_ISSTRUCT (sig->ret)) {
1168                                 callvirt = FALSE;
1169                                 enable_caching = FALSE;
1170                         }
1171                 }
1172
1173                 if (delegate->target && 
1174                         method->flags & METHOD_ATTRIBUTE_VIRTUAL && 
1175                         method->flags & METHOD_ATTRIBUTE_ABSTRACT &&
1176                         method->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) {
1177                         method = mono_object_get_virtual_method (delegate->target, method);
1178                         enable_caching = FALSE;
1179                 }
1180
1181                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1182                         method = mono_marshal_get_synchronized_wrapper (method);
1183
1184                 if (method == tramp_info->method)
1185                         need_rgctx_tramp = tramp_info->need_rgctx_tramp;
1186                 else if (mono_method_needs_static_rgctx_invoke (method, FALSE))
1187                         need_rgctx_tramp = TRUE;
1188         }
1189
1190         /* 
1191          * If the called address is a trampoline, replace it with the compiled method so
1192          * further calls don't have to go through the trampoline.
1193          */
1194         if (method && !callvirt) {
1195                 /* Avoid the overhead of looking up an already compiled method if possible */
1196                 if (enable_caching && delegate->method_code && *delegate->method_code) {
1197                         delegate->method_ptr = *delegate->method_code;
1198                 } else {
1199                         compiled_method = addr = mono_compile_method (method);
1200                         addr = mini_add_method_trampoline (method, compiled_method, need_rgctx_tramp, need_unbox_tramp);
1201                         delegate->method_ptr = addr;
1202                         if (enable_caching && delegate->method_code)
1203                                 *delegate->method_code = (guint8 *)delegate->method_ptr;
1204                 }
1205         } else {
1206                 if (need_rgctx_tramp)
1207                         delegate->method_ptr = mono_create_static_rgctx_trampoline (method, delegate->method_ptr);
1208         }
1209
1210         /* Necessary for !code condition to fallback to slow path */
1211         code = NULL;
1212
1213         multicast = ((MonoMulticastDelegate*)delegate)->delegates != NULL;
1214         if (!multicast && !callvirt) {
1215                 if (method && (method->flags & METHOD_ATTRIBUTE_STATIC) && mono_method_signature (method)->param_count == mono_method_signature (invoke)->param_count + 1)
1216                         /* Closed static delegate */
1217                         code = impl_this;
1218                 else
1219                         code = delegate->target ? impl_this : impl_nothis;
1220         }
1221
1222         if (!code) {
1223                 /* The general, unoptimized case */
1224                 m = mono_marshal_get_delegate_invoke (invoke, delegate);
1225                 code = (guint8 *)mono_compile_method (m);
1226                 code = (guint8 *)mini_add_method_trampoline (m, code, mono_method_needs_static_rgctx_invoke (m, FALSE), FALSE);
1227         }
1228
1229         delegate->invoke_impl = mono_get_addr_from_ftnptr (code);
1230         if (enable_caching && !callvirt && tramp_info->method) {
1231                 tramp_info->method_ptr = delegate->method_ptr;
1232                 tramp_info->invoke_impl = delegate->invoke_impl;
1233         }
1234
1235         return code;
1236 }
1237
1238 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1239 static gpointer
1240 mono_handler_block_guard_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_info, guint8* tramp)
1241 {
1242         MonoContext ctx;
1243         MonoException *exc;
1244         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
1245         gpointer resume_ip = jit_tls->handler_block_return_address;
1246
1247         memcpy (&ctx, &jit_tls->handler_block_context, sizeof (MonoContext));
1248         MONO_CONTEXT_SET_IP (&ctx, jit_tls->handler_block_return_address);
1249
1250         jit_tls->handler_block_return_address = NULL;
1251         jit_tls->handler_block = NULL;
1252
1253         if (!resume_ip) /*this should not happen, but we should avoid crashing */
1254                 exc = mono_get_exception_execution_engine ("Invalid internal state, resuming abort after handler block but no resume ip found");
1255         else
1256                 exc = mono_thread_resume_interruption ();
1257
1258         if (exc) {
1259                 mono_handle_exception (&ctx, (MonoObject *)exc);
1260                 mono_restore_context (&ctx);
1261         }
1262
1263         return resume_ip;
1264 }
1265
1266 gpointer
1267 mono_create_handler_block_trampoline (void)
1268 {
1269         static gpointer code;
1270         if (code) {
1271                 mono_memory_barrier ();
1272                 return code;
1273         }
1274
1275         g_assert (!mono_aot_only);
1276
1277         mono_trampolines_lock ();
1278
1279         if (!code) {
1280                 MonoTrampInfo *info;
1281                 gpointer tmp;
1282
1283                 tmp = mono_arch_create_handler_block_trampoline (&info, FALSE);
1284                 mono_tramp_info_register (info, NULL);
1285                 mono_memory_barrier ();
1286                 code = tmp;
1287         }
1288         mono_trampolines_unlock ();
1289
1290         return code;
1291 }
1292 #endif
1293
1294 /*
1295  * mono_get_trampoline_func:
1296  *
1297  *   Return the C function which needs to be called by the generic trampoline of type
1298  * TRAMP_TYPE.
1299  */
1300 gconstpointer
1301 mono_get_trampoline_func (MonoTrampolineType tramp_type)
1302 {
1303         switch (tramp_type) {
1304         case MONO_TRAMPOLINE_JIT:
1305         case MONO_TRAMPOLINE_JUMP:
1306                 return mono_magic_trampoline;
1307         case MONO_TRAMPOLINE_RGCTX_LAZY_FETCH:
1308                 return mono_rgctx_lazy_fetch_trampoline;
1309 #ifdef MONO_ARCH_AOT_SUPPORTED
1310         case MONO_TRAMPOLINE_AOT:
1311                 return mono_aot_trampoline;
1312         case MONO_TRAMPOLINE_AOT_PLT:
1313                 return mono_aot_plt_trampoline;
1314 #endif
1315         case MONO_TRAMPOLINE_DELEGATE:
1316                 return mono_delegate_trampoline;
1317         case MONO_TRAMPOLINE_RESTORE_STACK_PROT:
1318                 return mono_altstack_restore_prot;
1319 #ifndef DISABLE_REMOTING
1320         case MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING:
1321                 return mono_generic_virtual_remoting_trampoline;
1322 #endif
1323         case MONO_TRAMPOLINE_VCALL:
1324                 return mono_vcall_trampoline;
1325 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1326         case MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD:
1327                 return mono_handler_block_guard_trampoline;
1328 #endif
1329         default:
1330                 g_assert_not_reached ();
1331                 return NULL;
1332         }
1333 }
1334
1335 static guchar*
1336 create_trampoline_code (MonoTrampolineType tramp_type)
1337 {
1338         MonoTrampInfo *info;
1339         guchar *code;
1340
1341         code = mono_arch_create_generic_trampoline (tramp_type, &info, FALSE);
1342         mono_tramp_info_register (info, NULL);
1343
1344         return code;
1345 }
1346
1347 void
1348 mono_trampolines_init (void)
1349 {
1350         mono_os_mutex_init_recursive (&trampolines_mutex);
1351
1352         if (mono_aot_only)
1353                 return;
1354
1355         mono_trampoline_code [MONO_TRAMPOLINE_JIT] = create_trampoline_code (MONO_TRAMPOLINE_JIT);
1356         mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = create_trampoline_code (MONO_TRAMPOLINE_JUMP);
1357         mono_trampoline_code [MONO_TRAMPOLINE_RGCTX_LAZY_FETCH] = create_trampoline_code (MONO_TRAMPOLINE_RGCTX_LAZY_FETCH);
1358 #ifdef MONO_ARCH_AOT_SUPPORTED
1359         mono_trampoline_code [MONO_TRAMPOLINE_AOT] = create_trampoline_code (MONO_TRAMPOLINE_AOT);
1360         mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
1361 #endif
1362         mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
1363         mono_trampoline_code [MONO_TRAMPOLINE_RESTORE_STACK_PROT] = create_trampoline_code (MONO_TRAMPOLINE_RESTORE_STACK_PROT);
1364 #ifndef DISABLE_REMOTING
1365         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING] = create_trampoline_code (MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING);
1366 #endif
1367         mono_trampoline_code [MONO_TRAMPOLINE_VCALL] = create_trampoline_code (MONO_TRAMPOLINE_VCALL);
1368 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1369         mono_trampoline_code [MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD] = create_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1370         mono_create_handler_block_trampoline ();
1371 #endif
1372
1373         mono_counters_register ("Calls to trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &trampoline_calls);
1374         mono_counters_register ("JIT trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &jit_trampolines);
1375         mono_counters_register ("Unbox trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &unbox_trampolines);
1376         mono_counters_register ("Static rgctx trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &static_rgctx_trampolines);
1377 }
1378
1379 void
1380 mono_trampolines_cleanup (void)
1381 {
1382         if (rgctx_lazy_fetch_trampoline_hash)
1383                 g_hash_table_destroy (rgctx_lazy_fetch_trampoline_hash);
1384         if (rgctx_lazy_fetch_trampoline_hash_addr)
1385                 g_hash_table_destroy (rgctx_lazy_fetch_trampoline_hash_addr);
1386
1387         mono_os_mutex_destroy (&trampolines_mutex);
1388 }
1389
1390 guint8 *
1391 mono_get_trampoline_code (MonoTrampolineType tramp_type)
1392 {
1393         g_assert (mono_trampoline_code [tramp_type]);
1394
1395         return mono_trampoline_code [tramp_type];
1396 }
1397
1398 gpointer
1399 mono_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
1400 {
1401         if (mono_aot_only)
1402                 return mono_aot_create_specific_trampoline (mono_defaults.corlib, arg1, tramp_type, domain, code_len);
1403         else
1404                 return mono_arch_create_specific_trampoline (arg1, tramp_type, domain, code_len);
1405 }
1406
1407 gpointer
1408 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper)
1409 {
1410         MonoJitInfo *ji;
1411         gpointer code;
1412         guint32 code_size = 0;
1413
1414         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
1415         /*
1416          * We cannot recover the correct type of a shared generic
1417          * method from its native code address, so we use the
1418          * trampoline instead.
1419          * For synchronized methods, the trampoline adds the wrapper.
1420          */
1421         if (code && !ji->has_generic_jit_info && !(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1422                 return code;
1423
1424         if (mono_llvm_only)
1425                 return mono_jit_compile_method (method);
1426
1427         mono_domain_lock (domain);
1428         code = g_hash_table_lookup (domain_jit_info (domain)->jump_trampoline_hash, method);
1429         mono_domain_unlock (domain);
1430         if (code)
1431                 return code;
1432
1433         code = mono_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
1434         g_assert (code_size);
1435
1436         ji = (MonoJitInfo *)mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
1437         ji->code_start = code;
1438         ji->code_size = code_size;
1439         ji->d.method = method;
1440
1441         /*
1442          * mono_delegate_ctor needs to find the method metadata from the 
1443          * trampoline address, so we save it here.
1444          */
1445
1446         mono_jit_info_table_add (domain, ji);
1447
1448         mono_domain_lock (domain);
1449         g_hash_table_insert (domain_jit_info (domain)->jump_trampoline_hash, method, ji->code_start);
1450         mono_domain_unlock (domain);
1451
1452         return ji->code_start;
1453 }
1454
1455 static void
1456 method_not_found (void)
1457 {
1458         g_assert_not_reached ();
1459 }
1460
1461 gpointer
1462 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
1463 {
1464         gpointer tramp;
1465
1466         if (mono_aot_only) {
1467                 /* Avoid creating trampolines if possible */
1468                 gpointer code = mono_jit_find_compiled_method (domain, method);
1469                 
1470                 if (code)
1471                         return code;
1472                 if (mono_llvm_only) {
1473                         if (method->wrapper_type == MONO_WRAPPER_PROXY_ISINST || method->wrapper_type == MONO_WRAPPER_LDFLD_REMOTE ||
1474                                 method->wrapper_type == MONO_WRAPPER_STFLD_REMOTE)
1475                                 /* These wrappers are not generated */
1476                                 return method_not_found;
1477                         /* Methods are lazily initialized on first call, so this can't lead recursion */
1478                         return mono_compile_method (method);
1479                 }
1480         }
1481
1482         mono_domain_lock (domain);
1483         tramp = g_hash_table_lookup (domain_jit_info (domain)->jit_trampoline_hash, method);
1484         mono_domain_unlock (domain);
1485         if (tramp)
1486                 return tramp;
1487
1488         tramp = mono_create_specific_trampoline (method, MONO_TRAMPOLINE_JIT, domain, NULL);
1489         
1490         mono_domain_lock (domain);
1491         g_hash_table_insert (domain_jit_info (domain)->jit_trampoline_hash, method, tramp);
1492         mono_domain_unlock (domain);
1493
1494         jit_trampolines++;
1495
1496         return tramp;
1497 }       
1498
1499 gpointer
1500 mono_create_jit_trampoline (MonoMethod *method)
1501 {
1502         return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
1503 }
1504
1505 gpointer
1506 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
1507 {
1508         gpointer tramp;
1509
1510         MonoDomain *domain = mono_domain_get ();
1511         guint8 *buf, *start;
1512
1513         buf = start = (guint8 *)mono_domain_alloc0 (domain, 2 * sizeof (gpointer));
1514
1515         *(gpointer*)(gpointer)buf = image;
1516         buf += sizeof (gpointer);
1517         *(guint32*)(gpointer)buf = token;
1518
1519         tramp = mono_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
1520
1521         jit_trampolines++;
1522
1523         return tramp;
1524 }       
1525
1526
1527 /*
1528  * mono_create_delegate_trampoline_info:
1529  *
1530  *   Create a delegate trampoline for the KLASS+METHOD pair.
1531  */
1532 MonoDelegateTrampInfo*
1533 mono_create_delegate_trampoline_info (MonoDomain *domain, MonoClass *klass, MonoMethod *method)
1534 {
1535         MonoDelegateTrampInfo *tramp_info;
1536         MonoClassMethodPair pair, *dpair;
1537         guint32 code_size = 0;
1538
1539         pair.klass = klass;
1540         pair.method = method;
1541         mono_domain_lock (domain);
1542         tramp_info = (MonoDelegateTrampInfo *)g_hash_table_lookup (domain_jit_info (domain)->delegate_trampoline_hash, &pair);
1543         mono_domain_unlock (domain);
1544         if (tramp_info)
1545                 return tramp_info;
1546
1547         tramp_info = create_delegate_trampoline_data (domain, klass, method);
1548
1549         tramp_info->invoke_impl = mono_create_specific_trampoline (tramp_info, MONO_TRAMPOLINE_DELEGATE, domain, &code_size);
1550         g_assert (code_size);
1551
1552         dpair = (MonoClassMethodPair *)mono_domain_alloc0 (domain, sizeof (MonoClassMethodPair));
1553         memcpy (dpair, &pair, sizeof (MonoClassMethodPair));
1554
1555         /* store trampoline address */
1556         mono_domain_lock (domain);
1557         g_hash_table_insert (domain_jit_info (domain)->delegate_trampoline_hash, dpair, tramp_info);
1558         mono_domain_unlock (domain);
1559
1560         return tramp_info;
1561 }
1562
1563 static void
1564 no_delegate_trampoline (void)
1565 {
1566         g_assert_not_reached ();
1567 }
1568
1569 gpointer
1570 mono_create_delegate_trampoline (MonoDomain *domain, MonoClass *klass)
1571 {
1572         if (mono_llvm_only)
1573                 return no_delegate_trampoline;
1574
1575         return mono_create_delegate_trampoline_info (domain, klass, NULL)->invoke_impl;
1576 }
1577
1578 gpointer
1579 mono_create_delegate_virtual_trampoline (MonoDomain *domain, MonoClass *klass, MonoMethod *method)
1580 {
1581         MonoMethod *invoke = mono_get_delegate_invoke (klass);
1582         g_assert (invoke);
1583
1584         return mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), method);
1585 }
1586
1587 gpointer
1588 mono_create_rgctx_lazy_fetch_trampoline (guint32 offset)
1589 {
1590         static gboolean inited = FALSE;
1591         static int num_trampolines = 0;
1592         MonoTrampInfo *info;
1593
1594         gpointer tramp, ptr;
1595
1596         mono_trampolines_lock ();
1597         if (rgctx_lazy_fetch_trampoline_hash)
1598                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
1599         else
1600                 tramp = NULL;
1601         mono_trampolines_unlock ();
1602         if (tramp)
1603                 return tramp;
1604
1605         if (mono_aot_only) {
1606                 ptr = mono_aot_get_lazy_fetch_trampoline (offset);
1607         } else {
1608                 tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, FALSE);
1609                 mono_tramp_info_register (info, NULL);
1610                 ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
1611         }
1612
1613         mono_trampolines_lock ();
1614         if (!rgctx_lazy_fetch_trampoline_hash) {
1615                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
1616                 rgctx_lazy_fetch_trampoline_hash_addr = g_hash_table_new (NULL, NULL);
1617         }
1618         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
1619         g_assert (offset != -1);
1620         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash_addr, ptr, GUINT_TO_POINTER (offset + 1));
1621         mono_trampolines_unlock ();
1622
1623         if (!inited) {
1624                 mono_counters_register ("RGCTX num lazy fetch trampolines",
1625                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
1626                 inited = TRUE;
1627         }
1628         num_trampolines++;
1629
1630         return ptr;
1631 }
1632
1633 guint32
1634 mono_find_rgctx_lazy_fetch_trampoline_by_addr (gconstpointer addr)
1635 {
1636         int offset;
1637
1638         mono_trampolines_lock ();
1639         if (rgctx_lazy_fetch_trampoline_hash_addr) {
1640                 /* We store the real offset + 1 so we can detect when the lookup fails */
1641                 offset = GPOINTER_TO_INT (g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash_addr, addr));
1642                 if (offset)
1643                         offset -= 1;
1644                 else
1645                         offset = -1;
1646         } else {
1647                 offset = -1;
1648         }
1649         mono_trampolines_unlock ();
1650         return offset;
1651 }
1652
1653 static const char*tramp_names [MONO_TRAMPOLINE_NUM] = {
1654         "jit",
1655         "jump",
1656         "rgctx_lazy_fetch",
1657         "aot",
1658         "aot_plt",
1659         "delegate",
1660         "restore_stack_prot",
1661         "generic_virtual_remoting",
1662         "vcall",
1663         "handler_block_guard"
1664 };
1665
1666 /*
1667  * mono_get_generic_trampoline_simple_name:
1668  *
1669  */
1670 const char*
1671 mono_get_generic_trampoline_simple_name (MonoTrampolineType tramp_type)
1672 {
1673         return tramp_names [tramp_type];
1674 }
1675
1676 /*
1677  * mono_get_generic_trampoline_name:
1678  *
1679  *   Returns a pointer to malloc-ed memory.
1680  */
1681 char*
1682 mono_get_generic_trampoline_name (MonoTrampolineType tramp_type)
1683 {
1684         return g_strdup_printf ("generic_trampoline_%s", tramp_names [tramp_type]);
1685 }
1686
1687 /*
1688  * mono_get_rgctx_fetch_trampoline_name:
1689  *
1690  *   Returns a pointer to malloc-ed memory.
1691  */
1692 char*
1693 mono_get_rgctx_fetch_trampoline_name (int slot)
1694 {
1695         gboolean mrgctx;
1696         int index;
1697
1698         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
1699         index = MONO_RGCTX_SLOT_INDEX (slot);
1700
1701         return g_strdup_printf ("rgctx_fetch_trampoline_%s_%d", mrgctx ? "mrgctx" : "rgctx", index);
1702 }
1703
1704 /*
1705  * mini_get_single_step_trampoline:
1706  *
1707  *   Return a trampoline which calls debugger_agent_single_step_from_context ().
1708  */
1709 gpointer
1710 mini_get_single_step_trampoline (void)
1711 {
1712         static gpointer trampoline;
1713
1714         if (!trampoline) {
1715                 gpointer tramp;
1716
1717                 if (mono_aot_only) {
1718                         tramp = mono_aot_get_trampoline ("sdb_single_step_trampoline");
1719                 } else {
1720 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
1721                         MonoTrampInfo *info;
1722                         tramp = mono_arch_create_sdb_trampoline (TRUE, &info, FALSE);
1723                         mono_tramp_info_register (info, NULL);
1724 #else
1725                         tramp = NULL;
1726                         g_assert_not_reached ();
1727 #endif
1728                 }
1729                 mono_memory_barrier ();
1730                 trampoline = tramp;
1731         }
1732
1733         return trampoline;
1734 }
1735
1736 /*
1737  * mini_get_breakpoint_trampoline:
1738  *
1739  *   Return a trampoline which calls debugger_agent_breakpoint_from_context ().
1740  */
1741 gpointer
1742 mini_get_breakpoint_trampoline (void)
1743 {
1744         static gpointer trampoline;
1745
1746         if (!trampoline) {
1747                 gpointer tramp;
1748
1749                 if (mono_aot_only) {
1750                         tramp = mono_aot_get_trampoline ("sdb_breakpoint_trampoline");
1751                 } else {
1752 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
1753                         MonoTrampInfo *info;
1754                         tramp = mono_arch_create_sdb_trampoline (FALSE, &info, FALSE);
1755                         mono_tramp_info_register (info, NULL);
1756 #else
1757                         tramp = NULL;
1758                         g_assert_not_reached ();
1759 #endif
1760                 }
1761                 mono_memory_barrier ();
1762                 trampoline = tramp;
1763         }
1764
1765         return trampoline;
1766 }