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