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