Skip to content

Missed optimization: RVO isn't applied #116541

Open
@gootorov

Description

@gootorov

Consider the code below. At the first glace, it looks like RVO/destination propagation isn't applied, resulting in a stack overflow.

File structure

tree .

.
├── bin
│   └── rvo.rs
├── Cargo.toml
├── src
│   └── lib.rs

Code

Cargo.toml

[package]
name = "rvo"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "rvo"
path = "bin/rvo.rs"

[dependencies]

[profile.release]
lto = "fat"

bin/rvo.rs

use rvo::Outer;

fn main() {
    let _foo = Box::new(Outer::new());
}

src/lib.rs

#![allow(unused)]

const SIZE: usize = 1024 * 1024 * 1024;

pub struct Outer {
    a: LargeStruct,
}

impl Outer {
    #[inline(always)]
    pub fn new() -> Self {
        let a = LargeStruct::new();

        Self { a }
    }
}

pub struct LargeStruct {
    d0: Option<Box<u128>>,
    d1: Option<Box<u128>>,
    d2: Option<Box<u128>>,
    d3: Option<Box<u128>>,
    d4: Option<Box<u128>>,
    huge: [u8; SIZE],
}

impl LargeStruct {
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            d0: None,
            d1: None,
            d2: None,
            d3: None,
            d4: None,
            huge: [0; SIZE],
        }
    }
}

Running cargo run --release results in:

    Finished release [optimized] target(s) in 0.01s
     Running `target/release/rvo`

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted (core dumped)

Compiler version:
rustc --version --verbose

rustc 1.73.0 (cc66ad468 2023-10-03)
binary: rustc
commit-hash: cc66ad468955717ab92600c770da8c1601a4ff33
commit-date: 2023-10-03
host: x86_64-unknown-linux-gnu
release: 1.73.0
LLVM version: 17.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationA-mir-optArea: MIR optimizationsA-mir-opt-nrvoFixed by the Named Return Value Opt. (NRVO)C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions