Skip to main content

rustc_codegen_llvm/builder/
autodiff.rs

1use std::ptr;
2
3use rustc_ast::expand::autodiff_attrs::{DiffActivity, DiffMode};
4use rustc_ast::expand::typetree::FncTree;
5use rustc_codegen_ssa::common::TypeKind;
6use rustc_codegen_ssa::mir::IntrinsicResult;
7use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
8use rustc_codegen_ssa::mir::place::PlaceValue;
9use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods};
10use rustc_data_structures::thin_vec::ThinVec;
11use rustc_hir::attrs::RustcAutodiff;
12use rustc_middle::ty::{PseudoCanonicalInput, Ty, TyCtxt, TypingEnv};
13use rustc_middle::{bug, ty};
14use rustc_target::callconv::PassMode;
15use tracing::debug;
16
17use crate::builder::{Builder, UNNAMED};
18use crate::context::SimpleCx;
19use crate::declare::declare_simple_fn;
20use crate::llvm::{self, TRUE, Type, Value};
21
22pub(crate) fn adjust_activity_to_abi<'tcx>(
23    tcx: TyCtxt<'tcx>,
24    fn_ptr_ty: Ty<'tcx>,
25    typing_env: TypingEnv<'tcx>,
26    da: &mut ThinVec<DiffActivity>,
27) {
28    if !#[allow(non_exhaustive_omitted_patterns)] match fn_ptr_ty.kind() {
    ty::FnPtr(..) => true,
    _ => false,
}matches!(fn_ptr_ty.kind(), ty::FnPtr(..)) {
29        ::rustc_middle::util::bug::bug_fmt(format_args!("expected fn ptr for autodiff, got {0:?}",
        fn_ptr_ty));bug!("expected fn ptr for autodiff, got {:?}", fn_ptr_ty);
30    }
31
32    // We don't actually pass the types back into the type system.
33    // All we do is decide how to handle the arguments.
34    let fn_sig = fn_ptr_ty.fn_sig(tcx);
35    let sig = fn_sig.skip_binder();
36
37    // FIXME(Sa4dUs): pass proper varargs once we have support for differentiating variadic functions
38    let Ok(fn_abi) = tcx.fn_abi_of_fn_ptr(typing_env.as_query_input((fn_sig, ty::List::empty())))
39    else {
40        ::rustc_middle::util::bug::bug_fmt(format_args!("failed to get fn_abi of fn_ptr with empty varargs"));bug!("failed to get fn_abi of fn_ptr with empty varargs");
41    };
42
43    let mut new_activities = ::alloc::vec::Vec::new()vec![];
44    let mut new_positions = ::alloc::vec::Vec::new()vec![];
45    let mut del_activities = 0;
46    for (i, ty) in sig.inputs().iter().enumerate() {
47        if let Some(inner_ty) = ty.builtin_deref(true) {
48            if inner_ty.is_slice() {
49                // Now we need to figure out the size of each slice element in memory to allow
50                // safety checks and usability improvements in the backend.
51                let sty = match inner_ty.builtin_index() {
52                    Some(sty) => sty,
53                    None => {
54                        { ::core::panicking::panic_fmt(format_args!("slice element type unknown")); };panic!("slice element type unknown");
55                    }
56                };
57                let pci = PseudoCanonicalInput {
58                    typing_env: TypingEnv::fully_monomorphized(),
59                    value: sty,
60                };
61
62                let layout = tcx.layout_of(pci);
63                let elem_size = match layout {
64                    Ok(layout) => layout.size,
65                    Err(_) => {
66                        ::rustc_middle::util::bug::bug_fmt(format_args!("autodiff failed to compute slice element size"));bug!("autodiff failed to compute slice element size");
67                    }
68                };
69                let elem_size: u32 = elem_size.bytes() as u32;
70
71                // We know that the length will be passed as extra arg.
72                if !da.is_empty() {
73                    // We are looking at a slice. The length of that slice will become an
74                    // extra integer on llvm level. Integers are always const.
75                    // However, if the slice get's duplicated, we want to know to later check the
76                    // size. So we mark the new size argument as FakeActivitySize.
77                    // There is one FakeActivitySize per slice, so for convenience we store the
78                    // slice element size in bytes in it. We will use the size in the backend.
79                    let activity = match da[i] {
80                        DiffActivity::DualOnly
81                        | DiffActivity::Dual
82                        | DiffActivity::Dualv
83                        | DiffActivity::DuplicatedOnly
84                        | DiffActivity::Duplicated => {
85                            DiffActivity::FakeActivitySize(Some(elem_size))
86                        }
87                        DiffActivity::Const => DiffActivity::Const,
88                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected activity for ptr/ref"))bug!("unexpected activity for ptr/ref"),
89                    };
90                    new_activities.push(activity);
91                    new_positions.push(i + 1);
92                }
93
94                continue;
95            }
96        }
97
98        let pci = PseudoCanonicalInput { typing_env: TypingEnv::fully_monomorphized(), value: *ty };
99
100        let layout = match tcx.layout_of(pci) {
101            Ok(layout) => layout.layout,
102            Err(_) => {
103                ::rustc_middle::util::bug::bug_fmt(format_args!("failed to compute layout for type {0:?}",
        ty));bug!("failed to compute layout for type {:?}", ty);
104            }
105        };
106
107        let pass_mode = &fn_abi.args[i].mode;
108
109        // For ZST, just ignore and don't add its activity, as this arg won't be present
110        // in the LLVM passed to Enzyme.
111        // Some targets pass ZST indirectly in the C ABI, in that case, handle it as a normal arg
112        // FIXME(Sa4dUs): Enforce ZST corresponding diff activity be `Const`
113        if *pass_mode == PassMode::Ignore {
114            del_activities += 1;
115            da.remove(i);
116        }
117
118        // If the argument is lowered as a `ScalarPair`, we need to duplicate its activity.
119        // Otherwise, the number of activities won't match the number of LLVM arguments and
120        // this will lead to errors when verifying the Enzyme call.
121        if let rustc_abi::BackendRepr::ScalarPair(_, _) = layout.backend_repr() {
122            new_activities.push(da[i].clone());
123            new_positions.push(i + 1 - del_activities);
124        }
125    }
126    // now add the extra activities coming from slices
127    // Reverse order to not invalidate the indices
128    for _ in 0..new_activities.len() {
129        let pos = new_positions.pop().unwrap();
130        let activity = new_activities.pop().unwrap();
131        da.insert(pos, activity);
132    }
133}
134
135// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
136// original inputs, as well as metadata and the additional shadow arguments.
137// This function matches the arguments from the outer function to the inner enzyme call.
138//
139// This function also considers that Rust level arguments not always match the llvm-ir level
140// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
141// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
142// need to match those.
143// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
144// using iterators and peek()?
145fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
146    cx: &SimpleCx<'ll>,
147    builder: &mut Builder<'_, 'll, 'tcx>,
148    width: u32,
149    args: &mut Vec<&'ll Value>,
150    inputs: &[DiffActivity],
151    outer_args: &[&'ll Value],
152) {
153    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder/autodiff.rs:153",
                        "rustc_codegen_llvm::builder::autodiff",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder/autodiff.rs"),
                        ::tracing_core::__macro_support::Option::Some(153u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder::autodiff"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("matching autodiff arguments")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("matching autodiff arguments");
154    // We now handle the issue that Rust level arguments not always match the llvm-ir level
155    // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
156    // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
157    // need to match those.
158    // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
159    // using iterators and peek()?
160    let mut outer_pos: usize = 0;
161    let mut activity_pos = 0;
162
163    // We used to use llvm's metadata to instruct enzyme how to differentiate a function.
164    // In debug mode we would use incremental compilation which caused the metadata to be
165    // dropped. This is prevented by now using named globals, which are also understood
166    // by Enzyme.
167    let global_const = cx.declare_global("enzyme_const", cx.type_ptr());
168    let global_out = cx.declare_global("enzyme_out", cx.type_ptr());
169    let global_dup = cx.declare_global("enzyme_dup", cx.type_ptr());
170    let global_dupv = cx.declare_global("enzyme_dupv", cx.type_ptr());
171    let global_dupnoneed = cx.declare_global("enzyme_dupnoneed", cx.type_ptr());
172    let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr());
173
174    while activity_pos < inputs.len() {
175        let diff_activity = inputs[activity_pos as usize];
176        // Duplicated arguments received a shadow argument, into which enzyme will write the
177        // gradient.
178        let (activity, duplicated): (&Value, bool) = match diff_activity {
179            DiffActivity::None => { ::core::panicking::panic_fmt(format_args!("not a valid input activity")); }panic!("not a valid input activity"),
180            DiffActivity::Const => (global_const, false),
181            DiffActivity::Active => (global_out, false),
182            DiffActivity::ActiveOnly => (global_out, false),
183            DiffActivity::Dual => (global_dup, true),
184            DiffActivity::Dualv => (global_dupv, true),
185            DiffActivity::DualOnly => (global_dupnoneed, true),
186            DiffActivity::DualvOnly => (global_dupnoneedv, true),
187            DiffActivity::Duplicated => (global_dup, true),
188            DiffActivity::DuplicatedOnly => (global_dupnoneed, true),
189            DiffActivity::FakeActivitySize(_) => (global_const, false),
190        };
191        let outer_arg = outer_args[outer_pos];
192        args.push(activity);
193        if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
    DiffActivity::Dualv => true,
    _ => false,
}matches!(diff_activity, DiffActivity::Dualv) {
194            let next_outer_arg = outer_args[outer_pos + 1];
195            let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
196                DiffActivity::FakeActivitySize(Some(s)) => s.into(),
197                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("incorrect Dualv handling recognized."))bug!("incorrect Dualv handling recognized."),
198            };
199            // stride: sizeof(T) * n_elems.
200            // n_elems is the next integer.
201            // Now we multiply `4 * next_outer_arg` to get the stride.
202            let mul = unsafe {
203                llvm::LLVMBuildMul(
204                    builder.llbuilder,
205                    cx.get_const_int(cx.type_i64(), elem_bytes_size),
206                    next_outer_arg,
207                    UNNAMED,
208                )
209            };
210            args.push(mul);
211        }
212        args.push(outer_arg);
213        if duplicated {
214            // We know that duplicated args by construction have a following argument,
215            // so this can not be out of bounds.
216            let next_outer_arg = outer_args[outer_pos + 1];
217            let next_outer_ty = cx.val_ty(next_outer_arg);
218            // FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
219            // vectors behind references (&Vec<T>) are already supported. Users can not pass a
220            // Vec by value for reverse mode, so this would only help forward mode autodiff.
221            let slice = {
222                if activity_pos + 1 >= inputs.len() {
223                    // If there is no arg following our ptr, it also can't be a slice,
224                    // since that would lead to a ptr, int pair.
225                    false
226                } else {
227                    let next_activity = inputs[activity_pos + 1];
228                    // We analyze the MIR types and add this dummy activity if we visit a slice.
229                    #[allow(non_exhaustive_omitted_patterns)] match next_activity {
    DiffActivity::FakeActivitySize(_) => true,
    _ => false,
}matches!(next_activity, DiffActivity::FakeActivitySize(_))
230                }
231            };
232            if slice {
233                // A duplicated slice will have the following two outer_fn arguments:
234                // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
235                // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
236                // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
237                // int2 >= int1, which means the shadow vector is large enough to store the gradient.
238                {
    match (&cx.type_kind(next_outer_ty), &TypeKind::Integer) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer);
239
240                let iterations =
241                    if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
    DiffActivity::Dualv => true,
    _ => false,
}matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
242
243                for i in 0..iterations {
244                    let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
245                    let next_outer_ty2 = cx.val_ty(next_outer_arg2);
246                    {
    match (&cx.type_kind(next_outer_ty2), &TypeKind::Pointer) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer);
247                    let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
248                    let next_outer_ty3 = cx.val_ty(next_outer_arg3);
249                    {
    match (&cx.type_kind(next_outer_ty3), &TypeKind::Integer) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cx.type_kind(next_outer_ty3), TypeKind::Integer);
250                    args.push(next_outer_arg2);
251                }
252                args.push(global_const);
253                args.push(next_outer_arg);
254                outer_pos += 2 + 2 * iterations;
255                activity_pos += 2;
256            } else {
257                // A duplicated pointer will have the following two outer_fn arguments:
258                // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
259                // (..., metadata! enzyme_dup, ptr, ptr, ...).
260                if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
    DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => true,
    _ => false,
}matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)
261                {
262                    {
    match (&cx.type_kind(next_outer_ty), &TypeKind::Pointer) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Pointer);
263                }
264                // In the case of Dual we don't have assumptions, e.g. f32 would be valid.
265                args.push(next_outer_arg);
266                outer_pos += 2;
267                activity_pos += 1;
268
269                // Now, if width > 1, we need to account for that
270                for _ in 1..width {
271                    let next_outer_arg = outer_args[outer_pos];
272                    args.push(next_outer_arg);
273                    outer_pos += 1;
274                }
275            }
276        } else {
277            // We do not differentiate with resprect to this argument.
278            // We already added the metadata and argument above, so just increase the counters.
279            outer_pos += 1;
280            activity_pos += 1;
281        }
282    }
283}
284
285/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
286/// function with expected naming and calling conventions[^1] which will be
287/// discovered by the enzyme LLVM pass and its body populated with the differentiated
288/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
289/// function and handle the differences between the Rust calling convention and
290/// Enzyme.
291/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
292// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
293// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
294pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
295    builder: &mut Builder<'_, 'll, 'tcx>,
296    cx: &SimpleCx<'ll>,
297    fn_to_diff: &'ll Value,
298    outer_name: &str,
299    ret_ty: &'ll Type,
300    fn_args: &[&'ll Value],
301    attrs: &RustcAutodiff,
302    dest_layout: ty::layout::TyAndLayout<'tcx>,
303    dest_place: Option<PlaceValue<&'ll Value>>,
304    fnc_tree: FncTree,
305) -> IntrinsicResult<'tcx, &'ll Value> {
306    // We have to pick the name depending on whether we want forward or reverse mode autodiff.
307    let mut ad_name: String = match attrs.mode {
308        DiffMode::Forward => "__enzyme_fwddiff",
309        DiffMode::Reverse => "__enzyme_autodiff",
310        _ => {
    ::core::panicking::panic_fmt(format_args!("logic bug in autodiff, unrecognized mode"));
}panic!("logic bug in autodiff, unrecognized mode"),
311    }
312    .to_string();
313
314    // add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
315    // functions. Unwrap will only panic, if LLVM gave us an invalid string.
316    ad_name.push_str(outer_name);
317
318    // Let us assume the user wrote the following function square:
319    //
320    // ```llvm
321    // define double @square(double %x) {
322    // entry:
323    //  %0 = fmul double %x, %x
324    //  ret double %0
325    // }
326    //
327    // define double @dsquare(double %x) {
328    //  return 0.0;
329    // }
330    // ```
331    //
332    // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
333    // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
334    // Again, the arguments to all functions are slightly simplified.
335    // ```llvm
336    // declare double @__enzyme_autodiff_square(...)
337    //
338    // define double @dsquare(double %x) {
339    // entry:
340    //   %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
341    //   ret double %0
342    // }
343    // ```
344    let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
345
346    // FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
347    // think a bit more about what should go here.
348    let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
349    let ad_fn = declare_simple_fn(
350        cx,
351        &ad_name,
352        llvm::CallConv::try_from(cc).expect("invalid callconv"),
353        llvm::UnnamedAddr::No,
354        llvm::Visibility::Default,
355        enzyme_ty,
356    );
357
358    let num_args = llvm::LLVMCountParams(&fn_to_diff);
359    let mut args = Vec::with_capacity(num_args as usize + 1);
360    args.push(fn_to_diff);
361
362    let global_primal_ret = cx.declare_global("enzyme_primal_return", cx.type_ptr());
363    if #[allow(non_exhaustive_omitted_patterns)] match attrs.ret_activity {
    DiffActivity::Dual | DiffActivity::Active => true,
    _ => false,
}matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
364        args.push(global_primal_ret);
365    }
366    if attrs.width > 1 {
367        let global_width = cx.declare_global("enzyme_width", cx.type_ptr());
368        args.push(global_width);
369        args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
370    }
371
372    match_args_from_caller_to_enzyme(
373        &cx,
374        builder,
375        attrs.width,
376        &mut args,
377        &attrs.input_activity,
378        fn_args,
379    );
380
381    if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
382        crate::typetree::add_tt(cx.llmod, cx.llcx, fn_to_diff, fnc_tree);
383    }
384
385    let call = builder.call(enzyme_ty, None, None, ad_fn, &args, None, None);
386
387    let fn_ret_ty = builder.cx.val_ty(call);
388    if fn_ret_ty == builder.cx.type_void() || fn_ret_ty == builder.cx.type_struct(&[], false) {
389        // If we return void or an empty struct, then our caller (due to how we generated it)
390        // does not expect a return value. As such, we have no pointer (or place) into which
391        // we could store our value, and would store into an undef, which would cause UB.
392        // As such, we just ignore the return value in those cases.
393        IntrinsicResult::Operand(OperandValue::ZeroSized)
394    } else if let Some(dest_place) = dest_place {
395        builder.store_to_place(call, dest_place);
396        IntrinsicResult::WroteIntoPlace
397    } else {
398        IntrinsicResult::Operand(
399            OperandRef::from_immediate_or_packed_pair(builder, call, dest_layout).val,
400        )
401    }
402}