Skip to content

Fails to optimize away trivial ownership move of Vec in high optimization levels #140057

Open
@WindFrank

Description

@WindFrank

I tried these codes:
https://godbolt.org/z/3je47cr9a

#![allow(dead_code)]
#![allow(non_camel_case_types)]

struct trie_node {
    content: Vec<String>,
    children: Vec<trie_node>,
}

#[no_mangle]
fn print_str_vector(vector: Vec<String>) {
    for string in &vector {
        println!("{}", *string);
    }
}

pub fn main() {
    let mut node: trie_node = trie_node {
        content: Vec::new(),
        children: Vec::new(),
    };
    let v = vec!["123".to_string(), "abc".to_string()];
    node.content = vec!["123".to_string(), "abc".to_string()];
    print_str_vector(v);
    print_str_vector(node.content.clone());
}

and:

#![allow(dead_code)]
#![allow(non_camel_case_types)]
struct trie_node {
    content: Vec<String>,
    children: Vec<trie_node>,
}

#[no_mangle]
fn print_str_vector(vector: Vec<String>) {
    for string in &vector {
        println!("{}", *string);
    }
}
pub fn main() {
    let mut node: trie_node = trie_node {
        content: Vec::new(),
        children: Vec::new(),
    };
    let v = vec!["123".to_string(), "abc".to_string()];
    node.content = vec!["123".to_string(), "abc".to_string()];
    print_str_vector(v);
    let temp_bridge_1080 = node.content;
    print_str_vector(temp_bridge_1080.clone());
}

I expected to see this happen:
Both expressions should produce identical assembly code.

Instead, this happened:
The second version of the code generated approximately 200 more lines of assembly compared to the first version.

The additional assembly appears to stem from the line: let temp_bridge_1080 = node.content;
Since this is a simple move operation (zero-cost abstraction in Rust), it should not introduce any runtime overhead or code bloat. This suggests a potential missed optimization opportunity in the compiler.

Could you please review them? Thank you!

Meta

rustc 1.85.0-nightly (d117b7f21 2024-12-31)
binary: rustc
commit-hash: d117b7f211835282b3b177dc64245fff0327c04c
commit-date: 2024-12-31
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-heavyIssue: Problems and improvements with respect to binary size of generated code.T-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