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