]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect.rs
Rollup merge of #103280 - finnbear:impl_string_leak_2, r=joshtriplett
[rust.git] / compiler / rustc_hir_analysis / src / collect.rs
1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *inter-procedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
7 //! type *checking*).
8 //!
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
12 //! for the full set.
13 //!
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
16
17 use crate::astconv::AstConv;
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
19 use crate::errors;
20 use rustc_ast as ast;
21 use rustc_ast::{MetaItemKind, NestedMetaItem};
22 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
23 use rustc_data_structures::captures::Captures;
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
26 use rustc_hir as hir;
27 use rustc_hir::def::CtorKind;
28 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
29 use rustc_hir::intravisit::{self, Visitor};
30 use rustc_hir::weak_lang_items;
31 use rustc_hir::{GenericParamKind, Node};
32 use rustc_middle::hir::nested_filter;
33 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
34 use rustc_middle::mir::mono::Linkage;
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::util::{Discr, IntTypeExt};
37 use rustc_middle::ty::ReprOptions;
38 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, IsSuggestable, Ty, TyCtxt};
39 use rustc_session::lint;
40 use rustc_session::parse::feature_err;
41 use rustc_span::symbol::{kw, sym, Ident, Symbol};
42 use rustc_span::Span;
43 use rustc_target::spec::{abi, SanitizerSet};
44 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
45 use std::iter;
46
47 mod generics_of;
48 mod item_bounds;
49 mod lifetimes;
50 mod predicates_of;
51 mod type_of;
52
53 ///////////////////////////////////////////////////////////////////////////
54 // Main entry point
55
56 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
57     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
58 }
59
60 pub fn provide(providers: &mut Providers) {
61     lifetimes::provide(providers);
62     *providers = Providers {
63         opt_const_param_of: type_of::opt_const_param_of,
64         type_of: type_of::type_of,
65         item_bounds: item_bounds::item_bounds,
66         explicit_item_bounds: item_bounds::explicit_item_bounds,
67         generics_of: generics_of::generics_of,
68         predicates_of: predicates_of::predicates_of,
69         predicates_defined_on,
70         explicit_predicates_of: predicates_of::explicit_predicates_of,
71         super_predicates_of: predicates_of::super_predicates_of,
72         super_predicates_that_define_assoc_type:
73             predicates_of::super_predicates_that_define_assoc_type,
74         trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds,
75         type_param_predicates: predicates_of::type_param_predicates,
76         trait_def,
77         adt_def,
78         fn_sig,
79         impl_trait_ref,
80         impl_polarity,
81         is_foreign_item,
82         generator_kind,
83         codegen_fn_attrs,
84         asm_target_features,
85         collect_mod_item_types,
86         should_inherit_track_caller,
87         ..*providers
88     };
89 }
90
91 ///////////////////////////////////////////////////////////////////////////
92
93 /// Context specific to some particular item. This is what implements
94 /// [`AstConv`].
95 ///
96 /// # `ItemCtxt` vs `FnCtxt`
97 ///
98 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
99 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
100 /// It's also used for the bodies of items like structs where the body (the fields)
101 /// are just signatures.
102 ///
103 /// This is in contrast to `FnCtxt`, which is used to type-check bodies of
104 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
105 ///
106 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
107 /// while `FnCtxt` does do inference.
108 ///
109 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
110 ///
111 /// # Trait predicates
112 ///
113 /// `ItemCtxt` has information about the predicates that are defined
114 /// on the trait. Unfortunately, this predicate information is
115 /// available in various different forms at various points in the
116 /// process. So we can't just store a pointer to e.g., the AST or the
117 /// parsed ty form, we have to be more flexible. To this end, the
118 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
119 /// `get_type_parameter_bounds` requests, drawing the information from
120 /// the AST (`hir::Generics`), recursively.
121 pub struct ItemCtxt<'tcx> {
122     tcx: TyCtxt<'tcx>,
123     item_def_id: DefId,
124 }
125
126 ///////////////////////////////////////////////////////////////////////////
127
128 #[derive(Default)]
129 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
130
131 impl<'v> Visitor<'v> for HirPlaceholderCollector {
132     fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
133         if let hir::TyKind::Infer = t.kind {
134             self.0.push(t.span);
135         }
136         intravisit::walk_ty(self, t)
137     }
138     fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
139         match generic_arg {
140             hir::GenericArg::Infer(inf) => {
141                 self.0.push(inf.span);
142                 intravisit::walk_inf(self, inf);
143             }
144             hir::GenericArg::Type(t) => self.visit_ty(t),
145             _ => {}
146         }
147     }
148     fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
149         if let &hir::ArrayLen::Infer(_, span) = length {
150             self.0.push(span);
151         }
152         intravisit::walk_array_len(self, length)
153     }
154 }
155
156 struct CollectItemTypesVisitor<'tcx> {
157     tcx: TyCtxt<'tcx>,
158 }
159
160 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
161 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
162 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
163 pub(crate) fn placeholder_type_error<'tcx>(
164     tcx: TyCtxt<'tcx>,
165     generics: Option<&hir::Generics<'_>>,
166     placeholder_types: Vec<Span>,
167     suggest: bool,
168     hir_ty: Option<&hir::Ty<'_>>,
169     kind: &'static str,
170 ) {
171     if placeholder_types.is_empty() {
172         return;
173     }
174
175     placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
176         .emit();
177 }
178
179 pub(crate) fn placeholder_type_error_diag<'tcx>(
180     tcx: TyCtxt<'tcx>,
181     generics: Option<&hir::Generics<'_>>,
182     placeholder_types: Vec<Span>,
183     additional_spans: Vec<Span>,
184     suggest: bool,
185     hir_ty: Option<&hir::Ty<'_>>,
186     kind: &'static str,
187 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
188     if placeholder_types.is_empty() {
189         return bad_placeholder(tcx, additional_spans, kind);
190     }
191
192     let params = generics.map(|g| g.params).unwrap_or_default();
193     let type_name = params.next_type_param_name(None);
194     let mut sugg: Vec<_> =
195         placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
196
197     if let Some(generics) = generics {
198         if let Some(arg) = params.iter().find(|arg| {
199             matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
200         }) {
201             // Account for `_` already present in cases like `struct S<_>(_);` and suggest
202             // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
203             sugg.push((arg.span, (*type_name).to_string()));
204         } else if let Some(span) = generics.span_for_param_suggestion() {
205             // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
206             sugg.push((span, format!(", {}", type_name)));
207         } else {
208             sugg.push((generics.span, format!("<{}>", type_name)));
209         }
210     }
211
212     let mut err =
213         bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
214
215     // Suggest, but only if it is not a function in const or static
216     if suggest {
217         let mut is_fn = false;
218         let mut is_const_or_static = false;
219
220         if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
221             is_fn = true;
222
223             // Check if parent is const or static
224             let parent_id = tcx.hir().get_parent_node(hir_ty.hir_id);
225             let parent_node = tcx.hir().get(parent_id);
226
227             is_const_or_static = matches!(
228                 parent_node,
229                 Node::Item(&hir::Item {
230                     kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
231                     ..
232                 }) | Node::TraitItem(&hir::TraitItem {
233                     kind: hir::TraitItemKind::Const(..),
234                     ..
235                 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
236             );
237         }
238
239         // if function is wrapped around a const or static,
240         // then don't show the suggestion
241         if !(is_fn && is_const_or_static) {
242             err.multipart_suggestion(
243                 "use type parameters instead",
244                 sugg,
245                 Applicability::HasPlaceholders,
246             );
247         }
248     }
249
250     err
251 }
252
253 fn reject_placeholder_type_signatures_in_item<'tcx>(
254     tcx: TyCtxt<'tcx>,
255     item: &'tcx hir::Item<'tcx>,
256 ) {
257     let (generics, suggest) = match &item.kind {
258         hir::ItemKind::Union(_, generics)
259         | hir::ItemKind::Enum(_, generics)
260         | hir::ItemKind::TraitAlias(generics, _)
261         | hir::ItemKind::Trait(_, _, generics, ..)
262         | hir::ItemKind::Impl(hir::Impl { generics, .. })
263         | hir::ItemKind::Struct(_, generics) => (generics, true),
264         hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
265         | hir::ItemKind::TyAlias(_, generics) => (generics, false),
266         // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
267         _ => return,
268     };
269
270     let mut visitor = HirPlaceholderCollector::default();
271     visitor.visit_item(item);
272
273     placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
274 }
275
276 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
277     type NestedFilter = nested_filter::OnlyBodies;
278
279     fn nested_visit_map(&mut self) -> Self::Map {
280         self.tcx.hir()
281     }
282
283     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
284         convert_item(self.tcx, item.item_id());
285         reject_placeholder_type_signatures_in_item(self.tcx, item);
286         intravisit::walk_item(self, item);
287     }
288
289     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
290         for param in generics.params {
291             match param.kind {
292                 hir::GenericParamKind::Lifetime { .. } => {}
293                 hir::GenericParamKind::Type { default: Some(_), .. } => {
294                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
295                     self.tcx.ensure().type_of(def_id);
296                 }
297                 hir::GenericParamKind::Type { .. } => {}
298                 hir::GenericParamKind::Const { default, .. } => {
299                     let def_id = self.tcx.hir().local_def_id(param.hir_id);
300                     self.tcx.ensure().type_of(def_id);
301                     if let Some(default) = default {
302                         let default_def_id = self.tcx.hir().local_def_id(default.hir_id);
303                         // need to store default and type of default
304                         self.tcx.ensure().type_of(default_def_id);
305                         self.tcx.ensure().const_param_default(def_id);
306                     }
307                 }
308             }
309         }
310         intravisit::walk_generics(self, generics);
311     }
312
313     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
314         if let hir::ExprKind::Closure { .. } = expr.kind {
315             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
316             self.tcx.ensure().generics_of(def_id);
317             // We do not call `type_of` for closures here as that
318             // depends on typecheck and would therefore hide
319             // any further errors in case one typeck fails.
320         }
321         intravisit::walk_expr(self, expr);
322     }
323
324     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
325         convert_trait_item(self.tcx, trait_item.trait_item_id());
326         intravisit::walk_trait_item(self, trait_item);
327     }
328
329     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
330         convert_impl_item(self.tcx, impl_item.impl_item_id());
331         intravisit::walk_impl_item(self, impl_item);
332     }
333 }
334
335 ///////////////////////////////////////////////////////////////////////////
336 // Utility types and common code for the above passes.
337
338 fn bad_placeholder<'tcx>(
339     tcx: TyCtxt<'tcx>,
340     mut spans: Vec<Span>,
341     kind: &'static str,
342 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
343     let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
344
345     spans.sort();
346     let mut err = struct_span_err!(
347         tcx.sess,
348         spans.clone(),
349         E0121,
350         "the placeholder `_` is not allowed within types on item signatures for {}",
351         kind
352     );
353     for span in spans {
354         err.span_label(span, "not allowed in type signatures");
355     }
356     err
357 }
358
359 impl<'tcx> ItemCtxt<'tcx> {
360     pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
361         ItemCtxt { tcx, item_def_id }
362     }
363
364     pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
365         <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_ty)
366     }
367
368     pub fn hir_id(&self) -> hir::HirId {
369         self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
370     }
371
372     pub fn node(&self) -> hir::Node<'tcx> {
373         self.tcx.hir().get(self.hir_id())
374     }
375 }
376
377 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
378     fn tcx(&self) -> TyCtxt<'tcx> {
379         self.tcx
380     }
381
382     fn item_def_id(&self) -> Option<DefId> {
383         Some(self.item_def_id)
384     }
385
386     fn get_type_parameter_bounds(
387         &self,
388         span: Span,
389         def_id: DefId,
390         assoc_name: Ident,
391     ) -> ty::GenericPredicates<'tcx> {
392         self.tcx.at(span).type_param_predicates((
393             self.item_def_id,
394             def_id.expect_local(),
395             assoc_name,
396         ))
397     }
398
399     fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
400         None
401     }
402
403     fn allow_ty_infer(&self) -> bool {
404         false
405     }
406
407     fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
408         self.tcx().ty_error_with_message(span, "bad placeholder type")
409     }
410
411     fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
412         let ty = self.tcx.fold_regions(ty, |r, _| match *r {
413             ty::ReErased => self.tcx.lifetimes.re_static,
414             _ => r,
415         });
416         self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
417     }
418
419     fn projected_ty_from_poly_trait_ref(
420         &self,
421         span: Span,
422         item_def_id: DefId,
423         item_segment: &hir::PathSegment<'_>,
424         poly_trait_ref: ty::PolyTraitRef<'tcx>,
425     ) -> Ty<'tcx> {
426         if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
427             let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
428                 self,
429                 span,
430                 item_def_id,
431                 item_segment,
432                 trait_ref.substs,
433             );
434             self.tcx().mk_projection(item_def_id, item_substs)
435         } else {
436             // There are no late-bound regions; we can just ignore the binder.
437             let mut err = struct_span_err!(
438                 self.tcx().sess,
439                 span,
440                 E0212,
441                 "cannot use the associated type of a trait \
442                  with uninferred generic parameters"
443             );
444
445             match self.node() {
446                 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
447                     let item = self
448                         .tcx
449                         .hir()
450                         .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
451                     match &item.kind {
452                         hir::ItemKind::Enum(_, generics)
453                         | hir::ItemKind::Struct(_, generics)
454                         | hir::ItemKind::Union(_, generics) => {
455                             let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
456                             let (lt_sp, sugg) = match generics.params {
457                                 [] => (generics.span, format!("<{}>", lt_name)),
458                                 [bound, ..] => {
459                                     (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
460                                 }
461                             };
462                             let suggestions = vec![
463                                 (lt_sp, sugg),
464                                 (
465                                     span.with_hi(item_segment.ident.span.lo()),
466                                     format!(
467                                         "{}::",
468                                         // Replace the existing lifetimes with a new named lifetime.
469                                         self.tcx.replace_late_bound_regions_uncached(
470                                             poly_trait_ref,
471                                             |_| {
472                                                 self.tcx.mk_region(ty::ReEarlyBound(
473                                                     ty::EarlyBoundRegion {
474                                                         def_id: item_def_id,
475                                                         index: 0,
476                                                         name: Symbol::intern(&lt_name),
477                                                     },
478                                                 ))
479                                             }
480                                         ),
481                                     ),
482                                 ),
483                             ];
484                             err.multipart_suggestion(
485                                 "use a fully qualified path with explicit lifetimes",
486                                 suggestions,
487                                 Applicability::MaybeIncorrect,
488                             );
489                         }
490                         _ => {}
491                     }
492                 }
493                 hir::Node::Item(hir::Item {
494                     kind:
495                         hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
496                     ..
497                 }) => {}
498                 hir::Node::Item(_)
499                 | hir::Node::ForeignItem(_)
500                 | hir::Node::TraitItem(_)
501                 | hir::Node::ImplItem(_) => {
502                     err.span_suggestion_verbose(
503                         span.with_hi(item_segment.ident.span.lo()),
504                         "use a fully qualified path with inferred lifetimes",
505                         format!(
506                             "{}::",
507                             // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
508                             self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
509                         ),
510                         Applicability::MaybeIncorrect,
511                     );
512                 }
513                 _ => {}
514             }
515             err.emit();
516             self.tcx().ty_error()
517         }
518     }
519
520     fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
521         // Types in item signatures are not normalized to avoid undue dependencies.
522         ty
523     }
524
525     fn set_tainted_by_errors(&self) {
526         // There's no obvious place to track this, so just let it go.
527     }
528
529     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
530         // There's no place to record types from signatures?
531     }
532 }
533
534 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
535 fn get_new_lifetime_name<'tcx>(
536     tcx: TyCtxt<'tcx>,
537     poly_trait_ref: ty::PolyTraitRef<'tcx>,
538     generics: &hir::Generics<'tcx>,
539 ) -> String {
540     let existing_lifetimes = tcx
541         .collect_referenced_late_bound_regions(&poly_trait_ref)
542         .into_iter()
543         .filter_map(|lt| {
544             if let ty::BoundRegionKind::BrNamed(_, name) = lt {
545                 Some(name.as_str().to_string())
546             } else {
547                 None
548             }
549         })
550         .chain(generics.params.iter().filter_map(|param| {
551             if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
552                 Some(param.name.ident().as_str().to_string())
553             } else {
554                 None
555             }
556         }))
557         .collect::<FxHashSet<String>>();
558
559     let a_to_z_repeat_n = |n| {
560         (b'a'..=b'z').map(move |c| {
561             let mut s = '\''.to_string();
562             s.extend(std::iter::repeat(char::from(c)).take(n));
563             s
564         })
565     };
566
567     // If all single char lifetime names are present, we wrap around and double the chars.
568     (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
569 }
570
571 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
572     let it = tcx.hir().item(item_id);
573     debug!("convert: item {} with id {}", it.ident, it.hir_id());
574     let def_id = item_id.def_id.def_id;
575
576     match it.kind {
577         // These don't define types.
578         hir::ItemKind::ExternCrate(_)
579         | hir::ItemKind::Use(..)
580         | hir::ItemKind::Macro(..)
581         | hir::ItemKind::Mod(_)
582         | hir::ItemKind::GlobalAsm(_) => {}
583         hir::ItemKind::ForeignMod { items, .. } => {
584             for item in items {
585                 let item = tcx.hir().foreign_item(item.id);
586                 tcx.ensure().generics_of(item.def_id);
587                 tcx.ensure().type_of(item.def_id);
588                 tcx.ensure().predicates_of(item.def_id);
589                 match item.kind {
590                     hir::ForeignItemKind::Fn(..) => tcx.ensure().fn_sig(item.def_id),
591                     hir::ForeignItemKind::Static(..) => {
592                         let mut visitor = HirPlaceholderCollector::default();
593                         visitor.visit_foreign_item(item);
594                         placeholder_type_error(
595                             tcx,
596                             None,
597                             visitor.0,
598                             false,
599                             None,
600                             "static variable",
601                         );
602                     }
603                     _ => (),
604                 }
605             }
606         }
607         hir::ItemKind::Enum(ref enum_definition, _) => {
608             tcx.ensure().generics_of(def_id);
609             tcx.ensure().type_of(def_id);
610             tcx.ensure().predicates_of(def_id);
611             convert_enum_variant_types(tcx, def_id.to_def_id(), enum_definition.variants);
612         }
613         hir::ItemKind::Impl { .. } => {
614             tcx.ensure().generics_of(def_id);
615             tcx.ensure().type_of(def_id);
616             tcx.ensure().impl_trait_ref(def_id);
617             tcx.ensure().predicates_of(def_id);
618         }
619         hir::ItemKind::Trait(..) => {
620             tcx.ensure().generics_of(def_id);
621             tcx.ensure().trait_def(def_id);
622             tcx.at(it.span).super_predicates_of(def_id);
623             tcx.ensure().predicates_of(def_id);
624         }
625         hir::ItemKind::TraitAlias(..) => {
626             tcx.ensure().generics_of(def_id);
627             tcx.at(it.span).super_predicates_of(def_id);
628             tcx.ensure().predicates_of(def_id);
629         }
630         hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
631             tcx.ensure().generics_of(def_id);
632             tcx.ensure().type_of(def_id);
633             tcx.ensure().predicates_of(def_id);
634
635             for f in struct_def.fields() {
636                 let def_id = tcx.hir().local_def_id(f.hir_id);
637                 tcx.ensure().generics_of(def_id);
638                 tcx.ensure().type_of(def_id);
639                 tcx.ensure().predicates_of(def_id);
640             }
641
642             if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
643                 convert_variant_ctor(tcx, ctor_hir_id);
644             }
645         }
646
647         // Desugared from `impl Trait`, so visited by the function's return type.
648         hir::ItemKind::OpaqueTy(hir::OpaqueTy {
649             origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
650             ..
651         }) => {}
652
653         // Don't call `type_of` on opaque types, since that depends on type
654         // checking function bodies. `check_item_type` ensures that it's called
655         // instead.
656         hir::ItemKind::OpaqueTy(..) => {
657             tcx.ensure().generics_of(def_id);
658             tcx.ensure().predicates_of(def_id);
659             tcx.ensure().explicit_item_bounds(def_id);
660         }
661         hir::ItemKind::TyAlias(..)
662         | hir::ItemKind::Static(..)
663         | hir::ItemKind::Const(..)
664         | hir::ItemKind::Fn(..) => {
665             tcx.ensure().generics_of(def_id);
666             tcx.ensure().type_of(def_id);
667             tcx.ensure().predicates_of(def_id);
668             match it.kind {
669                 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
670                 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
671                 hir::ItemKind::Const(ty, ..) | hir::ItemKind::Static(ty, ..) => {
672                     if !is_suggestable_infer_ty(ty) {
673                         let mut visitor = HirPlaceholderCollector::default();
674                         visitor.visit_item(it);
675                         placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
676                     }
677                 }
678                 _ => (),
679             }
680         }
681     }
682 }
683
684 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
685     let trait_item = tcx.hir().trait_item(trait_item_id);
686     let def_id = trait_item_id.def_id;
687     tcx.ensure().generics_of(def_id);
688
689     match trait_item.kind {
690         hir::TraitItemKind::Fn(..) => {
691             tcx.ensure().type_of(def_id);
692             tcx.ensure().fn_sig(def_id);
693         }
694
695         hir::TraitItemKind::Const(.., Some(_)) => {
696             tcx.ensure().type_of(def_id);
697         }
698
699         hir::TraitItemKind::Const(hir_ty, _) => {
700             tcx.ensure().type_of(def_id);
701             // Account for `const C: _;`.
702             let mut visitor = HirPlaceholderCollector::default();
703             visitor.visit_trait_item(trait_item);
704             if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
705                 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
706             }
707         }
708
709         hir::TraitItemKind::Type(_, Some(_)) => {
710             tcx.ensure().item_bounds(def_id);
711             tcx.ensure().type_of(def_id);
712             // Account for `type T = _;`.
713             let mut visitor = HirPlaceholderCollector::default();
714             visitor.visit_trait_item(trait_item);
715             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
716         }
717
718         hir::TraitItemKind::Type(_, None) => {
719             tcx.ensure().item_bounds(def_id);
720             // #74612: Visit and try to find bad placeholders
721             // even if there is no concrete type.
722             let mut visitor = HirPlaceholderCollector::default();
723             visitor.visit_trait_item(trait_item);
724
725             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
726         }
727     };
728
729     tcx.ensure().predicates_of(def_id);
730 }
731
732 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
733     let def_id = impl_item_id.def_id;
734     tcx.ensure().generics_of(def_id);
735     tcx.ensure().type_of(def_id);
736     tcx.ensure().predicates_of(def_id);
737     let impl_item = tcx.hir().impl_item(impl_item_id);
738     match impl_item.kind {
739         hir::ImplItemKind::Fn(..) => {
740             tcx.ensure().fn_sig(def_id);
741         }
742         hir::ImplItemKind::Type(_) => {
743             // Account for `type T = _;`
744             let mut visitor = HirPlaceholderCollector::default();
745             visitor.visit_impl_item(impl_item);
746
747             placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
748         }
749         hir::ImplItemKind::Const(..) => {}
750     }
751 }
752
753 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
754     let def_id = tcx.hir().local_def_id(ctor_id);
755     tcx.ensure().generics_of(def_id);
756     tcx.ensure().type_of(def_id);
757     tcx.ensure().predicates_of(def_id);
758 }
759
760 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
761     let def = tcx.adt_def(def_id);
762     let repr_type = def.repr().discr_type();
763     let initial = repr_type.initial_discriminant(tcx);
764     let mut prev_discr = None::<Discr<'_>>;
765
766     // fill the discriminant values and field types
767     for variant in variants {
768         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
769         prev_discr = Some(
770             if let Some(ref e) = variant.disr_expr {
771                 let expr_did = tcx.hir().local_def_id(e.hir_id);
772                 def.eval_explicit_discr(tcx, expr_did.to_def_id())
773             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
774                 Some(discr)
775             } else {
776                 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
777                     .span_label(
778                         variant.span,
779                         format!("overflowed on value after {}", prev_discr.unwrap()),
780                     )
781                     .note(&format!(
782                         "explicitly set `{} = {}` if that is desired outcome",
783                         variant.ident, wrapped_discr
784                     ))
785                     .emit();
786                 None
787             }
788             .unwrap_or(wrapped_discr),
789         );
790
791         for f in variant.data.fields() {
792             let def_id = tcx.hir().local_def_id(f.hir_id);
793             tcx.ensure().generics_of(def_id);
794             tcx.ensure().type_of(def_id);
795             tcx.ensure().predicates_of(def_id);
796         }
797
798         // Convert the ctor, if any. This also registers the variant as
799         // an item.
800         if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
801             convert_variant_ctor(tcx, ctor_hir_id);
802         }
803     }
804 }
805
806 fn convert_variant(
807     tcx: TyCtxt<'_>,
808     variant_did: Option<LocalDefId>,
809     ctor_did: Option<LocalDefId>,
810     ident: Ident,
811     discr: ty::VariantDiscr,
812     def: &hir::VariantData<'_>,
813     adt_kind: ty::AdtKind,
814     parent_did: LocalDefId,
815 ) -> ty::VariantDef {
816     let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
817     let fields = def
818         .fields()
819         .iter()
820         .map(|f| {
821             let fid = tcx.hir().local_def_id(f.hir_id);
822             let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
823             if let Some(prev_span) = dup_span {
824                 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
825                     field_name: f.ident,
826                     span: f.span,
827                     prev_span,
828                 });
829             } else {
830                 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
831             }
832
833             ty::FieldDef { did: fid.to_def_id(), name: f.ident.name, vis: tcx.visibility(fid) }
834         })
835         .collect();
836     let recovered = match def {
837         hir::VariantData::Struct(_, r) => *r,
838         _ => false,
839     };
840     ty::VariantDef::new(
841         ident.name,
842         variant_did.map(LocalDefId::to_def_id),
843         ctor_did.map(LocalDefId::to_def_id),
844         discr,
845         fields,
846         CtorKind::from_hir(def),
847         adt_kind,
848         parent_did.to_def_id(),
849         recovered,
850         adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
851             || variant_did.map_or(false, |variant_did| {
852                 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
853             }),
854     )
855 }
856
857 fn adt_def<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::AdtDef<'tcx> {
858     use rustc_hir::*;
859
860     let def_id = def_id.expect_local();
861     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
862     let Node::Item(item) = tcx.hir().get(hir_id) else {
863         bug!();
864     };
865
866     let repr = ReprOptions::new(tcx, def_id.to_def_id());
867     let (kind, variants) = match item.kind {
868         ItemKind::Enum(ref def, _) => {
869             let mut distance_from_explicit = 0;
870             let variants = def
871                 .variants
872                 .iter()
873                 .map(|v| {
874                     let variant_did = Some(tcx.hir().local_def_id(v.id));
875                     let ctor_did =
876                         v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
877
878                     let discr = if let Some(ref e) = v.disr_expr {
879                         distance_from_explicit = 0;
880                         ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
881                     } else {
882                         ty::VariantDiscr::Relative(distance_from_explicit)
883                     };
884                     distance_from_explicit += 1;
885
886                     convert_variant(
887                         tcx,
888                         variant_did,
889                         ctor_did,
890                         v.ident,
891                         discr,
892                         &v.data,
893                         AdtKind::Enum,
894                         def_id,
895                     )
896                 })
897                 .collect();
898
899             (AdtKind::Enum, variants)
900         }
901         ItemKind::Struct(ref def, _) => {
902             let variant_did = None::<LocalDefId>;
903             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
904
905             let variants = std::iter::once(convert_variant(
906                 tcx,
907                 variant_did,
908                 ctor_did,
909                 item.ident,
910                 ty::VariantDiscr::Relative(0),
911                 def,
912                 AdtKind::Struct,
913                 def_id,
914             ))
915             .collect();
916
917             (AdtKind::Struct, variants)
918         }
919         ItemKind::Union(ref def, _) => {
920             let variant_did = None;
921             let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
922
923             let variants = std::iter::once(convert_variant(
924                 tcx,
925                 variant_did,
926                 ctor_did,
927                 item.ident,
928                 ty::VariantDiscr::Relative(0),
929                 def,
930                 AdtKind::Union,
931                 def_id,
932             ))
933             .collect();
934
935             (AdtKind::Union, variants)
936         }
937         _ => bug!(),
938     };
939     tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
940 }
941
942 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
943     let item = tcx.hir().expect_item(def_id.expect_local());
944
945     let (is_auto, unsafety, items) = match item.kind {
946         hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
947             (is_auto == hir::IsAuto::Yes, unsafety, items)
948         }
949         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
950         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
951     };
952
953     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
954     if paren_sugar && !tcx.features().unboxed_closures {
955         tcx.sess
956             .struct_span_err(
957                 item.span,
958                 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
959                  which traits can use parenthetical notation",
960             )
961             .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
962             .emit();
963     }
964
965     let is_marker = tcx.has_attr(def_id, sym::marker);
966     let skip_array_during_method_dispatch =
967         tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
968     let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
969         ty::trait_def::TraitSpecializationKind::Marker
970     } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
971         ty::trait_def::TraitSpecializationKind::AlwaysApplicable
972     } else {
973         ty::trait_def::TraitSpecializationKind::None
974     };
975     let must_implement_one_of = tcx
976         .get_attr(def_id, sym::rustc_must_implement_one_of)
977         // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
978         // and that they are all identifiers
979         .and_then(|attr| match attr.meta_item_list() {
980             Some(items) if items.len() < 2 => {
981                 tcx.sess
982                     .struct_span_err(
983                         attr.span,
984                         "the `#[rustc_must_implement_one_of]` attribute must be \
985                         used with at least 2 args",
986                     )
987                     .emit();
988
989                 None
990             }
991             Some(items) => items
992                 .into_iter()
993                 .map(|item| item.ident().ok_or(item.span()))
994                 .collect::<Result<Box<[_]>, _>>()
995                 .map_err(|span| {
996                     tcx.sess
997                         .struct_span_err(span, "must be a name of an associated function")
998                         .emit();
999                 })
1000                 .ok()
1001                 .zip(Some(attr.span)),
1002             // Error is reported by `rustc_attr!`
1003             None => None,
1004         })
1005         // Check that all arguments of `#[rustc_must_implement_one_of]` reference
1006         // functions in the trait with default implementations
1007         .and_then(|(list, attr_span)| {
1008             let errors = list.iter().filter_map(|ident| {
1009                 let item = items.iter().find(|item| item.ident == *ident);
1010
1011                 match item {
1012                     Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
1013                         if !tcx.impl_defaultness(item.id.def_id).has_value() {
1014                             tcx.sess
1015                                 .struct_span_err(
1016                                     item.span,
1017                                     "This function doesn't have a default implementation",
1018                                 )
1019                                 .span_note(attr_span, "required by this annotation")
1020                                 .emit();
1021
1022                             return Some(());
1023                         }
1024
1025                         return None;
1026                     }
1027                     Some(item) => {
1028                         tcx.sess
1029                             .struct_span_err(item.span, "Not a function")
1030                             .span_note(attr_span, "required by this annotation")
1031                             .note(
1032                                 "All `#[rustc_must_implement_one_of]` arguments \
1033                             must be associated function names",
1034                             )
1035                             .emit();
1036                     }
1037                     None => {
1038                         tcx.sess
1039                             .struct_span_err(ident.span, "Function not found in this trait")
1040                             .emit();
1041                     }
1042                 }
1043
1044                 Some(())
1045             });
1046
1047             (errors.count() == 0).then_some(list)
1048         })
1049         // Check for duplicates
1050         .and_then(|list| {
1051             let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1052             let mut no_dups = true;
1053
1054             for ident in &*list {
1055                 if let Some(dup) = set.insert(ident.name, ident.span) {
1056                     tcx.sess
1057                         .struct_span_err(vec![dup, ident.span], "Functions names are duplicated")
1058                         .note(
1059                             "All `#[rustc_must_implement_one_of]` arguments \
1060                             must be unique",
1061                         )
1062                         .emit();
1063
1064                     no_dups = false;
1065                 }
1066             }
1067
1068             no_dups.then_some(list)
1069         });
1070
1071     ty::TraitDef::new(
1072         def_id,
1073         unsafety,
1074         paren_sugar,
1075         is_auto,
1076         is_marker,
1077         skip_array_during_method_dispatch,
1078         spec_kind,
1079         must_implement_one_of,
1080     )
1081 }
1082
1083 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1084     generic_args.iter().any(|arg| match arg {
1085         hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1086         hir::GenericArg::Infer(_) => true,
1087         _ => false,
1088     })
1089 }
1090
1091 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1092 /// use inference to provide suggestions for the appropriate type if possible.
1093 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1094     debug!(?ty);
1095     use hir::TyKind::*;
1096     match &ty.kind {
1097         Infer => true,
1098         Slice(ty) => is_suggestable_infer_ty(ty),
1099         Array(ty, length) => {
1100             is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1101         }
1102         Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1103         Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1104         OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1105         Path(hir::QPath::TypeRelative(ty, segment)) => {
1106             is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1107         }
1108         Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1109             ty_opt.map_or(false, is_suggestable_infer_ty)
1110                 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1111         }
1112         _ => false,
1113     }
1114 }
1115
1116 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1117     if let hir::FnRetTy::Return(ty) = output {
1118         if is_suggestable_infer_ty(ty) {
1119             return Some(&*ty);
1120         }
1121     }
1122     None
1123 }
1124
1125 #[instrument(level = "debug", skip(tcx))]
1126 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1127     use rustc_hir::Node::*;
1128     use rustc_hir::*;
1129
1130     let def_id = def_id.expect_local();
1131     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1132
1133     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1134
1135     match tcx.hir().get(hir_id) {
1136         TraitItem(hir::TraitItem {
1137             kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1138             generics,
1139             ..
1140         })
1141         | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1142             infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1143         }
1144
1145         ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1146             // Do not try to inference the return type for a impl method coming from a trait
1147             if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1148                 tcx.hir().get(tcx.hir().get_parent_node(hir_id))
1149                 && i.of_trait.is_some()
1150             {
1151                 <dyn AstConv<'_>>::ty_of_fn(
1152                     &icx,
1153                     hir_id,
1154                     sig.header.unsafety,
1155                     sig.header.abi,
1156                     sig.decl,
1157                     Some(generics),
1158                     None,
1159                 )
1160             } else {
1161                 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1162             }
1163         }
1164
1165         TraitItem(hir::TraitItem {
1166             kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1167             generics,
1168             ..
1169         }) => <dyn AstConv<'_>>::ty_of_fn(
1170             &icx,
1171             hir_id,
1172             header.unsafety,
1173             header.abi,
1174             decl,
1175             Some(generics),
1176             None,
1177         ),
1178
1179         ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1180             let abi = tcx.hir().get_foreign_abi(hir_id);
1181             compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1182         }
1183
1184         Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1185             let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1186             let inputs =
1187                 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1188             ty::Binder::dummy(tcx.mk_fn_sig(
1189                 inputs,
1190                 ty,
1191                 false,
1192                 hir::Unsafety::Normal,
1193                 abi::Abi::Rust,
1194             ))
1195         }
1196
1197         Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1198             // Closure signatures are not like other function
1199             // signatures and cannot be accessed through `fn_sig`. For
1200             // example, a closure signature excludes the `self`
1201             // argument. In any case they are embedded within the
1202             // closure type as part of the `ClosureSubsts`.
1203             //
1204             // To get the signature of a closure, you should use the
1205             // `sig` method on the `ClosureSubsts`:
1206             //
1207             //    substs.as_closure().sig(def_id, tcx)
1208             bug!(
1209                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1210             );
1211         }
1212
1213         x => {
1214             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1215         }
1216     }
1217 }
1218
1219 fn infer_return_ty_for_fn_sig<'tcx>(
1220     tcx: TyCtxt<'tcx>,
1221     sig: &hir::FnSig<'_>,
1222     generics: &hir::Generics<'_>,
1223     def_id: LocalDefId,
1224     icx: &ItemCtxt<'tcx>,
1225 ) -> ty::PolyFnSig<'tcx> {
1226     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1227
1228     match get_infer_ret_ty(&sig.decl.output) {
1229         Some(ty) => {
1230             let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1231             // Typeck doesn't expect erased regions to be returned from `type_of`.
1232             let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1233                 ty::ReErased => tcx.lifetimes.re_static,
1234                 _ => r,
1235             });
1236             let fn_sig = ty::Binder::dummy(fn_sig);
1237
1238             let mut visitor = HirPlaceholderCollector::default();
1239             visitor.visit_ty(ty);
1240             let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1241             let ret_ty = fn_sig.skip_binder().output();
1242             if ret_ty.is_suggestable(tcx, false) {
1243                 diag.span_suggestion(
1244                     ty.span,
1245                     "replace with the correct return type",
1246                     ret_ty,
1247                     Applicability::MachineApplicable,
1248                 );
1249             } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1250                 let fn_sig = ret_ty.fn_sig(tcx);
1251                 if fn_sig
1252                     .skip_binder()
1253                     .inputs_and_output
1254                     .iter()
1255                     .all(|t| t.is_suggestable(tcx, false))
1256                 {
1257                     diag.span_suggestion(
1258                         ty.span,
1259                         "replace with the correct return type",
1260                         fn_sig,
1261                         Applicability::MachineApplicable,
1262                     );
1263                 }
1264             } else if ret_ty.is_closure() {
1265                 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1266                 // to prevent the user from getting a papercut while trying to use the unique closure
1267                 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1268                 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1269                 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1270             }
1271             diag.emit();
1272
1273             fn_sig
1274         }
1275         None => <dyn AstConv<'_>>::ty_of_fn(
1276             icx,
1277             hir_id,
1278             sig.header.unsafety,
1279             sig.header.abi,
1280             sig.decl,
1281             Some(generics),
1282             None,
1283         ),
1284     }
1285 }
1286
1287 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1288     let icx = ItemCtxt::new(tcx, def_id);
1289     match tcx.hir().expect_item(def_id.expect_local()).kind {
1290         hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1291             let selfty = tcx.type_of(def_id);
1292             <dyn AstConv<'_>>::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1293         }),
1294         _ => bug!(),
1295     }
1296 }
1297
1298 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1299     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1300     let item = tcx.hir().expect_item(def_id.expect_local());
1301     match &item.kind {
1302         hir::ItemKind::Impl(hir::Impl {
1303             polarity: hir::ImplPolarity::Negative(span),
1304             of_trait,
1305             ..
1306         }) => {
1307             if is_rustc_reservation {
1308                 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1309                 tcx.sess.span_err(span, "reservation impls can't be negative");
1310             }
1311             ty::ImplPolarity::Negative
1312         }
1313         hir::ItemKind::Impl(hir::Impl {
1314             polarity: hir::ImplPolarity::Positive,
1315             of_trait: None,
1316             ..
1317         }) => {
1318             if is_rustc_reservation {
1319                 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1320             }
1321             ty::ImplPolarity::Positive
1322         }
1323         hir::ItemKind::Impl(hir::Impl {
1324             polarity: hir::ImplPolarity::Positive,
1325             of_trait: Some(_),
1326             ..
1327         }) => {
1328             if is_rustc_reservation {
1329                 ty::ImplPolarity::Reservation
1330             } else {
1331                 ty::ImplPolarity::Positive
1332             }
1333         }
1334         item => bug!("impl_polarity: {:?} not an impl", item),
1335     }
1336 }
1337
1338 /// Returns the early-bound lifetimes declared in this generics
1339 /// listing. For anything other than fns/methods, this is just all
1340 /// the lifetimes that are declared. For fns or methods, we have to
1341 /// screen out those that do not appear in any where-clauses etc using
1342 /// `resolve_lifetime::early_bound_lifetimes`.
1343 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1344     tcx: TyCtxt<'tcx>,
1345     generics: &'a hir::Generics<'a>,
1346 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1347     generics.params.iter().filter(move |param| match param.kind {
1348         GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1349         _ => false,
1350     })
1351 }
1352
1353 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1354 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1355 /// inferred constraints concerning which regions outlive other regions.
1356 #[instrument(level = "debug", skip(tcx))]
1357 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1358     let mut result = tcx.explicit_predicates_of(def_id);
1359     debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1360     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1361     if !inferred_outlives.is_empty() {
1362         debug!(
1363             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1364             def_id, inferred_outlives,
1365         );
1366         if result.predicates.is_empty() {
1367             result.predicates = inferred_outlives;
1368         } else {
1369             result.predicates = tcx
1370                 .arena
1371                 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1372         }
1373     }
1374
1375     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1376     result
1377 }
1378
1379 fn compute_sig_of_foreign_fn_decl<'tcx>(
1380     tcx: TyCtxt<'tcx>,
1381     def_id: DefId,
1382     decl: &'tcx hir::FnDecl<'tcx>,
1383     abi: abi::Abi,
1384 ) -> ty::PolyFnSig<'tcx> {
1385     let unsafety = if abi == abi::Abi::RustIntrinsic {
1386         intrinsic_operation_unsafety(tcx, def_id)
1387     } else {
1388         hir::Unsafety::Unsafe
1389     };
1390     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1391     let fty = <dyn AstConv<'_>>::ty_of_fn(
1392         &ItemCtxt::new(tcx, def_id),
1393         hir_id,
1394         unsafety,
1395         abi,
1396         decl,
1397         None,
1398         None,
1399     );
1400
1401     // Feature gate SIMD types in FFI, since I am not sure that the
1402     // ABIs are handled at all correctly. -huonw
1403     if abi != abi::Abi::RustIntrinsic
1404         && abi != abi::Abi::PlatformIntrinsic
1405         && !tcx.features().simd_ffi
1406     {
1407         let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1408             if ty.is_simd() {
1409                 let snip = tcx
1410                     .sess
1411                     .source_map()
1412                     .span_to_snippet(ast_ty.span)
1413                     .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1414                 tcx.sess
1415                     .struct_span_err(
1416                         ast_ty.span,
1417                         &format!(
1418                             "use of SIMD type{} in FFI is highly experimental and \
1419                              may result in invalid code",
1420                             snip
1421                         ),
1422                     )
1423                     .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1424                     .emit();
1425             }
1426         };
1427         for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1428             check(input, *ty)
1429         }
1430         if let hir::FnRetTy::Return(ref ty) = decl.output {
1431             check(ty, fty.output().skip_binder())
1432         }
1433     }
1434
1435     fty
1436 }
1437
1438 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1439     match tcx.hir().get_if_local(def_id) {
1440         Some(Node::ForeignItem(..)) => true,
1441         Some(_) => false,
1442         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1443     }
1444 }
1445
1446 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1447     match tcx.hir().get_if_local(def_id) {
1448         Some(Node::Expr(&rustc_hir::Expr {
1449             kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1450             ..
1451         })) => tcx.hir().body(body).generator_kind(),
1452         Some(_) => None,
1453         _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1454     }
1455 }
1456
1457 fn from_target_feature(
1458     tcx: TyCtxt<'_>,
1459     attr: &ast::Attribute,
1460     supported_target_features: &FxHashMap<String, Option<Symbol>>,
1461     target_features: &mut Vec<Symbol>,
1462 ) {
1463     let Some(list) = attr.meta_item_list() else { return };
1464     let bad_item = |span| {
1465         let msg = "malformed `target_feature` attribute input";
1466         let code = "enable = \"..\"";
1467         tcx.sess
1468             .struct_span_err(span, msg)
1469             .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
1470             .emit();
1471     };
1472     let rust_features = tcx.features();
1473     for item in list {
1474         // Only `enable = ...` is accepted in the meta-item list.
1475         if !item.has_name(sym::enable) {
1476             bad_item(item.span());
1477             continue;
1478         }
1479
1480         // Must be of the form `enable = "..."` (a string).
1481         let Some(value) = item.value_str() else {
1482             bad_item(item.span());
1483             continue;
1484         };
1485
1486         // We allow comma separation to enable multiple features.
1487         target_features.extend(value.as_str().split(',').filter_map(|feature| {
1488             let Some(feature_gate) = supported_target_features.get(feature) else {
1489                 let msg =
1490                     format!("the feature named `{}` is not valid for this target", feature);
1491                 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
1492                 err.span_label(
1493                     item.span(),
1494                     format!("`{}` is not valid for this target", feature),
1495                 );
1496                 if let Some(stripped) = feature.strip_prefix('+') {
1497                     let valid = supported_target_features.contains_key(stripped);
1498                     if valid {
1499                         err.help("consider removing the leading `+` in the feature name");
1500                     }
1501                 }
1502                 err.emit();
1503                 return None;
1504             };
1505
1506             // Only allow features whose feature gates have been enabled.
1507             let allowed = match feature_gate.as_ref().copied() {
1508                 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
1509                 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
1510                 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
1511                 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
1512                 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
1513                 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
1514                 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
1515                 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
1516                 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
1517                 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
1518                 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
1519                 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
1520                 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
1521                 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
1522                 Some(sym::bpf_target_feature) => rust_features.bpf_target_feature,
1523                 Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature,
1524                 Some(name) => bug!("unknown target feature gate {}", name),
1525                 None => true,
1526             };
1527             if !allowed {
1528                 feature_err(
1529                     &tcx.sess.parse_sess,
1530                     feature_gate.unwrap(),
1531                     item.span(),
1532                     &format!("the target feature `{}` is currently unstable", feature),
1533                 )
1534                 .emit();
1535             }
1536             Some(Symbol::intern(feature))
1537         }));
1538     }
1539 }
1540
1541 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage {
1542     use rustc_middle::mir::mono::Linkage::*;
1543
1544     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1545     // applicable to variable declarations and may not really make sense for
1546     // Rust code in the first place but allow them anyway and trust that the
1547     // user knows what they're doing. Who knows, unanticipated use cases may pop
1548     // up in the future.
1549     //
1550     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1551     // and don't have to be, LLVM treats them as no-ops.
1552     match name {
1553         "appending" => Appending,
1554         "available_externally" => AvailableExternally,
1555         "common" => Common,
1556         "extern_weak" => ExternalWeak,
1557         "external" => External,
1558         "internal" => Internal,
1559         "linkonce" => LinkOnceAny,
1560         "linkonce_odr" => LinkOnceODR,
1561         "private" => Private,
1562         "weak" => WeakAny,
1563         "weak_odr" => WeakODR,
1564         _ => tcx.sess.span_fatal(tcx.def_span(def_id), "invalid linkage specified"),
1565     }
1566 }
1567
1568 fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
1569     if cfg!(debug_assertions) {
1570         let def_kind = tcx.def_kind(did);
1571         assert!(
1572             def_kind.has_codegen_attrs(),
1573             "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
1574         );
1575     }
1576
1577     let did = did.expect_local();
1578     let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(did));
1579     let mut codegen_fn_attrs = CodegenFnAttrs::new();
1580     if tcx.should_inherit_track_caller(did) {
1581         codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1582     }
1583
1584     let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
1585
1586     let mut inline_span = None;
1587     let mut link_ordinal_span = None;
1588     let mut no_sanitize_span = None;
1589     for attr in attrs.iter() {
1590         if attr.has_name(sym::cold) {
1591             codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
1592         } else if attr.has_name(sym::rustc_allocator) {
1593             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
1594         } else if attr.has_name(sym::ffi_returns_twice) {
1595             if tcx.is_foreign_item(did) {
1596                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
1597             } else {
1598                 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
1599                 struct_span_err!(
1600                     tcx.sess,
1601                     attr.span,
1602                     E0724,
1603                     "`#[ffi_returns_twice]` may only be used on foreign functions"
1604                 )
1605                 .emit();
1606             }
1607         } else if attr.has_name(sym::ffi_pure) {
1608             if tcx.is_foreign_item(did) {
1609                 if attrs.iter().any(|a| a.has_name(sym::ffi_const)) {
1610                     // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1611                     struct_span_err!(
1612                         tcx.sess,
1613                         attr.span,
1614                         E0757,
1615                         "`#[ffi_const]` function cannot be `#[ffi_pure]`"
1616                     )
1617                     .emit();
1618                 } else {
1619                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
1620                 }
1621             } else {
1622                 // `#[ffi_pure]` is only allowed on foreign functions
1623                 struct_span_err!(
1624                     tcx.sess,
1625                     attr.span,
1626                     E0755,
1627                     "`#[ffi_pure]` may only be used on foreign functions"
1628                 )
1629                 .emit();
1630             }
1631         } else if attr.has_name(sym::ffi_const) {
1632             if tcx.is_foreign_item(did) {
1633                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
1634             } else {
1635                 // `#[ffi_const]` is only allowed on foreign functions
1636                 struct_span_err!(
1637                     tcx.sess,
1638                     attr.span,
1639                     E0756,
1640                     "`#[ffi_const]` may only be used on foreign functions"
1641                 )
1642                 .emit();
1643             }
1644         } else if attr.has_name(sym::rustc_nounwind) {
1645             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
1646         } else if attr.has_name(sym::rustc_reallocator) {
1647             codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR;
1648         } else if attr.has_name(sym::rustc_deallocator) {
1649             codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR;
1650         } else if attr.has_name(sym::rustc_allocator_zeroed) {
1651             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED;
1652         } else if attr.has_name(sym::naked) {
1653             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
1654         } else if attr.has_name(sym::no_mangle) {
1655             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
1656         } else if attr.has_name(sym::no_coverage) {
1657             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE;
1658         } else if attr.has_name(sym::rustc_std_internal_symbol) {
1659             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
1660         } else if attr.has_name(sym::used) {
1661             let inner = attr.meta_item_list();
1662             match inner.as_deref() {
1663                 Some([item]) if item.has_name(sym::linker) => {
1664                     if !tcx.features().used_with_arg {
1665                         feature_err(
1666                             &tcx.sess.parse_sess,
1667                             sym::used_with_arg,
1668                             attr.span,
1669                             "`#[used(linker)]` is currently unstable",
1670                         )
1671                         .emit();
1672                     }
1673                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
1674                 }
1675                 Some([item]) if item.has_name(sym::compiler) => {
1676                     if !tcx.features().used_with_arg {
1677                         feature_err(
1678                             &tcx.sess.parse_sess,
1679                             sym::used_with_arg,
1680                             attr.span,
1681                             "`#[used(compiler)]` is currently unstable",
1682                         )
1683                         .emit();
1684                     }
1685                     codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
1686                 }
1687                 Some(_) => {
1688                     tcx.sess.emit_err(errors::ExpectedUsedSymbol { span: attr.span });
1689                 }
1690                 None => {
1691                     // Unfortunately, unconditionally using `llvm.used` causes
1692                     // issues in handling `.init_array` with the gold linker,
1693                     // but using `llvm.compiler.used` caused a nontrival amount
1694                     // of unintentional ecosystem breakage -- particularly on
1695                     // Mach-O targets.
1696                     //
1697                     // As a result, we emit `llvm.compiler.used` only on ELF
1698                     // targets. This is somewhat ad-hoc, but actually follows
1699                     // our pre-LLVM 13 behavior (prior to the ecosystem
1700                     // breakage), and seems to match `clang`'s behavior as well
1701                     // (both before and after LLVM 13), possibly because they
1702                     // have similar compatibility concerns to us. See
1703                     // https://github.com/rust-lang/rust/issues/47384#issuecomment-1019080146
1704                     // and following comments for some discussion of this, as
1705                     // well as the comments in `rustc_codegen_llvm` where these
1706                     // flags are handled.
1707                     //
1708                     // Anyway, to be clear: this is still up in the air
1709                     // somewhat, and is subject to change in the future (which
1710                     // is a good thing, because this would ideally be a bit
1711                     // more firmed up).
1712                     let is_like_elf = !(tcx.sess.target.is_like_osx
1713                         || tcx.sess.target.is_like_windows
1714                         || tcx.sess.target.is_like_wasm);
1715                     codegen_fn_attrs.flags |= if is_like_elf {
1716                         CodegenFnAttrFlags::USED
1717                     } else {
1718                         CodegenFnAttrFlags::USED_LINKER
1719                     };
1720                 }
1721             }
1722         } else if attr.has_name(sym::cmse_nonsecure_entry) {
1723             if !matches!(tcx.fn_sig(did).abi(), abi::Abi::C { .. }) {
1724                 struct_span_err!(
1725                     tcx.sess,
1726                     attr.span,
1727                     E0776,
1728                     "`#[cmse_nonsecure_entry]` requires C ABI"
1729                 )
1730                 .emit();
1731             }
1732             if !tcx.sess.target.llvm_target.contains("thumbv8m") {
1733                 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
1734                     .emit();
1735             }
1736             codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
1737         } else if attr.has_name(sym::thread_local) {
1738             codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
1739         } else if attr.has_name(sym::track_caller) {
1740             if !tcx.is_closure(did.to_def_id()) && tcx.fn_sig(did).abi() != abi::Abi::Rust {
1741                 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
1742                     .emit();
1743             }
1744             if tcx.is_closure(did.to_def_id()) && !tcx.features().closure_track_caller {
1745                 feature_err(
1746                     &tcx.sess.parse_sess,
1747                     sym::closure_track_caller,
1748                     attr.span,
1749                     "`#[track_caller]` on closures is currently unstable",
1750                 )
1751                 .emit();
1752             }
1753             codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1754         } else if attr.has_name(sym::export_name) {
1755             if let Some(s) = attr.value_str() {
1756                 if s.as_str().contains('\0') {
1757                     // `#[export_name = ...]` will be converted to a null-terminated string,
1758                     // so it may not contain any null characters.
1759                     struct_span_err!(
1760                         tcx.sess,
1761                         attr.span,
1762                         E0648,
1763                         "`export_name` may not contain null characters"
1764                     )
1765                     .emit();
1766                 }
1767                 codegen_fn_attrs.export_name = Some(s);
1768             }
1769         } else if attr.has_name(sym::target_feature) {
1770             if !tcx.is_closure(did.to_def_id())
1771                 && tcx.fn_sig(did).unsafety() == hir::Unsafety::Normal
1772             {
1773                 if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
1774                     // The `#[target_feature]` attribute is allowed on
1775                     // WebAssembly targets on all functions, including safe
1776                     // ones. Other targets require that `#[target_feature]` is
1777                     // only applied to unsafe functions (pending the
1778                     // `target_feature_11` feature) because on most targets
1779                     // execution of instructions that are not supported is
1780                     // considered undefined behavior. For WebAssembly which is a
1781                     // 100% safe target at execution time it's not possible to
1782                     // execute undefined instructions, and even if a future
1783                     // feature was added in some form for this it would be a
1784                     // deterministic trap. There is no undefined behavior when
1785                     // executing WebAssembly so `#[target_feature]` is allowed
1786                     // on safe functions (but again, only for WebAssembly)
1787                     //
1788                     // Note that this is also allowed if `actually_rustdoc` so
1789                     // if a target is documenting some wasm-specific code then
1790                     // it's not spuriously denied.
1791                 } else if !tcx.features().target_feature_11 {
1792                     let mut err = feature_err(
1793                         &tcx.sess.parse_sess,
1794                         sym::target_feature_11,
1795                         attr.span,
1796                         "`#[target_feature(..)]` can only be applied to `unsafe` functions",
1797                     );
1798                     err.span_label(tcx.def_span(did), "not an `unsafe` function");
1799                     err.emit();
1800                 } else {
1801                     check_target_feature_trait_unsafe(tcx, did, attr.span);
1802                 }
1803             }
1804             from_target_feature(
1805                 tcx,
1806                 attr,
1807                 supported_target_features,
1808                 &mut codegen_fn_attrs.target_features,
1809             );
1810         } else if attr.has_name(sym::linkage) {
1811             if let Some(val) = attr.value_str() {
1812                 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, did, val.as_str()));
1813             }
1814         } else if attr.has_name(sym::link_section) {
1815             if let Some(val) = attr.value_str() {
1816                 if val.as_str().bytes().any(|b| b == 0) {
1817                     let msg = format!(
1818                         "illegal null byte in link_section \
1819                          value: `{}`",
1820                         &val
1821                     );
1822                     tcx.sess.span_err(attr.span, &msg);
1823                 } else {
1824                     codegen_fn_attrs.link_section = Some(val);
1825                 }
1826             }
1827         } else if attr.has_name(sym::link_name) {
1828             codegen_fn_attrs.link_name = attr.value_str();
1829         } else if attr.has_name(sym::link_ordinal) {
1830             link_ordinal_span = Some(attr.span);
1831             if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
1832                 codegen_fn_attrs.link_ordinal = ordinal;
1833             }
1834         } else if attr.has_name(sym::no_sanitize) {
1835             no_sanitize_span = Some(attr.span);
1836             if let Some(list) = attr.meta_item_list() {
1837                 for item in list.iter() {
1838                     if item.has_name(sym::address) {
1839                         codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
1840                     } else if item.has_name(sym::cfi) {
1841                         codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI;
1842                     } else if item.has_name(sym::memory) {
1843                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
1844                     } else if item.has_name(sym::memtag) {
1845                         codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG;
1846                     } else if item.has_name(sym::shadow_call_stack) {
1847                         codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK;
1848                     } else if item.has_name(sym::thread) {
1849                         codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
1850                     } else if item.has_name(sym::hwaddress) {
1851                         codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS;
1852                     } else {
1853                         tcx.sess
1854                             .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
1855                             .note("expected one of: `address`, `cfi`, `hwaddress`, `memory`, `memtag`, `shadow-call-stack`, or `thread`")
1856                             .emit();
1857                     }
1858                 }
1859             }
1860         } else if attr.has_name(sym::instruction_set) {
1861             codegen_fn_attrs.instruction_set = match attr.meta_kind() {
1862                 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
1863                     [NestedMetaItem::MetaItem(set)] => {
1864                         let segments =
1865                             set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
1866                         match segments.as_slice() {
1867                             [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
1868                                 if !tcx.sess.target.has_thumb_interworking {
1869                                     struct_span_err!(
1870                                         tcx.sess.diagnostic(),
1871                                         attr.span,
1872                                         E0779,
1873                                         "target does not support `#[instruction_set]`"
1874                                     )
1875                                     .emit();
1876                                     None
1877                                 } else if segments[1] == sym::a32 {
1878                                     Some(InstructionSetAttr::ArmA32)
1879                                 } else if segments[1] == sym::t32 {
1880                                     Some(InstructionSetAttr::ArmT32)
1881                                 } else {
1882                                     unreachable!()
1883                                 }
1884                             }
1885                             _ => {
1886                                 struct_span_err!(
1887                                     tcx.sess.diagnostic(),
1888                                     attr.span,
1889                                     E0779,
1890                                     "invalid instruction set specified",
1891                                 )
1892                                 .emit();
1893                                 None
1894                             }
1895                         }
1896                     }
1897                     [] => {
1898                         struct_span_err!(
1899                             tcx.sess.diagnostic(),
1900                             attr.span,
1901                             E0778,
1902                             "`#[instruction_set]` requires an argument"
1903                         )
1904                         .emit();
1905                         None
1906                     }
1907                     _ => {
1908                         struct_span_err!(
1909                             tcx.sess.diagnostic(),
1910                             attr.span,
1911                             E0779,
1912                             "cannot specify more than one instruction set"
1913                         )
1914                         .emit();
1915                         None
1916                     }
1917                 },
1918                 _ => {
1919                     struct_span_err!(
1920                         tcx.sess.diagnostic(),
1921                         attr.span,
1922                         E0778,
1923                         "must specify an instruction set"
1924                     )
1925                     .emit();
1926                     None
1927                 }
1928             };
1929         } else if attr.has_name(sym::repr) {
1930             codegen_fn_attrs.alignment = match attr.meta_item_list() {
1931                 Some(items) => match items.as_slice() {
1932                     [item] => match item.name_value_literal() {
1933                         Some((sym::align, literal)) => {
1934                             let alignment = rustc_attr::parse_alignment(&literal.kind);
1935
1936                             match alignment {
1937                                 Ok(align) => Some(align),
1938                                 Err(msg) => {
1939                                     struct_span_err!(
1940                                         tcx.sess.diagnostic(),
1941                                         attr.span,
1942                                         E0589,
1943                                         "invalid `repr(align)` attribute: {}",
1944                                         msg
1945                                     )
1946                                     .emit();
1947
1948                                     None
1949                                 }
1950                             }
1951                         }
1952                         _ => None,
1953                     },
1954                     [] => None,
1955                     _ => None,
1956                 },
1957                 None => None,
1958             };
1959         }
1960     }
1961
1962     codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
1963         if !attr.has_name(sym::inline) {
1964             return ia;
1965         }
1966         match attr.meta_kind() {
1967             Some(MetaItemKind::Word) => InlineAttr::Hint,
1968             Some(MetaItemKind::List(ref items)) => {
1969                 inline_span = Some(attr.span);
1970                 if items.len() != 1 {
1971                     struct_span_err!(
1972                         tcx.sess.diagnostic(),
1973                         attr.span,
1974                         E0534,
1975                         "expected one argument"
1976                     )
1977                     .emit();
1978                     InlineAttr::None
1979                 } else if list_contains_name(&items, sym::always) {
1980                     InlineAttr::Always
1981                 } else if list_contains_name(&items, sym::never) {
1982                     InlineAttr::Never
1983                 } else {
1984                     struct_span_err!(
1985                         tcx.sess.diagnostic(),
1986                         items[0].span(),
1987                         E0535,
1988                         "invalid argument"
1989                     )
1990                     .help("valid inline arguments are `always` and `never`")
1991                     .emit();
1992
1993                     InlineAttr::None
1994                 }
1995             }
1996             Some(MetaItemKind::NameValue(_)) => ia,
1997             None => ia,
1998         }
1999     });
2000
2001     codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2002         if !attr.has_name(sym::optimize) {
2003             return ia;
2004         }
2005         let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2006         match attr.meta_kind() {
2007             Some(MetaItemKind::Word) => {
2008                 err(attr.span, "expected one argument");
2009                 ia
2010             }
2011             Some(MetaItemKind::List(ref items)) => {
2012                 inline_span = Some(attr.span);
2013                 if items.len() != 1 {
2014                     err(attr.span, "expected one argument");
2015                     OptimizeAttr::None
2016                 } else if list_contains_name(&items, sym::size) {
2017                     OptimizeAttr::Size
2018                 } else if list_contains_name(&items, sym::speed) {
2019                     OptimizeAttr::Speed
2020                 } else {
2021                     err(items[0].span(), "invalid argument");
2022                     OptimizeAttr::None
2023                 }
2024             }
2025             Some(MetaItemKind::NameValue(_)) => ia,
2026             None => ia,
2027         }
2028     });
2029
2030     // #73631: closures inherit `#[target_feature]` annotations
2031     if tcx.features().target_feature_11 && tcx.is_closure(did.to_def_id()) {
2032         let owner_id = tcx.parent(did.to_def_id());
2033         if tcx.def_kind(owner_id).has_codegen_attrs() {
2034             codegen_fn_attrs
2035                 .target_features
2036                 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
2037         }
2038     }
2039
2040     // If a function uses #[target_feature] it can't be inlined into general
2041     // purpose functions as they wouldn't have the right target features
2042     // enabled. For that reason we also forbid #[inline(always)] as it can't be
2043     // respected.
2044     if !codegen_fn_attrs.target_features.is_empty() {
2045         if codegen_fn_attrs.inline == InlineAttr::Always {
2046             if let Some(span) = inline_span {
2047                 tcx.sess.span_err(
2048                     span,
2049                     "cannot use `#[inline(always)]` with \
2050                      `#[target_feature]`",
2051                 );
2052             }
2053         }
2054     }
2055
2056     if !codegen_fn_attrs.no_sanitize.is_empty() {
2057         if codegen_fn_attrs.inline == InlineAttr::Always {
2058             if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2059                 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
2060                 tcx.struct_span_lint_hir(
2061                     lint::builtin::INLINE_NO_SANITIZE,
2062                     hir_id,
2063                     no_sanitize_span,
2064                     "`no_sanitize` will have no effect after inlining",
2065                     |lint| lint.span_note(inline_span, "inlining requested here"),
2066                 )
2067             }
2068         }
2069     }
2070
2071     // Weak lang items have the same semantics as "std internal" symbols in the
2072     // sense that they're preserved through all our LTO passes and only
2073     // strippable by the linker.
2074     //
2075     // Additionally weak lang items have predetermined symbol names.
2076     if tcx.is_weak_lang_item(did.to_def_id()) {
2077         codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2078     }
2079     if let Some(name) = weak_lang_items::link_name(attrs) {
2080         codegen_fn_attrs.export_name = Some(name);
2081         codegen_fn_attrs.link_name = Some(name);
2082     }
2083     check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2084
2085     // Internal symbols to the standard library all have no_mangle semantics in
2086     // that they have defined symbol names present in the function name. This
2087     // also applies to weak symbols where they all have known symbol names.
2088     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2089         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2090     }
2091
2092     // Any linkage to LLVM intrinsics for now forcibly marks them all as never
2093     // unwinds since LLVM sometimes can't handle codegen which `invoke`s
2094     // intrinsic functions.
2095     if let Some(name) = &codegen_fn_attrs.link_name {
2096         if name.as_str().starts_with("llvm.") {
2097             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
2098         }
2099     }
2100
2101     codegen_fn_attrs
2102 }
2103
2104 /// Computes the set of target features used in a function for the purposes of
2105 /// inline assembly.
2106 fn asm_target_features<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx FxHashSet<Symbol> {
2107     let mut target_features = tcx.sess.unstable_target_features.clone();
2108     if tcx.def_kind(did).has_codegen_attrs() {
2109         let attrs = tcx.codegen_fn_attrs(did);
2110         target_features.extend(&attrs.target_features);
2111         match attrs.instruction_set {
2112             None => {}
2113             Some(InstructionSetAttr::ArmA32) => {
2114                 target_features.remove(&sym::thumb_mode);
2115             }
2116             Some(InstructionSetAttr::ArmT32) => {
2117                 target_features.insert(sym::thumb_mode);
2118             }
2119         }
2120     }
2121
2122     tcx.arena.alloc(target_features)
2123 }
2124
2125 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2126 /// applied to the method prototype.
2127 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2128     if let Some(impl_item) = tcx.opt_associated_item(def_id)
2129         && let ty::AssocItemContainer::ImplContainer = impl_item.container
2130         && let Some(trait_item) = impl_item.trait_item_def_id
2131     {
2132         return tcx
2133             .codegen_fn_attrs(trait_item)
2134             .flags
2135             .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2136     }
2137
2138     false
2139 }
2140
2141 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
2142     use rustc_ast::{Lit, LitIntType, LitKind};
2143     if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" {
2144         feature_err(
2145             &tcx.sess.parse_sess,
2146             sym::raw_dylib,
2147             attr.span,
2148             "`#[link_ordinal]` is unstable on x86",
2149         )
2150         .emit();
2151     }
2152     let meta_item_list = attr.meta_item_list();
2153     let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2154     let sole_meta_list = match meta_item_list {
2155         Some([item]) => item.literal(),
2156         Some(_) => {
2157             tcx.sess
2158                 .struct_span_err(attr.span, "incorrect number of arguments to `#[link_ordinal]`")
2159                 .note("the attribute requires exactly one argument")
2160                 .emit();
2161             return None;
2162         }
2163         _ => None,
2164     };
2165     if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2166         // According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header,
2167         // the ordinal must fit into 16 bits.  Similarly, the Ordinal field in COFFShortExport (defined
2168         // in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information
2169         // to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
2170         //
2171         // FIXME: should we allow an ordinal of 0?  The MSVC toolchain has inconsistent support for this:
2172         // both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that specifies
2173         // a zero ordinal.  However, llvm-dlltool is perfectly happy to generate an import library
2174         // for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an import
2175         // library produced by LLVM with an ordinal of 0, and it generates an .EXE.  (I don't know yet
2176         // if the resulting EXE runs, as I haven't yet built the necessary DLL -- see earlier comment
2177         // about LINK.EXE failing.)
2178         if *ordinal <= u16::MAX as u128 {
2179             Some(*ordinal as u16)
2180         } else {
2181             let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2182             tcx.sess
2183                 .struct_span_err(attr.span, &msg)
2184                 .note("the value may not exceed `u16::MAX`")
2185                 .emit();
2186             None
2187         }
2188     } else {
2189         tcx.sess
2190             .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2191             .note("an unsuffixed integer value, e.g., `1`, is expected")
2192             .emit();
2193         None
2194     }
2195 }
2196
2197 fn check_link_name_xor_ordinal(
2198     tcx: TyCtxt<'_>,
2199     codegen_fn_attrs: &CodegenFnAttrs,
2200     inline_span: Option<Span>,
2201 ) {
2202     if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2203         return;
2204     }
2205     let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2206     if let Some(span) = inline_span {
2207         tcx.sess.span_err(span, msg);
2208     } else {
2209         tcx.sess.err(msg);
2210     }
2211 }
2212
2213 /// Checks the function annotated with `#[target_feature]` is not a safe
2214 /// trait method implementation, reporting an error if it is.
2215 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2216     let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2217     let node = tcx.hir().get(hir_id);
2218     if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2219         let parent_id = tcx.hir().get_parent_item(hir_id);
2220         let parent_item = tcx.hir().expect_item(parent_id.def_id);
2221         if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2222             tcx.sess
2223                 .struct_span_err(
2224                     attr_span,
2225                     "`#[target_feature(..)]` cannot be applied to safe trait method",
2226                 )
2227                 .span_label(attr_span, "cannot be applied to safe trait method")
2228                 .span_label(tcx.def_span(id), "not an `unsafe` function")
2229                 .emit();
2230         }
2231     }
2232 }