1use rustc_abi::{Align, ExternAbi};
2use rustc_attr_ir::{
3Attribute, AttributeKind, EiiImplResolution, InlineAttr, Linkage, OptimizeAttr, RtsanSetting,
4UsedBy, find_attr,
5};
6use rustc_hiras 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::{
12CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
13};
14use rustc_middle::mono::Visibility;
15use rustc_middle::query::Providers;
16use rustc_middle::ty::{selfas ty, TyCtxt};
17use rustc_span::{Span, bug};
18use rustc_target::spec::Os;
1920use crate::diagnostics;
21use crate::target_features::{
22check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
23};
2425/// 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>>> {
35use DefKind::*;
3637let def_kind = tcx.def_kind(did);
38if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
39Some(tcx.fn_sig(did))
40 } else {
41tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
42None43 }
44}
4546/// 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() -> Self {
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}
5556/// Process the builtin attrs ([`rustc_attr_ir::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 {
64let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
65let rust_target_features = tcx.all_rust_target_features(LOCAL_CRATE);
6667let parsed_attrs = attrs68 .iter()
69 .filter_map(|attr| if let Attribute::Parsed(attr) = attr { Some(attr) } else { None });
70for attr in parsed_attrs {
71match 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// On an `async fn` (or similar), inlining hints are meant for the code the user
76 // wrote, which lives in the body coroutine. The constructor is trivial and left to
77 // the usual heuristics.
78if !constructs_desugared_body_coroutine(tcx, did) {
79 codegen_fn_attrs.inline = *inline;
80 interesting_spans.inline = Some(*span);
81 }
82 }
83 AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
84 AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
85 AttributeKind::LinkName { name, .. } => {
86// FIXME Remove check for foreign functions once #[link_name] on non-foreign
87 // functions is a hard error
88if tcx.is_foreign_item(did) {
89 codegen_fn_attrs.symbol_name = Some(*name);
90 }
91 }
92 AttributeKind::LinkOrdinal { ordinal, span } => {
93 codegen_fn_attrs.link_ordinal = Some(*ordinal);
94 interesting_spans.link_ordinal = Some(*span);
95 }
96 AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name),
97 AttributeKind::NoMangle(attr_span) => {
98 interesting_spans.no_mangle = Some(*attr_span);
99if tcx.opt_item_name(did.to_def_id()).is_some() {
100 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
101 } else {
102 tcx.dcx()
103 .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
104 }
105 }
106 AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
107 AttributeKind::TargetFeature { features, attr_span, was_forced } => {
108let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
109 tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
110continue;
111 };
112let safe_target_features =
113#[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
hir::HeaderSafety::SafeTargetFeatures => true,
_ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
114 codegen_fn_attrs.safe_target_features = safe_target_features;
115if safe_target_features && !was_forced {
116if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
117// The `#[target_feature]` attribute is allowed on
118 // WebAssembly targets on all functions. Prior to stabilizing
119 // the `target_feature_11` feature, `#[target_feature]` was
120 // only permitted on unsafe functions because on most targets
121 // execution of instructions that are not supported is
122 // considered undefined behavior. For WebAssembly which is a
123 // 100% safe target at execution time it's not possible to
124 // execute undefined instructions, and even if a future
125 // feature was added in some form for this it would be a
126 // deterministic trap. There is no undefined behavior when
127 // executing WebAssembly so `#[target_feature]` is allowed
128 // on safe functions (but again, only for WebAssembly)
129 //
130 // Note that this is also allowed if `actually_rustdoc` so
131 // if a target is documenting some wasm-specific code then
132 // it's not spuriously denied.
133 //
134 // Now that `#[target_feature]` is permitted on safe functions,
135 // this exception must still exist for allowing the attribute on
136 // `main`, `start`, and other functions that are not usually
137 // allowed.
138} else {
139 check_target_feature_trait_unsafe(tcx, did, *attr_span);
140 }
141 }
142 from_target_feature_attr(
143 tcx,
144 did,
145 features,
146*was_forced,
147 rust_target_features,
148&mut codegen_fn_attrs.target_features,
149 );
150 }
151 AttributeKind::TrackCaller(attr_span) => {
152let is_closure = tcx.is_closure_like(did.to_def_id());
153154if !is_closure
155 && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
156 && fn_sig.skip_binder().abi() != ExternAbi::Rust
157 {
158// This error is already reported in `rustc_ast_passes/src/ast_validation.rs`.
159tcx.dcx().delayed_bug("`#[track_caller]` requires the Rust ABI");
160 }
161 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
162 }
163 AttributeKind::Used { used_by } => match used_by {
164 UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
165 UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
166 UsedBy::Default => {
167let used_form = if tcx.sess.target.os == Os::Illumos {
168// illumos' `ld` doesn't support a section header that would represent
169 // `#[used(linker)]`, see
170 // https://github.com/rust-lang/rust/issues/146169. For that target,
171 // downgrade as if `#[used(compiler)]` was requested and hope for the
172 // best.
173CodegenFnAttrFlags::USED_COMPILER
174 } else {
175 CodegenFnAttrFlags::USED_LINKER
176 };
177 codegen_fn_attrs.flags |= used_form;
178 }
179 },
180 AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
181 AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
182 AttributeKind::RustcStdInternalSymbol => {
183 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
184 }
185 AttributeKind::Linkage(linkage, span) => {
186let linkage = Some(*linkage);
187188if tcx.is_foreign_item(did) {
189 codegen_fn_attrs.import_linkage = linkage;
190191if tcx.is_mutable_static(did.into()) {
192 tcx.dcx().span_delayed_bug(
193*span,
194"`extern { #[linkage] static mut ...` is checked in check_attr}",
195 );
196 }
197 } else {
198 codegen_fn_attrs.linkage = linkage;
199 }
200 }
201 AttributeKind::Sanitize { span, .. } => {
202 interesting_spans.sanitize = Some(*span);
203 }
204 AttributeKind::RustcObjcClass { classname } => {
205 codegen_fn_attrs.objc_class = Some(*classname);
206 }
207 AttributeKind::RustcObjcSelector { methname } => {
208 codegen_fn_attrs.objc_selector = Some(*methname);
209 }
210 AttributeKind::RustcEiiForeignItem => {
211 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
212 }
213 AttributeKind::EiiImpl(i) => {
214let foreign_item = match i.resolution {
215 EiiImplResolution::Macro(def_id) => {
216let 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::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
217 )else {
218 tcx.dcx().span_delayed_bug(
219 i.span,
220"resolved to something that's not an EII",
221 );
222continue;
223 };
224 extern_item
225 }
226 EiiImplResolution::Known(def_id) => def_id,
227 EiiImplResolution::Error(_eg) => continue,
228 };
229230// this is to prevent a bug where a single crate defines both the default and explicit implementation
231 // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
232 // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
233 // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
234 // the default implementation is used while an explicit implementation is given.
235if
236// if this is a default impl
237i.is_default
238// iterate over all implementations *in the current crate*
239 // (this is ok since we generate codegen fn attrs in the local crate)
240 // if any of them is *not default* then don't emit the alias.
241&& {
242let (_, impls) = tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("EII impl should have an entry"), Location::caller())bug!("EII impl should have an entry"));
243 impls.iter().any(|(_, imp)| !imp.is_default)
244 }
245 {
246continue;
247 }
248249 codegen_fn_attrs.foreign_item_symbol_aliases.push((
250 foreign_item,
251if i.is_default { Linkage::WeakAny } else { Linkage::External },
252 Visibility::Default,
253 ));
254 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
255256// If the declaration is `#[track_caller]`, derive it onto the implementation
257 // too. The shim that forwards to this impl (see `add_function_aliases`) takes
258 // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
259 // caller-location argument is present, otherwise it would be silently dropped.
260if tcx
261 .codegen_fn_attrs(foreign_item)
262 .flags
263 .contains(CodegenFnAttrFlags::TRACK_CALLER)
264 {
265 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
266 }
267 }
268 AttributeKind::ThreadLocal => {
269 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
270 }
271 AttributeKind::InstructionSet(instruction_set) => {
272 codegen_fn_attrs.instruction_set = Some(*instruction_set)
273 }
274 AttributeKind::RustcAllocator => {
275 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
276 }
277 AttributeKind::RustcDeallocator => {
278 codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
279 }
280 AttributeKind::RustcReallocator => {
281 codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
282 }
283 AttributeKind::RustcAllocatorZeroed => {
284 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
285 }
286 AttributeKind::RustcNounwind => {
287 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
288 }
289 AttributeKind::RustcOffloadKernel => {
290 codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
291 }
292 AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
293 codegen_fn_attrs.patchable_function_entry =
294Some(PatchableFunctionEntry::from_prefix_entry_and_section(
295*prefix, *entry, *section,
296 ));
297 }
298 AttributeKind::InstrumentFn(instrument_fn) => {
299 codegen_fn_attrs.instrument_fn = Some(*instrument_fn);
300 }
301_ => {}
302 }
303 }
304305// The body coroutine can't carry attributes of its own, so it takes the ones describing the
306 // code the user wrote from the `async fn` (or similar) it was desugared from. This makes e.g.
307 // `#[inline(never)] async fn` affect `Future::poll`. See #129347.
308if is_desugared_body_coroutine(tcx, did) {
309let parent = tcx.local_parent(did);
310// `#[rustc_force_inline]` is already rejected on the parent. Propagating it would only
311 // cause `CheckForceInline` to report the same attribute again for the coroutine.
312if let Some((inline, span)) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(parent, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(inline, span)) if
!#[allow(non_exhaustive_omitted_patterns)] match inline {
InlineAttr::Force { .. } => true,
_ => false,
} => {
break 'done Some((*inline, *span));
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
313 tcx,
314 parent,
315 Inline(inline, span) if !matches!(inline, InlineAttr::Force { .. }) => (*inline, *span)
316 ) {
317codegen_fn_attrs.inline = inline;
318interesting_spans.inline = Some(span);
319 }
320// Unlike inlining hints, `#[cold]` stays on the constructor as well: calling it is just as
321 // unlikely, and its call sites are only recognized as cold through that.
322if {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(parent, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Cold) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, parent, Cold) {
323codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
324 }
325 }
326327interesting_spans328}
329330/// Whether `did` is the coroutine holding the body of an `async fn`, `gen fn`, `async gen fn`, or
331/// `async` closure, as opposed to one written as an `async {}` block.
332fn is_desugared_body_coroutine(tcx: TyCtxt<'_>, did: LocalDefId) -> bool {
333#[allow(non_exhaustive_omitted_patterns)] match tcx.coroutine_kind(did) {
Some(hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Fn | hir::CoroutineSource::Closure)) => true,
_ => false,
}matches!(
334 tcx.coroutine_kind(did),
335Some(hir::CoroutineKind::Desugared(
336_,
337 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure
338 ))
339 )340}
341342/// Whether `did` is an `async fn`, `gen fn`, `async gen fn`, or `async` closure, i.e. its body
343/// does nothing but construct a [desugared body coroutine](is_desugared_body_coroutine).
344fn constructs_desugared_body_coroutine(tcx: TyCtxt<'_>, did: LocalDefId) -> bool {
345tcx.hir_maybe_body_owned_by(did).is_some_and(|body| {
346#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Closure(closure) if
is_desugared_body_coroutine(tcx, closure.def_id) => true,
_ => false,
}matches!(
347 body.value.kind,
348 hir::ExprKind::Closure(closure) if is_desugared_body_coroutine(tcx, closure.def_id)
349 )350 })
351}
352353/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
354/// Please comment why when adding a new one!
355fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
356// Apply the minimum function alignment here. This ensures that a function's alignment is
357 // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
358 // it happens to be codegen'd (or const-eval'd) in.
359codegen_fn_attrs.alignment =
360 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
361362// Passed in sanitizer settings are always the default.
363if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
364// Replace with #[sanitize] value
365codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
366// On trait methods, inherit the `#[align]` of the trait's method prototype.
367codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
368369// naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
370 // but not for the code generation backend because at that point the naked function will just be
371 // a declaration, with a definition provided in global assembly.
372if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
373codegen_fn_attrs.inline = InlineAttr::Never;
374 }
375376// #73631: closures inherit `#[target_feature]` annotations
377 //
378 // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
379 //
380 // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
381 // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
382 // the function may be inlined into a caller with fewer target features. Also see
383 // <https://github.com/rust-lang/rust/issues/116573>.
384 //
385 // Using `#[inline(always)]` implies that this closure will most likely be inlined into
386 // its parent function, which effectively inherits the features anyway. Boxing this closure
387 // would result in this closure being compiled without the inherited target features, but this
388 // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
389 //
390 // That reasoning doesn't hold for the body coroutine of an `async fn` or `gen fn`: it is never
391 // inlined into the function constructing it, yet its body was checked as part of that function.
392 // It always inherits, so it is compiled with the same features as the function itself.
393if tcx.is_closure_like(did.to_def_id())
394 && (codegen_fn_attrs.inline != InlineAttr::Always395 || #[allow(non_exhaustive_omitted_patterns)] match tcx.coroutine_kind(did) {
Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Fn)) => true,
_ => false,
}matches!(
396 tcx.coroutine_kind(did),
397Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Fn))
398 ))
399 {
400let owner_id = tcx.parent(did.to_def_id());
401if tcx.def_kind(owner_id).has_codegen_attrs() {
402codegen_fn_attrs403 .target_features
404 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
405 }
406 }
407408// Closures inherit `#[optimize]` annotations.
409if tcx.is_closure_like(did.to_def_id()) {
410let owner_id = tcx.parent(did.to_def_id());
411if tcx.def_kind(owner_id).has_codegen_attrs() {
412let owner_attrs = tcx.codegen_fn_attrs(owner_id);
413if codegen_fn_attrs.optimize == OptimizeAttr::Default {
414codegen_fn_attrs.optimize = owner_attrs.optimize;
415 }
416 }
417 }
418419// When `no_builtins` is applied at the crate level, we should add the
420 // `no-builtins` attribute to each function to ensure it takes effect in LTO.
421let 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::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
422if no_builtins {
423codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
424 }
425426// inherit track-caller properly
427if tcx.should_inherit_track_caller(did) {
428codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
429 }
430431// Foreign items by default use no mangling for their symbol name.
432if tcx.is_foreign_item(did) {
433codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
434435// There's a few exceptions to this rule though:
436if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
437// * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
438 // both for exports and imports through foreign items. This is handled further,
439 // during symbol mangling logic.
440} else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
441 {
442// * externally implementable items keep their mangled symbol name.
443 // multiple EIIs can have the same name, so not mangling them would be a bug.
444 // Implementing an EII does the appropriate name resolution to make sure the implementations
445 // get the same symbol name as the *mangled* foreign item they refer to so that's all good.
446} else if codegen_fn_attrs.symbol_name.is_some() {
447// * This can be overridden with the `#[link_name]` attribute
448} else {
449// NOTE: there's one more exception that we cannot apply here. On wasm,
450 // some items cannot be `no_mangle`.
451 // However, we don't have enough information here to determine that.
452 // As such, no_mangle foreign items on wasm that have the same defid as some
453 // import will *still* be mangled despite this.
454 //
455 // if none of the exceptions apply; apply no_mangle
456codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
457 }
458 }
459}
460461#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for SanitizeOnInline {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
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)]
462#[diag("non-default `sanitize` will have no effect after inlining")]
463struct SanitizeOnInline {
464#[note("inlining requested here")]
465inline_span: Span,
466}
467468#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for AsyncBlocking {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
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)]
469#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
470struct AsyncBlocking;
471472fn check_result(
473 tcx: TyCtxt<'_>,
474 did: LocalDefId,
475 interesting_spans: InterestingAttributeDiagnosticSpans,
476 codegen_fn_attrs: &CodegenFnAttrs,
477) {
478// warn that inline has no effect when no_sanitize is present
479if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
480 && codegen_fn_attrs.inline.always()
481 && let (Some(sanitize_span), Some(inline_span)) =
482 (interesting_spans.sanitize, interesting_spans.inline)
483 {
484let hir_id = tcx.local_def_id_to_hir_id(did);
485tcx.emit_node_span_lint(
486INLINE_NO_SANITIZE,
487hir_id,
488sanitize_span,
489SanitizeOnInline { inline_span },
490 )
491 }
492493// warn for nonblocking async functions, blocks and closures.
494 // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
495if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking496 && let Some(sanitize_span) = interesting_spans.sanitize
497// async fn
498&& (tcx.asyncness(did).is_async()
499// async block
500|| tcx.is_coroutine(did.into())
501// async closure
502|| (tcx.is_closure_like(did.into())
503 && tcx.hir_node_by_def_id(did).expect_closure().kind
504 != rustc_hir::ClosureKind::Closure))
505 {
506let hir_id = tcx.local_def_id_to_hir_id(did);
507tcx.emit_node_span_lint(RTSAN_NONBLOCKING_ASYNC, hir_id, sanitize_span, AsyncBlocking);
508 }
509510// error when specifying link_name together with link_ordinal
511if let Some(_) = codegen_fn_attrs.symbol_name
512 && let Some(_) = codegen_fn_attrs.link_ordinal
513 {
514let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
515if let Some(span) = interesting_spans.link_ordinal {
516tcx.dcx().span_err(span, msg);
517 } else {
518tcx.dcx().err(msg);
519 }
520 }
521522if let Some(features) = check_tied_features(
523&tcx.sess.target,
524&codegen_fn_attrs525 .target_features
526 .iter()
527 .map(|features| (features.name.as_str(), true))
528 .collect(),
529 ) {
530let 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::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)531 .unwrap_or_else(|| tcx.def_span(did));
532533tcx.dcx().emit_err(diagnostics::TargetFeatureDisableOrEnable {
534features,
535 span: Some(span),
536 missing_features: Some(diagnostics::MissingFeatures),
537 });
538 }
539}
540541fn handle_lang_items(
542 tcx: TyCtxt<'_>,
543 did: LocalDefId,
544 interesting_spans: &InterestingAttributeDiagnosticSpans,
545 attrs: &[Attribute],
546 codegen_fn_attrs: &mut CodegenFnAttrs,
547) {
548let 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::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Lang(lang) => lang);
549550// Weak lang items have the same semantics as "std internal" symbols in the
551 // sense that they're preserved through all our LTO passes and only
552 // strippable by the linker.
553 //
554 // Additionally weak lang items have predetermined symbol names.
555if let Some(lang_item) = lang_item556 && let Some(link_name) = lang_item.link_name()
557 {
558codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
559codegen_fn_attrs.symbol_name = Some(link_name);
560 }
561562// error when using no_mangle on a lang item item
563if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
564 && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
565 {
566let mut err = tcx567 .dcx()
568 .struct_span_err(
569interesting_spans.no_mangle.unwrap_or_default(),
570"`#[no_mangle]` cannot be used on internal language items",
571 )
572 .with_note("Rustc requires this item to have a specific mangled name.")
573 .with_span_label(tcx.def_span(did), "should be the internal language item");
574if let Some(lang_item) = lang_item575 && let Some(link_name) = lang_item.link_name()
576 {
577err = err578 .with_note("If you are trying to prevent mangling to ease debugging, many")
579 .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"))
580 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
link_name))
})format!(
581"match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
582))
583 }
584err.emit();
585 }
586}
587588/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
589///
590/// This happens in 4 stages:
591/// - apply built-in attributes that directly translate to codegen attributes.
592/// - handle lang items. These have special codegen attrs applied to them.
593/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
594/// overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
595/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
596fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
597if truecfg!(debug_assertions) {
598let def_kind = tcx.def_kind(did);
599if !def_kind.has_codegen_attrs() {
{
::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
def_kind));
}
};assert!(
600 def_kind.has_codegen_attrs(),
601"unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
602 );
603 }
604605let mut codegen_fn_attrs = CodegenFnAttrs::new();
606let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
607608let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
609handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
610apply_overrides(tcx, did, &mut codegen_fn_attrs);
611check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
612613codegen_fn_attrs614}
615616fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
617// Backtrack to the crate root.
618let mut settings = match tcx.opt_local_parent(did) {
619// Check the parent (recursively).
620Some(parent) => tcx.sanitizer_settings_for(parent),
621// We reached the crate root without seeing an attribute, so
622 // there is no sanitizers to exclude.
623None => SanitizerFnAttrs::default(),
624 };
625626// Check for a sanitize annotation directly on this def.
627if let Some((on_set, off_set, rtsan)) =
628{
{
'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::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))629 {
630// the on set is the set of sanitizers explicitly enabled.
631 // we mask those out since we want the set of disabled sanitizers here
632settings.disabled &= !*on_set;
633// the off set is the set of sanitizers explicitly disabled.
634 // we or those in here.
635settings.disabled |= *off_set;
636// the on set and off set are distjoint since there's a third option: unset.
637 // a node may not set the sanitizer setting in which case it inherits from parents.
638 // the code above in this function does this backtracking
639640 // if rtsan was specified here override the parent
641if let Some(rtsan) = rtsan {
642settings.rtsan_setting = *rtsan;
643 }
644 }
645settings646}
647648/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
649/// applied to the method prototype.
650fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
651tcx.trait_item_of(def_id).is_some_and(|id| {
652tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
653 })
654}
655656/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
657/// attribute on the method prototype (if any).
658fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
659tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
660}
661662pub(crate) fn provide(providers: &mut Providers) {
663*providers = Providers {
664codegen_fn_attrs,
665should_inherit_track_caller,
666inherited_align,
667sanitizer_settings_for,
668 ..*providers669 };
670}