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()) {
201 tcx.dcx().span_delayed_bug(
202*span,
203"`extern { #[linkage] static mut ...` is checked in check_attr}",
204 );
205 }
206 } else {
207 codegen_fn_attrs.linkage = linkage;
208 }
209 }
210 AttributeKind::Sanitize { span, .. } => {
211 interesting_spans.sanitize = Some(*span);
212 }
213 AttributeKind::RustcObjcClass { classname } => {
214 codegen_fn_attrs.objc_class = Some(*classname);
215 }
216 AttributeKind::RustcObjcSelector { methname } => {
217 codegen_fn_attrs.objc_selector = Some(*methname);
218 }
219 AttributeKind::RustcEiiForeignItem => {
220 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
221 }
222 AttributeKind::EiiImpl(i) => {
223let foreign_item = match i.resolution {
224 EiiImplResolution::Macro(def_id) => {
225let Some(extern_item) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(target))
=> {
break 'done Some(target.foreign_item);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
226 )else {
227 tcx.dcx().span_delayed_bug(
228 i.span,
229"resolved to something that's not an EII",
230 );
231continue;
232 };
233 extern_item
234 }
235 EiiImplResolution::Known(def_id) => def_id,
236 EiiImplResolution::Error(_eg) => continue,
237 };
238239// this is to prevent a bug where a single crate defines both the default and explicit implementation
240 // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
241 // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
242 // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
243 // the default implementation is used while an explicit implementation is given.
244if
245// if this is a default impl
246i.is_default
247// iterate over all implementations *in the current crate*
248 // (this is ok since we generate codegen fn attrs in the local crate)
249 // if any of them is *not default* then don't emit the alias.
250&& {
251let (_, 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"));
252 impls.iter().any(|(_, imp)| !imp.is_default)
253 }
254 {
255continue;
256 }
257258 codegen_fn_attrs.foreign_item_symbol_aliases.push((
259 foreign_item,
260if i.is_default { Linkage::WeakAny } else { Linkage::External },
261 Visibility::Default,
262 ));
263 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
264265// If the declaration is `#[track_caller]`, derive it onto the implementation
266 // too. The shim that forwards to this impl (see `add_function_aliases`) takes
267 // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
268 // caller-location argument is present, otherwise it would be silently dropped.
269if tcx
270 .codegen_fn_attrs(foreign_item)
271 .flags
272 .contains(CodegenFnAttrFlags::TRACK_CALLER)
273 {
274 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
275 }
276 }
277 AttributeKind::ThreadLocal => {
278 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
279 }
280 AttributeKind::InstructionSet(instruction_set) => {
281 codegen_fn_attrs.instruction_set = Some(*instruction_set)
282 }
283 AttributeKind::RustcAllocator => {
284 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
285 }
286 AttributeKind::RustcDeallocator => {
287 codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
288 }
289 AttributeKind::RustcReallocator => {
290 codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
291 }
292 AttributeKind::RustcAllocatorZeroed => {
293 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
294 }
295 AttributeKind::RustcNounwind => {
296 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
297 }
298 AttributeKind::RustcOffloadKernel => {
299 codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
300 }
301 AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
302 codegen_fn_attrs.patchable_function_entry =
303Some(PatchableFunctionEntry::from_prefix_entry_and_section(
304*prefix, *entry, *section,
305 ));
306 }
307 AttributeKind::InstrumentFn(instrument_fn) => {
308 codegen_fn_attrs.instrument_fn = match instrument_fn {
309 HirInstrumentFnAttr::On => InstrumentFnAttr::On,
310 HirInstrumentFnAttr::Off => InstrumentFnAttr::Off,
311 };
312 }
313_ => {}
314 }
315 }
316317interesting_spans318}
319320/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
321/// Please comment why when adding a new one!
322fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
323// Apply the minimum function alignment here. This ensures that a function's alignment is
324 // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
325 // it happens to be codegen'd (or const-eval'd) in.
326codegen_fn_attrs.alignment =
327 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
328329// Passed in sanitizer settings are always the default.
330if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
331// Replace with #[sanitize] value
332codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
333// On trait methods, inherit the `#[align]` of the trait's method prototype.
334codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
335336// naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
337 // but not for the code generation backend because at that point the naked function will just be
338 // a declaration, with a definition provided in global assembly.
339if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
340codegen_fn_attrs.inline = InlineAttr::Never;
341 }
342343// #73631: closures inherit `#[target_feature]` annotations
344 //
345 // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
346 //
347 // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
348 // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
349 // the function may be inlined into a caller with fewer target features. Also see
350 // <https://github.com/rust-lang/rust/issues/116573>.
351 //
352 // Using `#[inline(always)]` implies that this closure will most likely be inlined into
353 // its parent function, which effectively inherits the features anyway. Boxing this closure
354 // would result in this closure being compiled without the inherited target features, but this
355 // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
356if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
357let owner_id = tcx.parent(did.to_def_id());
358if tcx.def_kind(owner_id).has_codegen_attrs() {
359codegen_fn_attrs360 .target_features
361 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
362 }
363 }
364365// Closures inherit `#[optimize]` annotations.
366if tcx.is_closure_like(did.to_def_id()) {
367let owner_id = tcx.parent(did.to_def_id());
368if tcx.def_kind(owner_id).has_codegen_attrs() {
369let owner_attrs = tcx.codegen_fn_attrs(owner_id);
370if codegen_fn_attrs.optimize == OptimizeAttr::Default {
371codegen_fn_attrs.optimize = owner_attrs.optimize;
372 }
373 }
374 }
375376// When `no_builtins` is applied at the crate level, we should add the
377 // `no-builtins` attribute to each function to ensure it takes effect in LTO.
378let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
379if no_builtins {
380codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
381 }
382383// inherit track-caller properly
384if tcx.should_inherit_track_caller(did) {
385codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
386 }
387388// Foreign items by default use no mangling for their symbol name.
389if tcx.is_foreign_item(did) {
390codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
391392// There's a few exceptions to this rule though:
393if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
394// * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
395 // both for exports and imports through foreign items. This is handled further,
396 // during symbol mangling logic.
397} else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
398 {
399// * externally implementable items keep their mangled symbol name.
400 // multiple EIIs can have the same name, so not mangling them would be a bug.
401 // Implementing an EII does the appropriate name resolution to make sure the implementations
402 // get the same symbol name as the *mangled* foreign item they refer to so that's all good.
403} else if codegen_fn_attrs.symbol_name.is_some() {
404// * This can be overridden with the `#[link_name]` attribute
405} else {
406// NOTE: there's one more exception that we cannot apply here. On wasm,
407 // some items cannot be `no_mangle`.
408 // However, we don't have enough information here to determine that.
409 // As such, no_mangle foreign items on wasm that have the same defid as some
410 // import will *still* be mangled despite this.
411 //
412 // if none of the exceptions apply; apply no_mangle
413codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
414 }
415 }
416}
417418#[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)]
419#[diag("non-default `sanitize` will have no effect after inlining")]
420struct SanitizeOnInline {
421#[note("inlining requested here")]
422inline_span: Span,
423}
424425#[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)]
426#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
427struct AsyncBlocking;
428429fn check_result(
430 tcx: TyCtxt<'_>,
431 did: LocalDefId,
432 interesting_spans: InterestingAttributeDiagnosticSpans,
433 codegen_fn_attrs: &CodegenFnAttrs,
434) {
435// If a function uses `#[target_feature]` it can't be inlined into general
436 // purpose functions as they wouldn't have the right target features
437 // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
438 // respected.
439 //
440 // `#[rustc_force_inline]` doesn't need to be prohibited here, only
441 // `#[inline(always)]`, as forced inlining is implemented entirely within
442 // rustc (and so the MIR inliner can do any necessary checks for compatible target
443 // features).
444 //
445 // This sidesteps the LLVM blockers in enabling `target_features` +
446 // `inline(always)` to be used together (see rust-lang/rust#116573 and
447 // llvm/llvm-project#70563).
448if !codegen_fn_attrs.target_features.is_empty()
449 && #[allow(non_exhaustive_omitted_patterns)] match codegen_fn_attrs.inline {
InlineAttr::Always => true,
_ => false,
}matches!(codegen_fn_attrs.inline, InlineAttr::Always)450 && let Some(span) = interesting_spans.inline
451 {
452let mut diag = tcx453 .dcx()
454 .struct_span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
455diag.note(
456"See this issue for full discussion: \
457 https://github.com/rust-lang/rust/issues/145574",
458 );
459diag.emit();
460 }
461462// warn that inline has no effect when no_sanitize is present
463if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
464 && codegen_fn_attrs.inline.always()
465 && let (Some(sanitize_span), Some(inline_span)) =
466 (interesting_spans.sanitize, interesting_spans.inline)
467 {
468let hir_id = tcx.local_def_id_to_hir_id(did);
469tcx.emit_node_span_lint(
470 lint::builtin::INLINE_NO_SANITIZE,
471hir_id,
472sanitize_span,
473SanitizeOnInline { inline_span },
474 )
475 }
476477// warn for nonblocking async functions, blocks and closures.
478 // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
479if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking480 && let Some(sanitize_span) = interesting_spans.sanitize
481// async fn
482&& (tcx.asyncness(did).is_async()
483// async block
484|| tcx.is_coroutine(did.into())
485// async closure
486|| (tcx.is_closure_like(did.into())
487 && tcx.hir_node_by_def_id(did).expect_closure().kind
488 != rustc_hir::ClosureKind::Closure))
489 {
490let hir_id = tcx.local_def_id_to_hir_id(did);
491tcx.emit_node_span_lint(
492 lint::builtin::RTSAN_NONBLOCKING_ASYNC,
493hir_id,
494sanitize_span,
495AsyncBlocking,
496 );
497 }
498499// error when specifying link_name together with link_ordinal
500if let Some(_) = codegen_fn_attrs.symbol_name
501 && let Some(_) = codegen_fn_attrs.link_ordinal
502 {
503let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
504if let Some(span) = interesting_spans.link_ordinal {
505tcx.dcx().span_err(span, msg);
506 } else {
507tcx.dcx().err(msg);
508 }
509 }
510511if let Some(features) = check_tied_features(
512tcx.sess,
513&codegen_fn_attrs514 .target_features
515 .iter()
516 .map(|features| (features.name.as_str(), true))
517 .collect(),
518 ) {
519let span = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(TargetFeature {
attr_span: span, .. }) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)520 .unwrap_or_else(|| tcx.def_span(did));
521522tcx.dcx()
523 .create_err(diagnostics::TargetFeatureDisableOrEnable {
524features,
525 span: Some(span),
526 missing_features: Some(diagnostics::MissingFeatures),
527 })
528 .emit();
529 }
530}
531532fn handle_lang_items(
533 tcx: TyCtxt<'_>,
534 did: LocalDefId,
535 interesting_spans: &InterestingAttributeDiagnosticSpans,
536 attrs: &[Attribute],
537 codegen_fn_attrs: &mut CodegenFnAttrs,
538) {
539let lang_item = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Lang(lang)) => {
break 'done Some(lang);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Lang(lang) => lang);
540541// Weak lang items have the same semantics as "std internal" symbols in the
542 // sense that they're preserved through all our LTO passes and only
543 // strippable by the linker.
544 //
545 // Additionally weak lang items have predetermined symbol names.
546if let Some(lang_item) = lang_item547 && let Some(link_name) = lang_item.link_name()
548 {
549codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
550codegen_fn_attrs.symbol_name = Some(link_name);
551 }
552553// error when using no_mangle on a lang item item
554if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
555 && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
556 {
557let mut err = tcx558 .dcx()
559 .struct_span_err(
560interesting_spans.no_mangle.unwrap_or_default(),
561"`#[no_mangle]` cannot be used on internal language items",
562 )
563 .with_note("Rustc requires this item to have a specific mangled name.")
564 .with_span_label(tcx.def_span(did), "should be the internal language item");
565if let Some(lang_item) = lang_item566 && let Some(link_name) = lang_item.link_name()
567 {
568err = err569 .with_note("If you are trying to prevent mangling to ease debugging, many")
570 .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"))
571 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
link_name))
})format!(
572"match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
573))
574 }
575err.emit();
576 }
577}
578579/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
580///
581/// This happens in 4 stages:
582/// - apply built-in attributes that directly translate to codegen attributes.
583/// - handle lang items. These have special codegen attrs applied to them.
584/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
585/// overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
586/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
587fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
588if truecfg!(debug_assertions) {
589let def_kind = tcx.def_kind(did);
590if !def_kind.has_codegen_attrs() {
{
::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
def_kind));
}
};assert!(
591 def_kind.has_codegen_attrs(),
592"unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
593 );
594 }
595596let mut codegen_fn_attrs = CodegenFnAttrs::new();
597let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
598599let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
600handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
601apply_overrides(tcx, did, &mut codegen_fn_attrs);
602check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
603604codegen_fn_attrs605}
606607fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
608// Backtrack to the crate root.
609let mut settings = match tcx.opt_local_parent(did) {
610// Check the parent (recursively).
611Some(parent) => tcx.sanitizer_settings_for(parent),
612// We reached the crate root without seeing an attribute, so
613 // there is no sanitizers to exclude.
614None => SanitizerFnAttrs::default(),
615 };
616617// Check for a sanitize annotation directly on this def.
618if let Some((on_set, off_set, rtsan)) =
619{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Sanitize {
on_set, off_set, rtsan, .. }) => {
break 'done Some((on_set, off_set, rtsan));
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))620 {
621// the on set is the set of sanitizers explicitly enabled.
622 // we mask those out since we want the set of disabled sanitizers here
623settings.disabled &= !*on_set;
624// the off set is the set of sanitizers explicitly disabled.
625 // we or those in here.
626settings.disabled |= *off_set;
627// the on set and off set are distjoint since there's a third option: unset.
628 // a node may not set the sanitizer setting in which case it inherits from parents.
629 // the code above in this function does this backtracking
630631 // if rtsan was specified here override the parent
632if let Some(rtsan) = rtsan {
633settings.rtsan_setting = *rtsan;
634 }
635 }
636settings637}
638639/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
640/// applied to the method prototype.
641fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
642tcx.trait_item_of(def_id).is_some_and(|id| {
643tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
644 })
645}
646647/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
648/// attribute on the method prototype (if any).
649fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
650tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
651}
652653pub(crate) fn provide(providers: &mut Providers) {
654*providers = Providers {
655codegen_fn_attrs,
656should_inherit_track_caller,
657inherited_align,
658sanitizer_settings_for,
659 ..*providers660 };
661}