From b85f6a55e5ce63cc3a1259802ec7b56510fc520c Mon Sep 17 00:00:00 2001 From: jmh530 Date: Sun, 1 Nov 2026 20:19:04 -0500 Subject: [PATCH] Avoid compound multiplication in contiguous slice indexing Compute the accumulated stride with explicit multiplication instead of compound assignment. This avoids DMD's stale-register bug during optimized, inlined contiguous slice indexing. Use the expression unconditionally, without compiler or version guards. LDC generates identical optimized code for both expressions in the tested x86 and x64 configurations. Retain the regression test preserving the scoped ownership and indexing sequence that triggers the failure. AI-Assisted-By: Codex (GPT-6 Astra Medium) --- source/mir/ndslice/slice.d | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/source/mir/ndslice/slice.d b/source/mir/ndslice/slice.d index 813da2fd..52f84bcb 100644 --- a/source/mir/ndslice/slice.d +++ b/source/mir/ndslice/slice.d @@ -790,7 +790,7 @@ package(mir): ptrdiff_t stride = _indices[E] * ball; foreach_reverse (i; Iota!E) //static { - ball *= _lengths[i + 1]; + ball = _lengths[i + 1] * ball; assert(_indices[i] < _lengths[i], indexError!(DeepElement, i, N)); stride += ball * _indices[i]; } @@ -4240,3 +4240,29 @@ unittest assert(empty.shape == [0, 3]); assert(empty.elementCount == 0); } + +// DMD 2.113.x can reuse a stale index after inlining contiguous indexing. +// Keep the scoped owner and helper calls: they preserve the triggering code shape. +version(mir_ndslice_test) +unittest +{ + import mir.ndslice.allocation: mininitRcslice; + import mir.rc.array: RCI; + import mir.exception: enforce; + + static size_t status(A)(A a) { return 0; } + static void consume(A)(A a) { enforce!"failure"(status(a) == 0); } + + static Slice!(RCI!double, 2) makeMatrix()() + { + auto result = mininitRcslice!double(3, 3); + consume(result); + return result; + } + + { auto previous = makeMatrix(); } + auto matrix = makeMatrix(); + foreach (i; 0 .. 9) + matrix._iterator[i] = 1.0; + assert(matrix[0, 0] == 1 && matrix[1, 0] == 1 && matrix[1, 1] == 1); +}