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