Skip to content

GVN misunderstands aliasing, can create overlapping assignments (again) #141313

Open
@saethlin

Description

@saethlin

This looks very similar to #141038, but the compiler that found this has the patch that was linked to that issue.

Reduced example from rustlantis, which is accepted by Miri without optimizations enabled:

#![feature(custom_mir, core_intrinsics)]
#![allow(internal_features)]

use std::intrinsics::mir::*;

#[custom_mir(dialect = "runtime")]
fn main() {
    mir!{
        let _1;
        let _2;
        let _3;
        {
            place!(Field(Variant(_1, 1), 0)) = 0u8;
            _3 = &_1;
            _2 = Field(Variant(*_3, 1), 0);
            _1 = Adt::Some(_2);
            Return()
        }
    }
}

#[allow(dead_code)]
enum Adt {
    None,
    Some(u8),
}

If I run this under Miri with -Zmir-enable-passes=+GVN, I see:

error: Undefined Behavior: `copy_nonoverlapping` called on overlapping ranges
  --> 4243580941269764965.rs:16:13
   |
16 |             _1 = Adt::Some(_2);
   |             ^^^^^^^^^^^^^^^^^^ `copy_nonoverlapping` called on overlapping ranges
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
   = note: BACKTRACE:
   = note: inside `main` at 4243580941269764965.rs:16:13: 16:31

The MIR diff for GVN is:

-// MIR for `main` before GVN
+// MIR for `main` after GVN
 
 fn main() -> () {
     let mut _0: ();
     let mut _1: Adt;
     let mut _2: u8;
     let mut _3: &Adt;
 
     bb0: {
         ((_1 as variant#1).0: u8) = const 0_u8;
         _3 = &_1;
         _2 = copy (((*_3) as variant#1).0: u8);
-        _1 = Adt::Some(copy _2);
+        _1 = copy (*_3);
         return;
     }
 }
rustc 1.89.0-nightly (60dabef95 2025-05-19)
binary: rustc
commit-hash: 60dabef95a3de3ec974dcb50926e4bfe743f078f
commit-date: 2025-05-19
host: aarch64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.5

Metadata

Metadata

Assignees

Labels

A-mir-optArea: MIR optimizationsA-mir-opt-GVNArea: MIR opt Global Value Numbering (GVN)A-rustlantisA miscompilation found by RustlantisC-bugCategory: This is a bug.I-miscompileIssue: Correct Rust code lowers to incorrect machine codeI-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-mediumMedium priorityT-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