Skip to main content

rustc_codegen_ssa/
codegen_attrs.rs

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