The OpenD Programming Language

1 /**
2  * This module provides an interface to the garbage collector used by
3  * applications written in the D programming language. It allows the
4  * garbage collector in the runtime to be swapped without affecting
5  * binary compatibility of applications.
6  *
7  * Using this module is not necessary in typical D code. It is mostly
8  * useful when doing low-level _memory management.
9  *
10  * Notes_to_users:
11  *
12    $(OL
13    $(LI The GC is a conservative mark-and-sweep collector. It only runs a
14         collection cycle when an allocation is requested of it, never
15         otherwise. Hence, if the program is not doing allocations,
16         there will be no GC collection pauses. The pauses occur because
17         all threads the GC knows about are halted so the threads' stacks
18         and registers can be scanned for references to GC allocated data.
19    )
20 
21    $(LI The GC does not know about threads that were created by directly calling
22         the OS/C runtime thread creation APIs and D threads that were detached
23         from the D runtime after creation.
24         Such threads will not be paused for a GC collection, and the GC might not detect
25         references to GC allocated data held by them. This can cause memory corruption.
26         There are several ways to resolve this issue:
27         $(OL
28         $(LI Do not hold references to GC allocated data in such threads.)
29         $(LI Register/unregister such data with calls to $(LREF addRoot)/$(LREF removeRoot) and
30         $(LREF addRange)/$(LREF removeRange).)
31         $(LI Maintain another reference to that same data in another thread that the
32         GC does know about.)
33         $(LI Disable GC collection cycles while that thread is active with $(LREF disable)/$(LREF enable).)
34         $(LI Register the thread with the GC using $(REF thread_attachThis, core,thread,osthread)/$(REF thread_detachThis, core,thread,threadbase).)
35         )
36    )
37    )
38  *
39  * Notes_to_implementors:
40  * $(UL
41  * $(LI On POSIX systems, the signals `SIGRTMIN` and `SIGRTMIN + 1` are reserved
42  *   by this module for use in the garbage collector implementation.
43  *   Typically, they will be used to stop and resume other threads
44  *   when performing a collection, but an implementation may choose
45  *   not to use this mechanism (or not stop the world at all, in the
46  *   case of concurrent garbage collectors).)
47  *
48  * $(LI Registers, the stack, and any other _memory locations added through
49  *   the $(D GC.$(LREF addRange)) function are always scanned conservatively.
50  *   This means that even if a variable is e.g. of type $(D float),
51  *   it will still be scanned for possible GC pointers. And, if the
52  *   word-interpreted representation of the variable matches a GC-managed
53  *   _memory block's address, that _memory block is considered live.)
54  *
55  * $(LI Implementations are free to scan the non-root heap in a precise
56  *   manner, so that fields of types like $(D float) will not be considered
57  *   relevant when scanning the heap. Thus, casting a GC pointer to an
58  *   integral type (e.g. $(D size_t)) and storing it in a field of that
59  *   type inside the GC heap may mean that it will not be recognized
60  *   if the _memory block was allocated with precise type info or with
61  *   the $(D GC.BlkAttr.$(LREF NO_SCAN)) attribute.)
62  *
63  * $(LI Destructors will always be executed while other threads are
64  *   active; that is, an implementation that stops the world must not
65  *   execute destructors until the world has been resumed.)
66  *
67  * $(LI A destructor of an object must not access object references
68  *   within the object. This means that an implementation is free to
69  *   optimize based on this rule.)
70  *
71  * $(LI An implementation is free to perform heap compaction and copying
72  *   so long as no valid GC pointers are invalidated in the process.
73  *   However, _memory allocated with $(D GC.BlkAttr.$(LREF NO_MOVE)) must
74  *   not be moved/copied.)
75  *
76  * $(LI Implementations must support interior pointers. That is, if the
77  *   only reference to a GC-managed _memory block points into the
78  *   middle of the block rather than the beginning (for example), the
79  *   GC must consider the _memory block live. The exception to this
80  *   rule is when a _memory block is allocated with the
81  *   $(D GC.BlkAttr.$(LREF NO_INTERIOR)) attribute; it is the user's
82  *   responsibility to make sure such _memory blocks have a proper pointer
83  *   to them when they should be considered live.)
84  *
85  * $(LI It is acceptable for an implementation to store bit flags into
86  *   pointer values and GC-managed _memory blocks, so long as such a
87  *   trick is not visible to the application. In practice, this means
88  *   that only a stop-the-world collector can do this.)
89  *
90  * $(LI Implementations are free to assume that GC pointers are only
91  *   stored on word boundaries. Unaligned pointers may be ignored
92  *   entirely.)
93  *
94  * $(LI Implementations are free to run collections at any point. It is,
95  *   however, recommendable to only do so when an allocation attempt
96  *   happens and there is insufficient _memory available.)
97  * )
98  *
99  * Copyright: Copyright Sean Kelly 2005 - 2015.
100  * License:   $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
101  * Authors:   Sean Kelly, Alex Rønne Petersen
102  * Source:    $(DRUNTIMESRC core/_memory.d)
103  */
104 
105 module core.memory;
106 
107 version (ARM)
108     version = AnyARM;
109 else version (AArch64)
110     version = AnyARM;
111 
112 version (iOS)
113     version = iOSDerived;
114 else version (TVOS)
115     version = iOSDerived;
116 else version (WatchOS)
117     version = iOSDerived;
118 
119 private
120 {
121     extern (C) uint gc_getAttr( void* p ) pure nothrow;
122     extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow;
123     extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow;
124 
125     extern (C) void*   gc_addrOf( void* p ) pure nothrow @nogc;
126     extern (C) size_t  gc_sizeOf( void* p ) pure nothrow @nogc;
127 
128     struct BlkInfo_
129     {
130         void*  base;
131         size_t size;
132         uint   attr;
133     }
134 
135     extern (C) BlkInfo_ gc_query(return scope void* p) pure nothrow;
136     extern (C) GC.Stats gc_stats ( ) @safe nothrow @nogc;
137     extern (C) GC.ProfileStats gc_profileStats ( ) nothrow @nogc @safe;
138 }
139 
140 version (CoreDoc)
141 {
142     /**
143      * The minimum size of a system page in bytes.
144      *
145      * This is a compile time, platform specific value. This value might not
146      * be accurate, since it might be possible to change this value. Whenever
147      * possible, please use $(LREF pageSize) instead, which is initialized
148      * during runtime.
149      *
150      * The minimum size is useful when the context requires a compile time known
151      * value, like the size of a static array: `ubyte[minimumPageSize] buffer`.
152      */
153     enum minimumPageSize : size_t;
154 }
155 else version (AnyARM)
156 {
157     version (iOSDerived)
158         enum size_t minimumPageSize = 16384;
159     else
160         enum size_t minimumPageSize = 4096;
161 }
162 else
163     enum size_t minimumPageSize = 4096;
164 
165 ///
166 unittest
167 {
168     ubyte[minimumPageSize] buffer;
169 }
170 
171 /**
172  * The size of a system page in bytes.
173  *
174  * This value is set at startup time of the application. It's safe to use
175  * early in the start process, like in shared module constructors and
176  * initialization of the D runtime itself.
177  */
178 immutable size_t pageSize;
179 
180 ///
181 unittest
182 {
183     ubyte[] buffer = new ubyte[pageSize];
184 }
185 
186 // The reason for this elaborated way of declaring a function is:
187 //
188 // * `pragma(crt_constructor)` is used to declare a constructor that is called by
189 // the C runtime, before C main. This allows the `pageSize` value to be used
190 // during initialization of the D runtime. This also avoids any issues with
191 // static module constructors and circular references.
192 //
193 // * `pragma(mangle)` is used because `pragma(crt_constructor)` requires a
194 // function with C linkage. To avoid any name conflict with other C symbols,
195 // standard D mangling is used.
196 //
197 // * The extra function declaration, without the body, is to be able to get the
198 // D mangling of the function without the need to hardcode the value.
199 //
200 // * The extern function declaration also has the side effect of making it
201 // impossible to manually call the function with standard syntax. This is to
202 // make it more difficult to call the function again, manually.
203 private void initialize();
204 pragma(crt_constructor)
205 pragma(mangle, initialize.mangleof)
206 private extern (C) void _initialize() @system
207 {
208     version (Posix)
209     {
210         import core.sys.posix.unistd : sysconf, _SC_PAGESIZE;
211 
212         (cast() pageSize) = cast(size_t) sysconf(_SC_PAGESIZE);
213     }
214     else version (Windows)
215     {
216         import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO;
217 
218         SYSTEM_INFO si;
219         GetSystemInfo(&si);
220         (cast() pageSize) = cast(size_t) si.dwPageSize;
221     }
222     else version (FreeStanding)
223     {
224 
225     }
226     else
227         static assert(false, __FUNCTION__ ~ " is not implemented on this platform");
228 }
229 
230 /**
231  * This struct encapsulates all garbage collection functionality for the D
232  * programming language.
233  */
234 struct GC
235 {
236     @disable this();
237 
238     /**
239      * Aggregation of GC stats to be exposed via public API
240      */
241     static struct Stats
242     {
243         /// number of used bytes on the GC heap (might only get updated after a collection)
244         size_t usedSize;
245         /// number of free bytes on the GC heap (might only get updated after a collection)
246         size_t freeSize;
247         /// number of bytes allocated for current thread since program start
248         ulong allocatedInCurrentThread;
249     }
250 
251     /**
252      * Aggregation of current profile information
253      */
254     static struct ProfileStats
255     {
256         import core.time : Duration;
257         /// total number of GC cycles
258         size_t numCollections;
259         /// total time spent doing GC
260         Duration totalCollectionTime;
261         /// total time threads were paused doing GC
262         Duration totalPauseTime;
263         /// largest time threads were paused during one GC cycle
264         Duration maxPauseTime;
265         /// largest time spent doing one GC cycle
266         Duration maxCollectionTime;
267     }
268 
269 extern(C):
270 
271     /**
272      * Enables automatic garbage collection behavior if collections have
273      * previously been suspended by a call to disable.  This function is
274      * reentrant, and must be called once for every call to disable before
275      * automatic collections are enabled.
276      */
277     pragma(mangle, "gc_enable") static void enable() @safe nothrow pure;
278 
279 
280     /**
281      * Disables automatic garbage collections performed to minimize the
282      * process footprint.  Collections may continue to occur in instances
283      * where the implementation deems necessary for correct program behavior,
284      * such as during an out of memory condition.  This function is reentrant,
285      * but enable must be called once for each call to disable.
286      */
287     pragma(mangle, "gc_disable") static void disable() @safe nothrow pure;
288 
289 
290     /**
291      * Begins a full collection.  While the meaning of this may change based
292      * on the garbage collector implementation, typical behavior is to scan
293      * all stack segments for roots, mark accessible memory blocks as alive,
294      * and then to reclaim free space.  This action may need to suspend all
295      * running threads for at least part of the collection process.
296      */
297     pragma(mangle, "gc_collect") static void collect() @safe nothrow pure;
298 
299     /**
300      * Indicates that the managed memory space be minimized by returning free
301      * physical memory to the operating system.  The amount of free memory
302      * returned depends on the allocator design and on program behavior.
303      */
304     pragma(mangle, "gc_minimize") static void minimize() @safe nothrow pure;
305 
306 extern(D):
307 
308     /**
309      * Elements for a bit field representing memory block attributes.  These
310      * are manipulated via the getAttr, setAttr, clrAttr functions.
311      */
312     enum BlkAttr : uint
313     {
314         NONE        = 0b0000_0000, /// No attributes set.
315         FINALIZE    = 0b0000_0001, /// Finalize the data in this block on collect.
316         NO_SCAN     = 0b0000_0010, /// Do not scan through this block on collect.
317         NO_MOVE     = 0b0000_0100, /// Do not move this memory block on collect.
318         /**
319         This block contains the info to allow appending.
320 
321         This can be used to manually allocate arrays. Initial slice size is 0.
322 
323         Note: The slice's usable size will not match the block size. Use
324         $(LREF capacity) to retrieve actual usable capacity.
325 
326         Example:
327         ----
328         // Allocate the underlying array.
329         int*  pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE);
330         // Bind a slice. Check the slice has capacity information.
331         int[] slice = pToArray[0 .. 0];
332         assert(capacity(slice) > 0);
333         // Appending to the slice will not relocate it.
334         slice.length = 5;
335         slice ~= 1;
336         assert(slice.ptr == p);
337         ----
338         */
339         APPENDABLE  = 0b0000_1000,
340 
341         /**
342         This block is guaranteed to have a pointer to its base while it is
343         alive.  Interior pointers can be safely ignored.  This attribute is
344         useful for eliminating false pointers in very large data structures
345         and is only implemented for data structures at least a page in size.
346         */
347         NO_INTERIOR = 0b0001_0000,
348 
349         STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs
350     }
351 
352 
353     /**
354      * Contains aggregate information about a block of managed memory.  The
355      * purpose of this struct is to support a more efficient query style in
356      * instances where detailed information is needed.
357      *
358      * base = A pointer to the base of the block in question.
359      * size = The size of the block, calculated from base.
360      * attr = Attribute bits set on the memory block.
361      */
362     alias BlkInfo = BlkInfo_;
363 
364 
365     /**
366      * Returns a bit field representing all block attributes set for the memory
367      * referenced by p.  If p references memory not originally allocated by
368      * this garbage collector, points to the interior of a memory block, or if
369      * p is null, zero will be returned.
370      *
371      * Params:
372      *  p = A pointer to the root of a valid memory block or to null.
373      *
374      * Returns:
375      *  A bit field containing any bits set for the memory block referenced by
376      *  p or zero on error.
377      */
378     static uint getAttr( const scope void* p ) nothrow
379     {
380         return gc_getAttr(cast(void*) p);
381     }
382 
383 
384     /// ditto
385     static uint getAttr(void* p) pure nothrow
386     {
387         return gc_getAttr( p );
388     }
389 
390 
391     /**
392      * Sets the specified bits for the memory references by p.  If p references
393      * memory not originally allocated by this garbage collector, points to the
394      * interior of a memory block, or if p is null, no action will be
395      * performed.
396      *
397      * Params:
398      *  p = A pointer to the root of a valid memory block or to null.
399      *  a = A bit field containing any bits to set for this memory block.
400      *
401      * Returns:
402      *  The result of a call to getAttr after the specified bits have been
403      *  set.
404      */
405     static uint setAttr( const scope void* p, uint a ) nothrow
406     {
407         return gc_setAttr(cast(void*) p, a);
408     }
409 
410 
411     /// ditto
412     static uint setAttr(void* p, uint a) pure nothrow
413     {
414         return gc_setAttr( p, a );
415     }
416 
417 
418     /**
419      * Clears the specified bits for the memory references by p.  If p
420      * references memory not originally allocated by this garbage collector,
421      * points to the interior of a memory block, or if p is null, no action
422      * will be performed.
423      *
424      * Params:
425      *  p = A pointer to the root of a valid memory block or to null.
426      *  a = A bit field containing any bits to clear for this memory block.
427      *
428      * Returns:
429      *  The result of a call to getAttr after the specified bits have been
430      *  cleared.
431      */
432     static uint clrAttr( const scope void* p, uint a ) nothrow
433     {
434         return gc_clrAttr(cast(void*) p, a);
435     }
436 
437 
438     /// ditto
439     static uint clrAttr(void* p, uint a) pure nothrow
440     {
441         return gc_clrAttr( p, a );
442     }
443 
444 extern(C):
445 
446     /**
447      * Requests an aligned block of managed memory from the garbage collector.
448      * This memory may be deleted at will with a call to free, or it may be
449      * discarded and cleaned up automatically during a collection run.  If
450      * allocation fails, this function will call onOutOfMemory which is
451      * expected to throw an OutOfMemoryError.
452      *
453      * Params:
454      *  sz = The desired allocation size in bytes.
455      *  ba = A bitmask of the attributes to set on this block.
456      *  ti = TypeInfo to describe the memory. The GC might use this information
457      *       to improve scanning for pointers or to call finalizers.
458      *
459      * Returns:
460      *  A reference to the allocated memory or null if insufficient memory
461      *  is available.
462      *
463      * Throws:
464      *  OutOfMemoryError on allocation failure.
465      */
466     version (D_ProfileGC)
467         pragma(mangle, "gc_mallocTrace") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null,
468             string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
469     else
470         pragma(mangle, "gc_malloc") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
471 
472     /**
473      * Requests an aligned block of managed memory from the garbage collector.
474      * This memory may be deleted at will with a call to free, or it may be
475      * discarded and cleaned up automatically during a collection run.  If
476      * allocation fails, this function will call onOutOfMemory which is
477      * expected to throw an OutOfMemoryError.
478      *
479      * Params:
480      *  sz = The desired allocation size in bytes.
481      *  ba = A bitmask of the attributes to set on this block.
482      *  ti = TypeInfo to describe the memory. The GC might use this information
483      *       to improve scanning for pointers or to call finalizers.
484      *
485      * Returns:
486      *  Information regarding the allocated memory block or BlkInfo.init on
487      *  error.
488      *
489      * Throws:
490      *  OutOfMemoryError on allocation failure.
491      */
492     version (D_ProfileGC)
493         pragma(mangle, "gc_qallocTrace") static BlkInfo qalloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null,
494             string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
495     else
496         pragma(mangle, "gc_qalloc") static BlkInfo qalloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
497 
498 
499     /**
500      * Requests an aligned block of managed memory from the garbage collector,
501      * which is initialized with all bits set to zero.  This memory may be
502      * deleted at will with a call to free, or it may be discarded and cleaned
503      * up automatically during a collection run.  If allocation fails, this
504      * function will call onOutOfMemory which is expected to throw an
505      * OutOfMemoryError.
506      *
507      * Params:
508      *  sz = The desired allocation size in bytes.
509      *  ba = A bitmask of the attributes to set on this block.
510      *  ti = TypeInfo to describe the memory. The GC might use this information
511      *       to improve scanning for pointers or to call finalizers.
512      *
513      * Returns:
514      *  A reference to the allocated memory or null if insufficient memory
515      *  is available.
516      *
517      * Throws:
518      *  OutOfMemoryError on allocation failure.
519      */
520     version (D_ProfileGC)
521         pragma(mangle, "gc_callocTrace") static void* calloc(size_t sz, uint ba = 0, const TypeInfo ti = null,
522             string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
523     else
524         pragma(mangle, "gc_calloc") static void* calloc(size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
525 
526 
527     /**
528      * Extend, shrink or allocate a new block of memory keeping the contents of
529      * an existing block
530      *
531      * If `sz` is zero, the memory referenced by p will be deallocated as if
532      * by a call to `free`.
533      * If `p` is `null`, new memory will be allocated via `malloc`.
534      * If `p` is pointing to memory not allocated from the GC or to the interior
535      * of an allocated memory block, no operation is performed and null is returned.
536      *
537      * Otherwise, a new memory block of size `sz` will be allocated as if by a
538      * call to `malloc`, or the implementation may instead resize or shrink the memory
539      * block in place.
540      * The contents of the new memory block will be the same as the contents
541      * of the old memory block, up to the lesser of the new and old sizes.
542      *
543      * The caller guarantees that there are no other live pointers to the
544      * passed memory block, still it might not be freed immediately by `realloc`.
545      * The garbage collector can reclaim the memory block in a later
546      * collection if it is unused.
547      * If allocation fails, this function will throw an `OutOfMemoryError`.
548      *
549      * If `ba` is zero (the default) the attributes of the existing memory
550      * will be used for an allocation.
551      * If `ba` is not zero and no new memory is allocated, the bits in ba will
552      * replace those of the current memory block.
553      *
554      * Params:
555      *  p  = A pointer to the base of a valid memory block or to `null`.
556      *  sz = The desired allocation size in bytes.
557      *  ba = A bitmask of the BlkAttr attributes to set on this block.
558      *  ti = TypeInfo to describe the memory. The GC might use this information
559      *       to improve scanning for pointers or to call finalizers.
560      *
561      * Returns:
562      *  A reference to the allocated memory on success or `null` if `sz` is
563      *  zero or the pointer does not point to the base of an GC allocated
564      *  memory block.
565      *
566      * Throws:
567      *  `OutOfMemoryError` on allocation failure.
568      */
569     version (D_ProfileGC)
570         pragma(mangle, "gc_reallocTrace") static void* realloc(return scope void* p, size_t sz, uint ba = 0, const TypeInfo ti = null,
571             string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
572     else
573         pragma(mangle, "gc_realloc") static void* realloc(return scope void* p, size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
574 
575     // https://issues.dlang.org/show_bug.cgi?id=13111
576     ///
577     unittest
578     {
579         enum size1 = 1 << 11 + 1; // page in large object pool
580         enum size2 = 1 << 22 + 1; // larger than large object pool size
581 
582         auto data1 = cast(ubyte*)GC.calloc(size1);
583         auto data2 = cast(ubyte*)GC.realloc(data1, size2);
584 
585         GC.BlkInfo info = GC.query(data2);
586         assert(info.size >= size2);
587     }
588 
589 
590     /**
591      * Requests that the managed memory block referenced by p be extended in
592      * place by at least mx bytes, with a desired extension of sz bytes.  If an
593      * extension of the required size is not possible or if p references memory
594      * not originally allocated by this garbage collector, no action will be
595      * taken.
596      *
597      * Params:
598      *  p  = A pointer to the root of a valid memory block or to null.
599      *  mx = The minimum extension size in bytes.
600      *  sz = The desired extension size in bytes.
601      *  ti = TypeInfo to describe the full memory block. The GC might use
602      *       this information to improve scanning for pointers or to
603      *       call finalizers.
604      *
605      * Returns:
606      *  The size in bytes of the extended memory block referenced by p or zero
607      *  if no extension occurred.
608      *
609      * Note:
610      *  Extend may also be used to extend slices (or memory blocks with
611      *  $(LREF APPENDABLE) info). However, use the return value only
612      *  as an indicator of success. $(LREF capacity) should be used to
613      *  retrieve actual usable slice capacity.
614      */
615     version (D_ProfileGC)
616         pragma(mangle, "gc_extendTrace") static size_t extend(void* p, size_t mx, size_t sz, const TypeInfo ti = null,
617             string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
618     else
619         pragma(mangle, "gc_extend") static size_t extend(void* p, size_t mx, size_t sz, const TypeInfo ti = null) pure nothrow;
620 
621     /// Standard extending
622     unittest
623     {
624         size_t size = 1000;
625         int* p = cast(int*)GC.malloc(size * int.sizeof, GC.BlkAttr.NO_SCAN);
626 
627         //Try to extend the allocated data by 1000 elements, preferred 2000.
628         size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
629         if (u != 0)
630             size = u / int.sizeof;
631     }
632     /// slice extending
633     unittest
634     {
635         int[] slice = new int[](1000);
636         int*  p     = slice.ptr;
637 
638         //Check we have access to capacity before attempting the extend
639         if (slice.capacity)
640         {
641             //Try to extend slice by 1000 elements, preferred 2000.
642             size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
643             if (u != 0)
644             {
645                 slice.length = slice.capacity;
646                 assert(slice.length >= 2000);
647             }
648         }
649     }
650 
651 
652     /**
653      * Requests that at least sz bytes of memory be obtained from the operating
654      * system and marked as free.
655      *
656      * Params:
657      *  sz = The desired size in bytes.
658      *
659      * Returns:
660      *  The actual number of bytes reserved or zero on error.
661      */
662     pragma(mangle, "gc_reserve") static size_t reserve(size_t sz) nothrow pure;
663 
664 
665     /**
666      * Deallocates the memory referenced by p.  If p is null, no action occurs.
667      * If p references memory not originally allocated by this garbage
668      * collector, if p points to the interior of a memory block, or if this
669      * method is called from a finalizer, no action will be taken.  The block
670      * will not be finalized regardless of whether the FINALIZE attribute is
671      * set.  If finalization is desired, call $(REF1 destroy, object) prior to `GC.free`.
672      *
673      * Params:
674      *  p = A pointer to the root of a valid memory block or to null.
675      */
676     pragma(mangle, "gc_free") static void free(void* p) pure nothrow @nogc;
677 
678 extern(D):
679 
680     /**
681      * Returns the base address of the memory block containing p.  This value
682      * is useful to determine whether p is an interior pointer, and the result
683      * may be passed to routines such as sizeOf which may otherwise fail.  If p
684      * references memory not originally allocated by this garbage collector, if
685      * p is null, or if the garbage collector does not support this operation,
686      * null will be returned.
687      *
688      * Params:
689      *  p = A pointer to the root or the interior of a valid memory block or to
690      *      null.
691      *
692      * Returns:
693      *  The base address of the memory block referenced by p or null on error.
694      */
695     static inout(void)* addrOf( inout(void)* p ) nothrow @nogc pure @trusted
696     {
697         return cast(inout(void)*)gc_addrOf(cast(void*)p);
698     }
699 
700     /// ditto
701     static void* addrOf(void* p) pure nothrow @nogc @trusted
702     {
703         return gc_addrOf(p);
704     }
705 
706     /**
707      * Returns the true size of the memory block referenced by p.  This value
708      * represents the maximum number of bytes for which a call to realloc may
709      * resize the existing block in place.  If p references memory not
710      * originally allocated by this garbage collector, points to the interior
711      * of a memory block, or if p is null, zero will be returned.
712      *
713      * Params:
714      *  p = A pointer to the root of a valid memory block or to null.
715      *
716      * Returns:
717      *  The size in bytes of the memory block referenced by p or zero on error.
718      */
719     static size_t sizeOf( const scope void* p ) nothrow @nogc /* FIXME pure */
720     {
721         return gc_sizeOf(cast(void*)p);
722     }
723 
724 
725     /// ditto
726     static size_t sizeOf(void* p) pure nothrow @nogc
727     {
728         return gc_sizeOf( p );
729     }
730 
731     // verify that the reallocation doesn't leave the size cache in a wrong state
732     unittest
733     {
734         auto data = cast(int*)realloc(null, 4096);
735         size_t size = GC.sizeOf(data);
736         assert(size >= 4096);
737         data = cast(int*)GC.realloc(data, 4100);
738         size = GC.sizeOf(data);
739         assert(size >= 4100);
740     }
741 
742     /**
743      * Returns aggregate information about the memory block containing p.  If p
744      * references memory not originally allocated by this garbage collector, if
745      * p is null, or if the garbage collector does not support this operation,
746      * BlkInfo.init will be returned.  Typically, support for this operation
747      * is dependent on support for addrOf.
748      *
749      * Params:
750      *  p = A pointer to the root or the interior of a valid memory block or to
751      *      null.
752      *
753      * Returns:
754      *  Information regarding the memory block referenced by p or BlkInfo.init
755      *  on error.
756      */
757     static BlkInfo query(return scope const void* p) nothrow
758     {
759         return gc_query(cast(void*)p);
760     }
761 
762 
763     /// ditto
764     static BlkInfo query(return scope void* p) pure nothrow
765     {
766         return gc_query( p );
767     }
768 
769     /**
770      * Returns runtime stats for currently active GC implementation
771      * See `core.memory.GC.Stats` for list of available metrics.
772      */
773     static Stats stats() @safe nothrow @nogc
774     {
775         return gc_stats();
776     }
777 
778     /**
779      * Returns runtime profile stats for currently active GC implementation
780      * See `core.memory.GC.ProfileStats` for list of available metrics.
781      */
782     static ProfileStats profileStats() nothrow @nogc @safe
783     {
784         return gc_profileStats();
785     }
786 
787 extern(C):
788 
789     /**
790      * Adds an internal root pointing to the GC memory block referenced by p.
791      * As a result, the block referenced by p itself and any blocks accessible
792      * via it will be considered live until the root is removed again.
793      *
794      * If p is null, no operation is performed.
795      *
796      * Params:
797      *  p = A pointer into a GC-managed memory block or null.
798      *
799      * Example:
800      * ---
801      * // Typical C-style callback mechanism; the passed function
802      * // is invoked with the user-supplied context pointer at a
803      * // later point.
804      * extern(C) void addCallback(void function(void*), void*);
805      *
806      * // Allocate an object on the GC heap (this would usually be
807      * // some application-specific context data).
808      * auto context = new Object;
809      *
810      * // Make sure that it is not collected even if it is no
811      * // longer referenced from D code (stack, GC heap, …).
812      * GC.addRoot(cast(void*)context);
813      *
814      * // Also ensure that a moving collector does not relocate
815      * // the object.
816      * GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);
817      *
818      * // Now context can be safely passed to the C library.
819      * addCallback(&myHandler, cast(void*)context);
820      *
821      * extern(C) void myHandler(void* ctx)
822      * {
823      *     // Assuming that the callback is invoked only once, the
824      *     // added root can be removed again now to allow the GC
825      *     // to collect it later.
826      *     GC.removeRoot(ctx);
827      *     GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);
828      *
829      *     auto context = cast(Object)ctx;
830      *     // Use context here…
831      * }
832      * ---
833      */
834     pragma(mangle, "gc_addRoot") static void addRoot(const void* p) nothrow @nogc pure;
835 
836 
837     /**
838      * Removes the memory block referenced by p from an internal list of roots
839      * to be scanned during a collection.  If p is null or is not a value
840      * previously passed to addRoot() then no operation is performed.
841      *
842      * Params:
843      *  p = A pointer into a GC-managed memory block or null.
844      */
845     pragma(mangle, "gc_removeRoot") static void removeRoot(const void* p) nothrow @nogc pure;
846 
847 
848     /**
849      * Adds $(D p[0 .. sz]) to the list of memory ranges to be scanned for
850      * pointers during a collection. If p is null, no operation is performed.
851      *
852      * Note that $(D p[0 .. sz]) is treated as an opaque range of memory assumed
853      * to be suitably managed by the caller. In particular, if p points into a
854      * GC-managed memory block, addRange does $(I not) mark this block as live.
855      *
856      * Params:
857      *  p  = A pointer to a valid memory address or to null.
858      *  sz = The size in bytes of the block to add. If sz is zero then the
859      *       no operation will occur. If p is null then sz must be zero.
860      *  ti = TypeInfo to describe the memory. The GC might use this information
861      *       to improve scanning for pointers or to call finalizers
862      *
863      * Example:
864      * ---
865      * // Allocate a piece of memory on the C heap.
866      * enum size = 1_000;
867      * auto rawMemory = core.stdc.stdlib.malloc(size);
868      *
869      * // Add it as a GC range.
870      * GC.addRange(rawMemory, size);
871      *
872      * // Now, pointers to GC-managed memory stored in
873      * // rawMemory will be recognized on collection.
874      * ---
875      */
876     pragma(mangle, "gc_addRange")
877     static void addRange(const void* p, size_t sz, const TypeInfo ti = null) @nogc nothrow pure;
878 
879 
880     /**
881      * Removes the memory range starting at p from an internal list of ranges
882      * to be scanned during a collection. If p is null or does not represent
883      * a value previously passed to addRange() then no operation is
884      * performed.
885      *
886      * Params:
887      *  p  = A pointer to a valid memory address or to null.
888      */
889     pragma(mangle, "gc_removeRange") static void removeRange(const void* p) nothrow @nogc pure;
890 
891 
892     /**
893      * Runs any finalizer that is located in address range of the
894      * given code segment.  This is used before unloading shared
895      * libraries.  All matching objects which have a finalizer in this
896      * code segment are assumed to be dead, using them while or after
897      * calling this method has undefined behavior.
898      *
899      * Params:
900      *  segment = address range of a code segment.
901      */
902     pragma(mangle, "gc_runFinalizers") static void runFinalizers(const scope void[] segment);
903 
904     /**
905      * Queries the GC whether the current thread is running object finalization
906      * as part of a GC collection, or an explicit call to runFinalizers.
907      *
908      * As some GC implementations (such as the current conservative one) don't
909      * support GC memory allocation during object finalization, this function
910      * can be used to guard against such programming errors.
911      *
912      * Returns:
913      *  true if the current thread is in a finalizer, a destructor invoked by
914      *  the GC.
915      */
916     pragma(mangle, "gc_inFinalizer") static bool inFinalizer() nothrow @nogc @safe;
917 
918     ///
919     @safe nothrow @nogc unittest
920     {
921         // Only code called from a destructor is executed during finalization.
922         assert(!GC.inFinalizer);
923     }
924 
925     ///
926     unittest
927     {
928         enum Outcome
929         {
930             notCalled,
931             calledManually,
932             calledFromDruntime
933         }
934 
935         static class Resource
936         {
937             static Outcome outcome;
938 
939             this()
940             {
941                 outcome = Outcome.notCalled;
942             }
943 
944             ~this()
945             {
946                 if (GC.inFinalizer)
947                 {
948                     outcome = Outcome.calledFromDruntime;
949 
950                     import core.exception : InvalidMemoryOperationError;
951                     try
952                     {
953                         /*
954                          * Presently, allocating GC memory during finalization
955                          * is forbidden and leads to
956                          * `InvalidMemoryOperationError` being thrown.
957                          *
958                          * `GC.inFinalizer` can be used to guard against
959                          * programming erros such as these and is also a more
960                          * efficient way to verify whether a destructor was
961                          * invoked by the GC.
962                          */
963                         cast(void) GC.malloc(1);
964                         assert(false);
965                     }
966                     catch (InvalidMemoryOperationError e)
967                     {
968                         return;
969                     }
970                     assert(false);
971                 }
972                 else
973                     outcome = Outcome.calledManually;
974             }
975         }
976 
977         static void createGarbage()
978         {
979             auto r = new Resource;
980             r = null;
981         }
982 
983         assert(Resource.outcome == Outcome.notCalled);
984         createGarbage();
985         GC.collect;
986         assert(
987             Resource.outcome == Outcome.notCalled ||
988             Resource.outcome == Outcome.calledFromDruntime);
989 
990         auto r = new Resource;
991         GC.runFinalizers((cast(const void*)typeid(Resource).destructor)[0..1]);
992         assert(Resource.outcome == Outcome.calledFromDruntime);
993         Resource.outcome = Outcome.notCalled;
994 
995         debug(MEMSTOMP) {} else
996         {
997             // assume Resource data is still available
998             r.destroy;
999             assert(Resource.outcome == Outcome.notCalled);
1000         }
1001 
1002         r = new Resource;
1003         assert(Resource.outcome == Outcome.notCalled);
1004         r.destroy;
1005         assert(Resource.outcome == Outcome.calledManually);
1006     }
1007 
1008     /**
1009      * Returns the number of bytes allocated for the current thread
1010      * since program start. It is the same as
1011      * GC.stats().allocatedInCurrentThread, but faster.
1012      */
1013     pragma(mangle, "gc_allocatedInCurrentThread") static ulong allocatedInCurrentThread() nothrow;
1014 
1015     /// Using allocatedInCurrentThread
1016     nothrow unittest
1017     {
1018         ulong currentlyAllocated = GC.allocatedInCurrentThread();
1019         struct DataStruct
1020         {
1021             long l1;
1022             long l2;
1023             long l3;
1024             long l4;
1025         }
1026         DataStruct* unused = new DataStruct;
1027         assert(GC.allocatedInCurrentThread() == currentlyAllocated + 32);
1028         assert(GC.stats().allocatedInCurrentThread == currentlyAllocated + 32);
1029     }
1030 }
1031 
1032 /**
1033  * Pure variants of C's memory allocation functions `malloc`, `calloc`, and
1034  * `realloc` and deallocation function `free`.
1035  *
1036  * UNIX 98 requires that errno be set to ENOMEM upon failure.
1037  * Purity is achieved by saving and restoring the value of `errno`, thus
1038  * behaving as if it were never changed.
1039  *
1040  * See_Also:
1041  *     $(LINK2 https://dlang.org/spec/function.html#pure-functions, D's rules for purity),
1042  *     which allow for memory allocation under specific circumstances.
1043  */
1044 void* pureMalloc()(size_t size) @trusted pure @nogc nothrow
1045 {
1046     const errnosave = fakePureErrno;
1047     void* ret = fakePureMalloc(size);
1048     fakePureErrno = errnosave;
1049     return ret;
1050 }
1051 /// ditto
1052 void* pureCalloc()(size_t nmemb, size_t size) @trusted pure @nogc nothrow
1053 {
1054     const errnosave = fakePureErrno;
1055     void* ret = fakePureCalloc(nmemb, size);
1056     fakePureErrno = errnosave;
1057     return ret;
1058 }
1059 /// ditto
1060 void* pureRealloc()(void* ptr, size_t size) @system pure @nogc nothrow
1061 {
1062     const errnosave = fakePureErrno;
1063     void* ret = fakePureRealloc(ptr, size);
1064     fakePureErrno = errnosave;
1065     return ret;
1066 }
1067 
1068 /// ditto
1069 void pureFree()(void* ptr) @system pure @nogc nothrow
1070 {
1071     version (Posix)
1072     {
1073         // POSIX free doesn't set errno
1074         fakePureFree(ptr);
1075     }
1076     else
1077     {
1078         const errnosave = fakePureErrno;
1079         fakePureFree(ptr);
1080         fakePureErrno = errnosave;
1081     }
1082 }
1083 
1084 ///
1085 @system pure nothrow @nogc unittest
1086 {
1087     ubyte[] fun(size_t n) pure
1088     {
1089         void* p = pureMalloc(n);
1090         p !is null || n == 0 || assert(0);
1091         scope(failure) p = pureRealloc(p, 0);
1092         p = pureRealloc(p, n *= 2);
1093         p !is null || n == 0 || assert(0);
1094         return cast(ubyte[]) p[0 .. n];
1095     }
1096 
1097     auto buf = fun(100);
1098     assert(buf.length == 200);
1099     pureFree(buf.ptr);
1100 }
1101 
1102 @system pure nothrow @nogc unittest
1103 {
1104     const int errno = fakePureErrno();
1105 
1106     void* x = pureMalloc(10);            // normal allocation
1107     assert(errno == fakePureErrno()); // errno shouldn't change
1108     assert(x !is null);                   // allocation should succeed
1109 
1110     x = pureRealloc(x, 10);              // normal reallocation
1111     assert(errno == fakePureErrno()); // errno shouldn't change
1112     assert(x !is null);                   // allocation should succeed
1113 
1114     fakePureFree(x);
1115 
1116     void* y = pureCalloc(10, 1);         // normal zeroed allocation
1117     assert(errno == fakePureErrno()); // errno shouldn't change
1118     assert(y !is null);                   // allocation should succeed
1119 
1120     fakePureFree(y);
1121 
1122   version (LDC_AddressSanitizer)
1123   {
1124     // Test must be disabled because ASan will report an error: requested allocation size 0xffffffffffffff00 (0x700 after adjustments for alignment, red zones etc.) exceeds maximum supported size of 0x10000000000
1125   }
1126   else
1127   {
1128     // Workaround bug in glibc 2.26
1129     // See also: https://issues.dlang.org/show_bug.cgi?id=17956
1130     void* z = pureMalloc(size_t.max & ~255); // won't affect `errno`
1131     assert(errno == fakePureErrno()); // errno shouldn't change
1132   }
1133   version (LDC)
1134   {
1135     // LLVM's 'Combine redundant instructions' optimization pass
1136     // completely elides allocating `y` and `z`. Allocations with
1137     // sizes > 0 are apparently assumed to always succeed (and
1138     // return non-null), so the following assert fails with -O3.
1139   }
1140   else
1141   {
1142     assert(z is null);
1143   }
1144 }
1145 
1146 // locally purified for internal use here only
1147 
1148 static import core.stdc.errno;
1149 static if (__traits(getOverloads, core.stdc.errno, "errno").length == 1
1150     && __traits(getLinkage, core.stdc.errno.errno) == "C")
1151 {
1152     extern(C) pragma(mangle, __traits(identifier, core.stdc.errno.errno))
1153     private ref int fakePureErrno() @nogc nothrow pure @system;
1154 }
1155 else
1156 {
1157     extern(C) private @nogc nothrow pure @system
1158     {
1159         pragma(mangle, __traits(identifier, core.stdc.errno.getErrno))
1160         @property int fakePureErrno();
1161 
1162         pragma(mangle, __traits(identifier, core.stdc.errno.setErrno))
1163         @property int fakePureErrno(int);
1164     }
1165 }
1166 
1167 version (D_BetterC) {}
1168 else // TODO: remove this function after Phobos no longer needs it.
1169 extern (C) private @system @nogc nothrow
1170 {
1171     ref int fakePureErrnoImpl()
1172     {
1173         import core.stdc.errno;
1174         return errno();
1175     }
1176 }
1177 
1178 extern (C) private pure @system @nogc nothrow
1179 {
1180     pragma(mangle, "malloc") void* fakePureMalloc(size_t);
1181     pragma(mangle, "calloc") void* fakePureCalloc(size_t nmemb, size_t size);
1182     pragma(mangle, "realloc") void* fakePureRealloc(void* ptr, size_t size);
1183 
1184     pragma(mangle, "free") void fakePureFree(void* ptr);
1185 }
1186 
1187 /**
1188 Destroys and then deallocates an object.
1189 
1190 In detail, `__delete(x)` returns with no effect if `x` is `null`. Otherwise, it
1191 performs the following actions in sequence:
1192 $(UL
1193     $(LI
1194         Calls the destructor `~this()` for the object referred to by `x`
1195         (if `x` is a class or interface reference) or
1196         for the object pointed to by `x` (if `x` is a pointer to a `struct`).
1197         Arrays of structs call the destructor, if defined, for each element in the array.
1198         If no destructor is defined, this step has no effect.
1199     )
1200     $(LI
1201         Frees the memory allocated for `x`. If `x` is a reference to a class
1202         or interface, the memory allocated for the underlying instance is freed. If `x` is
1203         a pointer, the memory allocated for the pointed-to object is freed. If `x` is a
1204         built-in array, the memory allocated for the array is freed.
1205         If `x` does not refer to memory previously allocated with `new` (or the lower-level
1206         equivalents in the GC API), the behavior is undefined.
1207     )
1208     $(LI
1209         Lastly, `x` is set to `null`. Any attempt to read or write the freed memory via
1210         other references will result in undefined behavior.
1211     )
1212 )
1213 
1214 Note: Users should prefer $(REF1 destroy, object) to explicitly finalize objects,
1215 and only resort to $(REF __delete, core,memory) when $(REF destroy, object)
1216 wouldn't be a feasible option.
1217 
1218 Params:
1219     x = aggregate object that should be destroyed
1220 
1221 See_Also: $(REF1 destroy, object), $(REF free, core,GC)
1222 
1223 History:
1224 
1225 The `delete` keyword allowed to free GC-allocated memory.
1226 As this is inherently not `@safe`, it has been deprecated.
1227 This function has been added to provide an easy transition from `delete`.
1228 It performs the same functionality as the former `delete` keyword.
1229 */
1230 void __delete(T)(ref T x) @system
1231 {
1232     static void _destructRecurse(S)(ref S s)
1233     if (is(S == struct))
1234     {
1235         static if (__traits(hasMember, S, "__xdtor") &&
1236                    // Bugzilla 14746: Check that it's the exact member of S.
1237                    __traits(isSame, S, __traits(parent, s.__xdtor)))
1238             s.__xdtor();
1239     }
1240 
1241     // See also: https://github.com/dlang/dmd/blob/v2.078.0/src/dmd/e2ir.d#L3886
1242     static if (is(T == interface))
1243     {
1244         .object.destroy(x);
1245     }
1246     else static if (is(T == class))
1247     {
1248         .object.destroy(x);
1249     }
1250     else static if (is(T == U*, U))
1251     {
1252         static if (is(U == struct))
1253         {
1254             if (x)
1255                 _destructRecurse(*x);
1256         }
1257     }
1258     else static if (is(T : E[], E))
1259     {
1260         static if (is(E == struct))
1261         {
1262             foreach_reverse (ref e; x)
1263                 _destructRecurse(e);
1264         }
1265     }
1266     else
1267     {
1268         static assert(0, "It is not possible to delete: `" ~ T.stringof ~ "`");
1269     }
1270 
1271     static if (is(T == interface) ||
1272               is(T == class) ||
1273               is(T == U2*, U2))
1274     {
1275         GC.free(GC.addrOf(cast(void*) x));
1276         x = null;
1277     }
1278     else static if (is(T : E2[], E2))
1279     {
1280         GC.free(GC.addrOf(cast(void*) x.ptr));
1281         x = null;
1282     }
1283 }
1284 
1285 /// Deleting classes
1286 unittest
1287 {
1288     bool dtorCalled;
1289     class B
1290     {
1291         int test;
1292         ~this()
1293         {
1294             dtorCalled = true;
1295         }
1296     }
1297     B b = new B();
1298     B a = b;
1299     b.test = 10;
1300 
1301     assert(GC.addrOf(cast(void*) b) != null);
1302     __delete(b);
1303     assert(b is null);
1304     assert(dtorCalled);
1305     assert(GC.addrOf(cast(void*) b) == null);
1306     // but be careful, a still points to it
1307     assert(a !is null);
1308     assert(GC.addrOf(cast(void*) a) == null); // but not a valid GC pointer
1309 }
1310 
1311 /// Deleting interfaces
1312 unittest
1313 {
1314     bool dtorCalled;
1315     interface A
1316     {
1317         int quack();
1318     }
1319     class B : A
1320     {
1321         int a;
1322         int quack()
1323         {
1324             a++;
1325             return a;
1326         }
1327         ~this()
1328         {
1329             dtorCalled = true;
1330         }
1331     }
1332     A a = new B();
1333     a.quack();
1334 
1335     assert(GC.addrOf(cast(void*) a) != null);
1336     __delete(a);
1337     assert(a is null);
1338     assert(dtorCalled);
1339     assert(GC.addrOf(cast(void*) a) == null);
1340 }
1341 
1342 /// Deleting structs
1343 unittest
1344 {
1345     bool dtorCalled;
1346     struct A
1347     {
1348         string test;
1349         ~this()
1350         {
1351             dtorCalled = true;
1352         }
1353     }
1354     auto a = new A("foo");
1355 
1356     assert(GC.addrOf(cast(void*) a) != null);
1357     __delete(a);
1358     assert(a is null);
1359     assert(dtorCalled);
1360     assert(GC.addrOf(cast(void*) a) == null);
1361 
1362     // https://issues.dlang.org/show_bug.cgi?id=22779
1363     A *aptr;
1364     __delete(aptr);
1365 }
1366 
1367 /// Deleting arrays
1368 unittest
1369 {
1370     int[] a = [1, 2, 3];
1371     auto b = a;
1372 
1373     assert(GC.addrOf(b.ptr) != null);
1374     __delete(b);
1375     assert(b is null);
1376     assert(GC.addrOf(b.ptr) == null);
1377     // but be careful, a still points to it
1378     assert(a !is null);
1379     assert(GC.addrOf(a.ptr) == null); // but not a valid GC pointer
1380 }
1381 
1382 /// Deleting arrays of structs
1383 unittest
1384 {
1385     int dtorCalled;
1386     struct A
1387     {
1388         int a;
1389         ~this()
1390         {
1391             assert(dtorCalled == a);
1392             dtorCalled++;
1393         }
1394     }
1395     auto arr = [A(1), A(2), A(3)];
1396     arr[0].a = 2;
1397     arr[1].a = 1;
1398     arr[2].a = 0;
1399 
1400     assert(GC.addrOf(arr.ptr) != null);
1401     __delete(arr);
1402     assert(dtorCalled == 3);
1403     assert(GC.addrOf(arr.ptr) == null);
1404 }
1405 
1406 // Deleting raw memory
1407 unittest
1408 {
1409     import core.memory : GC;
1410     auto a = GC.malloc(5);
1411     assert(GC.addrOf(cast(void*) a) != null);
1412     __delete(a);
1413     assert(a is null);
1414     assert(GC.addrOf(cast(void*) a) == null);
1415 }
1416 
1417 // __delete returns with no effect if x is null
1418 unittest
1419 {
1420     Object x = null;
1421     __delete(x);
1422 
1423     struct S { ~this() { } }
1424     class C { }
1425     interface I { }
1426 
1427     int[] a; __delete(a);
1428     S[] as; __delete(as);
1429     C c; __delete(c);
1430     I i; __delete(i);
1431     C* pc = &c; __delete(*pc);
1432     I* pi = &i; __delete(*pi);
1433     int* pint; __delete(pint);
1434     S* ps; __delete(ps);
1435 }
1436 
1437 // https://issues.dlang.org/show_bug.cgi?id=19092
1438 unittest
1439 {
1440     const(int)[] x = [1, 2, 3];
1441     assert(GC.addrOf(x.ptr) != null);
1442     __delete(x);
1443     assert(x is null);
1444     assert(GC.addrOf(x.ptr) == null);
1445 
1446     immutable(int)[] y = [1, 2, 3];
1447     assert(GC.addrOf(y.ptr) != null);
1448     __delete(y);
1449     assert(y is null);
1450     assert(GC.addrOf(y.ptr) == null);
1451 }
1452 
1453 // test realloc behaviour
1454 unittest
1455 {
1456     static void set(int* p, size_t size)
1457     {
1458         foreach (i; 0 .. size)
1459             *p++ = cast(int) i;
1460     }
1461     static void verify(int* p, size_t size)
1462     {
1463         foreach (i; 0 .. size)
1464             assert(*p++ == i);
1465     }
1466     static void test(size_t memsize)
1467     {
1468         int* p = cast(int*) GC.malloc(memsize * int.sizeof);
1469         assert(p);
1470         set(p, memsize);
1471         verify(p, memsize);
1472 
1473         int* q = cast(int*) GC.realloc(p + 4, 2 * memsize * int.sizeof);
1474         assert(q == null);
1475 
1476         q = cast(int*) GC.realloc(p + memsize / 2, 2 * memsize * int.sizeof);
1477         assert(q == null);
1478 
1479         q = cast(int*) GC.realloc(p + memsize - 1, 2 * memsize * int.sizeof);
1480         assert(q == null);
1481 
1482         int* r = cast(int*) GC.realloc(p, 5 * memsize * int.sizeof);
1483         verify(r, memsize);
1484         set(r, 5 * memsize);
1485 
1486         int* s = cast(int*) GC.realloc(r, 2 * memsize * int.sizeof);
1487         verify(s, 2 * memsize);
1488 
1489         assert(GC.realloc(s, 0) == null); // free
1490         assert(GC.addrOf(p) == null);
1491     }
1492 
1493     test(16);
1494     test(200);
1495     test(800); // spans large and small pools
1496     test(1200);
1497     test(8000);
1498 
1499     void* p = GC.malloc(100);
1500     assert(GC.realloc(&p, 50) == null); // non-GC pointer
1501 }
1502 
1503 // test GC.profileStats
1504 unittest
1505 {
1506     auto stats = GC.profileStats();
1507     GC.collect();
1508     auto nstats = GC.profileStats();
1509     assert(nstats.numCollections > stats.numCollections);
1510 }
1511 
1512 // in rt.lifetime:
1513 private extern (C) void* _d_newitemU(scope const TypeInfo _ti) @system pure nothrow;
1514 
1515 /**
1516 Moves a value to a new GC allocation.
1517 
1518 Params:
1519     value = Value to be moved. If the argument is an lvalue and a struct with a
1520             destructor or postblit, it will be reset to its `.init` value.
1521 
1522 Returns:
1523     A pointer to the new GC-allocated value.
1524 */
1525 T* moveToGC(T)(auto ref T value)
1526 {
1527     static T* doIt(ref T value) @trusted
1528     {
1529         import core.lifetime : moveEmplace;
1530         auto mem = cast(T*) _d_newitemU(typeid(T)); // allocate but don't initialize
1531         moveEmplace(value, *mem);
1532         return mem;
1533     }
1534 
1535     return doIt(value); // T dtor might be @system
1536 }
1537 
1538 ///
1539 @safe pure nothrow unittest
1540 {
1541     struct S
1542     {
1543         int x;
1544         this(this) @disable;
1545         ~this() @safe pure nothrow @nogc {}
1546     }
1547 
1548     S* p;
1549 
1550     // rvalue
1551     p = moveToGC(S(123));
1552     assert(p.x == 123);
1553 
1554     // lvalue
1555     auto lval = S(456);
1556     p = moveToGC(lval);
1557     assert(p.x == 456);
1558     assert(lval.x == 0);
1559 }
1560 
1561 // @system dtor
1562 unittest
1563 {
1564     struct S
1565     {
1566         int x;
1567         ~this() @system {}
1568     }
1569 
1570     // lvalue case is @safe, ref param isn't destructed
1571     static assert(__traits(compiles, (ref S lval) @safe { moveToGC(lval); }));
1572 
1573     // rvalue case is @system, value param is destructed
1574     static assert(!__traits(compiles, () @safe { moveToGC(S(0)); }));
1575 }