rustc_codegen_ssa/
codegen_attrs.rs

1use std::str::FromStr;
2
3use rustc_abi::{Align, ExternAbi};
4use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
5use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr};
6use rustc_hir::attrs::{AttributeKind, InlineAttr, InstructionSetAttr, UsedBy};
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_hir::{self as hir, Attribute, LangItem, find_attr, lang_items};
10use rustc_middle::middle::codegen_fn_attrs::{
11    CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
12};
13use rustc_middle::query::Providers;
14use rustc_middle::span_bug;
15use rustc_middle::ty::{self as ty, TyCtxt};
16use rustc_session::lint;
17use rustc_session::parse::feature_err;
18use rustc_span::{Ident, Span, sym};
19use rustc_target::spec::SanitizerSet;
20
21use crate::errors;
22use crate::errors::NoMangleNameless;
23use crate::target_features::{
24    check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
25};
26
27/// In some cases, attributes are only valid on functions, but it's the `check_attr`
28/// pass that checks that they aren't used anywhere else, rather than this module.
29/// In these cases, we bail from performing further checks that are only meaningful for
30/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
31/// report a delayed bug, just in case `check_attr` isn't doing its job.
32fn try_fn_sig<'tcx>(
33    tcx: TyCtxt<'tcx>,
34    did: LocalDefId,
35    attr_span: Span,
36) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
37    use DefKind::*;
38
39    let def_kind = tcx.def_kind(did);
40    if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
41        Some(tcx.fn_sig(did))
42    } else {
43        tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
44        None
45    }
46}
47
48// FIXME(jdonszelmann): remove when instruction_set becomes a parsed attr
49fn parse_instruction_set_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> Option<InstructionSetAttr> {
50    let list = attr.meta_item_list()?;
51
52    match &list[..] {
53        [MetaItemInner::MetaItem(set)] => {
54            let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
55            match segments.as_slice() {
56                [sym::arm, sym::a32 | sym::t32] if !tcx.sess.target.has_thumb_interworking => {
57                    tcx.dcx().emit_err(errors::UnsupportedInstructionSet { span: attr.span() });
58                    None
59                }
60                [sym::arm, sym::a32] => Some(InstructionSetAttr::ArmA32),
61                [sym::arm, sym::t32] => Some(InstructionSetAttr::ArmT32),
62                _ => {
63                    tcx.dcx().emit_err(errors::InvalidInstructionSet { span: attr.span() });
64                    None
65                }
66            }
67        }
68        [] => {
69            tcx.dcx().emit_err(errors::BareInstructionSet { span: attr.span() });
70            None
71        }
72        _ => {
73            tcx.dcx().emit_err(errors::MultipleInstructionSet { span: attr.span() });
74            None
75        }
76    }
77}
78
79// FIXME(jdonszelmann): remove when patchable_function_entry becomes a parsed attr
80fn parse_patchable_function_entry(
81    tcx: TyCtxt<'_>,
82    attr: &Attribute,
83) -> Option<PatchableFunctionEntry> {
84    attr.meta_item_list().and_then(|l| {
85        let mut prefix = None;
86        let mut entry = None;
87        for item in l {
88            let Some(meta_item) = item.meta_item() else {
89                tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
90                continue;
91            };
92
93            let Some(name_value_lit) = meta_item.name_value_literal() else {
94                tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
95                continue;
96            };
97
98            let attrib_to_write = match meta_item.name() {
99                Some(sym::prefix_nops) => &mut prefix,
100                Some(sym::entry_nops) => &mut entry,
101                _ => {
102                    tcx.dcx().emit_err(errors::UnexpectedParameterName {
103                        span: item.span(),
104                        prefix_nops: sym::prefix_nops,
105                        entry_nops: sym::entry_nops,
106                    });
107                    continue;
108                }
109            };
110
111            let rustc_ast::LitKind::Int(val, _) = name_value_lit.kind else {
112                tcx.dcx().emit_err(errors::InvalidLiteralValue { span: name_value_lit.span });
113                continue;
114            };
115
116            let Ok(val) = val.get().try_into() else {
117                tcx.dcx().emit_err(errors::OutOfRangeInteger { span: name_value_lit.span });
118                continue;
119            };
120
121            *attrib_to_write = Some(val);
122        }
123
124        if let (None, None) = (prefix, entry) {
125            tcx.dcx().span_err(attr.span(), "must specify at least one parameter");
126        }
127
128        Some(PatchableFunctionEntry::from_prefix_and_entry(prefix.unwrap_or(0), entry.unwrap_or(0)))
129    })
130}
131
132/// Spans that are collected when processing built-in attributes,
133/// that are useful for emitting diagnostics later.
134#[derive(Default)]
135struct InterestingAttributeDiagnosticSpans {
136    link_ordinal: Option<Span>,
137    sanitize: Option<Span>,
138    inline: Option<Span>,
139    no_mangle: Option<Span>,
140}
141
142/// Process the builtin attrs ([`hir::Attribute`]) on the item.
143/// Many of them directly translate to codegen attrs.
144fn process_builtin_attrs(
145    tcx: TyCtxt<'_>,
146    did: LocalDefId,
147    attrs: &[Attribute],
148    codegen_fn_attrs: &mut CodegenFnAttrs,
149) -> InterestingAttributeDiagnosticSpans {
150    let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
151    let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
152
153    for attr in attrs.iter() {
154        if let hir::Attribute::Parsed(p) = attr {
155            match p {
156                AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
157                AttributeKind::ExportName { name, .. } => {
158                    codegen_fn_attrs.symbol_name = Some(*name)
159                }
160                AttributeKind::Inline(inline, span) => {
161                    codegen_fn_attrs.inline = *inline;
162                    interesting_spans.inline = Some(*span);
163                }
164                AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
165                AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
166                AttributeKind::LinkName { name, .. } => {
167                    // FIXME Remove check for foreign functions once #[link_name] on non-foreign
168                    // functions is a hard error
169                    if tcx.is_foreign_item(did) {
170                        codegen_fn_attrs.symbol_name = Some(*name);
171                    }
172                }
173                AttributeKind::LinkOrdinal { ordinal, span } => {
174                    codegen_fn_attrs.link_ordinal = Some(*ordinal);
175                    interesting_spans.link_ordinal = Some(*span);
176                }
177                AttributeKind::LinkSection { name, .. } => {
178                    codegen_fn_attrs.link_section = Some(*name)
179                }
180                AttributeKind::NoMangle(attr_span) => {
181                    interesting_spans.no_mangle = Some(*attr_span);
182                    if tcx.opt_item_name(did.to_def_id()).is_some() {
183                        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
184                    } else {
185                        tcx.dcx().emit_err(NoMangleNameless {
186                            span: *attr_span,
187                            definition: format!(
188                                "{} {}",
189                                tcx.def_descr_article(did.to_def_id()),
190                                tcx.def_descr(did.to_def_id())
191                            ),
192                        });
193                    }
194                }
195                AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
196                AttributeKind::TargetFeature(features, attr_span) => {
197                    let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
198                        tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
199                        continue;
200                    };
201                    let safe_target_features =
202                        matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
203                    codegen_fn_attrs.safe_target_features = safe_target_features;
204                    if safe_target_features {
205                        if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
206                            // The `#[target_feature]` attribute is allowed on
207                            // WebAssembly targets on all functions. Prior to stabilizing
208                            // the `target_feature_11` feature, `#[target_feature]` was
209                            // only permitted on unsafe functions because on most targets
210                            // execution of instructions that are not supported is
211                            // considered undefined behavior. For WebAssembly which is a
212                            // 100% safe target at execution time it's not possible to
213                            // execute undefined instructions, and even if a future
214                            // feature was added in some form for this it would be a
215                            // deterministic trap. There is no undefined behavior when
216                            // executing WebAssembly so `#[target_feature]` is allowed
217                            // on safe functions (but again, only for WebAssembly)
218                            //
219                            // Note that this is also allowed if `actually_rustdoc` so
220                            // if a target is documenting some wasm-specific code then
221                            // it's not spuriously denied.
222                            //
223                            // Now that `#[target_feature]` is permitted on safe functions,
224                            // this exception must still exist for allowing the attribute on
225                            // `main`, `start`, and other functions that are not usually
226                            // allowed.
227                        } else {
228                            check_target_feature_trait_unsafe(tcx, did, *attr_span);
229                        }
230                    }
231                    from_target_feature_attr(
232                        tcx,
233                        did,
234                        features,
235                        rust_target_features,
236                        &mut codegen_fn_attrs.target_features,
237                    );
238                }
239                AttributeKind::TrackCaller(attr_span) => {
240                    let is_closure = tcx.is_closure_like(did.to_def_id());
241
242                    if !is_closure
243                        && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
244                        && fn_sig.skip_binder().abi() != ExternAbi::Rust
245                    {
246                        tcx.dcx().emit_err(errors::RequiresRustAbi { span: *attr_span });
247                    }
248                    if is_closure
249                        && !tcx.features().closure_track_caller()
250                        && !attr_span.allows_unstable(sym::closure_track_caller)
251                    {
252                        feature_err(
253                            &tcx.sess,
254                            sym::closure_track_caller,
255                            *attr_span,
256                            "`#[track_caller]` on closures is currently unstable",
257                        )
258                        .emit();
259                    }
260                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
261                }
262                AttributeKind::Used { used_by, .. } => match used_by {
263                    UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
264                    UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
265                },
266                AttributeKind::FfiConst(_) => {
267                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST
268                }
269                AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
270                AttributeKind::StdInternalSymbol(_) => {
271                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
272                }
273                AttributeKind::Linkage(linkage, _) => {
274                    let linkage = Some(*linkage);
275
276                    if tcx.is_foreign_item(did) {
277                        codegen_fn_attrs.import_linkage = linkage;
278
279                        if tcx.is_mutable_static(did.into()) {
280                            let mut diag = tcx.dcx().struct_span_err(
281                                attr.span(),
282                                "extern mutable statics are not allowed with `#[linkage]`",
283                            );
284                            diag.note(
285                                "marking the extern static mutable would allow changing which \
286                                symbol the static references rather than make the target of the \
287                                symbol mutable",
288                            );
289                            diag.emit();
290                        }
291                    } else {
292                        codegen_fn_attrs.linkage = linkage;
293                    }
294                }
295                _ => {}
296            }
297        }
298
299        let Some(Ident { name, .. }) = attr.ident() else {
300            continue;
301        };
302
303        match name {
304            sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR,
305            sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND,
306            sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR,
307            sym::rustc_deallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR,
308            sym::rustc_allocator_zeroed => {
309                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
310            }
311            sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
312            sym::sanitize => interesting_spans.sanitize = Some(attr.span()),
313            sym::instruction_set => {
314                codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr)
315            }
316            sym::patchable_function_entry => {
317                codegen_fn_attrs.patchable_function_entry =
318                    parse_patchable_function_entry(tcx, attr);
319            }
320            _ => {}
321        }
322    }
323
324    interesting_spans
325}
326
327/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
328/// Please comment why when adding a new one!
329fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
330    // Apply the minimum function alignment here. This ensures that a function's alignment is
331    // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
332    // it happens to be codegen'd (or const-eval'd) in.
333    codegen_fn_attrs.alignment =
334        Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
335
336    // Compute the disabled sanitizers.
337    codegen_fn_attrs.no_sanitize |= tcx.disabled_sanitizers_for(did);
338    // On trait methods, inherit the `#[align]` of the trait's method prototype.
339    codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
340
341    // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
342    // but not for the code generation backend because at that point the naked function will just be
343    // a declaration, with a definition provided in global assembly.
344    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
345        codegen_fn_attrs.inline = InlineAttr::Never;
346    }
347
348    // #73631: closures inherit `#[target_feature]` annotations
349    //
350    // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
351    //
352    // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
353    // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
354    // the function may be inlined into a caller with fewer target features. Also see
355    // <https://github.com/rust-lang/rust/issues/116573>.
356    //
357    // Using `#[inline(always)]` implies that this closure will most likely be inlined into
358    // its parent function, which effectively inherits the features anyway. Boxing this closure
359    // would result in this closure being compiled without the inherited target features, but this
360    // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
361    if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
362        let owner_id = tcx.parent(did.to_def_id());
363        if tcx.def_kind(owner_id).has_codegen_attrs() {
364            codegen_fn_attrs
365                .target_features
366                .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
367        }
368    }
369
370    // When `no_builtins` is applied at the crate level, we should add the
371    // `no-builtins` attribute to each function to ensure it takes effect in LTO.
372    let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
373    let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
374    if no_builtins {
375        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
376    }
377
378    // inherit track-caller properly
379    if tcx.should_inherit_track_caller(did) {
380        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
381    }
382
383    // Foreign items by default use no mangling for their symbol name.
384    if tcx.is_foreign_item(did) {
385        // There's a few exceptions to this rule though:
386        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
387            // * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
388            //   both for exports and imports through foreign items. This is handled further,
389            //   during symbol mangling logic.
390        } else if codegen_fn_attrs.symbol_name.is_some() {
391            // * This can be overridden with the `#[link_name]` attribute
392        } else {
393            // NOTE: there's one more exception that we cannot apply here. On wasm,
394            // some items cannot be `no_mangle`.
395            // However, we don't have enough information here to determine that.
396            // As such, no_mangle foreign items on wasm that have the same defid as some
397            // import will *still* be mangled despite this.
398            //
399            // if none of the exceptions apply; apply no_mangle
400            codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
401        }
402    }
403}
404
405fn check_result(
406    tcx: TyCtxt<'_>,
407    did: LocalDefId,
408    interesting_spans: InterestingAttributeDiagnosticSpans,
409    codegen_fn_attrs: &CodegenFnAttrs,
410) {
411    // If a function uses `#[target_feature]` it can't be inlined into general
412    // purpose functions as they wouldn't have the right target features
413    // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
414    // respected.
415    //
416    // `#[rustc_force_inline]` doesn't need to be prohibited here, only
417    // `#[inline(always)]`, as forced inlining is implemented entirely within
418    // rustc (and so the MIR inliner can do any necessary checks for compatible target
419    // features).
420    //
421    // This sidesteps the LLVM blockers in enabling `target_features` +
422    // `inline(always)` to be used together (see rust-lang/rust#116573 and
423    // llvm/llvm-project#70563).
424    if !codegen_fn_attrs.target_features.is_empty()
425        && matches!(codegen_fn_attrs.inline, InlineAttr::Always)
426        && let Some(span) = interesting_spans.inline
427    {
428        tcx.dcx().span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
429    }
430
431    // warn that inline has no effect when no_sanitize is present
432    if !codegen_fn_attrs.no_sanitize.is_empty()
433        && codegen_fn_attrs.inline.always()
434        && let (Some(no_sanitize_span), Some(inline_span)) =
435            (interesting_spans.sanitize, interesting_spans.inline)
436    {
437        let hir_id = tcx.local_def_id_to_hir_id(did);
438        tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, no_sanitize_span, |lint| {
439            lint.primary_message("setting `sanitize` off will have no effect after inlining");
440            lint.span_note(inline_span, "inlining requested here");
441        })
442    }
443
444    // error when specifying link_name together with link_ordinal
445    if let Some(_) = codegen_fn_attrs.symbol_name
446        && let Some(_) = codegen_fn_attrs.link_ordinal
447    {
448        let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
449        if let Some(span) = interesting_spans.link_ordinal {
450            tcx.dcx().span_err(span, msg);
451        } else {
452            tcx.dcx().err(msg);
453        }
454    }
455
456    if let Some(features) = check_tied_features(
457        tcx.sess,
458        &codegen_fn_attrs
459            .target_features
460            .iter()
461            .map(|features| (features.name.as_str(), true))
462            .collect(),
463    ) {
464        let span =
465            find_attr!(tcx.get_all_attrs(did), AttributeKind::TargetFeature(_, span) => *span)
466                .unwrap_or_else(|| tcx.def_span(did));
467
468        tcx.dcx()
469            .create_err(errors::TargetFeatureDisableOrEnable {
470                features,
471                span: Some(span),
472                missing_features: Some(errors::MissingFeatures),
473            })
474            .emit();
475    }
476}
477
478fn handle_lang_items(
479    tcx: TyCtxt<'_>,
480    did: LocalDefId,
481    interesting_spans: &InterestingAttributeDiagnosticSpans,
482    attrs: &[Attribute],
483    codegen_fn_attrs: &mut CodegenFnAttrs,
484) {
485    let lang_item = lang_items::extract(attrs).and_then(|(name, _)| LangItem::from_name(name));
486
487    // Weak lang items have the same semantics as "std internal" symbols in the
488    // sense that they're preserved through all our LTO passes and only
489    // strippable by the linker.
490    //
491    // Additionally weak lang items have predetermined symbol names.
492    if let Some(lang_item) = lang_item
493        && let Some(link_name) = lang_item.link_name()
494    {
495        codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
496        codegen_fn_attrs.symbol_name = Some(link_name);
497    }
498
499    // error when using no_mangle on a lang item item
500    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
501        && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
502    {
503        let mut err = tcx
504            .dcx()
505            .struct_span_err(
506                interesting_spans.no_mangle.unwrap_or_default(),
507                "`#[no_mangle]` cannot be used on internal language items",
508            )
509            .with_note("Rustc requires this item to have a specific mangled name.")
510            .with_span_label(tcx.def_span(did), "should be the internal language item");
511        if let Some(lang_item) = lang_item
512            && let Some(link_name) = lang_item.link_name()
513        {
514            err = err
515                .with_note("If you are trying to prevent mangling to ease debugging, many")
516                .with_note(format!("debuggers support a command such as `rbreak {link_name}` to"))
517                .with_note(format!(
518                    "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
519                ))
520        }
521        err.emit();
522    }
523}
524
525/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
526///
527/// This happens in 4 stages:
528/// - apply built-in attributes that directly translate to codegen attributes.
529/// - handle lang items. These have special codegen attrs applied to them.
530/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
531///   overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
532/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
533fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
534    if cfg!(debug_assertions) {
535        let def_kind = tcx.def_kind(did);
536        assert!(
537            def_kind.has_codegen_attrs(),
538            "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
539        );
540    }
541
542    let mut codegen_fn_attrs = CodegenFnAttrs::new();
543    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
544
545    let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
546    handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
547    apply_overrides(tcx, did, &mut codegen_fn_attrs);
548    check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
549
550    codegen_fn_attrs
551}
552
553/// If the provided DefId is a method in a trait impl, return the DefId of the method prototype.
554fn opt_trait_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
555    let impl_item = tcx.opt_associated_item(def_id)?;
556    match impl_item.container {
557        ty::AssocItemContainer::Impl => impl_item.trait_item_def_id,
558        _ => None,
559    }
560}
561
562/// For an attr that has the `sanitize` attribute, read the list of
563/// disabled sanitizers. `current_attr` holds the information about
564/// previously parsed attributes.
565fn parse_sanitize_attr(
566    tcx: TyCtxt<'_>,
567    attr: &Attribute,
568    current_attr: SanitizerSet,
569) -> SanitizerSet {
570    let mut result = current_attr;
571    if let Some(list) = attr.meta_item_list() {
572        for item in list.iter() {
573            let MetaItemInner::MetaItem(set) = item else {
574                tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
575                break;
576            };
577            let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
578            match segments.as_slice() {
579                // Similar to clang, sanitize(address = ..) and
580                // sanitize(kernel_address = ..) control both ASan and KASan
581                // Source: https://reviews.llvm.org/D44981.
582                [sym::address] | [sym::kernel_address] if set.value_str() == Some(sym::off) => {
583                    result |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS
584                }
585                [sym::address] | [sym::kernel_address] if set.value_str() == Some(sym::on) => {
586                    result &= !SanitizerSet::ADDRESS;
587                    result &= !SanitizerSet::KERNELADDRESS;
588                }
589                [sym::cfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::CFI,
590                [sym::cfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::CFI,
591                [sym::kcfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::KCFI,
592                [sym::kcfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::KCFI,
593                [sym::memory] if set.value_str() == Some(sym::off) => {
594                    result |= SanitizerSet::MEMORY
595                }
596                [sym::memory] if set.value_str() == Some(sym::on) => {
597                    result &= !SanitizerSet::MEMORY
598                }
599                [sym::memtag] if set.value_str() == Some(sym::off) => {
600                    result |= SanitizerSet::MEMTAG
601                }
602                [sym::memtag] if set.value_str() == Some(sym::on) => {
603                    result &= !SanitizerSet::MEMTAG
604                }
605                [sym::shadow_call_stack] if set.value_str() == Some(sym::off) => {
606                    result |= SanitizerSet::SHADOWCALLSTACK
607                }
608                [sym::shadow_call_stack] if set.value_str() == Some(sym::on) => {
609                    result &= !SanitizerSet::SHADOWCALLSTACK
610                }
611                [sym::thread] if set.value_str() == Some(sym::off) => {
612                    result |= SanitizerSet::THREAD
613                }
614                [sym::thread] if set.value_str() == Some(sym::on) => {
615                    result &= !SanitizerSet::THREAD
616                }
617                [sym::hwaddress] if set.value_str() == Some(sym::off) => {
618                    result |= SanitizerSet::HWADDRESS
619                }
620                [sym::hwaddress] if set.value_str() == Some(sym::on) => {
621                    result &= !SanitizerSet::HWADDRESS
622                }
623                _ => {
624                    tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
625                }
626            }
627        }
628    }
629    result
630}
631
632fn disabled_sanitizers_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerSet {
633    // Backtrack to the crate root.
634    let disabled = match tcx.opt_local_parent(did) {
635        // Check the parent (recursively).
636        Some(parent) => tcx.disabled_sanitizers_for(parent),
637        // We reached the crate root without seeing an attribute, so
638        // there is no sanitizers to exclude.
639        None => SanitizerSet::empty(),
640    };
641
642    // Check for a sanitize annotation directly on this def.
643    if let Some(attr) = tcx.get_attr(did, sym::sanitize) {
644        return parse_sanitize_attr(tcx, attr, disabled);
645    }
646    disabled
647}
648
649/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
650/// applied to the method prototype.
651fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
652    let Some(trait_item) = opt_trait_item(tcx, def_id) else { return false };
653    tcx.codegen_fn_attrs(trait_item).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
654}
655
656/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
657/// attribute on the method prototype (if any).
658fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
659    tcx.codegen_fn_attrs(opt_trait_item(tcx, def_id)?).alignment
660}
661
662/// We now check the #\[rustc_autodiff\] attributes which we generated from the #[autodiff(...)]
663/// macros. There are two forms. The pure one without args to mark primal functions (the functions
664/// being differentiated). The other form is #[rustc_autodiff(Mode, ActivityList)] on top of the
665/// placeholder functions. We wrote the rustc_autodiff attributes ourself, so this should never
666/// panic, unless we introduced a bug when parsing the autodiff macro.
667//FIXME(jdonszelmann): put in the main loop. No need to have two..... :/ Let's do that when we make autodiff parsed.
668pub fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option<AutoDiffAttrs> {
669    let attrs = tcx.get_attrs(id, sym::rustc_autodiff);
670
671    let attrs = attrs.filter(|attr| attr.has_name(sym::rustc_autodiff)).collect::<Vec<_>>();
672
673    // check for exactly one autodiff attribute on placeholder functions.
674    // There should only be one, since we generate a new placeholder per ad macro.
675    let attr = match &attrs[..] {
676        [] => return None,
677        [attr] => attr,
678        _ => {
679            span_bug!(attrs[1].span(), "cg_ssa: rustc_autodiff should only exist once per source");
680        }
681    };
682
683    let list = attr.meta_item_list().unwrap_or_default();
684
685    // empty autodiff attribute macros (i.e. `#[autodiff]`) are used to mark source functions
686    if list.is_empty() {
687        return Some(AutoDiffAttrs::source());
688    }
689
690    let [mode, width_meta, input_activities @ .., ret_activity] = &list[..] else {
691        span_bug!(attr.span(), "rustc_autodiff attribute must contain mode, width and activities");
692    };
693    let mode = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = mode {
694        p1.segments.first().unwrap().ident
695    } else {
696        span_bug!(attr.span(), "rustc_autodiff attribute must contain mode");
697    };
698
699    // parse mode
700    let mode = match mode.as_str() {
701        "Forward" => DiffMode::Forward,
702        "Reverse" => DiffMode::Reverse,
703        _ => {
704            span_bug!(mode.span, "rustc_autodiff attribute contains invalid mode");
705        }
706    };
707
708    let width: u32 = match width_meta {
709        MetaItemInner::MetaItem(MetaItem { path: p1, .. }) => {
710            let w = p1.segments.first().unwrap().ident;
711            match w.as_str().parse() {
712                Ok(val) => val,
713                Err(_) => {
714                    span_bug!(w.span, "rustc_autodiff width should fit u32");
715                }
716            }
717        }
718        MetaItemInner::Lit(lit) => {
719            if let LitKind::Int(val, _) = lit.kind {
720                match val.get().try_into() {
721                    Ok(val) => val,
722                    Err(_) => {
723                        span_bug!(lit.span, "rustc_autodiff width should fit u32");
724                    }
725                }
726            } else {
727                span_bug!(lit.span, "rustc_autodiff width should be an integer");
728            }
729        }
730    };
731
732    // First read the ret symbol from the attribute
733    let ret_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = ret_activity {
734        p1.segments.first().unwrap().ident
735    } else {
736        span_bug!(attr.span(), "rustc_autodiff attribute must contain the return activity");
737    };
738
739    // Then parse it into an actual DiffActivity
740    let Ok(ret_activity) = DiffActivity::from_str(ret_symbol.as_str()) else {
741        span_bug!(ret_symbol.span, "invalid return activity");
742    };
743
744    // Now parse all the intermediate (input) activities
745    let mut arg_activities: Vec<DiffActivity> = vec![];
746    for arg in input_activities {
747        let arg_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p2, .. }) = arg {
748            match p2.segments.first() {
749                Some(x) => x.ident,
750                None => {
751                    span_bug!(
752                        arg.span(),
753                        "rustc_autodiff attribute must contain the input activity"
754                    );
755                }
756            }
757        } else {
758            span_bug!(arg.span(), "rustc_autodiff attribute must contain the input activity");
759        };
760
761        match DiffActivity::from_str(arg_symbol.as_str()) {
762            Ok(arg_activity) => arg_activities.push(arg_activity),
763            Err(_) => {
764                span_bug!(arg_symbol.span, "invalid input activity");
765            }
766        }
767    }
768
769    Some(AutoDiffAttrs { mode, width, ret_activity, input_activity: arg_activities })
770}
771
772pub(crate) fn provide(providers: &mut Providers) {
773    *providers = Providers {
774        codegen_fn_attrs,
775        should_inherit_track_caller,
776        inherited_align,
777        disabled_sanitizers_for,
778        ..*providers
779    };
780}