Iterating an array by value keeps a second copy of it on the stack even though the original is dead

オープン
#166,627 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
38/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
compilers, rust

調査の方向性

Start by reproducing the reported stack frames and memcpy calls with the linked Godbolt example, then trace how array by-value iteration is lowered through core::array::IntoIter and optimized by rustc and LLVM. Compare by_value with by_reference and drain_gen_block; done when the cause is identified and a compiler change eliminates the redundant array copy without changing iteration behavior.

索引モデルが issue の本文から書いたものです。

説明

A-array A-codegen A-iterators A-LLVM C-optimization S-has-mcve T-compiler

Iterating a local array by value (for value in array) copies the whole array into core::array::IntoIter with a memcpy, and both copies stay in the stack frame, even though the original array is never used again.

Iterating by reference doesn't have the copy.

Example (reduced by LLM from a real project for demo purposes):

#![feature(gen_blocks)]

use std::hint::black_box;

const N: usize = 128;

unsafe extern "Rust" {
    safe fn consume(value: u64);
}

/// Fully visible to the optimizer, the address of `batch` doesn't escape
#[inline(always)]
fn fill(batch: &mut [u64; N]) {
    let seed = black_box(1u64);
    for (offset, value) in (0u64..).zip(batch.iter_mut()) {
        *value = seed.wrapping_mul(offset);
    }
}

/// Iterating the array by value: the array is copied into `array::IntoIter`, the original is dead
/// afterwards, yet both copies stay on the stack
#[unsafe(no_mangle)]
pub fn by_value() {
    let mut batch = [0u64; N];
    fill(&mut batch);
    for value in batch {
        consume(value);
    }
}

/// The same with iteration by reference, only one array on the stack
#[unsafe(no_mangle)]
pub fn by_reference() {
    let mut batch = [0u64; N];
    fill(&mut batch);
    for &value in &batch {
        consume(value);
    }
}

/// In a `gen` block the iterator must live in the coroutine state, and the array is still built on
/// the stack of the resume function first
#[unsafe(no_mangle)]
pub fn gen_block() -> impl Iterator<Item = u64> {
    gen {
        let mut batch = [0u64; N];
        fill(&mut batch);
        for value in batch {
            yield value;
        }
    }
}

#[unsafe(no_mangle)]
pub fn drain_gen_block() {
    for value in gen_block() {
        consume(black_box(value));
    }
}

https://rust.godbolt.org/z/3rY7qcY79

On x86-64:

function frame (sub rsp) memcpy calls
by_value 2072 B 1 (1024 bytes, right after fill)
by_reference 1032 B 0
drain_gen_block 2080 B 1

I expected by_value to only need one array since batch is dead after it is moved (copied) into the iterator, so the iterator can use its storage, and the frame should be about the size of by_reference.

LLVM apparently has stack-move optimization in MemCpyOpt (https://reviews.llvm.org/D153453), but it doesn't kick in here.

While workarounds for this are possible, neither of them look as pretty as gen {} block.

Possibly related issues found by LLM
  • #87949 (array::IntoIter doesn't get optimized as well as vec::IntoIter, closed)
  • #86912 (array::map stack usage)
  • #84513 (the "copying large arrays" footgun listed as an open item of edition-dependent IntoIterator for arrays)
  • #64301 (too many memcpys)
  • #42763 (self moved with a memmove into an inlined into_iter())
  • #52274 (large by-value Copy arguments copied)
  • #99504 (callee futures built in a stack temporary and then copied into the caller's state)
  • #161506, #161568 (separate stack slots for call results due to MIR passes or MemCpyOpt)
Meta
rustc 1.102.0-nightly (65ce8611f 2026-11-18)
binary: rustc
commit-hash: 65ce8611fed3142053320be6996ef00e9992671f
commit-date: 2026-11-18
host: x86_64-unknown-linux-gnu
release: 1.102.0-nightly
LLVM version: 23.1.6
主要言語
Rust
スター
123k
フォーク
16.6k
平均マージ
2日 17時間
マージ済み PR(30日)
532

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

rust-lang/rust のほかの issue

rust-lang/rust の issue をすべて見る

似ている issue

Rust の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。