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