Skip to main content

rustc_codegen_ssa/
codegen_attrs.rs

1use rustc_abi::{Align, ExternAbi};
2use rustc_hir::attrs::{
3    AttributeKind, EiiImplResolution, InlineAttr, InstrumentFnAttr as HirInstrumentFnAttr, Linkage,
4    RtsanSetting, UsedBy,
5};
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
8use rustc_hir::{self as hir, Attribute, find_attr};
9use rustc_macros::Diagnostic;
10use rustc_middle::bug;
11use rustc_middle::middle::codegen_fn_attrs::{
12    CodegenFnAttrFlags, CodegenFnAttrs, InstrumentFnAttr, PatchableFunctionEntry, SanitizerFnAttrs,
13};
14use rustc_middle::mono::Visibility;
15use rustc_middle::query::Providers;
16use rustc_middle::ty::{self as ty, TyCtxt};
17use rustc_session::diagnostics::feature_err;
18use rustc_session::lint;
19use rustc_span::{Span, sym};
20use rustc_target::spec::Os;
21
22use crate::diagnostics;
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/// Spans that are collected when processing built-in attributes,
49/// that are useful for emitting diagnostics later.
50#[derive(#[automatically_derived]
impl ::core::default::Default for InterestingAttributeDiagnosticSpans {
    #[inline]
    fn default() -> InterestingAttributeDiagnosticSpans {
        InterestingAttributeDiagnosticSpans {
            link_ordinal: ::core::default::Default::default(),
            sanitize: ::core::default::Default::default(),
            inline: ::core::default::Default::default(),
            no_mangle: ::core::default::Default::default(),
        }
    }
}Default)]
51struct InterestingAttributeDiagnosticSpans {
52    link_ordinal: Option<Span>,
53    sanitize: Option<Span>,
54    inline: Option<Span>,
55    no_mangle: Option<Span>,
56}
57
58/// Process the builtin attrs ([`hir::Attribute`]) on the item.
59/// Many of them directly translate to codegen attrs.
60fn process_builtin_attrs(
61    tcx: TyCtxt<'_>,
62    did: LocalDefId,
63    attrs: &[Attribute],
64    codegen_fn_attrs: &mut CodegenFnAttrs,
65) -> InterestingAttributeDiagnosticSpans {
66    let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
67    let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
68
69    let parsed_attrs = attrs
70        .iter()
71        .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None });
72    for attr in parsed_attrs {
73        match attr {
74            AttributeKind::Cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
75            AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name),
76            AttributeKind::Inline(inline, span) => {
77                codegen_fn_attrs.inline = *inline;
78                interesting_spans.inline = Some(*span);
79            }
80            AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
81            AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
82            AttributeKind::LinkName { name, .. } => {
83                // FIXME Remove check for foreign functions once #[link_name] on non-foreign
84                // functions is a hard error
85                if tcx.is_foreign_item(did) {
86                    codegen_fn_attrs.symbol_name = Some(*name);
87                }
88            }
89            AttributeKind::LinkOrdinal { ordinal, span } => {
90                codegen_fn_attrs.link_ordinal = Some(*ordinal);
91                interesting_spans.link_ordinal = Some(*span);
92            }
93            AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name),
94            AttributeKind::NoMangle(attr_span) => {
95                interesting_spans.no_mangle = Some(*attr_span);
96                if tcx.opt_item_name(did.to_def_id()).is_some() {
97                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
98                } else {
99                    tcx.dcx()
100                        .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
101                }
102            }
103            AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
104            AttributeKind::TargetFeature { features, attr_span, was_forced } => {
105                let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
106                    tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
107                    continue;
108                };
109                let safe_target_features =
110                    #[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
    hir::HeaderSafety::SafeTargetFeatures => true,
    _ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
