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