Wrap always_inline and noinline attributes in compiler checks and use MSVC equivalent.
[mono.git] / mono / metadata / sgen-alloc.c
1 /*
2  * sgen-alloc.c: Object allocation routines + managed allocators
3  *
4  * Author:
5  *      Paolo Molaro (lupus@ximian.com)
6  *  Rodrigo Kumpera (kumpera@gmail.com)
7  *
8  * Copyright 2005-2011 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  * Copyright 2011 Xamarin, Inc.
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining
13  * a copy of this software and associated documentation files (the
14  * "Software"), to deal in the Software without restriction, including
15  * without limitation the rights to use, copy, modify, merge, publish,
16  * distribute, sublicense, and/or sell copies of the Software, and to
17  * permit persons to whom the Software is furnished to do so, subject to
18  * the following conditions:
19  * 
20  * The above copyright notice and this permission notice shall be
21  * included in all copies or substantial portions of the Software.
22  * 
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30  */
31
32 /*
33  * ######################################################################
34  * ########  Object allocation
35  * ######################################################################
36  * This section of code deals with allocating memory for objects.
37  * There are several ways:
38  * *) allocate large objects
39  * *) allocate normal objects
40  * *) fast lock-free allocation
41  * *) allocation of pinned objects
42  */
43
44 #include "config.h"
45 #ifdef HAVE_SGEN_GC
46
47 #include "metadata/sgen-gc.h"
48 #include "metadata/sgen-protocol.h"
49 #include "metadata/sgen-memory-governor.h"
50 #include "metadata/profiler-private.h"
51 #include "metadata/marshal.h"
52 #include "metadata/method-builder.h"
53 #include "utils/mono-memory-model.h"
54 #include "utils/mono-counters.h"
55
56 #define ALIGN_UP                SGEN_ALIGN_UP
57 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
58 #define ALLOC_ALIGN_BITS        SGEN_ALLOC_ALIGN_BITS
59 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
60 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
61
62 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
63         a = i,
64
65 enum {
66 #include "mono/cil/opcode.def"
67         CEE_LAST
68 };
69
70 #undef OPDEF
71
72 #ifdef HEAVY_STATISTICS
73 static long long stat_objects_alloced = 0;
74 static long long stat_bytes_alloced = 0;
75 static long long stat_bytes_alloced_los = 0;
76
77 #endif
78
79 /*
80  * Allocation is done from a Thread Local Allocation Buffer (TLAB). TLABs are allocated
81  * from nursery fragments.
82  * tlab_next is the pointer to the space inside the TLAB where the next object will 
83  * be allocated.
84  * tlab_temp_end is the pointer to the end of the temporary space reserved for
85  * the allocation: it allows us to set the scan starts at reasonable intervals.
86  * tlab_real_end points to the end of the TLAB.
87  */
88
89 /*
90  * FIXME: What is faster, a TLS variable pointing to a structure, or separate TLS 
91  * variables for next+temp_end ?
92  */
93 #ifdef HAVE_KW_THREAD
94 static __thread char *tlab_start;
95 static __thread char *tlab_next;
96 static __thread char *tlab_temp_end;
97 static __thread char *tlab_real_end;
98 /* Used by the managed allocator/wbarrier */
99 static __thread char **tlab_next_addr;
100 #endif
101
102 #ifdef HAVE_KW_THREAD
103 #define TLAB_START      tlab_start
104 #define TLAB_NEXT       tlab_next
105 #define TLAB_TEMP_END   tlab_temp_end
106 #define TLAB_REAL_END   tlab_real_end
107 #else
108 #define TLAB_START      (__thread_info__->tlab_start)
109 #define TLAB_NEXT       (__thread_info__->tlab_next)
110 #define TLAB_TEMP_END   (__thread_info__->tlab_temp_end)
111 #define TLAB_REAL_END   (__thread_info__->tlab_real_end)
112 #endif
113
114 static void*
115 alloc_degraded (MonoVTable *vtable, size_t size, gboolean for_mature)
116 {
117         static int last_major_gc_warned = -1;
118         static int num_degraded = 0;
119
120         if (!for_mature) {
121                 if (last_major_gc_warned < stat_major_gcs) {
122                         ++num_degraded;
123                         if (num_degraded == 1 || num_degraded == 3)
124                                 fprintf (stderr, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.\n");
125                         else if (num_degraded == 10)
126                                 fprintf (stderr, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.\n");
127                         last_major_gc_warned = stat_major_gcs;
128                 }
129                 InterlockedExchangeAdd (&degraded_mode, size);
130         }
131
132         sgen_ensure_free_space (size);
133
134         return major_collector.alloc_degraded (vtable, size);
135 }
136
137 /*
138  * Provide a variant that takes just the vtable for small fixed-size objects.
139  * The aligned size is already computed and stored in vt->gc_descr.
140  * Note: every SGEN_SCAN_START_SIZE or so we are given the chance to do some special
141  * processing. We can keep track of where objects start, for example,
142  * so when we scan the thread stacks for pinned objects, we can start
143  * a search for the pinned object in SGEN_SCAN_START_SIZE chunks.
144  */
145 static void*
146 mono_gc_alloc_obj_nolock (MonoVTable *vtable, size_t size)
147 {
148         /* FIXME: handle OOM */
149         void **p;
150         char *new_next;
151         TLAB_ACCESS_INIT;
152
153         HEAVY_STAT (++stat_objects_alloced);
154         if (size <= SGEN_MAX_SMALL_OBJ_SIZE)
155                 HEAVY_STAT (stat_bytes_alloced += size);
156         else
157                 HEAVY_STAT (stat_bytes_alloced_los += size);
158
159         size = ALIGN_UP (size);
160
161         g_assert (vtable->gc_descr);
162
163         if (G_UNLIKELY (has_per_allocation_action)) {
164                 static int alloc_count;
165                 int current_alloc = InterlockedIncrement (&alloc_count);
166
167                 if (collect_before_allocs) {
168                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
169                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered");
170                                 if (!degraded_mode && sgen_can_alloc_size (size) && size <= SGEN_MAX_SMALL_OBJ_SIZE) {
171                                         // FIXME:
172                                         g_assert_not_reached ();
173                                 }
174                         }
175                 } else if (verify_before_allocs) {
176                         if ((current_alloc % verify_before_allocs) == 0)
177                                 sgen_check_whole_heap_stw ();
178                 }
179         }
180
181         /*
182          * We must already have the lock here instead of after the
183          * fast path because we might be interrupted in the fast path
184          * (after confirming that new_next < TLAB_TEMP_END) by the GC,
185          * and we'll end up allocating an object in a fragment which
186          * no longer belongs to us.
187          *
188          * The managed allocator does not do this, but it's treated
189          * specially by the world-stopping code.
190          */
191
192         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
193                 p = sgen_los_alloc_large_inner (vtable, size);
194         } else {
195                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
196
197                 p = (void**)TLAB_NEXT;
198                 /* FIXME: handle overflow */
199                 new_next = (char*)p + size;
200                 TLAB_NEXT = new_next;
201
202                 if (G_LIKELY (new_next < TLAB_TEMP_END)) {
203                         /* Fast path */
204
205                         /* 
206                          * FIXME: We might need a memory barrier here so the change to tlab_next is 
207                          * visible before the vtable store.
208                          */
209
210                         DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
211                         binary_protocol_alloc (p , vtable, size);
212                         g_assert (*p == NULL);
213                         mono_atomic_store_seq (p, vtable);
214
215                         return p;
216                 }
217
218                 /* Slow path */
219
220                 /* there are two cases: the object is too big or we run out of space in the TLAB */
221                 /* we also reach here when the thread does its first allocation after a minor 
222                  * collection, since the tlab_ variables are initialized to NULL.
223                  * there can be another case (from ORP), if we cooperate with the runtime a bit:
224                  * objects that need finalizers can have the high bit set in their size
225                  * so the above check fails and we can readily add the object to the queue.
226                  * This avoids taking again the GC lock when registering, but this is moot when
227                  * doing thread-local allocation, so it may not be a good idea.
228                  */
229                 if (TLAB_NEXT >= TLAB_REAL_END) {
230                         int available_in_tlab;
231                         /* 
232                          * Run out of space in the TLAB. When this happens, some amount of space
233                          * remains in the TLAB, but not enough to satisfy the current allocation
234                          * request. Currently, we retire the TLAB in all cases, later we could
235                          * keep it if the remaining space is above a treshold, and satisfy the
236                          * allocation directly from the nursery.
237                          */
238                         TLAB_NEXT -= size;
239                         /* when running in degraded mode, we continue allocing that way
240                          * for a while, to decrease the number of useless nursery collections.
241                          */
242                         if (degraded_mode && degraded_mode < DEFAULT_NURSERY_SIZE) {
243                                 p = alloc_degraded (vtable, size, FALSE);
244                                 binary_protocol_alloc_degraded (p, vtable, size);
245                                 return p;
246                         }
247
248                         available_in_tlab = TLAB_REAL_END - TLAB_NEXT;
249                         if (size > tlab_size || available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
250                                 /* Allocate directly from the nursery */
251                                 do {
252                                         p = sgen_nursery_alloc (size);
253                                         if (!p) {
254                                                 sgen_ensure_free_space (size);
255                                                 if (degraded_mode) {
256                                                         p = alloc_degraded (vtable, size, FALSE);
257                                                         binary_protocol_alloc_degraded (p, vtable, size);
258                                                         return p;
259                                                 } else {
260                                                         p = sgen_nursery_alloc (size);
261                                                 }
262                                         }
263                                 } while (!p);
264                                 if (!p) {
265                                         // no space left
266                                         g_assert (0);
267                                 }
268
269                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
270                                         memset (p, 0, size);
271                                 }
272                         } else {
273                                 size_t alloc_size = 0;
274                                 if (TLAB_START)
275                                         DEBUG (3, fprintf (gc_debug_file, "Retire TLAB: %p-%p [%ld]\n", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size)));
276                                 sgen_nursery_retire_region (p, available_in_tlab);
277
278                                 do {
279                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
280                                         if (!p) {
281                                                 sgen_ensure_free_space (tlab_size);
282                                                 if (degraded_mode) {
283                                                         p = alloc_degraded (vtable, size, FALSE);
284                                                         binary_protocol_alloc_degraded (p, vtable, size);
285                                                         return p;
286                                                 } else {
287                                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
288                                                 }               
289                                         }
290                                 } while (!p);
291                                         
292                                 if (!p) {
293                                         // no space left
294                                         g_assert (0);
295                                 }
296
297                                 /* Allocate a new TLAB from the current nursery fragment */
298                                 TLAB_START = (char*)p;
299                                 TLAB_NEXT = TLAB_START;
300                                 TLAB_REAL_END = TLAB_START + alloc_size;
301                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
302
303                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
304                                         memset (TLAB_START, 0, alloc_size);
305                                 }
306
307                                 /* Allocate from the TLAB */
308                                 p = (void*)TLAB_NEXT;
309                                 TLAB_NEXT += size;
310                                 sgen_set_nursery_scan_start ((char*)p);
311                         }
312                 } else {
313                         /* Reached tlab_temp_end */
314
315                         /* record the scan start so we can find pinned objects more easily */
316                         sgen_set_nursery_scan_start ((char*)p);
317                         /* we just bump tlab_temp_end as well */
318                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
319                         DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));
320                 }
321         }
322
323         if (G_LIKELY (p)) {
324                 DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
325                 binary_protocol_alloc (p, vtable, size);
326                 mono_atomic_store_seq (p, vtable);
327         }
328
329         return p;
330 }
331
332 static void*
333 mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
334 {
335         void **p;
336         char *new_next;
337         TLAB_ACCESS_INIT;
338
339         size = ALIGN_UP (size);
340
341         g_assert (vtable->gc_descr);
342         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
343                 return NULL;
344
345         if (G_UNLIKELY (size > tlab_size)) {
346                 /* Allocate directly from the nursery */
347                 p = sgen_nursery_alloc (size);
348                 if (!p)
349                         return NULL;
350                 sgen_set_nursery_scan_start ((char*)p);
351
352                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
353                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
354                         memset (p, 0, size);
355         } else {
356                 int available_in_tlab;
357                 char *real_end;
358                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
359
360                 p = (void**)TLAB_NEXT;
361                 /* FIXME: handle overflow */
362                 new_next = (char*)p + size;
363
364                 real_end = TLAB_REAL_END;
365                 available_in_tlab = real_end - (char*)p;
366
367                 if (G_LIKELY (new_next < real_end)) {
368                         TLAB_NEXT = new_next;
369
370                         /* Second case, we overflowed temp end */
371                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
372                                 sgen_set_nursery_scan_start (new_next);
373                                 /* we just bump tlab_temp_end as well */
374                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
375                                 DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));         
376                         }
377                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
378                         /* Allocate directly from the nursery */
379                         p = sgen_nursery_alloc (size);
380                         if (!p)
381                                 return NULL;
382
383                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
384                                 memset (p, 0, size);                    
385                 } else {
386                         size_t alloc_size = 0;
387
388                         sgen_nursery_retire_region (p, available_in_tlab);
389                         new_next = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
390                         p = (void**)new_next;
391                         if (!p)
392                                 return NULL;
393
394                         TLAB_START = (char*)new_next;
395                         TLAB_NEXT = new_next + size;
396                         TLAB_REAL_END = new_next + alloc_size;
397                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
398                         sgen_set_nursery_scan_start ((char*)p);
399
400                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
401                                 memset (new_next, 0, alloc_size);
402                 }
403         }
404
405         HEAVY_STAT (++stat_objects_alloced);
406         HEAVY_STAT (stat_bytes_alloced += size);
407
408         DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
409         binary_protocol_alloc (p, vtable, size);
410         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
411
412         mono_atomic_store_seq (p, vtable);
413
414         return p;
415 }
416
417 void*
418 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
419 {
420         void *res;
421 #ifndef DISABLE_CRITICAL_REGION
422         TLAB_ACCESS_INIT;
423         ENTER_CRITICAL_REGION;
424         res = mono_gc_try_alloc_obj_nolock (vtable, size);
425         if (res) {
426                 EXIT_CRITICAL_REGION;
427                 return res;
428         }
429         EXIT_CRITICAL_REGION;
430 #endif
431         LOCK_GC;
432         res = mono_gc_alloc_obj_nolock (vtable, size);
433         UNLOCK_GC;
434         if (G_UNLIKELY (!res))
435                 return mono_gc_out_of_memory (size);
436         return res;
437 }
438
439 void*
440 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
441 {
442         MonoArray *arr;
443 #ifndef DISABLE_CRITICAL_REGION
444         TLAB_ACCESS_INIT;
445         ENTER_CRITICAL_REGION;
446         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
447         if (arr) {
448                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
449                 arr->max_length = max_length;
450                 EXIT_CRITICAL_REGION;
451                 return arr;
452         }
453         EXIT_CRITICAL_REGION;
454 #endif
455
456         LOCK_GC;
457
458         arr = mono_gc_alloc_obj_nolock (vtable, size);
459         if (G_UNLIKELY (!arr)) {
460                 UNLOCK_GC;
461                 return mono_gc_out_of_memory (size);
462         }
463
464         arr->max_length = max_length;
465
466         UNLOCK_GC;
467
468         return arr;
469 }
470
471 void*
472 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
473 {
474         MonoArray *arr;
475         MonoArrayBounds *bounds;
476
477 #ifndef DISABLE_CRITICAL_REGION
478         TLAB_ACCESS_INIT;
479         ENTER_CRITICAL_REGION;
480         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
481         if (arr) {
482                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
483                 arr->max_length = max_length;
484
485                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
486                 arr->bounds = bounds;
487                 EXIT_CRITICAL_REGION;
488                 return arr;
489         }
490         EXIT_CRITICAL_REGION;
491 #endif
492
493         LOCK_GC;
494
495         arr = mono_gc_alloc_obj_nolock (vtable, size);
496         if (G_UNLIKELY (!arr)) {
497                 UNLOCK_GC;
498                 return mono_gc_out_of_memory (size);
499         }
500
501         arr->max_length = max_length;
502
503         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
504         arr->bounds = bounds;
505
506         UNLOCK_GC;
507
508         return arr;
509 }
510
511 void*
512 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
513 {
514         MonoString *str;
515 #ifndef DISABLE_CRITICAL_REGION
516         TLAB_ACCESS_INIT;
517         ENTER_CRITICAL_REGION;
518         str = mono_gc_try_alloc_obj_nolock (vtable, size);
519         if (str) {
520                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
521                 str->length = len;
522                 EXIT_CRITICAL_REGION;
523                 return str;
524         }
525         EXIT_CRITICAL_REGION;
526 #endif
527
528         LOCK_GC;
529
530         str = mono_gc_alloc_obj_nolock (vtable, size);
531         if (G_UNLIKELY (!str)) {
532                 UNLOCK_GC;
533                 return mono_gc_out_of_memory (size);
534         }
535
536         str->length = len;
537
538         UNLOCK_GC;
539
540         return str;
541 }
542
543 /*
544  * To be used for interned strings and possibly MonoThread, reflection handles.
545  * We may want to explicitly free these objects.
546  */
547 void*
548 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
549 {
550         void **p;
551         size = ALIGN_UP (size);
552         LOCK_GC;
553
554         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
555                 /* large objects are always pinned anyway */
556                 p = sgen_los_alloc_large_inner (vtable, size);
557         } else {
558                 DEBUG (9, g_assert (vtable->klass->inited));
559                 p = major_collector.alloc_small_pinned_obj (size, SGEN_VTABLE_HAS_REFERENCES (vtable));
560         }
561         if (G_LIKELY (p)) {
562                 DEBUG (6, fprintf (gc_debug_file, "Allocated pinned object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
563                 binary_protocol_alloc_pinned (p, vtable, size);
564                 mono_atomic_store_seq (p, vtable);
565         }
566         UNLOCK_GC;
567         return p;
568 }
569
570 void*
571 mono_gc_alloc_mature (MonoVTable *vtable)
572 {
573         void **res;
574         size_t size = ALIGN_UP (vtable->klass->instance_size);
575         LOCK_GC;
576         res = alloc_degraded (vtable, size, TRUE);
577         mono_atomic_store_seq (res, vtable);
578         UNLOCK_GC;
579         if (G_UNLIKELY (vtable->klass->has_finalize))
580                 mono_object_register_finalizer ((MonoObject*)res);
581
582         return res;
583 }
584
585 void*
586 mono_gc_alloc_fixed (size_t size, void *descr)
587 {
588         /* FIXME: do a single allocation */
589         void *res = calloc (1, size);
590         if (!res)
591                 return NULL;
592         if (!mono_gc_register_root (res, size, descr)) {
593                 free (res);
594                 res = NULL;
595         }
596         return res;
597 }
598
599 void
600 mono_gc_free_fixed (void* addr)
601 {
602         mono_gc_deregister_root (addr);
603         free (addr);
604 }
605
606 void
607 sgen_init_tlab_info (SgenThreadInfo* info)
608 {
609 #ifndef HAVE_KW_THREAD
610         SgenThreadInfo *__thread_info__ = info;
611 #endif
612
613         info->tlab_start_addr = &TLAB_START;
614         info->tlab_next_addr = &TLAB_NEXT;
615         info->tlab_temp_end_addr = &TLAB_TEMP_END;
616         info->tlab_real_end_addr = &TLAB_REAL_END;
617
618 #ifdef HAVE_KW_THREAD
619         tlab_next_addr = &tlab_next;
620 #endif
621 }
622
623 /*
624  * Clear the thread local TLAB variables for all threads.
625  */
626 void
627 sgen_clear_tlabs (void)
628 {
629         SgenThreadInfo *info;
630
631         FOREACH_THREAD (info) {
632                 /* A new TLAB will be allocated when the thread does its first allocation */
633                 *info->tlab_start_addr = NULL;
634                 *info->tlab_next_addr = NULL;
635                 *info->tlab_temp_end_addr = NULL;
636                 *info->tlab_real_end_addr = NULL;
637         } END_FOREACH_THREAD
638 }
639
640 static MonoMethod* alloc_method_cache [ATYPE_NUM];
641
642 #ifdef MANAGED_ALLOCATION
643 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
644  * for each class. This is currently not easy to do, as it is hard to generate basic 
645  * blocks + branches, but it is easy with the linear IL codebase.
646  *
647  * For this to work we'd need to solve the TLAB race, first.  Now we
648  * require the allocator to be in a few known methods to make sure
649  * that they are executed atomically via the restart mechanism.
650  */
651 static MonoMethod*
652 create_allocator (int atype)
653 {
654         int p_var, size_var;
655         guint32 slowpath_branch, max_size_branch;
656         MonoMethodBuilder *mb;
657         MonoMethod *res;
658         MonoMethodSignature *csig;
659         static gboolean registered = FALSE;
660         int tlab_next_addr_var, new_next_var;
661         int num_params, i;
662         const char *name = NULL;
663         AllocatorWrapperInfo *info;
664
665 #ifdef HAVE_KW_THREAD
666         int tlab_next_addr_offset = -1;
667         int tlab_temp_end_offset = -1;
668
669         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
670         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
671
672         g_assert (tlab_next_addr_offset != -1);
673         g_assert (tlab_temp_end_offset != -1);
674 #endif
675
676         if (!registered) {
677                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
678                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
679                 registered = TRUE;
680         }
681
682         if (atype == ATYPE_SMALL) {
683                 num_params = 1;
684                 name = "AllocSmall";
685         } else if (atype == ATYPE_NORMAL) {
686                 num_params = 1;
687                 name = "Alloc";
688         } else if (atype == ATYPE_VECTOR) {
689                 num_params = 2;
690                 name = "AllocVector";
691         } else {
692                 g_assert_not_reached ();
693         }
694
695         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
696         csig->ret = &mono_defaults.object_class->byval_arg;
697         for (i = 0; i < num_params; ++i)
698                 csig->params [i] = &mono_defaults.int_class->byval_arg;
699
700         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
701         size_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
702         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
703                 /* size = vtable->klass->instance_size; */
704                 mono_mb_emit_ldarg (mb, 0);
705                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
706                 mono_mb_emit_byte (mb, CEE_ADD);
707                 mono_mb_emit_byte (mb, CEE_LDIND_I);
708                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
709                 mono_mb_emit_byte (mb, CEE_ADD);
710                 /* FIXME: assert instance_size stays a 4 byte integer */
711                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
712                 mono_mb_emit_stloc (mb, size_var);
713         } else if (atype == ATYPE_VECTOR) {
714                 MonoExceptionClause *clause;
715                 int pos, pos_leave;
716                 MonoClass *oom_exc_class;
717                 MonoMethod *ctor;
718
719                 /* n >  MONO_ARRAY_MAX_INDEX -> OverflowException */
720                 mono_mb_emit_ldarg (mb, 1);
721                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
722                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
723                 mono_mb_emit_exception (mb, "OverflowException", NULL);
724                 mono_mb_patch_short_branch (mb, pos);
725
726                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
727                 clause->try_offset = mono_mb_get_label (mb);
728
729                 /* vtable->klass->sizes.element_size */
730                 mono_mb_emit_ldarg (mb, 0);
731                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
732                 mono_mb_emit_byte (mb, CEE_ADD);
733                 mono_mb_emit_byte (mb, CEE_LDIND_I);
734                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, sizes.element_size));
735                 mono_mb_emit_byte (mb, CEE_ADD);
736                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
737
738                 /* * n */
739                 mono_mb_emit_ldarg (mb, 1);
740                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
741                 /* + sizeof (MonoArray) */
742                 mono_mb_emit_icon (mb, sizeof (MonoArray));
743                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
744                 mono_mb_emit_stloc (mb, size_var);
745
746                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
747
748                 /* catch */
749                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
750                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
751                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
752                                 "System", "OverflowException");
753                 g_assert (clause->data.catch_class);
754                 clause->handler_offset = mono_mb_get_label (mb);
755
756                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
757                                 "System", "OutOfMemoryException");
758                 g_assert (oom_exc_class);
759                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
760                 g_assert (ctor);
761
762                 mono_mb_emit_byte (mb, CEE_POP);
763                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
764                 mono_mb_emit_byte (mb, CEE_THROW);
765
766                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
767                 mono_mb_set_clauses (mb, 1, clause);
768                 mono_mb_patch_branch (mb, pos_leave);
769                 /* end catch */
770         } else {
771                 g_assert_not_reached ();
772         }
773
774         /* size += ALLOC_ALIGN - 1; */
775         mono_mb_emit_ldloc (mb, size_var);
776         mono_mb_emit_icon (mb, ALLOC_ALIGN - 1);
777         mono_mb_emit_byte (mb, CEE_ADD);
778         /* size &= ~(ALLOC_ALIGN - 1); */
779         mono_mb_emit_icon (mb, ~(ALLOC_ALIGN - 1));
780         mono_mb_emit_byte (mb, CEE_AND);
781         mono_mb_emit_stloc (mb, size_var);
782
783         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
784         if (atype != ATYPE_SMALL) {
785                 mono_mb_emit_ldloc (mb, size_var);
786                 mono_mb_emit_icon (mb, MAX_SMALL_OBJ_SIZE);
787                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
788         }
789
790         /*
791          * We need to modify tlab_next, but the JIT only supports reading, so we read
792          * another tls var holding its address instead.
793          */
794
795         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
796         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
797         EMIT_TLS_ACCESS (mb, tlab_next_addr, tlab_next_addr_offset);
798         mono_mb_emit_stloc (mb, tlab_next_addr_var);
799
800         /* p = (void**)tlab_next; */
801         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
802         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
803         mono_mb_emit_byte (mb, CEE_LDIND_I);
804         mono_mb_emit_stloc (mb, p_var);
805         
806         /* new_next = (char*)p + size; */
807         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
808         mono_mb_emit_ldloc (mb, p_var);
809         mono_mb_emit_ldloc (mb, size_var);
810         mono_mb_emit_byte (mb, CEE_CONV_I);
811         mono_mb_emit_byte (mb, CEE_ADD);
812         mono_mb_emit_stloc (mb, new_next_var);
813
814         /* if (G_LIKELY (new_next < tlab_temp_end)) */
815         mono_mb_emit_ldloc (mb, new_next_var);
816         EMIT_TLS_ACCESS (mb, tlab_temp_end, tlab_temp_end_offset);
817         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
818
819         /* Slowpath */
820         if (atype != ATYPE_SMALL)
821                 mono_mb_patch_short_branch (mb, max_size_branch);
822
823         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
824         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
825
826         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
827         mono_mb_emit_ldarg (mb, 0);
828         mono_mb_emit_ldloc (mb, size_var);
829         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
830                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
831         } else if (atype == ATYPE_VECTOR) {
832                 mono_mb_emit_ldarg (mb, 1);
833                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
834         } else {
835                 g_assert_not_reached ();
836         }
837         mono_mb_emit_byte (mb, CEE_RET);
838
839         /* Fastpath */
840         mono_mb_patch_short_branch (mb, slowpath_branch);
841
842         /* FIXME: Memory barrier */
843
844         /* tlab_next = new_next */
845         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
846         mono_mb_emit_ldloc (mb, new_next_var);
847         mono_mb_emit_byte (mb, CEE_STIND_I);
848
849         /*The tlab store must be visible before the the vtable store. This could be replaced with a DDS but doing it with IL would be tricky. */
850         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
851         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
852
853         /* *p = vtable; */
854         mono_mb_emit_ldloc (mb, p_var);
855         mono_mb_emit_ldarg (mb, 0);
856         mono_mb_emit_byte (mb, CEE_STIND_I);
857
858         if (atype == ATYPE_VECTOR) {
859                 /* arr->max_length = max_length; */
860                 mono_mb_emit_ldloc (mb, p_var);
861                 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, max_length));
862                 mono_mb_emit_ldarg (mb, 1);
863 #ifdef MONO_BIG_ARRAYS
864                 mono_mb_emit_byte (mb, CEE_STIND_I);
865 #else
866                 mono_mb_emit_byte (mb, CEE_STIND_I4);
867 #endif
868         }
869
870         /*
871         We must make sure both vtable and max_length are globaly visible before returning to managed land.
872         */
873         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
874         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
875
876         /* return p */
877         mono_mb_emit_ldloc (mb, p_var);
878         mono_mb_emit_byte (mb, CEE_RET);
879
880         res = mono_mb_create_method (mb, csig, 8);
881         mono_mb_free (mb);
882         mono_method_get_header (res)->init_locals = FALSE;
883
884         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
885         info->gc_name = "sgen";
886         info->alloc_type = atype;
887         mono_marshal_set_wrapper_info (res, info);
888
889         return res;
890 }
891 #endif
892
893 /*
894  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
895  * The signature of the called method is:
896  *      object allocate (MonoVTable *vtable)
897  */
898 MonoMethod*
899 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
900 {
901 #ifdef MANAGED_ALLOCATION
902         MonoClass *klass = vtable->klass;
903
904 #ifdef HAVE_KW_THREAD
905         int tlab_next_offset = -1;
906         int tlab_temp_end_offset = -1;
907         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
908         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
909
910         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
911                 return NULL;
912 #endif
913
914         if (!mono_runtime_has_tls_get ())
915                 return NULL;
916         if (klass->instance_size > tlab_size)
917                 return NULL;
918         if (klass->has_finalize || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
919                 return NULL;
920         if (klass->rank)
921                 return NULL;
922         if (klass->byval_arg.type == MONO_TYPE_STRING)
923                 return NULL;
924         if (collect_before_allocs)
925                 return NULL;
926
927         if (ALIGN_TO (klass->instance_size, ALLOC_ALIGN) < MAX_SMALL_OBJ_SIZE)
928                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL);
929         else
930                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL);
931 #else
932         return NULL;
933 #endif
934 }
935
936 MonoMethod*
937 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
938 {
939 #ifdef MANAGED_ALLOCATION
940         MonoClass *klass = vtable->klass;
941
942 #ifdef HAVE_KW_THREAD
943         int tlab_next_offset = -1;
944         int tlab_temp_end_offset = -1;
945         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
946         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
947
948         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
949                 return NULL;
950 #endif
951
952         if (rank != 1)
953                 return NULL;
954         if (!mono_runtime_has_tls_get ())
955                 return NULL;
956         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
957                 return NULL;
958         if (has_per_allocation_action)
959                 return NULL;
960         g_assert (!mono_class_has_finalizer (klass) && !klass->marshalbyref);
961
962         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
963 #else
964         return NULL;
965 #endif
966 }
967
968 MonoMethod*
969 mono_gc_get_managed_allocator_by_type (int atype)
970 {
971 #ifdef MANAGED_ALLOCATION
972         MonoMethod *res;
973
974         if (!mono_runtime_has_tls_get ())
975                 return NULL;
976
977         mono_loader_lock ();
978         res = alloc_method_cache [atype];
979         if (!res)
980                 res = alloc_method_cache [atype] = create_allocator (atype);
981         mono_loader_unlock ();
982         return res;
983 #else
984         return NULL;
985 #endif
986 }
987
988 guint32
989 mono_gc_get_managed_allocator_types (void)
990 {
991         return ATYPE_NUM;
992 }
993
994 gboolean
995 sgen_is_managed_allocator (MonoMethod *method)
996 {
997         int i;
998
999         for (i = 0; i < ATYPE_NUM; ++i)
1000                 if (method == alloc_method_cache [i])
1001                         return TRUE;
1002         return FALSE;
1003 }
1004
1005 #ifdef HEAVY_STATISTICS
1006 void
1007 sgen_alloc_init_heavy_stats (void)
1008 {
1009         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);     
1010         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
1011         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
1012 }
1013 #endif
1014
1015 #endif /*HAVE_SGEN_GC*/