rustc_builtin_macros/
autodiff.rs

1//! This module contains the implementation of the `#[autodiff]` attribute.
2//! Currently our linter isn't smart enough to see that each import is used in one of the two
3//! configs (autodiff enabled or disabled), so we have to add cfg's to each import.
4//! FIXME(ZuseZ4): Remove this once we have a smarter linter.
5
6mod llvm_enzyme {
7    use std::str::FromStr;
8    use std::string::String;
9
10    use rustc_ast::expand::autodiff_attrs::{
11        AutoDiffAttrs, DiffActivity, DiffMode, valid_input_activity, valid_ret_activity,
12        valid_ty_for_activity,
13    };
14    use rustc_ast::token::{Lit, LitKind, Token, TokenKind};
15    use rustc_ast::tokenstream::*;
16    use rustc_ast::visit::AssocCtxt::*;
17    use rustc_ast::{
18        self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemKind, BindingMode,
19        FnRetTy, FnSig, GenericArg, GenericArgs, GenericParamKind, Generics, ItemKind,
20        MetaItemInner, PatKind, Path, PathSegment, TyKind, Visibility,
21    };
22    use rustc_expand::base::{Annotatable, ExtCtxt};
23    use rustc_span::{Ident, Span, Symbol, sym};
24    use thin_vec::{ThinVec, thin_vec};
25    use tracing::{debug, trace};
26
27    use crate::errors;
28
29    pub(crate) fn outer_normal_attr(
30        kind: &Box<rustc_ast::NormalAttr>,
31        id: rustc_ast::AttrId,
32        span: Span,
33    ) -> rustc_ast::Attribute {
34        let style = rustc_ast::AttrStyle::Outer;
35        let kind = rustc_ast::AttrKind::Normal(kind.clone());
36        rustc_ast::Attribute { kind, id, style, span }
37    }
38
39    // If we have a default `()` return type or explicitley `()` return type,
40    // then we often can skip doing some work.
41    fn has_ret(ty: &FnRetTy) -> bool {
42        match ty {
43            FnRetTy::Ty(ty) => !ty.kind.is_unit(),
44            FnRetTy::Default(_) => false,
45        }
46    }
47    fn first_ident(x: &MetaItemInner) -> rustc_span::Ident {
48        if let Some(l) = x.lit() {
49            match l.kind {
50                ast::LitKind::Int(val, _) => {
51                    // get an Ident from a lit
52                    return rustc_span::Ident::from_str(val.get().to_string().as_str());
53                }
54                _ => {}
55            }
56        }
57
58        let segments = &x.meta_item().unwrap().path.segments;
59        assert!(segments.len() == 1);
60        segments[0].ident
61    }
62
63    fn name(x: &MetaItemInner) -> String {
64        first_ident(x).name.to_string()
65    }
66
67    fn width(x: &MetaItemInner) -> Option<u128> {
68        let lit = x.lit()?;
69        match lit.kind {
70            ast::LitKind::Int(x, _) => Some(x.get()),
71            _ => return None,
72        }
73    }
74
75    // Get information about the function the macro is applied to
76    fn extract_item_info(iitem: &Box<ast::Item>) -> Option<(Visibility, FnSig, Ident, Generics)> {
77        match &iitem.kind {
78            ItemKind::Fn(box ast::Fn { sig, ident, generics, .. }) => {
79                Some((iitem.vis.clone(), sig.clone(), ident.clone(), generics.clone()))
80            }
81            _ => None,
82        }
83    }
84
85    pub(crate) fn from_ast(
86        ecx: &mut ExtCtxt<'_>,
87        meta_item: &ThinVec<MetaItemInner>,
88        has_ret: bool,
89        mode: DiffMode,
90    ) -> AutoDiffAttrs {
91        let dcx = ecx.sess.dcx();
92
93        // Now we check, whether the user wants autodiff in batch/vector mode, or scalar mode.
94        // If he doesn't specify an integer (=width), we default to scalar mode, thus width=1.
95        let mut first_activity = 1;
96
97        let width = if let [_, x, ..] = &meta_item[..]
98            && let Some(x) = width(x)
99        {
100            first_activity = 2;
101            match x.try_into() {
102                Ok(x) => x,
103                Err(_) => {
104                    dcx.emit_err(errors::AutoDiffInvalidWidth {
105                        span: meta_item[1].span(),
106                        width: x,
107                    });
108                    return AutoDiffAttrs::error();
109                }
110            }
111        } else {
112            1
113        };
114
115        let mut activities: Vec<DiffActivity> = vec![];
116        let mut errors = false;
117        for x in &meta_item[first_activity..] {
118            let activity_str = name(&x);
119            let res = DiffActivity::from_str(&activity_str);
120            match res {
121                Ok(x) => activities.push(x),
122                Err(_) => {
123                    dcx.emit_err(errors::AutoDiffUnknownActivity {
124                        span: x.span(),
125                        act: activity_str,
126                    });
127                    errors = true;
128                }
129            };
130        }
131        if errors {
132            return AutoDiffAttrs::error();
133        }
134
135        // If a return type exist, we need to split the last activity,
136        // otherwise we return None as placeholder.
137        let (ret_activity, input_activity) = if has_ret {
138            let Some((last, rest)) = activities.split_last() else {
139                unreachable!(
140                    "should not be reachable because we counted the number of activities previously"
141                );
142            };
143            (last, rest)
144        } else {
145            (&DiffActivity::None, activities.as_slice())
146        };
147
148        AutoDiffAttrs {
149            mode,
150            width,
151            ret_activity: *ret_activity,
152            input_activity: input_activity.to_vec(),
153        }
154    }
155
156    fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec<TokenTree>) {
157        let comma: Token = Token::new(TokenKind::Comma, Span::default());
158        let val = first_ident(t);
159        let t = Token::from_ast_ident(val);
160        ts.push(TokenTree::Token(t, Spacing::Joint));
161        ts.push(TokenTree::Token(comma.clone(), Spacing::Alone));
162    }
163
164    pub(crate) fn expand_forward(
165        ecx: &mut ExtCtxt<'_>,
166        expand_span: Span,
167        meta_item: &ast::MetaItem,
168        item: Annotatable,
169    ) -> Vec<Annotatable> {
170        expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Forward)
171    }
172
173    pub(crate) fn expand_reverse(
174        ecx: &mut ExtCtxt<'_>,
175        expand_span: Span,
176        meta_item: &ast::MetaItem,
177        item: Annotatable,
178    ) -> Vec<Annotatable> {
179        expand_with_mode(ecx, expand_span, meta_item, item, DiffMode::Reverse)
180    }
181
182    /// We expand the autodiff macro to generate a new placeholder function which passes
183    /// type-checking and can be called by users. The exact signature of the generated function
184    /// depends on the configuration provided by the user, but here is an example:
185    ///
186    /// ```
187    /// #[autodiff(cos_box, Reverse, Duplicated, Active)]
188    /// fn sin(x: &Box<f32>) -> f32 {
189    ///     f32::sin(**x)
190    /// }
191    /// ```
192    /// which becomes expanded to:
193    /// ```
194    /// #[rustc_autodiff]
195    /// fn sin(x: &Box<f32>) -> f32 {
196    ///     f32::sin(**x)
197    /// }
198    /// #[rustc_autodiff(Reverse, Duplicated, Active)]
199    /// fn cos_box(x: &Box<f32>, dx: &mut Box<f32>, dret: f32) -> f32 {
200    ///     std::intrinsics::autodiff(sin::<>, cos_box::<>, (x, dx, dret))
201    /// }
202    /// ```
203    /// FIXME(ZuseZ4): Once autodiff is enabled by default, make this a doc comment which is checked
204    /// in CI.
205    pub(crate) fn expand_with_mode(
206        ecx: &mut ExtCtxt<'_>,
207        expand_span: Span,
208        meta_item: &ast::MetaItem,
209        mut item: Annotatable,
210        mode: DiffMode,
211    ) -> Vec<Annotatable> {
212        if cfg!(not(llvm_enzyme)) {
213            ecx.sess.dcx().emit_err(errors::AutoDiffSupportNotBuild { span: meta_item.span });
214            return vec![item];
215        }
216        let dcx = ecx.sess.dcx();
217
218        // first get information about the annotable item: visibility, signature, name and generic
219        // parameters.
220        // these will be used to generate the differentiated version of the function
221        let Some((vis, sig, primal, generics, impl_of_trait)) = (match &item {
222            Annotatable::Item(iitem) => {
223                extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false))
224            }
225            Annotatable::Stmt(stmt) => match &stmt.kind {
226                ast::StmtKind::Item(iitem) => {
227                    extract_item_info(iitem).map(|(v, s, p, g)| (v, s, p, g, false))
228                }
229                _ => None,
230            },
231            Annotatable::AssocItem(assoc_item, Impl { of_trait }) => match &assoc_item.kind {
232                ast::AssocItemKind::Fn(box ast::Fn { sig, ident, generics, .. }) => Some((
233                    assoc_item.vis.clone(),
234                    sig.clone(),
235                    ident.clone(),
236                    generics.clone(),
237                    *of_trait,
238                )),
239                _ => None,
240            },
241            _ => None,
242        }) else {
243            dcx.emit_err(errors::AutoDiffInvalidApplication { span: item.span() });
244            return vec![item];
245        };
246
247        let meta_item_vec: ThinVec<MetaItemInner> = match meta_item.kind {
248            ast::MetaItemKind::List(ref vec) => vec.clone(),
249            _ => {
250                dcx.emit_err(errors::AutoDiffMissingConfig { span: item.span() });
251                return vec![item];
252            }
253        };
254
255        let has_ret = has_ret(&sig.decl.output);
256
257        // create TokenStream from vec elemtents:
258        // meta_item doesn't have a .tokens field
259        let mut ts: Vec<TokenTree> = vec![];
260        if meta_item_vec.len() < 1 {
261            // At the bare minimum, we need a fnc name.
262            dcx.emit_err(errors::AutoDiffMissingConfig { span: item.span() });
263            return vec![item];
264        }
265
266        let mode_symbol = match mode {
267            DiffMode::Forward => sym::Forward,
268            DiffMode::Reverse => sym::Reverse,
269            _ => unreachable!("Unsupported mode: {:?}", mode),
270        };
271
272        // Insert mode token
273        let mode_token = Token::new(TokenKind::Ident(mode_symbol, false.into()), Span::default());
274        ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint));
275        ts.insert(
276            1,
277            TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone),
278        );
279
280        // Now, if the user gave a width (vector aka batch-mode ad), then we copy it.
281        // If it is not given, we default to 1 (scalar mode).
282        let start_position;
283        let kind: LitKind = LitKind::Integer;
284        let symbol;
285        if meta_item_vec.len() >= 2
286            && let Some(width) = width(&meta_item_vec[1])
287        {
288            start_position = 2;
289            symbol = Symbol::intern(&width.to_string());
290        } else {
291            start_position = 1;
292            symbol = sym::integer(1);
293        }
294
295        let l: Lit = Lit { kind, symbol, suffix: None };
296        let t = Token::new(TokenKind::Literal(l), Span::default());
297        let comma = Token::new(TokenKind::Comma, Span::default());
298        ts.push(TokenTree::Token(t, Spacing::Joint));
299        ts.push(TokenTree::Token(comma.clone(), Spacing::Alone));
300
301        for t in meta_item_vec.clone()[start_position..].iter() {
302            meta_item_inner_to_ts(t, &mut ts);
303        }
304
305        if !has_ret {
306            // We don't want users to provide a return activity if the function doesn't return anything.
307            // For simplicity, we just add a dummy token to the end of the list.
308            let t = Token::new(TokenKind::Ident(sym::None, false.into()), Span::default());
309            ts.push(TokenTree::Token(t, Spacing::Joint));
310            ts.push(TokenTree::Token(comma, Spacing::Alone));
311        }
312        // We remove the last, trailing comma.
313        ts.pop();
314        let ts: TokenStream = TokenStream::from_iter(ts);
315
316        let x: AutoDiffAttrs = from_ast(ecx, &meta_item_vec, has_ret, mode);
317        if !x.is_active() {
318            // We encountered an error, so we return the original item.
319            // This allows us to potentially parse other attributes.
320            return vec![item];
321        }
322        let span = ecx.with_def_site_ctxt(expand_span);
323
324        let d_sig = gen_enzyme_decl(ecx, &sig, &x, span);
325
326        let d_body = ecx.block(
327            span,
328            thin_vec![call_autodiff(
329                ecx,
330                primal,
331                first_ident(&meta_item_vec[0]),
332                span,
333                &d_sig,
334                &generics,
335                impl_of_trait,
336            )],
337        );
338
339        // The first element of it is the name of the function to be generated
340        let d_fn = Box::new(ast::Fn {
341            defaultness: ast::Defaultness::Final,
342            sig: d_sig,
343            ident: first_ident(&meta_item_vec[0]),
344            generics,
345            contract: None,
346            body: Some(d_body),
347            define_opaque: None,
348        });
349        let mut rustc_ad_attr =
350            Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff)));
351
352        let ts2: Vec<TokenTree> = vec![TokenTree::Token(
353            Token::new(TokenKind::Ident(sym::never, false.into()), span),
354            Spacing::Joint,
355        )];
356        let never_arg = ast::DelimArgs {
357            dspan: DelimSpan::from_single(span),
358            delim: ast::token::Delimiter::Parenthesis,
359            tokens: TokenStream::from_iter(ts2),
360        };
361        let inline_item = ast::AttrItem {
362            unsafety: ast::Safety::Default,
363            path: ast::Path::from_ident(Ident::with_dummy_span(sym::inline)),
364            args: ast::AttrArgs::Delimited(never_arg),
365            tokens: None,
366        };
367        let inline_never_attr = Box::new(ast::NormalAttr { item: inline_item, tokens: None });
368        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
369        let attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
370        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
371        let inline_never = outer_normal_attr(&inline_never_attr, new_id, span);
372
373        // We're avoid duplicating the attribute `#[rustc_autodiff]`.
374        fn same_attribute(attr: &ast::AttrKind, item: &ast::AttrKind) -> bool {
375            match (attr, item) {
376                (ast::AttrKind::Normal(a), ast::AttrKind::Normal(b)) => {
377                    let a = &a.item.path;
378                    let b = &b.item.path;
379                    a.segments.len() == b.segments.len()
380                        && a.segments.iter().zip(b.segments.iter()).all(|(a, b)| a.ident == b.ident)
381                }
382                _ => false,
383            }
384        }
385
386        let mut has_inline_never = false;
387
388        // Don't add it multiple times:
389        let orig_annotatable: Annotatable = match item {
390            Annotatable::Item(ref mut iitem) => {
391                if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
392                    iitem.attrs.push(attr);
393                }
394                if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
395                    has_inline_never = true;
396                }
397                Annotatable::Item(iitem.clone())
398            }
399            Annotatable::AssocItem(ref mut assoc_item, i @ Impl { .. }) => {
400                if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
401                    assoc_item.attrs.push(attr);
402                }
403                if assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
404                    has_inline_never = true;
405                }
406                Annotatable::AssocItem(assoc_item.clone(), i)
407            }
408            Annotatable::Stmt(ref mut stmt) => {
409                match stmt.kind {
410                    ast::StmtKind::Item(ref mut iitem) => {
411                        if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
412                            iitem.attrs.push(attr);
413                        }
414                        if iitem.attrs.iter().any(|a| same_attribute(&a.kind, &inline_never.kind)) {
415                            has_inline_never = true;
416                        }
417                    }
418                    _ => unreachable!("stmt kind checked previously"),
419                };
420
421                Annotatable::Stmt(stmt.clone())
422            }
423            _ => {
424                unreachable!("annotatable kind checked previously")
425            }
426        };
427        // Now update for d_fn
428        rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs {
429            dspan: DelimSpan::dummy(),
430            delim: rustc_ast::token::Delimiter::Parenthesis,
431            tokens: ts,
432        });
433
434        let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id();
435        let d_attr = outer_normal_attr(&rustc_ad_attr, new_id, span);
436
437        // If the source function has the `#[inline(never)]` attribute, we'll also add it to the diff function
438        let mut d_attrs = thin_vec![d_attr];
439
440        if has_inline_never {
441            d_attrs.push(inline_never);
442        }
443
444        let d_annotatable = match &item {
445            Annotatable::AssocItem(_, _) => {
446                let assoc_item: AssocItemKind = ast::AssocItemKind::Fn(d_fn);
447                let d_fn = Box::new(ast::AssocItem {
448                    attrs: d_attrs,
449                    id: ast::DUMMY_NODE_ID,
450                    span,
451                    vis,
452                    kind: assoc_item,
453                    tokens: None,
454                });
455                Annotatable::AssocItem(d_fn, Impl { of_trait: false })
456            }
457            Annotatable::Item(_) => {
458                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
459                d_fn.vis = vis;
460
461                Annotatable::Item(d_fn)
462            }
463            Annotatable::Stmt(_) => {
464                let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn));
465                d_fn.vis = vis;
466
467                Annotatable::Stmt(Box::new(ast::Stmt {
468                    id: ast::DUMMY_NODE_ID,
469                    kind: ast::StmtKind::Item(d_fn),
470                    span,
471                }))
472            }
473            _ => {
474                unreachable!("item kind checked previously")
475            }
476        };
477
478        return vec![orig_annotatable, d_annotatable];
479    }
480
481    // shadow arguments (the extra ones which were not in the original (primal) function), in reverse mode must be
482    // mutable references or ptrs, because Enzyme will write into them.
483    fn assure_mut_ref(ty: &ast::Ty) -> ast::Ty {
484        let mut ty = ty.clone();
485        match ty.kind {
486            TyKind::Ptr(ref mut mut_ty) => {
487                mut_ty.mutbl = ast::Mutability::Mut;
488            }
489            TyKind::Ref(_, ref mut mut_ty) => {
490                mut_ty.mutbl = ast::Mutability::Mut;
491            }
492            _ => {
493                panic!("unsupported type: {:?}", ty);
494            }
495        }
496        ty
497    }
498
499    // Generate `autodiff` intrinsic call
500    // ```
501    // std::intrinsics::autodiff(source, diff, (args))
502    // ```
503    fn call_autodiff(
504        ecx: &ExtCtxt<'_>,
505        primal: Ident,
506        diff: Ident,
507        span: Span,
508        d_sig: &FnSig,
509        generics: &Generics,
510        is_impl: bool,
511    ) -> rustc_ast::Stmt {
512        let primal_path_expr = gen_turbofish_expr(ecx, primal, generics, span, is_impl);
513        let diff_path_expr = gen_turbofish_expr(ecx, diff, generics, span, is_impl);
514
515        let tuple_expr = ecx.expr_tuple(
516            span,
517            d_sig
518                .decl
519                .inputs
520                .iter()
521                .map(|arg| match arg.pat.kind {
522                    PatKind::Ident(_, ident, _) => ecx.expr_path(ecx.path_ident(span, ident)),
523                    _ => todo!(),
524                })
525                .collect::<ThinVec<_>>()
526                .into(),
527        );
528
529        let enzyme_path_idents = ecx.std_path(&[sym::intrinsics, sym::autodiff]);
530        let enzyme_path = ecx.path(span, enzyme_path_idents);
531        let call_expr = ecx.expr_call(
532            span,
533            ecx.expr_path(enzyme_path),
534            vec![primal_path_expr, diff_path_expr, tuple_expr].into(),
535        );
536
537        ecx.stmt_expr(call_expr)
538    }
539
540    // Generate turbofish expression from fn name and generics
541    // Given `foo` and `<A, B, C>` params, gen `foo::<A, B, C>`
542    // We use this expression when passing primal and diff function to the autodiff intrinsic
543    fn gen_turbofish_expr(
544        ecx: &ExtCtxt<'_>,
545        ident: Ident,
546        generics: &Generics,
547        span: Span,
548        is_impl: bool,
549    ) -> Box<ast::Expr> {
550        let generic_args = generics
551            .params
552            .iter()
553            .filter_map(|p| match &p.kind {
554                GenericParamKind::Type { .. } => {
555                    let path = ast::Path::from_ident(p.ident);
556                    let ty = ecx.ty_path(path);
557                    Some(AngleBracketedArg::Arg(GenericArg::Type(ty)))
558                }
559                GenericParamKind::Const { .. } => {
560                    let expr = ecx.expr_path(ast::Path::from_ident(p.ident));
561                    let anon_const = AnonConst { id: ast::DUMMY_NODE_ID, value: expr };
562                    Some(AngleBracketedArg::Arg(GenericArg::Const(anon_const)))
563                }
564                GenericParamKind::Lifetime { .. } => None,
565            })
566            .collect::<ThinVec<_>>();
567
568        let args: AngleBracketedArgs = AngleBracketedArgs { span, args: generic_args };
569
570        let segment = PathSegment {
571            ident,
572            id: ast::DUMMY_NODE_ID,
573            args: Some(Box::new(GenericArgs::AngleBracketed(args))),
574        };
575
576        let segments = if is_impl {
577            thin_vec![
578                PathSegment { ident: Ident::from_str("Self"), id: ast::DUMMY_NODE_ID, args: None },
579                segment,
580            ]
581        } else {
582            thin_vec![segment]
583        };
584
585        let path = Path { span, segments, tokens: None };
586
587        ecx.expr_path(path)
588    }
589
590    // Generate the new function declaration. Const arguments are kept as is. Duplicated arguments must
591    // be pointers or references. Those receive a shadow argument, which is a mutable reference/pointer.
592    // Active arguments must be scalars. Their shadow argument is added to the return type (and will be
593    // zero-initialized by Enzyme).
594    // Each argument of the primal function (and the return type if existing) must be annotated with an
595    // activity.
596    //
597    // Error handling: If the user provides an invalid configuration (incorrect numbers, types, or
598    // both), we emit an error and return the original signature. This allows us to continue parsing.
599    // FIXME(Sa4dUs): make individual activities' span available so errors
600    // can point to only the activity instead of the entire attribute
601    fn gen_enzyme_decl(
602        ecx: &ExtCtxt<'_>,
603        sig: &ast::FnSig,
604        x: &AutoDiffAttrs,
605        span: Span,
606    ) -> ast::FnSig {
607        let dcx = ecx.sess.dcx();
608        let has_ret = has_ret(&sig.decl.output);
609        let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 };
610        let num_activities = x.input_activity.len() + if x.has_ret_activity() { 1 } else { 0 };
611        if sig_args != num_activities {
612            dcx.emit_err(errors::AutoDiffInvalidNumberActivities {
613                span,
614                expected: sig_args,
615                found: num_activities,
616            });
617            // This is not the right signature, but we can continue parsing.
618            return sig.clone();
619        }
620        assert!(sig.decl.inputs.len() == x.input_activity.len());
621        assert!(has_ret == x.has_ret_activity());
622        let mut d_decl = sig.decl.clone();
623        let mut d_inputs = Vec::new();
624        let mut new_inputs = Vec::new();
625        let mut idents = Vec::new();
626        let mut act_ret = ThinVec::new();
627
628        // We have two loops, a first one just to check the activities and types and possibly report
629        // multiple errors in one compilation session.
630        let mut errors = false;
631        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
632            if !valid_input_activity(x.mode, *activity) {
633                dcx.emit_err(errors::AutoDiffInvalidApplicationModeAct {
634                    span,
635                    mode: x.mode.to_string(),
636                    act: activity.to_string(),
637                });
638                errors = true;
639            }
640            if !valid_ty_for_activity(&arg.ty, *activity) {
641                dcx.emit_err(errors::AutoDiffInvalidTypeForActivity {
642                    span: arg.ty.span,
643                    act: activity.to_string(),
644                });
645                errors = true;
646            }
647        }
648
649        if has_ret && !valid_ret_activity(x.mode, x.ret_activity) {
650            dcx.emit_err(errors::AutoDiffInvalidRetAct {
651                span,
652                mode: x.mode.to_string(),
653                act: x.ret_activity.to_string(),
654            });
655            // We don't set `errors = true` to avoid annoying type errors relative
656            // to the expanded macro type signature
657        }
658
659        if errors {
660            // This is not the right signature, but we can continue parsing.
661            return sig.clone();
662        }
663
664        let unsafe_activities = x
665            .input_activity
666            .iter()
667            .any(|&act| matches!(act, DiffActivity::DuplicatedOnly | DiffActivity::DualOnly));
668        for (arg, activity) in sig.decl.inputs.iter().zip(x.input_activity.iter()) {
669            d_inputs.push(arg.clone());
670            match activity {
671                DiffActivity::Active => {
672                    act_ret.push(arg.ty.clone());
673                    // if width =/= 1, then push [arg.ty; width] to act_ret
674                }
675                DiffActivity::ActiveOnly => {
676                    // We will add the active scalar to the return type.
677                    // This is handled later.
678                }
679                DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => {
680                    for i in 0..x.width {
681                        let mut shadow_arg = arg.clone();
682                        // We += into the shadow in reverse mode.
683                        shadow_arg.ty = Box::new(assure_mut_ref(&arg.ty));
684                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
685                            ident.name
686                        } else {
687                            debug!("{:#?}", &shadow_arg.pat);
688                            panic!("not an ident?");
689                        };
690                        let name: String = format!("d{}_{}", old_name, i);
691                        new_inputs.push(name.clone());
692                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
693                        shadow_arg.pat = Box::new(ast::Pat {
694                            id: ast::DUMMY_NODE_ID,
695                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
696                            span: shadow_arg.pat.span,
697                            tokens: shadow_arg.pat.tokens.clone(),
698                        });
699                        d_inputs.push(shadow_arg.clone());
700                    }
701                }
702                DiffActivity::Dual
703                | DiffActivity::DualOnly
704                | DiffActivity::Dualv
705                | DiffActivity::DualvOnly => {
706                    // the *v variants get lowered to enzyme_dupv and enzyme_dupnoneedv, which cause
707                    // Enzyme to not expect N arguments, but one argument (which is instead larger).
708                    let iterations =
709                        if matches!(activity, DiffActivity::Dualv | DiffActivity::DualvOnly) {
710                            1
711                        } else {
712                            x.width
713                        };
714                    for i in 0..iterations {
715                        let mut shadow_arg = arg.clone();
716                        let old_name = if let PatKind::Ident(_, ident, _) = arg.pat.kind {
717                            ident.name
718                        } else {
719                            debug!("{:#?}", &shadow_arg.pat);
720                            panic!("not an ident?");
721                        };
722                        let name: String = format!("b{}_{}", old_name, i);
723                        new_inputs.push(name.clone());
724                        let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span);
725                        shadow_arg.pat = Box::new(ast::Pat {
726                            id: ast::DUMMY_NODE_ID,
727                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
728                            span: shadow_arg.pat.span,
729                            tokens: shadow_arg.pat.tokens.clone(),
730                        });
731                        d_inputs.push(shadow_arg.clone());
732                    }
733                }
734                DiffActivity::Const => {
735                    // Nothing to do here.
736                }
737                DiffActivity::None | DiffActivity::FakeActivitySize(_) => {
738                    panic!("Should not happen");
739                }
740            }
741            if let PatKind::Ident(_, ident, _) = arg.pat.kind {
742                idents.push(ident.clone());
743            } else {
744                panic!("not an ident?");
745            }
746        }
747
748        let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly;
749        if active_only_ret {
750            assert!(x.mode.is_rev());
751        }
752
753        // If we return a scalar in the primal and the scalar is active,
754        // then add it as last arg to the inputs.
755        if x.mode.is_rev() {
756            match x.ret_activity {
757                DiffActivity::Active | DiffActivity::ActiveOnly => {
758                    let ty = match d_decl.output {
759                        FnRetTy::Ty(ref ty) => ty.clone(),
760                        FnRetTy::Default(span) => {
761                            panic!("Did not expect Default ret ty: {:?}", span);
762                        }
763                    };
764                    let name = "dret".to_string();
765                    let ident = Ident::from_str_and_span(&name, ty.span);
766                    let shadow_arg = ast::Param {
767                        attrs: ThinVec::new(),
768                        ty: ty.clone(),
769                        pat: Box::new(ast::Pat {
770                            id: ast::DUMMY_NODE_ID,
771                            kind: PatKind::Ident(BindingMode::NONE, ident, None),
772                            span: ty.span,
773                            tokens: None,
774                        }),
775                        id: ast::DUMMY_NODE_ID,
776                        span: ty.span,
777                        is_placeholder: false,
778                    };
779                    d_inputs.push(shadow_arg);
780                    new_inputs.push(name);
781                }
782                _ => {}
783            }
784        }
785        d_decl.inputs = d_inputs.into();
786
787        if x.mode.is_fwd() {
788            let ty = match d_decl.output {
789                FnRetTy::Ty(ref ty) => ty.clone(),
790                FnRetTy::Default(span) => {
791                    // We want to return std::hint::black_box(()).
792                    let kind = TyKind::Tup(ThinVec::new());
793                    let ty = Box::new(rustc_ast::Ty {
794                        kind,
795                        id: ast::DUMMY_NODE_ID,
796                        span,
797                        tokens: None,
798                    });
799                    d_decl.output = FnRetTy::Ty(ty.clone());
800                    assert!(matches!(x.ret_activity, DiffActivity::None));
801                    // this won't be used below, so any type would be fine.
802                    ty
803                }
804            };
805
806            if matches!(x.ret_activity, DiffActivity::Dual | DiffActivity::Dualv) {
807                let kind = if x.width == 1 || matches!(x.ret_activity, DiffActivity::Dualv) {
808                    // Dual can only be used for f32/f64 ret.
809                    // In that case we return now a tuple with two floats.
810                    TyKind::Tup(thin_vec![ty.clone(), ty.clone()])
811                } else {
812                    // We have to return [T; width+1], +1 for the primal return.
813                    let anon_const = rustc_ast::AnonConst {
814                        id: ast::DUMMY_NODE_ID,
815                        value: ecx.expr_usize(span, 1 + x.width as usize),
816                    };
817                    TyKind::Array(ty.clone(), anon_const)
818                };
819                let ty = Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None });
820                d_decl.output = FnRetTy::Ty(ty);
821            }
822            if matches!(x.ret_activity, DiffActivity::DualOnly | DiffActivity::DualvOnly) {
823                // No need to change the return type,
824                // we will just return the shadow in place of the primal return.
825                // However, if we have a width > 1, then we don't return -> T, but -> [T; width]
826                if x.width > 1 {
827                    let anon_const = rustc_ast::AnonConst {
828                        id: ast::DUMMY_NODE_ID,
829                        value: ecx.expr_usize(span, x.width as usize),
830                    };
831                    let kind = TyKind::Array(ty.clone(), anon_const);
832                    let ty =
833                        Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None });
834                    d_decl.output = FnRetTy::Ty(ty);
835                }
836            }
837        }
838
839        // If we use ActiveOnly, drop the original return value.
840        d_decl.output =
841            if active_only_ret { FnRetTy::Default(span) } else { d_decl.output.clone() };
842
843        trace!("act_ret: {:?}", act_ret);
844
845        // If we have an active input scalar, add it's gradient to the
846        // return type. This might require changing the return type to a
847        // tuple.
848        if act_ret.len() > 0 {
849            let ret_ty = match d_decl.output {
850                FnRetTy::Ty(ref ty) => {
851                    if !active_only_ret {
852                        act_ret.insert(0, ty.clone());
853                    }
854                    let kind = TyKind::Tup(act_ret);
855                    Box::new(rustc_ast::Ty { kind, id: ty.id, span: ty.span, tokens: None })
856                }
857                FnRetTy::Default(span) => {
858                    if act_ret.len() == 1 {
859                        act_ret[0].clone()
860                    } else {
861                        let kind = TyKind::Tup(act_ret.iter().map(|arg| arg.clone()).collect());
862                        Box::new(rustc_ast::Ty { kind, id: ast::DUMMY_NODE_ID, span, tokens: None })
863                    }
864                }
865            };
866            d_decl.output = FnRetTy::Ty(ret_ty);
867        }
868
869        let mut d_header = sig.header.clone();
870        if unsafe_activities {
871            d_header.safety = rustc_ast::Safety::Unsafe(span);
872        }
873        let d_sig = FnSig { header: d_header, decl: d_decl, span };
874        trace!("Generated signature: {:?}", d_sig);
875        d_sig
876    }
877}
878
879pub(crate) use llvm_enzyme::{expand_forward, expand_reverse};