1use std::ptr;
23use 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;
1617use crate::builder::{Builder, UNNAMED};
18use crate::context::SimpleCx;
19use crate::declare::declare_simple_fn;
20use crate::llvm::{self, TRUE, Type, Value};
2122pub(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) {
28if !#[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 }
3132// We don't actually pass the types back into the type system.
33 // All we do is decide how to handle the arguments.
34let fn_sig = fn_ptr_ty.fn_sig(tcx);
35let sig = fn_sig.skip_binder();
3637// FIXME(Sa4dUs): pass proper varargs once we have support for differentiating variadic functions
38let Ok(fn_abi) = tcx.fn_abi_of_fn_ptr(typing_env.as_query_input((fn_sig, ty::List::empty())))
39else {
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 };
4243let mut new_activities = ::alloc::vec::Vec::new()vec![];
44let mut new_positions = ::alloc::vec::Vec::new()vec![];
45let mut del_activities = 0;
46for (i, ty) in sig.inputs().iter().enumerate() {
47if let Some(inner_ty) = ty.builtin_deref(true) {
48if 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.
51let sty = match inner_ty.builtin_index() {
52Some(sty) => sty,
53None => {
54{ ::core::panicking::panic_fmt(format_args!("slice element type unknown")); };panic!("slice element type unknown");
55 }
56 };
57let pci = PseudoCanonicalInput {
58 typing_env: TypingEnv::fully_monomorphized(),
59 value: sty,
60 };
6162let layout = tcx.layout_of(pci);
63let elem_size = match layout {
64Ok(layout) => layout.size,
65Err(_) => {
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 };
69let elem_size: u32 = elem_size.bytes() as u32;
7071// We know that the length will be passed as extra arg.
72if !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.
79let 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 }
9394continue;
95 }
96 }
9798let pci = PseudoCanonicalInput { typing_env: TypingEnv::fully_monomorphized(), value: *ty };
99100let layout = match tcx.layout_of(pci) {
101Ok(layout) => layout.layout,
102Err(_) => {
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 };
106107let pass_mode = &fn_abi.args[i].mode;
108109// 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`
113if *pass_mode == PassMode::Ignore {
114 del_activities += 1;
115 da.remove(i);
116 }
117118// 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.
121if let rustc_abi::BackendRepr::ScalarPair { a: _, b: _, b_offset: _ } =
122 layout.backend_repr()
123 {
124 new_activities.push(da[i].clone());
125 new_positions.push(i + 1 - del_activities);
126 }
127 }
128// now add the extra activities coming from slices
129 // Reverse order to not invalidate the indices
130for _ in 0..new_activities.len() {
131let pos = new_positions.pop().unwrap();
132let activity = new_activities.pop().unwrap();
133 da.insert(pos, activity);
134 }
135}
136137// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
138// original inputs, as well as metadata and the additional shadow arguments.
139// This function matches the arguments from the outer function to the inner enzyme call.
140//
141// This function also considers that Rust level arguments not always match the llvm-ir level
142// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
143// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
144// need to match those.
145// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
146// using iterators and peek()?
147fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
148 builder: &mut Builder<'_, 'll, 'tcx>,
149 width: u32,
150 args: &mut Vec<&'ll Value>,
151 inputs: &[DiffActivity],
152 outer_args: &[&'ll Value],
153) {
154{
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:154",
"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(154u32),
::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");
155// We now handle the issue that Rust level arguments not always match the llvm-ir level
156 // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
157 // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
158 // need to match those.
159 // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
160 // using iterators and peek()?
161let cx = &builder.scx;
162let mut outer_pos: usize = 0;
163let mut activity_pos = 0;
164165// We used to use llvm's metadata to instruct enzyme how to differentiate a function.
166 // In debug mode we would use incremental compilation which caused the metadata to be
167 // dropped. This is prevented by now using named globals, which are also understood
168 // by Enzyme.
169let global_const = cx.declare_global("enzyme_const", cx.type_ptr());
170let global_out = cx.declare_global("enzyme_out", cx.type_ptr());
171let global_dup = cx.declare_global("enzyme_dup", cx.type_ptr());
172let global_dupv = cx.declare_global("enzyme_dupv", cx.type_ptr());
173let global_dupnoneed = cx.declare_global("enzyme_dupnoneed", cx.type_ptr());
174let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr());
175176while activity_pos < inputs.len() {
177let diff_activity = inputs[activity_pos as usize];
178// Duplicated arguments received a shadow argument, into which enzyme will write the
179 // gradient.
180let (activity, duplicated): (&Value, bool) = match diff_activity {
181 DiffActivity::None => { ::core::panicking::panic_fmt(format_args!("not a valid input activity")); }panic!("not a valid input activity"),
182 DiffActivity::Const => (global_const, false),
183 DiffActivity::Active => (global_out, false),
184 DiffActivity::ActiveOnly => (global_out, false),
185 DiffActivity::Dual => (global_dup, true),
186 DiffActivity::Dualv => (global_dupv, true),
187 DiffActivity::DualOnly => (global_dupnoneed, true),
188 DiffActivity::DualvOnly => (global_dupnoneedv, true),
189 DiffActivity::Duplicated => (global_dup, true),
190 DiffActivity::DuplicatedOnly => (global_dupnoneed, true),
191 DiffActivity::FakeActivitySize(_) => (global_const, false),
192 };
193let outer_arg = outer_args[outer_pos];
194 args.push(activity);
195if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) {
196let next_outer_arg = outer_args[outer_pos + 1];
197let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
198 DiffActivity::FakeActivitySize(Some(s)) => s.into(),
199_ => ::rustc_middle::util::bug::bug_fmt(format_args!("incorrect Dualv handling recognized."))bug!("incorrect Dualv handling recognized."),
200 };
201// stride: sizeof(T) * n_elems.
202 // n_elems is the next integer.
203 // Now we multiply `4 * next_outer_arg` to get the stride.
204let mul = unsafe {
205 llvm::LLVMBuildMul(
206 builder.llbuilder,
207 cx.get_const_int(cx.type_i64(), elem_bytes_size),
208 next_outer_arg,
209 UNNAMED,
210 )
211 };
212 args.push(mul);
213 }
214 args.push(outer_arg);
215if duplicated {
216// We know that duplicated args by construction have a following argument,
217 // so this can not be out of bounds.
218let next_outer_arg = outer_args[outer_pos + 1];
219let next_outer_ty = cx.val_ty(next_outer_arg);
220// FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
221 // vectors behind references (&Vec<T>) are already supported. Users can not pass a
222 // Vec by value for reverse mode, so this would only help forward mode autodiff.
223let slice = {
224if activity_pos + 1 >= inputs.len() {
225// If there is no arg following our ptr, it also can't be a slice,
226 // since that would lead to a ptr, int pair.
227false
228} else {
229let next_activity = inputs[activity_pos + 1];
230// We analyze the MIR types and add this dummy activity if we visit a slice.
231#[allow(non_exhaustive_omitted_patterns)] match next_activity {
DiffActivity::FakeActivitySize(_) => true,
_ => false,
}matches!(next_activity, DiffActivity::FakeActivitySize(_))232 }
233 };
234if slice {
235// A duplicated slice will have the following two outer_fn arguments:
236 // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
237 // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
238 // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
239 // int2 >= int1, which means the shadow vector is large enough to store the gradient.
240{
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);
241242let iterations =
243if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
244245for i in 0..iterations {
246let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
247let next_outer_ty2 = cx.val_ty(next_outer_arg2);
248{
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);
249let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
250let next_outer_ty3 = cx.val_ty(next_outer_arg3);
251{
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);
252 args.push(next_outer_arg2);
253 }
254 args.push(global_const);
255 args.push(next_outer_arg);
256 outer_pos += 2 + 2 * iterations;
257 activity_pos += 2;
258 } else {
259// A duplicated pointer will have the following two outer_fn arguments:
260 // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
261 // (..., metadata! enzyme_dup, ptr, ptr, ...).
262if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => true,
_ => false,
}matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)263 {
264{
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);
265 }
266// In the case of Dual we don't have assumptions, e.g. f32 would be valid.
267args.push(next_outer_arg);
268 outer_pos += 2;
269 activity_pos += 1;
270271// Now, if width > 1, we need to account for that
272for _ in 1..width {
273let next_outer_arg = outer_args[outer_pos];
274 args.push(next_outer_arg);
275 outer_pos += 1;
276 }
277 }
278 } else {
279// We do not differentiate with resprect to this argument.
280 // We already added the metadata and argument above, so just increase the counters.
281outer_pos += 1;
282 activity_pos += 1;
283 }
284 }
285}
286287/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
288/// function with expected naming and calling conventions[^1] which will be
289/// discovered by the enzyme LLVM pass and its body populated with the differentiated
290/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
291/// function and handle the differences between the Rust calling convention and
292/// Enzyme.
293/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
294// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
295// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
296pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
297 bx: &mut Builder<'_, 'll, 'tcx>,
298 fn_to_diff: &'ll Value,
299 outer_name: &str,
300 ret_ty: &'ll Type,
301 fn_args: &[&'ll Value],
302 attrs: &RustcAutodiff,
303 dest_layout: ty::layout::TyAndLayout<'tcx>,
304 dest_place: Option<PlaceValue<&'ll Value>>,
305 fnc_tree: FncTree,
306) -> IntrinsicResult<'tcx, &'ll Value> {
307let cx: &SimpleCx<'ll> = &bx.scx;
308// We have to pick the name depending on whether we want forward or reverse mode autodiff.
309let mut ad_name: String = match attrs.mode {
310 DiffMode::Forward => "__enzyme_fwddiff",
311 DiffMode::Reverse => "__enzyme_autodiff",
312_ => {
::core::panicking::panic_fmt(format_args!("logic bug in autodiff, unrecognized mode"));
}panic!("logic bug in autodiff, unrecognized mode"),
313 }
314 .to_string();
315316// add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
317 // functions. Unwrap will only panic, if LLVM gave us an invalid string.
318ad_name.push_str(outer_name);
319320// Let us assume the user wrote the following function square:
321 //
322 // ```llvm
323 // define double @square(double %x) {
324 // entry:
325 // %0 = fmul double %x, %x
326 // ret double %0
327 // }
328 //
329 // define double @dsquare(double %x) {
330 // return 0.0;
331 // }
332 // ```
333 //
334 // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
335 // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
336 // Again, the arguments to all functions are slightly simplified.
337 // ```llvm
338 // declare double @__enzyme_autodiff_square(...)
339 //
340 // define double @dsquare(double %x) {
341 // entry:
342 // %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
343 // ret double %0
344 // }
345 // ```
346let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
347348// FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
349 // think a bit more about what should go here.
350let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
351let ad_fn = declare_simple_fn(
352cx,
353&ad_name,
354 llvm::CallConv::try_from(cc).expect("invalid callconv"),
355 llvm::UnnamedAddr::No,
356 llvm::Visibility::Default,
357enzyme_ty,
358 );
359360let num_args = llvm::LLVMCountParams(&fn_to_diff);
361let mut args = Vec::with_capacity(num_argsas usize + 1);
362args.push(fn_to_diff);
363364let global_primal_ret = cx.declare_global("enzyme_primal_return", cx.type_ptr());
365if #[allow(non_exhaustive_omitted_patterns)] match attrs.ret_activity {
DiffActivity::Dual | DiffActivity::Active => true,
_ => false,
}matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
366args.push(global_primal_ret);
367 }
368if attrs.width > 1 {
369let global_width = cx.declare_global("enzyme_width", cx.type_ptr());
370args.push(global_width);
371args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
372 }
373374match_args_from_caller_to_enzyme(bx, attrs.width, &mut args, &attrs.input_activity, fn_args);
375376if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
377crate::typetree::add_tt(&bx, fn_to_diff, fnc_tree);
378 }
379380let call = bx.call(enzyme_ty, None, None, ad_fn, &args, None, None);
381382let fn_ret_ty = bx.cx.val_ty(call);
383if fn_ret_ty == bx.cx.type_void() || fn_ret_ty == bx.cx.type_struct(&[], false) {
384// If we return void or an empty struct, then our caller (due to how we generated it)
385 // does not expect a return value. As such, we have no pointer (or place) into which
386 // we could store our value, and would store into an undef, which would cause UB.
387 // As such, we just ignore the return value in those cases.
388IntrinsicResult::Operand(OperandValue::ZeroSized)
389 } else if let Some(dest_place) = dest_place {
390bx.store_to_place(call, dest_place);
391 IntrinsicResult::WroteIntoPlace
392 } else {
393 IntrinsicResult::Operand(
394 OperandRef::from_immediate_or_packed_pair(bx, call, dest_layout).val,
395 )
396 }
397}