Skip to content

autodiff not handling void returns #147144

@ZuseZ4

Description

@ZuseZ4

I tried this code:

#![feature(autodiff)]                       
use std::autodiff::*;

#[autodiff_reverse(bar, Duplicated, Duplicated)]
pub fn foo(r: &[f64; 10], res: &mut f64) {
    let mut output = [0.0; 10];
    output[0] = r[0];
    output[1] = r[1] * r[2];
    output[2] = r[4] * r[5];
    output[3] = r[2] * r[6];
    output[4] = r[1] * r[7];
    output[5] = r[2] * r[8];
    output[6] = r[1] * r[9];
    output[7] = r[5] * r[6];
    output[8] = r[5] * r[7];
    output[9] = r[4] * r[8];
    *res = output.iter().sum();
}
fn main() {
    let inputs = Box::new([3.1; 10]);
    let mut d_inputs = Box::new([0.0; 10]);
    let mut res = Box::new(0.0);
    let mut d_res = Box::new(1.0);

    bar(&inputs, &mut d_inputs, &mut res, &mut d_res);
    dbg!(&d_inputs);
}

I expected to see this happen: runs

Instead, this happened:

    Finished `release` profile [optimized] target(s) in 4.82s
     Running `target/release/foo`
[1]    396935 illegal hardware instruction (core dumped)  RUSTFLAGS="-Z autodiff=Enable,LooseTypes" cargo +enzyme run --release

The reason is the IR which we generate, it has UB if our autodiff call doesn't return anything:

%27 = call {} (...) @__enzyme_autodiff_ZN5piprx8d_energy17hfdc5833849837ebfE(ptr @_ZN5piprx16f_energy_inplace17h5cbf6d64465cb049E, metadata !"enzyme_dup", ptr %18, ptr          %20, metadata !"enzyme_const", ptr %22, metadata !"enzyme_dup", ptr %24, ptr %26)
       1   store {} %27, ptr undef, align 1

As a consequence, everything afterwards is marked as unreachable, triggering the error.

Solution. If I remove builder.store_to_place(call, dest.val); from

builder.store_to_place(call, dest.val);
,
then it works in this case.
@Sa4dUs Do you think that just checking for void return here is enough, or are there more things to consider?

Meta

The latest master.

Backtrace

<backtrace>

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.F-autodiff`#![feature(autodiff)]`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