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