Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asm_goto_with_outputs miscompilation #137867

Closed
quaternic opened this issue Mar 1, 2025 · 2 comments · Fixed by #138073
Closed

asm_goto_with_outputs miscompilation #137867

quaternic opened this issue Mar 1, 2025 · 2 comments · Fixed by #138073
Labels
A-inline-assembly Area: Inline assembly (`asm!(…)`) C-bug Category: This is a bug. F-asm `#![feature(asm)]` (not `llvm_asm`) I-miscompile Issue: Correct Rust code lowers to incorrect machine code T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@quaternic
Copy link

This should return 7, but returns a, with or without optimizations.

#![feature(asm_goto)]
#![feature(asm_goto_with_outputs)]

#[unsafe(no_mangle)]
pub fn asm_goto_test(
    mut a: i16,
) -> i16 {
    unsafe {
        std::arch::asm!(
            "jmp {op}",
            inout("eax") a,
            op = label { a = 7; },
            options(nostack,nomem)
        );
        a
    }
}

https://godbolt.org/z/Efze66G84

As far as I can tell, the MIR looks correct:

fn asm_goto_test(_1: i16) -> i16 {
    debug a => _1;
    let mut _0: i16;

    bb0: {
        asm!("jmp {1}", inout("ax") copy _1 => _1, label 1, options(NOMEM | NOSTACK)) -> [return: bb1, label: bb2, unwind unreachable];
    }

    bb1: {
        _0 = copy _1;
        return;
    }

    bb2: {
        _1 = const 7_i16;
        goto -> bb1;
    }
}

In particular, the value assigned to _1 in bb2 is returned in bb1.

The LLVM-IR is incorrect, as bb2 stores the value to ptr %a, but bb1 then overwrites that with the previous value in %2.

define i16 @asm_goto_test(i16 %0) unnamed_addr {
start:
  %a = alloca [2 x i8], align 2
  store i16 %0, ptr %a, align 2
  %1 = load i16, ptr %a, align 2
  %2 = callbr i16 asm sideeffect inteldialect "jmp ${2:l}", "=&{ax},0,!i,~{dirflag},~{fpsr},~{flags}"(i16 %1) #1
          to label %bb1 [label %bb2]

bb2:
  store i16 %2, ptr %a, align 2
  store i16 7, ptr %a, align 2
  br label %bb1

bb1:
  store i16 %2, ptr %a, align 2
  %_0 = load i16, ptr %a, align 2
  ret i16 %_0
}

rustc --version --verbose:

rustc 1.86.0-nightly (f85c6de55 2025-01-26)
binary: rustc
commit-hash: f85c6de55206dbee5ffedfd821df1503a7b92346
commit-date: 2025-01-26
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly
LLVM version: 19.1.7

asm_goto tracking issue: #119364

@rustbot label +F-asm +A-inline-assembly +T-compiler

@quaternic quaternic added the C-bug Category: This is a bug. label Mar 1, 2025
@rustbot rustbot added needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. A-inline-assembly Area: Inline assembly (`asm!(…)`) F-asm `#![feature(asm)]` (not `llvm_asm`) T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Mar 1, 2025
@Noratrieb Noratrieb added I-miscompile Issue: Correct Rust code lowers to incorrect machine code and removed needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. labels Mar 1, 2025
@tgross35
Copy link
Contributor

tgross35 commented Mar 2, 2025

Cc @nbdd0121

@bjorn3
Copy link
Member

bjorn3 commented Mar 4, 2025

Looks like

// Write results to outputs. We need to do this for all possible control flow.
//
// Note that `dest` maybe populated with unreachable_block when asm goto with outputs
// is used (because we need to codegen callbr which always needs a destination), so
// here we use the NORETURN option to determine if `dest` should be used.
for block in (if options.contains(InlineAsmOptions::NORETURN) { None } else { Some(dest) })
.into_iter()
.chain(labels.iter().copied().map(Some))
{
if let Some(block) = block {
self.switch_to_block(block);
}
for (idx, op) in operands.iter().enumerate() {
if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
| InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
{
let value = if output_types.len() == 1 {
result
} else {
self.extract_value(result, op_idx[&idx] as u64)
};
let value =
llvm_fixup_output(self, value, reg.reg_class(), &place.layout, instance);
OperandValue::Immediate(value).store(self, place);
}
}
}
appends the output write to every target block. In case of a critical edge that is not correct. Maybe the CriticalCallEdges MIR pass should perform the same critical edge splitting as for Call terminators?

@tmiasko tmiasko self-assigned this Mar 4, 2025
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Mar 7, 2025
… r=bjorn3

Break critical edges in inline asm before code generation

An inline asm terminator defines outputs along its target edges -- a
fallthrough target and labeled targets. Code generation implements this
by inserting code directly into the target blocks. This approach works
only if the target blocks don't have other predecessors.

Establish required invariant by extending existing code that breaks
critical edges before code generation.

Fixes rust-lang#137867.

r? `@bjorn3`
@bors bors closed this as completed in 1155f01 Mar 7, 2025
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Mar 7, 2025
Rollup merge of rust-lang#138073 - tmiasko:inline-asm-critical-edges, r=bjorn3

Break critical edges in inline asm before code generation

An inline asm terminator defines outputs along its target edges -- a
fallthrough target and labeled targets. Code generation implements this
by inserting code directly into the target blocks. This approach works
only if the target blocks don't have other predecessors.

Establish required invariant by extending existing code that breaks
critical edges before code generation.

Fixes rust-lang#137867.

r? ``@bjorn3``
@tmiasko tmiasko removed their assignment Mar 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-inline-assembly Area: Inline assembly (`asm!(…)`) C-bug Category: This is a bug. F-asm `#![feature(asm)]` (not `llvm_asm`) I-miscompile Issue: Correct Rust code lowers to incorrect machine code T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants