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