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