111                codegen_fn_attrs.safe_target_features = safe_target_features;
112                if safe_target_features && !was_forced {
113                    if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
114                        // The `#[target_feature]` attribute is allowed on
115                        // WebAssembly targets on all functions. Prior to stabilizing
116                        // the `target_feature_11` feature, `#[target_feature]` was
117                        // only permitted on unsafe functions because on most targets
118                        // execution of instructions that are not supported is
119                        // considered undefined behavior. For WebAssembly which is a
120                        // 100% safe target at execution time it's not possible to
121                        // execute undefined instructions, and even if a future
122                        // feature was added in some form for this it would be a
123                        // deterministic trap. There is no undefined behavior when
124                        // executing WebAssembly so `#[target_feature]` is allowed
125                        // on safe functions (but again, only for WebAssembly)
126                        //
127                        // Note that this is also allowed if `actually_rustdoc` so
128                        // if a target is documenting some wasm-specific code then
129                        // it's not spuriously denied.
130                        //
131                        // Now that `#[target_feature]` is permitted on safe functions,
132                        // this exception must still exist for allowing the attribute on
133                        // `main`, `start`, and other functions that are not usually
134                        // allowed.
135                    } else {
136                        check_target_feature_trait_unsafe(tcx, did, *attr_span);
137                    }
138                }
139                from_target_feature_attr(
140                    tcx,
141                    did,
142                    features,
143                    *was_forced,
144                    rust_target_features,
145                    &mut codegen_fn_attrs.target_features,
146                );
147            }
148            AttributeKind::TrackCaller(attr_span) => {
149                let is_closure = tcx.is_closure_like(did.to_def_id());
150
151                if !is_closure
152                    && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
153                    && fn_sig.skip_binder().abi() != ExternAbi::Rust
154                {
155                    // This error is already reported in `rustc_ast_passes/src/ast_validation.rs`.
156                    tcx.dcx().delayed_bug("`#[track_caller]` requires the Rust ABI");
157                }
158                if is_closure
159                    && !tcx.features().closure_track_caller()
160                    && !attr_span.allows_unstable(sym::closure_track_caller)
161                {
162                    feature_err(
163                        &tcx.sess,
164                        sym::closure_track_caller,
165                        *attr_span,
166                        "`#[track_caller]` on closures is currently unstable",
167                    )
168                    .emit();
169                }
170                codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
171            }
172            AttributeKind::Used { used_by } => match used_by {
173                UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
174                UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
175                UsedBy::Default => {
176                    let used_form = if tcx.sess.target.os == Os::Illumos {
177                        // illumos' `ld` doesn't support a section header that would represent
178                        // `#[used(linker)]`, see
179                        // https://github.com/rust-lang/rust/issues/146169. For that target,
180                        // downgrade as if `#[used(compiler)]` was requested and hope for the
181                        // best.
182                        CodegenFnAttrFlags::USED_COMPILER
183                    } else {
184                        CodegenFnAttrFlags::USED_LINKER
185                    };
186                    codegen_fn_attrs.flags |= used_form;
187                }
188            },
189            AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
190            AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
191            AttributeKind::RustcStdInternalSymbol => {
192                codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
193            }
194            AttributeKind::Linkage(linkage, span) => {
195                let linkage = Some(*linkage);
196
197                if tcx.is_foreign_item(did) {
198                    codegen_fn_attrs.import_linkage = linkage;
199
200                    if tcx.is_mutable_static(did.into()) {
201                        let mut diag = tcx.dcx().struct_span_err(
202                            *span,
203                            "extern mutable statics are not allowed with `#[linkage]`",
204                        );
205                        diag.note(
206                            "marking the extern static mutable would allow changing which \
207                            symbol the static references rather than make the target of the \
208                            symbol mutable",
209                        );
210                        diag.emit();
211                    }
212                } else {
213                    codegen_fn_attrs.linkage = linkage;
214                }
215            }
216            AttributeKind::Sanitize { span, .. } => {
217                interesting_spans.sanitize = Some(*span);
218            }
219            AttributeKind::RustcObjcClass { classname } => {
220                codegen_fn_attrs.objc_class = Some(*classname);
221            }
222            AttributeKind::RustcObjcSelector { methname } => {
223                codegen_fn_attrs.objc_selector = Some(*methname);
224            }
225            AttributeKind::RustcEiiForeignItem => {
226                codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
227            }
228            AttributeKind::EiiImpls(impls) => {
229                for i in impls {
230                    let foreign_item = match i.resolution {
231                        EiiImplResolution::Macro(def_id) => {
232                            let Some(extern_item) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiDeclaration(target)) => {
                        break 'done Some(target.foreign_item);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
233                            ) else {
234                                tcx.dcx().span_delayed_bug(
235                                    i.span,
236                                    "resolved to something that's not an EII",
237                                );
238                                continue;
239                            };
240                            extern_item
241                        }
242                        EiiImplResolution::Known(def_id) => def_id,
243                        EiiImplResolution::Error(_eg) => continue,
244                    };
245
246                    // this is to prevent a bug where a single crate defines both the default and explicit implementation
247                    // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
248                    // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
249                    // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
250                    // the default implementation is used while an explicit implementation is given.
251                    if
252                    // if this is a default impl
253                    i.is_default
254                        // iterate over all implementations *in the current crate*
255                        // (this is ok since we generate codegen fn attrs in the local crate)
256                        // if any of them is *not default* then don't emit the alias.
257                        && {
258                            let (_, impls) = tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("EII impl should have an entry"))bug!("EII impl should have an entry"));
259                            impls.iter().any(|(_, imp)| !imp.is_default)
260                        }
261                    {
262                        continue;
263                    }
264
265                    codegen_fn_attrs.foreign_item_symbol_aliases.push((
266                        foreign_item,
267                        if i.is_default { Linkage::WeakAny } else { Linkage::External },
268                        Visibility::Default,
269                    ));
270                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
271
272                    // If the declaration is `#[track_caller]`, derive it onto the implementation
273                    // too. The shim that forwards to this impl (see `add_function_aliases`) takes
274                    // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
275                    // caller-location argument is present, otherwise it would be silently dropped.
276                    if tcx
277                        .codegen_fn_attrs(foreign_item)
278                        .flags
279                        .contains(CodegenFnAttrFlags::TRACK_CALLER)
280                    {
281                        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
282                    }
283                }
284            }
285            AttributeKind::ThreadLocal => {
286                codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
287            }
288            AttributeKind::InstructionSet(instruction_set) => {
289                codegen_fn_attrs.instruction_set = Some(*instruction_set)
290            }
291            AttributeKind::RustcAllocator => {
292                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
293            }
294            AttributeKind::RustcDeallocator => {
295                codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
296            }
297            AttributeKind::RustcReallocator => {
298                codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
299            }
300            AttributeKind::RustcAllocatorZeroed => {
301                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
302            }
303            AttributeKind::RustcNounwind => {
304                codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
305            }
306            AttributeKind::RustcOffloadKernel => {
307                codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
308            }
309            AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
310                codegen_fn_attrs.patchable_function_entry =
311                    Some(PatchableFunctionEntry::from_prefix_entry_and_section(
312                        *prefix, *entry, *section,
313                    ));
314            }
315            AttributeKind::InstrumentFn(instrument_fn) => {
316                codegen_fn_attrs.instrument_fn = match instrument_fn {
317                    HirInstrumentFnAttr::On => InstrumentFnAttr::On,
318                    HirInstrumentFnAttr::Off => InstrumentFnAttr::Off,
319                };
320            }
321            _ => {}
322        }
323    }
324
325    interesting_spans
326}
327
328/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
329/// Please comment why when adding a new one!
330fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
331    // Apply the minimum function alignment here. This ensures that a function's alignment is
332    // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
333    // it happens to be codegen'd (or const-eval'd) in.
334    codegen_fn_attrs.alignment =
335        Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
336
337    // Passed in sanitizer settings are always the default.
338    if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
    ::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
