1use std::ptr;
23use 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;
1617use crate::builder::{Builder, UNNAMED};
18use crate::context::SimpleCx;
19use crate::declare::declare_simple_fn;
20use crate::llvm::{self, TRUE, Type, TypeKind, 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_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 }
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_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 };
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) {
48let tail_ty = tcx.struct_tail_for_codegen(inner_ty, typing_env);
49if 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.
5253let layout = tcx.layout_of(typing_env.as_query_input(*element_ty));
54let elem_size = match layout {
55Ok(layout) => layout.size,
56Err(_) => {
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 };
60let elem_size: u32 = elem_size.bytes() as u32;
6162// We know that the length will be passed as extra arg.
63if !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.
70let 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 }
8485continue;
86 }
87 }
8889let layout = match tcx.layout_of(typing_env.as_query_input(*ty)) {
90Ok(layout) => layout.layout,
91Err(_) => {
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 };
9596let pass_mode = &fn_abi.args[i].mode;
9798// 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`
102if *pass_mode == PassMode::Ignore {
103 del_activities += 1;
104 da.remove(i);
105 }
106107// 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.
110if 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
119for _ in 0..new_activities.len() {
120let pos = new_positions.pop().unwrap();
121let activity = new_activities.pop().unwrap();
122 da.insert(pos, activity);
123 }
124}
125126// 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()?
150let cx = &builder.scx;
151let mut outer_pos: usize = 0;
152let mut activity_pos = 0;
153154// 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.
158let global_const = cx.declare_global("enzyme_const", cx.type_ptr());
159let global_out = cx.declare_global("enzyme_out", cx.type_ptr());
160let global_dup = cx.declare_global("enzyme_dup", cx.type_ptr());
161let global_dupv = cx.declare_global("enzyme_dupv", cx.type_ptr());
162let global_dupnoneed = cx.declare_global("enzyme_dupnoneed", cx.type_ptr());
163let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr());
164165while activity_pos < inputs.len() {
166let diff_activity = inputs[activity_pos];
167// Duplicated arguments received a shadow argument, into which enzyme will write the
168 // gradient.
169let (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 };
182let outer_arg = outer_args[outer_pos];
183 args.push(activity);
184if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) {
185let next_outer_arg = outer_args[outer_pos + 1];
186let 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.
193let 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);
204if duplicated {
205// We know that duplicated args by construction have a following argument,
206 // so this can not be out of bounds.
207let next_outer_arg = outer_args[outer_pos + 1];
208let 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.
212let slice = {
213if 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.
216false
217} else {
218let 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 };
223if 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);
230231let iterations =
232if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
233234for i in 0..iterations {
235let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
236let 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);
238let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
239let 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, ...).
251if #[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.
256args.push(next_outer_arg);
257 outer_pos += 2;
258 activity_pos += 1;
259260// Now, if width > 1, we need to account for that
261for _ in 1..width {
262let 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.
270outer_pos += 1;
271 activity_pos += 1;
272 }
273 }
274}
275276/// 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>> {
296let cx: &SimpleCx<'ll> = &bx.scx;
297// We have to pick the name depending on whether we want forward or reverse mode autodiff.
298let 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();
304305// 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.
307ad_name.push_str(outer_name);
308309// 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 // ```
335let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
336337// 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.
339let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
340let ad_fn = declare_simple_fn(
341cx,
342&ad_name,
343 llvm::CallConv::try_from(cc).expect("invalid callconv"),
344 llvm::UnnamedAddr::No,
345 llvm::Visibility::Default,
346enzyme_ty,
347 );
348349let num_args = llvm::LLVMCountParams(fn_to_diff);
350let mut args = Vec::with_capacity(num_argsas usize + 1);
351args.push(fn_to_diff);
352353let global_primal_ret = cx.declare_global("enzyme_primal_return", cx.type_ptr());
354if #[allow(non_exhaustive_omitted_patterns)] match attrs.ret_activity {
DiffActivity::Dual | DiffActivity::Active => true,
_ => false,
}matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
355args.push(global_primal_ret);
356 }
357if attrs.width > 1 {
358let global_width = cx.declare_global("enzyme_width", cx.type_ptr());
359args.push(global_width);
360args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
361 }
362363match_args_from_caller_to_enzyme(bx, attrs.width, &mut args, &attrs.input_activity, fn_args);
364365if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
366crate::typetree::add_tt(bx, fn_to_diff, fnc_tree);
367 }
368369let call = bx.call(enzyme_ty, None, None, ad_fn, ReturnSlot::Direct, &args, None, None);
370371let fn_ret_ty = bx.cx.val_ty(call);
372if 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.
377IntrinsicResult::Operand(OperandValue::ZeroSized)
378 } else if let Some(dest_place) = dest_place {
379bx.store_to_place(call, dest_place);
380 IntrinsicResult::WroteIntoPlace381 } else {
382 IntrinsicResult::Operand(
383OperandRef::from_immediate_or_packed_pair(bx, call, dest_layout).val,
384 )
385 }
386}