Fix bugs in sizing TableLayoutPanel (Xamarin bug 18638)
[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                                 p = sgen_nursery_alloc (size);
295                                 if (!p) {
296                                         /*
297                                          * We couldn't allocate from the nursery, so we try
298                                          * collecting.  Even after the collection, we might
299                                          * still not have enough memory to allocate the
300                                          * object.  The reason will most likely be that we've
301                                          * run out of memory, but there is the theoretical
302                                          * possibility that other threads might have consumed
303                                          * the freed up memory ahead of us, so doing another
304                                          * collection and trying again might actually help.
305                                          * Of course the same thing might happen again.
306                                          *
307                                          * Ideally we'd like to detect that case and loop (if
308                                          * we always loop we will loop endlessly in the case of
309                                          * OOM).  What we do here is give up right away.
310                                          */
311                                         sgen_ensure_free_space (real_size);
312                                         if (degraded_mode)
313                                                 return alloc_degraded (vtable, size, FALSE);
314                                         else
315                                                 p = sgen_nursery_alloc (size);
316                                 }
317                                 SGEN_ASSERT (0, p, "Out of memory");
318
319                                 zero_tlab_if_necessary (p, size);
320                         } else {
321                                 size_t alloc_size = 0;
322                                 if (TLAB_START)
323                                         SGEN_LOG (3, "Retire TLAB: %p-%p [%ld]", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size));
324                                 sgen_nursery_retire_region (p, available_in_tlab);
325
326                                 p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
327                                 if (!p) {
328                                         /* See comment above in similar case. */
329                                         sgen_ensure_free_space (tlab_size);
330                                         if (degraded_mode)
331                                                 return alloc_degraded (vtable, size, FALSE);
332                                         else
333                                                 p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
334                                 }
335                                 SGEN_ASSERT (0, p, "Out of memory");
336
337                                 /* Allocate a new TLAB from the current nursery fragment */
338                                 TLAB_START = (char*)p;
339                                 TLAB_NEXT = TLAB_START;
340                                 TLAB_REAL_END = TLAB_START + alloc_size;
341                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
342
343                                 zero_tlab_if_necessary (TLAB_START, alloc_size);
344
345                                 /* Allocate from the TLAB */
346                                 p = (void*)TLAB_NEXT;
347                                 TLAB_NEXT += size;
348                                 sgen_set_nursery_scan_start ((char*)p);
349                         }
350                 } else {
351                         /* Reached tlab_temp_end */
352
353                         /* record the scan start so we can find pinned objects more easily */
354                         sgen_set_nursery_scan_start ((char*)p);
355                         /* we just bump tlab_temp_end as well */
356                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
357                         SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
358                 }
359                 CANARIFY_ALLOC(p,real_size);
360         }
361
362         if (G_LIKELY (p)) {
363                 SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
364                 binary_protocol_alloc (p, vtable, size);
365                 if (G_UNLIKELY (MONO_GC_MAJOR_OBJ_ALLOC_LARGE_ENABLED ()|| MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ())) {
366                         if (real_size > SGEN_MAX_SMALL_OBJ_SIZE)
367                                 MONO_GC_MAJOR_OBJ_ALLOC_LARGE ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
368                         else
369                                 MONO_GC_NURSERY_OBJ_ALLOC ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
370                 }
371                 mono_atomic_store_seq (p, vtable);
372         }
373
374         return p;
375 }
376
377 static void*
378 mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
379 {
380         void **p;
381         char *new_next;
382         TLAB_ACCESS_INIT;
383         size_t real_size = size;
384
385         CANARIFY_SIZE(size);
386
387         size = ALIGN_UP (size);
388         SGEN_ASSERT (9, real_size >= sizeof (MonoObject), "Object too small");
389
390         g_assert (vtable->gc_descr);
391         if (real_size > SGEN_MAX_SMALL_OBJ_SIZE)
392                 return NULL;
393
394         if (G_UNLIKELY (size > tlab_size)) {
395                 /* Allocate directly from the nursery */
396                 p = sgen_nursery_alloc (size);
397                 if (!p)
398                         return NULL;
399                 sgen_set_nursery_scan_start ((char*)p);
400
401                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
402                 zero_tlab_if_necessary (p, size);
403         } else {
404                 int available_in_tlab;
405                 char *real_end;
406                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
407
408                 p = (void**)TLAB_NEXT;
409                 /* FIXME: handle overflow */
410                 new_next = (char*)p + size;
411
412                 real_end = TLAB_REAL_END;
413                 available_in_tlab = (int)(real_end - (char*)p);//We'll never have tlabs > 2Gb
414
415                 if (G_LIKELY (new_next < real_end)) {
416                         TLAB_NEXT = new_next;
417
418                         /* Second case, we overflowed temp end */
419                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
420                                 sgen_set_nursery_scan_start (new_next);
421                                 /* we just bump tlab_temp_end as well */
422                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
423                                 SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
424                         }
425                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
426                         /* Allocate directly from the nursery */
427                         p = sgen_nursery_alloc (size);
428                         if (!p)
429                                 return NULL;
430
431                         zero_tlab_if_necessary (p, size);
432                 } else {
433                         size_t alloc_size = 0;
434
435                         sgen_nursery_retire_region (p, available_in_tlab);
436                         new_next = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
437                         p = (void**)new_next;
438                         if (!p)
439                                 return NULL;
440
441                         TLAB_START = (char*)new_next;
442                         TLAB_NEXT = new_next + size;
443                         TLAB_REAL_END = new_next + alloc_size;
444                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
445                         sgen_set_nursery_scan_start ((char*)p);
446
447                         zero_tlab_if_necessary (new_next, alloc_size);
448
449                         MONO_GC_NURSERY_TLAB_ALLOC ((mword)new_next, alloc_size);
450                 }
451         }
452
453         HEAVY_STAT (++stat_objects_alloced);
454         HEAVY_STAT (stat_bytes_alloced += size);
455
456         CANARIFY_ALLOC(p,real_size);
457         SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
458         binary_protocol_alloc (p, vtable, size);
459         if (G_UNLIKELY (MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ()))
460                 MONO_GC_NURSERY_OBJ_ALLOC ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
461         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
462
463         mono_atomic_store_seq (p, vtable);
464
465         return p;
466 }
467
468 void*
469 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
470 {
471         void *res;
472         TLAB_ACCESS_INIT;
473
474         if (!SGEN_CAN_ALIGN_UP (size))
475                 return NULL;
476
477 #ifndef DISABLE_CRITICAL_REGION
478
479         if (G_UNLIKELY (has_per_allocation_action)) {
480                 static int alloc_count;
481                 int current_alloc = InterlockedIncrement (&alloc_count);
482
483                 if (verify_before_allocs) {
484                         if ((current_alloc % verify_before_allocs) == 0)
485                                 sgen_check_whole_heap_stw ();
486                 }
487                 if (collect_before_allocs) {
488                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
489                                 LOCK_GC;
490                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered", TRUE);
491                                 UNLOCK_GC;
492                         }
493                 }
494         }
495
496         ENTER_CRITICAL_REGION;
497         res = mono_gc_try_alloc_obj_nolock (vtable, size);
498         if (res) {
499                 EXIT_CRITICAL_REGION;
500                 return res;
501         }
502         EXIT_CRITICAL_REGION;
503 #endif
504         LOCK_GC;
505         res = mono_gc_alloc_obj_nolock (vtable, size);
506         UNLOCK_GC;
507         if (G_UNLIKELY (!res))
508                 return mono_gc_out_of_memory (size);
509         return res;
510 }
511
512 void*
513 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
514 {
515         MonoArray *arr;
516         TLAB_ACCESS_INIT;
517
518         if (!SGEN_CAN_ALIGN_UP (size))
519                 return NULL;
520
521 #ifndef DISABLE_CRITICAL_REGION
522         ENTER_CRITICAL_REGION;
523         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
524         if (arr) {
525                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
526                 arr->max_length = (mono_array_size_t)max_length;
527                 EXIT_CRITICAL_REGION;
528                 return arr;
529         }
530         EXIT_CRITICAL_REGION;
531 #endif
532
533         LOCK_GC;
534
535         arr = mono_gc_alloc_obj_nolock (vtable, size);
536         if (G_UNLIKELY (!arr)) {
537                 UNLOCK_GC;
538                 return mono_gc_out_of_memory (size);
539         }
540
541         arr->max_length = (mono_array_size_t)max_length;
542
543         UNLOCK_GC;
544
545         return arr;
546 }
547
548 void*
549 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
550 {
551         MonoArray *arr;
552         MonoArrayBounds *bounds;
553         TLAB_ACCESS_INIT;
554
555         if (!SGEN_CAN_ALIGN_UP (size))
556                 return NULL;
557
558 #ifndef DISABLE_CRITICAL_REGION
559         ENTER_CRITICAL_REGION;
560         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
561         if (arr) {
562                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
563                 arr->max_length = (mono_array_size_t)max_length;
564
565                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
566                 arr->bounds = bounds;
567                 EXIT_CRITICAL_REGION;
568                 return arr;
569         }
570         EXIT_CRITICAL_REGION;
571 #endif
572
573         LOCK_GC;
574
575         arr = mono_gc_alloc_obj_nolock (vtable, size);
576         if (G_UNLIKELY (!arr)) {
577                 UNLOCK_GC;
578                 return mono_gc_out_of_memory (size);
579         }
580
581         arr->max_length = (mono_array_size_t)max_length;
582
583         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
584         arr->bounds = bounds;
585
586         UNLOCK_GC;
587
588         return arr;
589 }
590
591 void*
592 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
593 {
594         MonoString *str;
595         TLAB_ACCESS_INIT;
596
597         if (!SGEN_CAN_ALIGN_UP (size))
598                 return NULL;
599
600 #ifndef DISABLE_CRITICAL_REGION
601         ENTER_CRITICAL_REGION;
602         str = mono_gc_try_alloc_obj_nolock (vtable, size);
603         if (str) {
604                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
605                 str->length = len;
606                 EXIT_CRITICAL_REGION;
607                 return str;
608         }
609         EXIT_CRITICAL_REGION;
610 #endif
611
612         LOCK_GC;
613
614         str = mono_gc_alloc_obj_nolock (vtable, size);
615         if (G_UNLIKELY (!str)) {
616                 UNLOCK_GC;
617                 return mono_gc_out_of_memory (size);
618         }
619
620         str->length = len;
621
622         UNLOCK_GC;
623
624         return str;
625 }
626
627 /*
628  * To be used for interned strings and possibly MonoThread, reflection handles.
629  * We may want to explicitly free these objects.
630  */
631 void*
632 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
633 {
634         void **p;
635
636         if (!SGEN_CAN_ALIGN_UP (size))
637                 return NULL;
638         size = ALIGN_UP (size);
639
640         LOCK_GC;
641
642         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
643                 /* large objects are always pinned anyway */
644                 p = sgen_los_alloc_large_inner (vtable, size);
645         } else {
646                 SGEN_ASSERT (9, vtable->klass->inited, "class %s:%s is not initialized", vtable->klass->name_space, vtable->klass->name);
647                 p = major_collector.alloc_small_pinned_obj (vtable, size, SGEN_VTABLE_HAS_REFERENCES (vtable));
648         }
649         if (G_LIKELY (p)) {
650                 SGEN_LOG (6, "Allocated pinned object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
651                 if (size > SGEN_MAX_SMALL_OBJ_SIZE)
652                         MONO_GC_MAJOR_OBJ_ALLOC_LARGE ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
653                 else
654                         MONO_GC_MAJOR_OBJ_ALLOC_PINNED ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
655                 binary_protocol_alloc_pinned (p, vtable, size);
656         }
657         UNLOCK_GC;
658         return p;
659 }
660
661 void*
662 mono_gc_alloc_mature (MonoVTable *vtable)
663 {
664         void **res;
665         size_t size = vtable->klass->instance_size;
666
667         if (!SGEN_CAN_ALIGN_UP (size))
668                 return NULL;
669         size = ALIGN_UP (size);
670
671         LOCK_GC;
672         res = alloc_degraded (vtable, size, TRUE);
673         UNLOCK_GC;
674         if (G_UNLIKELY (vtable->klass->has_finalize))
675                 mono_object_register_finalizer ((MonoObject*)res);
676
677         return res;
678 }
679
680 void*
681 mono_gc_alloc_fixed (size_t size, void *descr)
682 {
683         /* FIXME: do a single allocation */
684         void *res = calloc (1, size);
685         if (!res)
686                 return NULL;
687         if (!mono_gc_register_root (res, size, descr)) {
688                 free (res);
689                 res = NULL;
690         }
691         return res;
692 }
693
694 void
695 mono_gc_free_fixed (void* addr)
696 {
697         mono_gc_deregister_root (addr);
698         free (addr);
699 }
700
701 void
702 sgen_init_tlab_info (SgenThreadInfo* info)
703 {
704 #ifndef HAVE_KW_THREAD
705         SgenThreadInfo *__thread_info__ = info;
706 #endif
707
708         info->tlab_start_addr = &TLAB_START;
709         info->tlab_next_addr = &TLAB_NEXT;
710         info->tlab_temp_end_addr = &TLAB_TEMP_END;
711         info->tlab_real_end_addr = &TLAB_REAL_END;
712
713 #ifdef HAVE_KW_THREAD
714         tlab_next_addr = &tlab_next;
715 #endif
716 }
717
718 /*
719  * Clear the thread local TLAB variables for all threads.
720  */
721 void
722 sgen_clear_tlabs (void)
723 {
724         SgenThreadInfo *info;
725
726         FOREACH_THREAD (info) {
727                 /* A new TLAB will be allocated when the thread does its first allocation */
728                 *info->tlab_start_addr = NULL;
729                 *info->tlab_next_addr = NULL;
730                 *info->tlab_temp_end_addr = NULL;
731                 *info->tlab_real_end_addr = NULL;
732         } END_FOREACH_THREAD
733 }
734
735 static MonoMethod* alloc_method_cache [ATYPE_NUM];
736
737 #ifdef MANAGED_ALLOCATION
738 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
739  * for each class. This is currently not easy to do, as it is hard to generate basic 
740  * blocks + branches, but it is easy with the linear IL codebase.
741  *
742  * For this to work we'd need to solve the TLAB race, first.  Now we
743  * require the allocator to be in a few known methods to make sure
744  * that they are executed atomically via the restart mechanism.
745  */
746 static MonoMethod*
747 create_allocator (int atype)
748 {
749         int p_var, size_var;
750         guint32 slowpath_branch, max_size_branch;
751         MonoMethodBuilder *mb;
752         MonoMethod *res;
753         MonoMethodSignature *csig;
754         static gboolean registered = FALSE;
755         int tlab_next_addr_var, new_next_var;
756         int num_params, i;
757         const char *name = NULL;
758         AllocatorWrapperInfo *info;
759
760 #ifdef HAVE_KW_THREAD
761         int tlab_next_addr_offset = -1;
762         int tlab_temp_end_offset = -1;
763
764         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
765         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
766
767         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_NEXT_ADDR, tlab_next_addr_offset);
768         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_TEMP_END, tlab_temp_end_offset);
769
770         g_assert (tlab_next_addr_offset != -1);
771         g_assert (tlab_temp_end_offset != -1);
772 #endif
773
774         if (!registered) {
775                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
776                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
777                 mono_register_jit_icall (mono_gc_alloc_string, "mono_gc_alloc_string", mono_create_icall_signature ("object ptr int int32"), FALSE);
778                 registered = TRUE;
779         }
780
781         if (atype == ATYPE_SMALL) {
782                 num_params = 1;
783                 name = "AllocSmall";
784         } else if (atype == ATYPE_NORMAL) {
785                 num_params = 1;
786                 name = "Alloc";
787         } else if (atype == ATYPE_VECTOR) {
788                 num_params = 2;
789                 name = "AllocVector";
790         } else if (atype == ATYPE_STRING) {
791                 num_params = 2;
792                 name = "AllocString";
793         } else {
794                 g_assert_not_reached ();
795         }
796
797         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
798         if (atype == ATYPE_STRING) {
799                 csig->ret = &mono_defaults.string_class->byval_arg;
800                 csig->params [0] = &mono_defaults.int_class->byval_arg;
801                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
802         } else {
803                 csig->ret = &mono_defaults.object_class->byval_arg;
804                 for (i = 0; i < num_params; ++i)
805                         csig->params [i] = &mono_defaults.int_class->byval_arg;
806         }
807
808         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
809
810 #ifndef DISABLE_JIT
811         size_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
812         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
813                 /* size = vtable->klass->instance_size; */
814                 mono_mb_emit_ldarg (mb, 0);
815                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
816                 mono_mb_emit_byte (mb, CEE_ADD);
817                 mono_mb_emit_byte (mb, CEE_LDIND_I);
818                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, instance_size));
819                 mono_mb_emit_byte (mb, CEE_ADD);
820                 /* FIXME: assert instance_size stays a 4 byte integer */
821                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
822                 mono_mb_emit_byte (mb, CEE_CONV_I);
823                 mono_mb_emit_stloc (mb, size_var);
824         } else if (atype == ATYPE_VECTOR) {
825                 MonoExceptionClause *clause;
826                 int pos, pos_leave, pos_error;
827                 MonoClass *oom_exc_class;
828                 MonoMethod *ctor;
829
830                 /*
831                  * n > MONO_ARRAY_MAX_INDEX => OutOfMemoryException
832                  * n < 0                    => OverflowException
833                  *
834                  * We can do an unsigned comparison to catch both cases, then in the error
835                  * case compare signed to distinguish between them.
836                  */
837                 mono_mb_emit_ldarg (mb, 1);
838                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
839                 mono_mb_emit_byte (mb, CEE_CONV_U);
840                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
841
842                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
843                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
844                 mono_mb_emit_ldarg (mb, 1);
845                 mono_mb_emit_icon (mb, 0);
846                 pos_error = mono_mb_emit_short_branch (mb, CEE_BLT_S);
847                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
848                 mono_mb_patch_short_branch (mb, pos_error);
849                 mono_mb_emit_exception (mb, "OverflowException", NULL);
850
851                 mono_mb_patch_short_branch (mb, pos);
852
853                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
854                 clause->try_offset = mono_mb_get_label (mb);
855
856                 /* vtable->klass->sizes.element_size */
857                 mono_mb_emit_ldarg (mb, 0);
858                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
859                 mono_mb_emit_byte (mb, CEE_ADD);
860                 mono_mb_emit_byte (mb, CEE_LDIND_I);
861                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
862                 mono_mb_emit_byte (mb, CEE_ADD);
863                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
864                 mono_mb_emit_byte (mb, CEE_CONV_I);
865
866                 /* * n */
867                 mono_mb_emit_ldarg (mb, 1);
868                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
869                 /* + sizeof (MonoArray) */
870                 mono_mb_emit_icon (mb, sizeof (MonoArray));
871                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
872                 mono_mb_emit_stloc (mb, size_var);
873
874                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
875
876                 /* catch */
877                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
878                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
879                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
880                                 "System", "OverflowException");
881                 g_assert (clause->data.catch_class);
882                 clause->handler_offset = mono_mb_get_label (mb);
883
884                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
885                                 "System", "OutOfMemoryException");
886                 g_assert (oom_exc_class);
887                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
888                 g_assert (ctor);
889
890                 mono_mb_emit_byte (mb, CEE_POP);
891                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
892                 mono_mb_emit_byte (mb, CEE_THROW);
893
894                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
895                 mono_mb_set_clauses (mb, 1, clause);
896                 mono_mb_patch_branch (mb, pos_leave);
897                 /* end catch */
898         } else if (atype == ATYPE_STRING) {
899                 int pos;
900
901                 /*
902                  * a string allocator method takes the args: (vtable, len)
903                  *
904                  * bytes = offsetof (MonoString, chars) + ((len + 1) * 2)
905                  *
906                  * condition:
907                  *
908                  * bytes <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
909                  *
910                  * therefore:
911                  *
912                  * offsetof (MonoString, chars) + ((len + 1) * 2) <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
913                  * len <= (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - offsetof (MonoString, chars)) / 2 - 1
914                  */
915                 mono_mb_emit_ldarg (mb, 1);
916                 mono_mb_emit_icon (mb, (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - MONO_STRUCT_OFFSET (MonoString, chars)) / 2 - 1);
917                 pos = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
918
919                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
920                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
921                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
922                 mono_mb_patch_short_branch (mb, pos);
923
924                 mono_mb_emit_ldarg (mb, 1);
925                 mono_mb_emit_icon (mb, 1);
926                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
927                 //WE manually fold the above + 2 here
928                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, chars) + 2);
929                 mono_mb_emit_byte (mb, CEE_ADD);
930                 mono_mb_emit_stloc (mb, size_var);
931         } else {
932                 g_assert_not_reached ();
933         }
934
935         /* size += ALLOC_ALIGN - 1; */
936         mono_mb_emit_ldloc (mb, size_var);
937         mono_mb_emit_icon (mb, ALLOC_ALIGN - 1);
938         mono_mb_emit_byte (mb, CEE_ADD);
939         /* size &= ~(ALLOC_ALIGN - 1); */
940         mono_mb_emit_icon (mb, ~(ALLOC_ALIGN - 1));
941         mono_mb_emit_byte (mb, CEE_AND);
942         mono_mb_emit_stloc (mb, size_var);
943
944         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
945         if (atype != ATYPE_SMALL) {
946                 mono_mb_emit_ldloc (mb, size_var);
947                 mono_mb_emit_icon (mb, MAX_SMALL_OBJ_SIZE);
948                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
949         }
950
951         /*
952          * We need to modify tlab_next, but the JIT only supports reading, so we read
953          * another tls var holding its address instead.
954          */
955
956         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
957         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
958         EMIT_TLS_ACCESS_NEXT_ADDR (mb);
959         mono_mb_emit_stloc (mb, tlab_next_addr_var);
960
961         /* p = (void**)tlab_next; */
962         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
963         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
964         mono_mb_emit_byte (mb, CEE_LDIND_I);
965         mono_mb_emit_stloc (mb, p_var);
966         
967         /* new_next = (char*)p + size; */
968         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
969         mono_mb_emit_ldloc (mb, p_var);
970         mono_mb_emit_ldloc (mb, size_var);
971         mono_mb_emit_byte (mb, CEE_CONV_I);
972         mono_mb_emit_byte (mb, CEE_ADD);
973         mono_mb_emit_stloc (mb, new_next_var);
974
975         /* if (G_LIKELY (new_next < tlab_temp_end)) */
976         mono_mb_emit_ldloc (mb, new_next_var);
977         EMIT_TLS_ACCESS_TEMP_END (mb);
978         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
979
980         /* Slowpath */
981         if (atype != ATYPE_SMALL)
982                 mono_mb_patch_short_branch (mb, max_size_branch);
983
984         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
985         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
986
987         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
988         mono_mb_emit_ldarg (mb, 0);
989         mono_mb_emit_ldloc (mb, size_var);
990         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
991                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
992         } else if (atype == ATYPE_VECTOR) {
993                 mono_mb_emit_ldarg (mb, 1);
994                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
995         } else if (atype == ATYPE_STRING) {
996                 mono_mb_emit_ldarg (mb, 1);
997                 mono_mb_emit_icall (mb, mono_gc_alloc_string);
998         } else {
999                 g_assert_not_reached ();
1000         }
1001         mono_mb_emit_byte (mb, CEE_RET);
1002
1003         /* Fastpath */
1004         mono_mb_patch_short_branch (mb, slowpath_branch);
1005
1006         /* FIXME: Memory barrier */
1007
1008         /* tlab_next = new_next */
1009         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
1010         mono_mb_emit_ldloc (mb, new_next_var);
1011         mono_mb_emit_byte (mb, CEE_STIND_I);
1012
1013         /*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. */
1014         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
1015         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, (gpointer)StoreStoreBarrier);
1016
1017         /* *p = vtable; */
1018         mono_mb_emit_ldloc (mb, p_var);
1019         mono_mb_emit_ldarg (mb, 0);
1020         mono_mb_emit_byte (mb, CEE_STIND_I);
1021
1022         if (atype == ATYPE_VECTOR) {
1023                 /* arr->max_length = max_length; */
1024                 mono_mb_emit_ldloc (mb, p_var);
1025                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, max_length));
1026                 mono_mb_emit_ldarg (mb, 1);
1027 #ifdef MONO_BIG_ARRAYS
1028                 mono_mb_emit_byte (mb, CEE_STIND_I);
1029 #else
1030                 mono_mb_emit_byte (mb, CEE_STIND_I4);
1031 #endif
1032         } else  if (atype == ATYPE_STRING) {
1033                 /* need to set length and clear the last char */
1034                 /* s->length = len; */
1035                 mono_mb_emit_ldloc (mb, p_var);
1036                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, length));
1037                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1038                 mono_mb_emit_ldarg (mb, 1);
1039                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
1040                 /* s->chars [len] = 0; */
1041                 mono_mb_emit_ldloc (mb, p_var);
1042                 mono_mb_emit_ldloc (mb, size_var);
1043                 mono_mb_emit_icon (mb, 2);
1044                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
1045                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1046                 mono_mb_emit_icon (mb, 0);
1047                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
1048         }
1049
1050         /*
1051         We must make sure both vtable and max_length are globaly visible before returning to managed land.
1052         */
1053         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
1054         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, (gpointer)StoreStoreBarrier);
1055
1056         /* return p */
1057         mono_mb_emit_ldloc (mb, p_var);
1058         mono_mb_emit_byte (mb, CEE_RET);
1059 #endif
1060
1061         res = mono_mb_create_method (mb, csig, 8);
1062         mono_mb_free (mb);
1063         mono_method_get_header (res)->init_locals = FALSE;
1064
1065         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
1066         info->gc_name = "sgen";
1067         info->alloc_type = atype;
1068         mono_marshal_set_wrapper_info (res, info);
1069
1070         return res;
1071 }
1072 #endif
1073
1074 /*
1075  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
1076  * The signature of the called method is:
1077  *      object allocate (MonoVTable *vtable)
1078  */
1079 MonoMethod*
1080 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box)
1081 {
1082 #ifdef MANAGED_ALLOCATION
1083
1084 #ifdef HAVE_KW_THREAD
1085         int tlab_next_offset = -1;
1086         int tlab_temp_end_offset = -1;
1087         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
1088         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
1089
1090         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
1091                 return NULL;
1092 #endif
1093         if (collect_before_allocs)
1094                 return NULL;
1095         if (!mono_runtime_has_tls_get ())
1096                 return NULL;
1097         if (klass->instance_size > tlab_size)
1098                 return NULL;
1099
1100         if (klass->has_finalize || mono_class_is_marshalbyref (klass) || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
1101                 return NULL;
1102         if (klass->rank)
1103                 return NULL;
1104         if (klass->byval_arg.type == MONO_TYPE_STRING)
1105                 return mono_gc_get_managed_allocator_by_type (ATYPE_STRING);
1106         /* Generic classes have dynamic field and can go above MAX_SMALL_OBJ_SIZE. */
1107         if (ALIGN_TO (klass->instance_size, ALLOC_ALIGN) < MAX_SMALL_OBJ_SIZE && !mono_class_is_open_constructed_type (&klass->byval_arg))
1108                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL);
1109         else
1110                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL);
1111 #else
1112         return NULL;
1113 #endif
1114 }
1115
1116 MonoMethod*
1117 mono_gc_get_managed_array_allocator (MonoClass *klass)
1118 {
1119 #ifdef MANAGED_ALLOCATION
1120 #ifdef HAVE_KW_THREAD
1121         int tlab_next_offset = -1;
1122         int tlab_temp_end_offset = -1;
1123         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
1124         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
1125
1126         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
1127                 return NULL;
1128 #endif
1129
1130         if (klass->rank != 1)
1131                 return NULL;
1132         if (!mono_runtime_has_tls_get ())
1133                 return NULL;
1134         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
1135                 return NULL;
1136         if (has_per_allocation_action)
1137                 return NULL;
1138         g_assert (!mono_class_has_finalizer (klass) && !mono_class_is_marshalbyref (klass));
1139
1140         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
1141 #else
1142         return NULL;
1143 #endif
1144 }
1145
1146 void
1147 sgen_set_use_managed_allocator (gboolean flag)
1148 {
1149         use_managed_allocator = flag;
1150 }
1151
1152 MonoMethod*
1153 mono_gc_get_managed_allocator_by_type (int atype)
1154 {
1155 #ifdef MANAGED_ALLOCATION
1156         MonoMethod *res;
1157
1158         if (!use_managed_allocator)
1159                 return NULL;
1160
1161         if (!mono_runtime_has_tls_get ())
1162                 return NULL;
1163
1164         res = alloc_method_cache [atype];
1165         if (res)
1166                 return res;
1167
1168         res = create_allocator (atype);
1169         LOCK_GC;
1170         if (alloc_method_cache [atype]) {
1171                 mono_free_method (res);
1172                 res = alloc_method_cache [atype];
1173         } else {
1174                 mono_memory_barrier ();
1175                 alloc_method_cache [atype] = res;
1176         }
1177         UNLOCK_GC;
1178
1179         return res;
1180 #else
1181         return NULL;
1182 #endif
1183 }
1184
1185 guint32
1186 mono_gc_get_managed_allocator_types (void)
1187 {
1188         return ATYPE_NUM;
1189 }
1190
1191 gboolean
1192 sgen_is_managed_allocator (MonoMethod *method)
1193 {
1194         int i;
1195
1196         for (i = 0; i < ATYPE_NUM; ++i)
1197                 if (method == alloc_method_cache [i])
1198                         return TRUE;
1199         return FALSE;
1200 }
1201
1202 gboolean
1203 sgen_has_managed_allocator (void)
1204 {
1205         int i;
1206
1207         for (i = 0; i < ATYPE_NUM; ++i)
1208                 if (alloc_method_cache [i])
1209                         return TRUE;
1210         return FALSE;
1211 }       
1212
1213 #ifdef HEAVY_STATISTICS
1214 void
1215 sgen_alloc_init_heavy_stats (void)
1216 {
1217         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);     
1218         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
1219         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
1220 }
1221 #endif
1222
1223 #endif /*HAVE_SGEN_GC*/