339    // Replace with #[sanitize] value
340    codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
341    // On trait methods, inherit the `#[align]` of the trait's method prototype.
342    codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
343
344    // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
345    // but not for the code generation backend because at that point the naked function will just be
346    // a declaration, with a definition provided in global assembly.
347    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
348        codegen_fn_attrs.inline = InlineAttr::Never;
349    }
350
351    // #73631: closures inherit `#[target_feature]` annotations
352    //
353    // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
354    //
355    // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
356    // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
357    // the function may be inlined into a caller with fewer target features. Also see
358    // <https://github.com/rust-lang/rust/issues/116573>.
359    //
360    // Using `#[inline(always)]` implies that this closure will most likely be inlined into
361    // its parent function, which effectively inherits the features anyway. Boxing this closure
362    // would result in this closure being compiled without the inherited target features, but this
363    // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
364    if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
365        let owner_id = tcx.parent(did.to_def_id());
366        if tcx.def_kind(owner_id).has_codegen_attrs() {
367            codegen_fn_attrs
368                .target_features
369                .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
370        }
371    }
372
373    // When `no_builtins` is applied at the crate level, we should add the
374    // `no-builtins` attribute to each function to ensure it takes effect in LTO.
375    let no_builtins = {
        'done:
            {
            for i in tcx.hir_krate_attrs() {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(NoBuiltins) => {
                        break 'done Some(());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(tcx, crate, NoBuiltins);
376    if no_builtins {
377        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
378    }
379
380    // inherit track-caller properly
381    if tcx.should_inherit_track_caller(did) {
382        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
383    }
384
385    // Foreign items by default use no mangling for their symbol name.
386    if tcx.is_foreign_item(did) {
387        codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
388
389        // There's a few exceptions to this rule though:
390        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
391            // * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
392            //   both for exports and imports through foreign items. This is handled further,
393            //   during symbol mangling logic.
394        } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
395        {
396            // * externally implementable items keep their mangled symbol name.
397            //   multiple EIIs can have the same name, so not mangling them would be a bug.
398            //   Implementing an EII does the appropriate name resolution to make sure the implementations
399            //   get the same symbol name as the *mangled* foreign item they refer to so that's all good.
400        } else if codegen_fn_attrs.symbol_name.is_some() {
401            // * This can be overridden with the `#[link_name]` attribute
402        } else {
403            // NOTE: there's one more exception that we cannot apply here. On wasm,
404            // some items cannot be `no_mangle`.
405            // However, we don't have enough information here to determine that.
406            // As such, no_mangle foreign items on wasm that have the same defid as some
407            // import will *still* be mangled despite this.
408            //
409            // if none of the exceptions apply; apply no_mangle
410            codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
411        }
412    }
413}
414
415#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            SanitizeOnInline where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    SanitizeOnInline { inline_span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("non-default `sanitize` will have no effect after inlining")));
                        ;
                        diag.span_note(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inlining requested here")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
416#[diag("non-default `sanitize` will have no effect after inlining")]
417struct SanitizeOnInline {
418    #[note("inlining requested here")]
419    inline_span: Span,
420}
421
422#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for AsyncBlocking
            where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    AsyncBlocking => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the async executor can run blocking code, without realtime sanitizer catching it")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
423#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
424struct AsyncBlocking;
425
426fn check_result(
427    tcx: TyCtxt<'_>,
428    did: LocalDefId,
429    interesting_spans: InterestingAttributeDiagnosticSpans,
430    codegen_fn_attrs: &CodegenFnAttrs,
431) {
432    // If a function uses `#[target_feature]` it can't be inlined into general
433    // purpose functions as they wouldn't have the right target features
434    // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
435    // respected.
436    //
437    // `#[rustc_force_inline]` doesn't need to be prohibited here, only
438    // `#[inline(always)]`, as forced inlining is implemented entirely within
439    // rustc (and so the MIR inliner can do any necessary checks for compatible target
440    // features).
441    //
442    // This sidesteps the LLVM blockers in enabling `target_features` +
443    // `inline(always)` to be used together (see rust-lang/rust#116573 and
444    // llvm/llvm-project#70563).
445    if !codegen_fn_attrs.target_features.is_empty()
446        && #[allow(non_exhaustive_omitted_patterns)] match codegen_fn_attrs.inline {
    InlineAttr::Always => true,
    _ => false,
}matches!(codegen_fn_attrs.inline, InlineAttr::Always)
447        && let Some(span) = interesting_spans.inline
448    {
449        let mut diag = tcx
450            .dcx()
451            .struct_span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
452        diag.note(
453            "See this issue for full discussion: \
454            https://github.com/rust-lang/rust/issues/145574",
455        );
456        diag.emit();
457    }
458
459    // warn that inline has no effect when no_sanitize is present
460    if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
461        && codegen_fn_attrs.inline.always()
462        && let (Some(sanitize_span), Some(inline_span)) =
463            (interesting_spans.sanitize, interesting_spans.inline)
464    {
465        let hir_id = tcx.local_def_id_to_hir_id(did);
466        tcx.emit_node_span_lint(
467            lint::builtin::INLINE_NO_SANITIZE,
468            hir_id,
469            sanitize_span,
470            SanitizeOnInline { inline_span },
471        )
472    }
473
474    // warn for nonblocking async functions, blocks and closures.
475    // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
476    if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking
477        && let Some(sanitize_span) = interesting_spans.sanitize
478        // async fn
479        && (tcx.asyncness(did).is_async()
480            // async block
481            || tcx.is_coroutine(did.into())
482            // async closure
483            || (tcx.is_closure_like(did.into())
484                && tcx.hir_node_by_def_id(did).expect_closure().kind
485                    != rustc_hir::ClosureKind::Closure))
486    {
487        let hir_id = tcx.local_def_id_to_hir_id(did);
488        tcx.emit_node_span_lint(
489            lint::builtin::RTSAN_NONBLOCKING_ASYNC,
490            hir_id,
491            sanitize_span,
492            AsyncBlocking,
493        );
494    }
495
496    // error when specifying link_name together with link_ordinal
497    if let Some(_) = codegen_fn_attrs.symbol_name
498        && let Some(_) = codegen_fn_attrs.link_ordinal
499    {
500        let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
501        if let Some(span) = interesting_spans.link_ordinal {
502            tcx.dcx().span_err(span, msg);
503        } else {
504            tcx.dcx().err(msg);
505        }
506    }
507
508    if let Some(features) = check_tied_features(
509        tcx.sess,
510        &codegen_fn_attrs
511            .target_features
512            .iter()
513            .map(|features| (features.name.as_str(), true))
514            .collect(),
515    ) {
516        let span = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(TargetFeature {
                        attr_span: span, .. }) => {
                        break 'done Some(*span);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)
517            .unwrap_or_else(|| tcx.def_span(did));
518
519        tcx.dcx()
520            .create_err(diagnostics::TargetFeatureDisableOrEnable {
521                features,
522                span: Some(span),
523                missing_features: Some(diagnostics::MissingFeatures),
524            })
525            .emit();
526    }
527}
528
529fn handle_lang_items(
530    tcx: TyCtxt<'_>,
531    did: LocalDefId,
532    interesting_spans: &InterestingAttributeDiagnosticSpans,
533    attrs: &[Attribute],
534    codegen_fn_attrs: &mut CodegenFnAttrs,
535) {
536    let lang_item = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Lang(lang)) => {
                    break 'done Some(lang);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Lang(lang) => lang);
537
538    // Weak lang items have the same semantics as "std internal" symbols in the
539    // sense that they're preserved through all our LTO passes and only
540    // strippable by the linker.
541    //
542    // Additionally weak lang items have predetermined symbol names.
543    if let Some(lang_item) = lang_item
544        && let Some(link_name) = lang_item.link_name()
545    {
546        codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
547        codegen_fn_attrs.symbol_name = Some(link_name);
548    }
549
550    // error when using no_mangle on a lang item item
551    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
552        && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
553    {
554        let mut err = tcx
555            .dcx()
556            .struct_span_err(
557                interesting_spans.no_mangle.unwrap_or_default(),
558                "`#[no_mangle]` cannot be used on internal language items",
559            )
560            .with_note("Rustc requires this item to have a specific mangled name.")
561            .with_span_label(tcx.def_span(did), "should be the internal language item");
562        if let Some(lang_item) = lang_item
563            && let Some(link_name) = lang_item.link_name()
564        {
565            err = err
566                .with_note("If you are trying to prevent mangling to ease debugging, many")
567                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("debuggers support a command such as `rbreak {0}` to",
                link_name))
    })format!("debuggers support a command such as `rbreak {link_name}` to"))
568                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
                link_name))
    })format!(
569                    "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
570                ))
571        }
572        err.emit();
573    }
574}
575
576/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
577///
578/// This happens in 4 stages:
579/// - apply built-in attributes that directly translate to codegen attributes.
580/// - handle lang items. These have special codegen attrs applied to them.
581/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
582///   overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
583/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
584fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
585    if truecfg!(debug_assertions) {
586        let def_kind = tcx.def_kind(did);
587        if !def_kind.has_codegen_attrs() {
    {
        ::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
                def_kind));
    }
};assert!(
588            def_kind.has_codegen_attrs(),
589            "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
590        );
591    }
592
593    let mut codegen_fn_attrs = CodegenFnAttrs::new();
594    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
595
596    let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
597    handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
598    apply_overrides(tcx, did, &mut codegen_fn_attrs);
599    check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
600
601    codegen_fn_attrs
602}
603
604fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
605    // Backtrack to the crate root.
606    let mut settings = match tcx.opt_local_parent(did) {
607        // Check the parent (recursively).
608        Some(parent) => tcx.sanitizer_settings_for(parent),
609        // We reached the crate root without seeing an attribute, so
610        // there is no sanitizers to exclude.
611        None => SanitizerFnAttrs::default(),
612    };
613
614    // Check for a sanitize annotation directly on this def.
615    if let Some((on_set, off_set, rtsan)) =
616        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(Sanitize {
                        on_set, off_set, rtsan, .. }) => {
                        break 'done Some((on_set, off_set, rtsan));
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))
617    {
618        // the on set is the set of sanitizers explicitly enabled.
619        // we mask those out since we want the set of disabled sanitizers here
620        settings.disabled &= !*on_set;
621        // the off set is the set of sanitizers explicitly disabled.
622        // we or those in here.
623        settings.disabled |= *off_set;
624        // the on set and off set are distjoint since there's a third option: unset.
625        // a node may not set the sanitizer setting in which case it inherits from parents.
626        // the code above in this function does this backtracking
627
628        // if rtsan was specified here override the parent
629        if let Some(rtsan) = rtsan {
630            settings.rtsan_setting = *rtsan;
631        }
632    }
633    settings
634}
635
636/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
637/// applied to the method prototype.
638fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
639    tcx.trait_item_of(def_id).is_some_and(|id| {
640        tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
641    })
642}
643
644/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
645/// attribute on the method prototype (if any).
646fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
647    tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
648}
649
650pub(crate) fn provide(providers: &mut Providers) {
651    *providers = Providers {
652        codegen_fn_attrs,
653        should_inherit_track_caller,
654        inherited_align,
655        sanitizer_settings_for,
656        ..*providers
657    };
658}