Debian Codegraph @

libphobos/libdruntime/core/internal/array/construction.d

raw
1 /**
2 This module contains compiler support for constructing dynamic arrays
3
4 Copyright: Copyright Digital Mars 2000 - 2019.
5 License: Distributed under the
6 $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
7 (See accompanying file LICENSE)
8 Source: $(DRUNTIMESRC core/internal/_array/_construction.d)
9 */
10 module core.internal.array.construction;
11
12 import core.internal.traits : Unqual;
13
14 debug(PRINTF)
15 {
16 import core.stdc.stdio : printf;
17 }
18
19 /**
20 * Does array initialization (not assignment) from another array of the same element type.
21 * Params:
22 * to = what array to initialize
23 * from = what data the array should be initialized with
24 * makeWeaklyPure = unused; its purpose is to prevent the function from becoming
25 * strongly pure and risk being optimised out
26 * Returns:
27 * The created and initialized array `to`
28 * Bugs:
29 * This function template was ported from a much older runtime hook that bypassed safety,
30 * purity, and throwabilty checks. To prevent breaking existing code, this function template
31 * is temporarily declared `@trusted` until the implementation can be brought up to modern D expectations.
32 *
33 * The third parameter is never used, but is necessary in order for the
34 * function be treated as weakly pure, instead of strongly pure.
35 * This is needed because constructions such as the one below can be ignored by
36 * the compiler if `_d_arrayctor` is believed to be pure, because purity would
37 * mean the call to `_d_arrayctor` has no effects (no side effects and the
38 * return value is ignored), despite it actually modifying the contents of `a`.
39 * const S[2] b;
40 * const S[2] a = b; // this would get lowered to _d_arrayctor(a, b)
41 */
42 Tarr _d_arrayctor(Tarr : T[], T)(return scope Tarr to, scope Tarr from, char* makeWeaklyPure = null) @trusted
43 {
44 version (DigitalMars) pragma(inline, false);
45 import core.internal.traits : hasElaborateCopyConstructor;
46 import core.lifetime : copyEmplace;
47 import core.stdc.string : memcpy;
48 import core.stdc.stdint : uintptr_t;
49
50 debug(PRINTF) printf("_d_arrayctor(from = %p,%zd) size = %zd\n", from.ptr, from.length, T.sizeof);
51
52 void[] vFrom = (cast(void*) from.ptr)[0..from.length];
53 void[] vTo = (cast(void*) to.ptr)[0..to.length];
54
55 // Force `enforceRawArraysConformable` to remain weakly `pure`
56 void enforceRawArraysConformable(const char[] action, const size_t elementSize,
57 const void[] a1, const void[] a2) @trusted
58 {
59 import core.internal.util.array : enforceRawArraysConformableNogc;
60
61 alias Type = void function(const char[] action, const size_t elementSize,
62 const void[] a1, const void[] a2, in bool allowOverlap = false) @nogc pure nothrow;
63 (cast(Type)&enforceRawArraysConformableNogc)(action, elementSize, a1, a2, false);
64 }
65
66 enforceRawArraysConformable("initialization", T.sizeof, vFrom, vTo);
67
68 static if (hasElaborateCopyConstructor!T)
69 {
70 size_t i;
71 try
72 {
73 for (i = 0; i < to.length; i++)
74 copyEmplace(from[i], to[i]);
75 }
76 catch (Exception o)
77 {
78 /* Destroy, in reverse order, what we've constructed so far
79 */
80 while (i--)
81 {
82 auto elem = cast(Unqual!T*) &to[i];
83 destroy(*elem);
84 }
85
86 throw o;
87 }
88 }
89 else
90 {
91 // blit all elements at once
92 memcpy(cast(void*) to.ptr, from.ptr, to.length * T.sizeof);
93 }
94
95 return to;
96 }
97
98 // postblit
99 @safe unittest
100 {
101 int counter;
102 struct S
103 {
104 int val;
105 this(this) { counter++; }
106 }
107
108 S[4] arr1;
109 S[4] arr2 = [S(0), S(1), S(2), S(3)];
110 _d_arrayctor(arr1[], arr2[]);
111
112 assert(counter == 4);
113 assert(arr1 == arr2);
114 }
115
116 // copy constructor
117 @safe unittest
118 {
119 int counter;
120 struct S
121 {
122 int val;
123 this(int val) { this.val = val; }
124 this(const scope ref S rhs)
125 {
126 val = rhs.val;
127 counter++;
128 }
129 }
130
131 S[4] arr1;
132 S[4] arr2 = [S(0), S(1), S(2), S(3)];
133 _d_arrayctor(arr1[], arr2[]);
134
135 assert(counter == 4);
136 assert(arr1 == arr2);
137 }
138
139 @safe nothrow unittest
140 {
141 // Test that throwing works
142 int counter;
143 bool didThrow;
144
145 struct Throw
146 {
147 int val;
148 this(this)
149 {
150 counter++;
151 if (counter == 2)
152 throw new Exception("");
153 }
154 }
155 try
156 {
157 Throw[4] a;
158 Throw[4] b = [Throw(1), Throw(2), Throw(3), Throw(4)];
159 _d_arrayctor(a[], b[]);
160 }
161 catch (Exception)
162 {
163 didThrow = true;
164 }
165 assert(didThrow);
166 assert(counter == 2);
167
168
169 // Test that `nothrow` works
170 didThrow = false;
171 counter = 0;
172 struct NoThrow
173 {
174 int val;
175 this(this)
176 {
177 counter++;
178 }
179 }
180 try
181 {
182 NoThrow[4] a;
183 NoThrow[4] b = [NoThrow(1), NoThrow(2), NoThrow(3), NoThrow(4)];
184 _d_arrayctor(a[], b[]);
185 }
186 catch (Exception)
187 {
188 didThrow = false;
189 }
190 assert(!didThrow);
191 assert(counter == 4);
192 }
193
194 /**
195 * Do construction of an array.
196 * ti[count] p = value;
197 * Params:
198 * p = what array to initialize
199 * value = what data to construct the array with
200 * Bugs:
201 * This function template was ported from a much older runtime hook that bypassed safety,
202 * purity, and throwabilty checks. To prevent breaking existing code, this function template
203 * is temporarily declared `@trusted` until the implementation can be brought up to modern D expectations.
204 */
205 void _d_arraysetctor(Tarr : T[], T)(scope Tarr p, scope ref T value) @trusted
206 {
207 version (DigitalMars) pragma(inline, false);
208 import core.lifetime : copyEmplace;
209
210 size_t i;
211 try
212 {
213 for (i = 0; i < p.length; i++)
214 copyEmplace(value, p[i]);
215 }
216 catch (Exception o)
217 {
218 // Destroy, in reverse order, what we've constructed so far
219 while (i--)
220 {
221 auto elem = cast(Unqual!T*)&p[i];
222 destroy(*elem);
223 }
224
225 throw o;
226 }
227 }
228
229 // postblit
230 @safe unittest
231 {
232 int counter;
233 struct S
234 {
235 int val;
236 this(this)
237 {
238 counter++;
239 }
240 }
241
242 S[4] arr;
243 S s = S(1234);
244 _d_arraysetctor(arr[], s);
245 assert(counter == arr.length);
246 assert(arr == [S(1234), S(1234), S(1234), S(1234)]);
247 }
248
249 // copy constructor
250 @safe unittest
251 {
252 int counter;
253 struct S
254 {
255 int val;
256 this(int val) { this.val = val; }
257 this(const scope ref S rhs)
258 {
259 val = rhs.val;
260 counter++;
261 }
262 }
263
264 S[4] arr;
265 S s = S(1234);
266 _d_arraysetctor(arr[], s);
267 assert(counter == arr.length);
268 assert(arr == [S(1234), S(1234), S(1234), S(1234)]);
269 }
270
271 @safe nothrow unittest
272 {
273 // Test that throwing works
274 int counter;
275 bool didThrow;
276 struct Throw
277 {
278 int val;
279 this(this)
280 {
281 counter++;
282 if (counter == 2)
283 throw new Exception("Oh no.");
284 }
285 }
286 try
287 {
288 Throw[4] a;
289 Throw[4] b = [Throw(1), Throw(2), Throw(3), Throw(4)];
290 _d_arrayctor(a[], b[]);
291 }
292 catch (Exception)
293 {
294 didThrow = true;
295 }
296 assert(didThrow);
297 assert(counter == 2);
298
299
300 // Test that `nothrow` works
301 didThrow = false;
302 counter = 0;
303 struct NoThrow
304 {
305 int val;
306 this(this)
307 {
308 counter++;
309 }
310 }
311 try
312 {
313 NoThrow[4] a;
314 NoThrow b = NoThrow(1);
315 _d_arraysetctor(a[], b);
316 foreach (ref e; a)
317 assert(e == NoThrow(1));
318 }
319 catch (Exception)
320 {
321 didThrow = false;
322 }
323 assert(!didThrow);
324 assert(counter == 4);
325 }
326
327 /**
328 * Allocate an array with the garbage collector. Also initalize elements if
329 * their type has an initializer. Otherwise, not zero-initialize the array.
330 *
331 * Has three variants:
332 * `_d_newarrayU` leaves elements uninitialized
333 * `_d_newarrayT` initializes to 0 or based on initializer
334 *
335 * Params:
336 * length = `.length` of resulting array
337 *
338 * Returns:
339 * newly allocated array
340 */
341 T[] _d_newarrayUPureNothrow(T)(size_t length, bool isShared=false) pure nothrow @trusted
342 {
343 alias PureType = T[] function(size_t length, bool isShared) pure nothrow @trusted;
344 return (cast(PureType) &_d_newarrayU!T)(length, isShared);
345 }
346
347 T[] _d_newarrayU(T)(size_t length, bool isShared=false) @trusted
348 {
349 import core.exception : onOutOfMemoryError;
350 import core.internal.traits : Unqual;
351 import core.internal.array.utils : __arrayAlloc;
352
353 alias UnqT = Unqual!T;
354
355 size_t elemSize = T.sizeof;
356 size_t arraySize;
357
358 debug(PRINTF) printf("_d_newarrayU(length = x%zu, size = %zu)\n", length, elemSize);
359 if (length == 0 || elemSize == 0)
360 return null;
361
362 version (D_InlineAsm_X86)
363 {
364 asm pure nothrow @nogc
365 {
366 mov EAX, elemSize ;
367 mul EAX, length ;
368 mov arraySize, EAX ;
369 jnc Lcontinue ;
370 }
371 }
372 else version (D_InlineAsm_X86_64)
373 {
374 asm pure nothrow @nogc
375 {
376 mov RAX, elemSize ;
377 mul RAX, length ;
378 mov arraySize, RAX ;
379 jnc Lcontinue ;
380 }
381 }
382 else
383 {
384 import core.checkedint : mulu;
385
386 bool overflow = false;
387 arraySize = mulu(elemSize, length, overflow);
388 if (!overflow)
389 goto Lcontinue;
390 }
391
392 Loverflow:
393 onOutOfMemoryError();
394 assert(0);
395
396 Lcontinue:
397 auto arr = __arrayAlloc!UnqT(arraySize);
398 if (!arr.ptr)
399 goto Loverflow;
400 debug(PRINTF) printf("p = %p\n", arr.ptr);
401 return (cast(T*) arr.ptr)[0 .. length];
402 }
403
404 /// ditto
405 T[] _d_newarrayT(T)(size_t length, bool isShared=false) @trusted
406 {
407 T[] result = _d_newarrayU!T(length, isShared);
408
409 static if (__traits(isZeroInit, T))
410 {
411 import core.stdc.string : memset;
412 memset(result.ptr, 0, length * T.sizeof);
413 }
414 else
415 {
416 import core.internal.lifetime : emplaceInitializer;
417 foreach (ref elem; result)
418 emplaceInitializer(elem);
419 }
420
421 return result;
422 }
423
424 unittest
425 {
426 {
427 // zero-initialization
428 struct S { int x, y; }
429 S[] s = _d_newarrayT!S(10);
430
431 assert(s !is null);
432 assert(s.length == 10);
433 foreach (ref elem; s)
434 {
435 assert(elem.x == 0);
436 assert(elem.y == 0);
437 }
438 }
439 {
440 // S.init
441 struct S { int x = 2, y = 3; }
442 S[] s = _d_newarrayT!S(10);
443
444 assert(s.length == 10);
445 foreach (ref elem; s)
446 {
447 assert(elem.x == 2);
448 assert(elem.y == 3);
449 }
450 }
451 }
452
453 unittest
454 {
455 int pblits;
456
457 struct S
458 {
459 this(this) { pblits++; }
460 }
461
462 S[] s = _d_newarrayT!S(2);
463
464 assert(s.length == 2);
465 assert(pblits == 0);
466 }
467
468 version (D_ProfileGC)
469 {
470 /**
471 * TraceGC wrapper around $(REF _d_newitemT, core,lifetime).
472 */
473 T[] _d_newarrayTTrace(T)(size_t length, bool isShared, string file = __FILE__, int line = __LINE__, string funcname = __FUNCTION__) @trusted
474 {
475 version (D_TypeInfo)
476 {
477 import core.internal.array.utils : TraceHook, gcStatsPure, accumulatePure;
478 mixin(TraceHook!(T.stringof, "_d_newarrayT"));
479
480 return _d_newarrayT!T(length, isShared);
481 }
482 else
483 assert(0, "Cannot create new array if compiling without support for runtime type information!");
484 }
485 }
486
487 /**
488 * Create a new multi-dimensional array. Also initalize elements if their type has an initializer.
489 * Otherwise, not zero-initialize the array.
490 *
491 * ---
492 * void main()
493 * {
494 * S[][] s = new S[][](2, 3)
495 *
496 * // lowering:
497 * S[] s = _d_newarraymTX!(S[][], S)([2, 3]);
498 * }
499 * ---
500 *
501 * Params:
502 * dims = array length values for each dimension
503 * isShared = whether the array should be shared
504 *
505 * Returns:
506 * newly allocated array
507 */
508 Tarr _d_newarraymTX(Tarr : U[], T, U)(size_t[] dims, bool isShared=false) @trusted
509 {
510 debug(PRINTF) printf("_d_newarraymTX(dims.length = %zd)\n", dims.length);
511
512 if (dims.length == 0)
513 return null;
514
515 alias UnqT = Unqual!(T);
516
517 void[] __allocateInnerArray(size_t[] dims)
518 {
519 import core.internal.array.utils : __arrayAlloc;
520
521 auto dim = dims[0];
522
523 debug(PRINTF) printf("__allocateInnerArray(UnqT = %s, dim = %lu, ndims = %lu\n", UnqT.stringof.ptr, dim, dims.length);
524 if (dims.length == 1)
525 {
526 auto r = _d_newarrayT!UnqT(dim, isShared);
527 return *cast(void[]*)&r;
528 }
529
530 auto allocSize = (void[]).sizeof * dim;
531 // the array-of-arrays holds pointers! Don't use UnqT here!
532 auto arr = __arrayAlloc!(void[])(allocSize);
533
534 foreach (i; 0..dim)
535 {
536 (cast(void[]*)arr.ptr)[i] = __allocateInnerArray(dims[1..$]);
537 }
538 return arr.ptr[0 .. dim];
539 }
540
541 auto result = __allocateInnerArray(dims);
542 debug(PRINTF) printf("result = %p\n", result.ptr);
543
544 return (cast(U*) result.ptr)[0 .. dims[0]];
545 }
546
547 unittest
548 {
549 int[][] a = _d_newarraymTX!(int[][], int)([2, 3]);
550
551 assert(a.length == 2);
552 for (size_t i = 0; i < a.length; i++)
553 {
554 assert(a[i].length == 3);
555 for (size_t j = 0; j < a[i].length; j++)
556 assert(a[i][j] == 0);
557 }
558 }
559
560 unittest
561 {
562 struct S { int x = 1; }
563
564 S[][] a = _d_newarraymTX!(S[][], S)([2, 3]);
565
566 assert(a.length == 2);
567 for (size_t i = 0; i < a.length; i++)
568 {
569 assert(a[i].length == 3);
570 for (size_t j = 0; j < a[i].length; j++)
571 assert(a[i][j].x == 1);
572 }
573 }
574
575 // Test 3-level array allocation (this uses different code paths).
576 unittest
577 {
578 int[][][] a = _d_newarraymTX!(int[][][], int)([3, 4, 5]);
579 int[5] zeros = 0;
580
581 assert(a.length == 3);
582 foreach(l2; a)
583 {
584 assert(l2.length == 4);
585 foreach(l3; l2)
586 assert(l3 == zeros[]);
587 }
588 }
589
590 // https://issues.dlang.org/show_bug.cgi?id=24436
591 @system unittest
592 {
593 import core.memory : GC;
594
595 int[][] a = _d_newarraymTX!(int[][], int)([2, 2]);
596
597 assert(!(GC.getAttr(a.ptr) & GC.BlkAttr.NO_SCAN));
598 }
599
600 version (D_ProfileGC)
601 {
602 /**
603 * TraceGC wrapper around $(REF _d_newarraymT, core,internal,array,construction).
604 */
605 Tarr _d_newarraymTXTrace(Tarr : U[], T, U)(size_t[] dims, bool isShared=false, string file = __FILE__, int line = __LINE__, string funcname = __FUNCTION__) @trusted
606 {
607 version (D_TypeInfo)
608 {
609 import core.internal.array.utils : TraceHook, gcStatsPure, accumulatePure;
610 mixin(TraceHook!(T.stringof, "_d_newarraymTX"));
611
612 return _d_newarraymTX!(Tarr, T)(dims, isShared);
613 }
614 else
615 assert(0, "Cannot create new multi-dimensional array if compiling without support for runtime type information!");
616 }
617 }