]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/check_unsafety.rs
Rollup merge of #103674 - ehuss:split-debuginfo-doc-unstable, r=davidtwco
[rust.git] / compiler / rustc_mir_build / src / check_unsafety.rs
1 use crate::build::ExprCategory;
2 use rustc_middle::thir::visit::{self, Visitor};
3
4 use rustc_errors::struct_span_err;
5 use rustc_hir as hir;
6 use rustc_middle::mir::BorrowKind;
7 use rustc_middle::thir::*;
8 use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
9 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
10 use rustc_session::lint::Level;
11 use rustc_span::def_id::{DefId, LocalDefId};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::Span;
14
15 use std::borrow::Cow;
16 use std::ops::Bound;
17
18 struct UnsafetyVisitor<'a, 'tcx> {
19     tcx: TyCtxt<'tcx>,
20     thir: &'a Thir<'tcx>,
21     /// The `HirId` of the current scope, which would be the `HirId`
22     /// of the current HIR node, modulo adjustments. Used for lint levels.
23     hir_context: hir::HirId,
24     /// The current "safety context". This notably tracks whether we are in an
25     /// `unsafe` block, and whether it has been used.
26     safety_context: SafetyContext,
27     body_unsafety: BodyUnsafety,
28     /// The `#[target_feature]` attributes of the body. Used for checking
29     /// calls to functions with `#[target_feature]` (RFC 2396).
30     body_target_features: &'tcx [Symbol],
31     /// When inside the LHS of an assignment to a field, this is the type
32     /// of the LHS and the span of the assignment expression.
33     assignment_info: Option<(Ty<'tcx>, Span)>,
34     in_union_destructure: bool,
35     param_env: ParamEnv<'tcx>,
36     inside_adt: bool,
37 }
38
39 impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
40     fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
41         if let (
42             SafetyContext::UnsafeBlock { span: enclosing_span, .. },
43             SafetyContext::UnsafeBlock { span: block_span, hir_id, .. },
44         ) = (self.safety_context, safety_context)
45         {
46             self.warn_unused_unsafe(
47                 hir_id,
48                 block_span,
49                 Some((self.tcx.sess.source_map().guess_head_span(enclosing_span), "block")),
50             );
51             f(self);
52         } else {
53             let prev_context = self.safety_context;
54             self.safety_context = safety_context;
55
56             f(self);
57
58             if let SafetyContext::UnsafeBlock { used: false, span, hir_id } = self.safety_context {
59                 self.warn_unused_unsafe(
60                     hir_id,
61                     span,
62                     if self.unsafe_op_in_unsafe_fn_allowed() {
63                         self.body_unsafety.unsafe_fn_sig_span().map(|span| (span, "fn"))
64                     } else {
65                         None
66                     },
67                 );
68             }
69             self.safety_context = prev_context;
70         }
71     }
72
73     fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
74         let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
75         match self.safety_context {
76             SafetyContext::BuiltinUnsafeBlock => {}
77             SafetyContext::UnsafeBlock { ref mut used, .. } => {
78                 // Mark this block as useful (even inside `unsafe fn`, where it is technically
79                 // redundant -- but we want to eventually enable `unsafe_op_in_unsafe_fn` by
80                 // default which will require those blocks:
81                 // https://github.com/rust-lang/rust/issues/71668#issuecomment-1203075594).
82                 *used = true;
83             }
84             SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
85             SafetyContext::UnsafeFn => {
86                 let (description, note) = kind.description_and_note(self.tcx);
87                 // unsafe_op_in_unsafe_fn is disallowed
88                 self.tcx.struct_span_lint_hir(
89                     UNSAFE_OP_IN_UNSAFE_FN,
90                     self.hir_context,
91                     span,
92                     format!("{} is unsafe and requires unsafe block (error E0133)", description,),
93                     |lint| lint.span_label(span, kind.simple_description()).note(note),
94                 )
95             }
96             SafetyContext::Safe => {
97                 let (description, note) = kind.description_and_note(self.tcx);
98                 let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
99                 struct_span_err!(
100                     self.tcx.sess,
101                     span,
102                     E0133,
103                     "{} is unsafe and requires unsafe{} block",
104                     description,
105                     fn_sugg,
106                 )
107                 .span_label(span, kind.simple_description())
108                 .note(note)
109                 .emit();
110             }
111         }
112     }
113
114     fn warn_unused_unsafe(
115         &self,
116         hir_id: hir::HirId,
117         block_span: Span,
118         enclosing_unsafe: Option<(Span, &'static str)>,
119     ) {
120         let block_span = self.tcx.sess.source_map().guess_head_span(block_span);
121         let msg = "unnecessary `unsafe` block";
122         self.tcx.struct_span_lint_hir(UNUSED_UNSAFE, hir_id, block_span, msg, |lint| {
123             lint.span_label(block_span, msg);
124             if let Some((span, kind)) = enclosing_unsafe {
125                 lint.span_label(span, format!("because it's nested under this `unsafe` {}", kind));
126             }
127             lint
128         });
129     }
130
131     /// Whether the `unsafe_op_in_unsafe_fn` lint is `allow`ed at the current HIR node.
132     fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
133         self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow
134     }
135 }
136
137 // Searches for accesses to layout constrained fields.
138 struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
139     found: bool,
140     thir: &'a Thir<'tcx>,
141     tcx: TyCtxt<'tcx>,
142 }
143
144 impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
145     fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
146         Self { found: false, thir, tcx }
147     }
148 }
149
150 impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
151     fn thir(&self) -> &'a Thir<'tcx> {
152         self.thir
153     }
154
155     fn visit_expr(&mut self, expr: &Expr<'tcx>) {
156         match expr.kind {
157             ExprKind::Field { lhs, .. } => {
158                 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
159                     if (Bound::Unbounded, Bound::Unbounded)
160                         != self.tcx.layout_scalar_valid_range(adt_def.did())
161                     {
162                         self.found = true;
163                     }
164                 }
165                 visit::walk_expr(self, expr);
166             }
167
168             // Keep walking through the expression as long as we stay in the same
169             // place, i.e. the expression is a place expression and not a dereference
170             // (since dereferencing something leads us to a different place).
171             ExprKind::Deref { .. } => {}
172             ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => {
173                 visit::walk_expr(self, expr);
174             }
175
176             _ => {}
177         }
178     }
179 }
180
181 impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
182     fn thir(&self) -> &'a Thir<'tcx> {
183         &self.thir
184     }
185
186     fn visit_block(&mut self, block: &Block) {
187         match block.safety_mode {
188             // compiler-generated unsafe code should not count towards the usefulness of
189             // an outer unsafe block
190             BlockSafety::BuiltinUnsafe => {
191                 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
192                     visit::walk_block(this, block)
193                 });
194             }
195             BlockSafety::ExplicitUnsafe(hir_id) => {
196                 self.in_safety_context(
197                     SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
198                     |this| visit::walk_block(this, block),
199                 );
200             }
201             BlockSafety::Safe => {
202                 visit::walk_block(self, block);
203             }
204         }
205     }
206
207     fn visit_pat(&mut self, pat: &Pat<'tcx>) {
208         if self.in_union_destructure {
209             match pat.kind {
210                 // binding to a variable allows getting stuff out of variable
211                 PatKind::Binding { .. }
212                 // match is conditional on having this value
213                 | PatKind::Constant { .. }
214                 | PatKind::Variant { .. }
215                 | PatKind::Leaf { .. }
216                 | PatKind::Deref { .. }
217                 | PatKind::Range { .. }
218                 | PatKind::Slice { .. }
219                 | PatKind::Array { .. } => {
220                     self.requires_unsafe(pat.span, AccessToUnionField);
221                     return; // we can return here since this already requires unsafe
222                 }
223                 // wildcard doesn't take anything
224                 PatKind::Wild |
225                 // these just wrap other patterns
226                 PatKind::Or { .. } |
227                 PatKind::AscribeUserType { .. } => {}
228             }
229         };
230
231         match &pat.kind {
232             PatKind::Leaf { .. } => {
233                 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
234                     if adt_def.is_union() {
235                         let old_in_union_destructure =
236                             std::mem::replace(&mut self.in_union_destructure, true);
237                         visit::walk_pat(self, pat);
238                         self.in_union_destructure = old_in_union_destructure;
239                     } else if (Bound::Unbounded, Bound::Unbounded)
240                         != self.tcx.layout_scalar_valid_range(adt_def.did())
241                     {
242                         let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
243                         visit::walk_pat(self, pat);
244                         self.inside_adt = old_inside_adt;
245                     } else {
246                         visit::walk_pat(self, pat);
247                     }
248                 } else {
249                     visit::walk_pat(self, pat);
250                 }
251             }
252             PatKind::Binding { mode: BindingMode::ByRef(borrow_kind), ty, .. } => {
253                 if self.inside_adt {
254                     let ty::Ref(_, ty, _) = ty.kind() else {
255                         span_bug!(
256                             pat.span,
257                             "BindingMode::ByRef in pattern, but found non-reference type {}",
258                             ty
259                         );
260                     };
261                     match borrow_kind {
262                         BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {
263                             if !ty.is_freeze(self.tcx, self.param_env) {
264                                 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
265                             }
266                         }
267                         BorrowKind::Mut { .. } => {
268                             self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
269                         }
270                     }
271                 }
272                 visit::walk_pat(self, pat);
273             }
274             PatKind::Deref { .. } => {
275                 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
276                 visit::walk_pat(self, pat);
277                 self.inside_adt = old_inside_adt;
278             }
279             _ => {
280                 visit::walk_pat(self, pat);
281             }
282         }
283     }
284
285     fn visit_expr(&mut self, expr: &Expr<'tcx>) {
286         // could we be in the LHS of an assignment to a field?
287         match expr.kind {
288             ExprKind::Field { .. }
289             | ExprKind::VarRef { .. }
290             | ExprKind::UpvarRef { .. }
291             | ExprKind::Scope { .. }
292             | ExprKind::Cast { .. } => {}
293
294             ExprKind::AddressOf { .. }
295             | ExprKind::Adt { .. }
296             | ExprKind::Array { .. }
297             | ExprKind::Binary { .. }
298             | ExprKind::Block { .. }
299             | ExprKind::Borrow { .. }
300             | ExprKind::Literal { .. }
301             | ExprKind::NamedConst { .. }
302             | ExprKind::NonHirLiteral { .. }
303             | ExprKind::ZstLiteral { .. }
304             | ExprKind::ConstParam { .. }
305             | ExprKind::ConstBlock { .. }
306             | ExprKind::Deref { .. }
307             | ExprKind::Index { .. }
308             | ExprKind::NeverToAny { .. }
309             | ExprKind::PlaceTypeAscription { .. }
310             | ExprKind::ValueTypeAscription { .. }
311             | ExprKind::Pointer { .. }
312             | ExprKind::Repeat { .. }
313             | ExprKind::StaticRef { .. }
314             | ExprKind::ThreadLocalRef { .. }
315             | ExprKind::Tuple { .. }
316             | ExprKind::Unary { .. }
317             | ExprKind::Call { .. }
318             | ExprKind::Assign { .. }
319             | ExprKind::AssignOp { .. }
320             | ExprKind::Break { .. }
321             | ExprKind::Closure { .. }
322             | ExprKind::Continue { .. }
323             | ExprKind::Return { .. }
324             | ExprKind::Yield { .. }
325             | ExprKind::Loop { .. }
326             | ExprKind::Let { .. }
327             | ExprKind::Match { .. }
328             | ExprKind::Box { .. }
329             | ExprKind::If { .. }
330             | ExprKind::InlineAsm { .. }
331             | ExprKind::LogicalOp { .. }
332             | ExprKind::Use { .. } => {
333                 // We don't need to save the old value and restore it
334                 // because all the place expressions can't have more
335                 // than one child.
336                 self.assignment_info = None;
337             }
338         };
339         match expr.kind {
340             ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
341                 let prev_id = self.hir_context;
342                 self.hir_context = hir_id;
343                 self.visit_expr(&self.thir[value]);
344                 self.hir_context = prev_id;
345                 return; // don't visit the whole expression
346             }
347             ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
348                 if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
349                     let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
350                         Some(*func_id)
351                     } else {
352                         None
353                     };
354                     self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
355                 } else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
356                     // If the called function has target features the calling function hasn't,
357                     // the call requires `unsafe`. Don't check this on wasm
358                     // targets, though. For more information on wasm see the
359                     // is_like_wasm check in hir_analysis/src/collect.rs
360                     if !self.tcx.sess.target.options.is_like_wasm
361                         && !self
362                             .tcx
363                             .codegen_fn_attrs(func_did)
364                             .target_features
365                             .iter()
366                             .all(|feature| self.body_target_features.contains(feature))
367                     {
368                         self.requires_unsafe(expr.span, CallToFunctionWith(func_did));
369                     }
370                 }
371             }
372             ExprKind::Deref { arg } => {
373                 if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
374                     if self.tcx.is_mutable_static(def_id) {
375                         self.requires_unsafe(expr.span, UseOfMutableStatic);
376                     } else if self.tcx.is_foreign_item(def_id) {
377                         self.requires_unsafe(expr.span, UseOfExternStatic);
378                     }
379                 } else if self.thir[arg].ty.is_unsafe_ptr() {
380                     self.requires_unsafe(expr.span, DerefOfRawPointer);
381                 }
382             }
383             ExprKind::InlineAsm { .. } => {
384                 self.requires_unsafe(expr.span, UseOfInlineAssembly);
385             }
386             ExprKind::Adt(box AdtExpr {
387                 adt_def,
388                 variant_index: _,
389                 substs: _,
390                 user_ty: _,
391                 fields: _,
392                 base: _,
393             }) => match self.tcx.layout_scalar_valid_range(adt_def.did()) {
394                 (Bound::Unbounded, Bound::Unbounded) => {}
395                 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
396             },
397             ExprKind::Closure(box ClosureExpr {
398                 closure_id,
399                 substs: _,
400                 upvars: _,
401                 movability: _,
402                 fake_reads: _,
403             }) => {
404                 let closure_def = if let Some((did, const_param_id)) =
405                     ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
406                 {
407                     ty::WithOptConstParam { did, const_param_did: Some(const_param_id) }
408                 } else {
409                     ty::WithOptConstParam::unknown(closure_id)
410                 };
411                 let (closure_thir, expr) = self.tcx.thir_body(closure_def).unwrap_or_else(|_| {
412                     (self.tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0))
413                 });
414                 let closure_thir = &closure_thir.borrow();
415                 let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id);
416                 let mut closure_visitor =
417                     UnsafetyVisitor { thir: closure_thir, hir_context, ..*self };
418                 closure_visitor.visit_expr(&closure_thir[expr]);
419                 // Unsafe blocks can be used in closures, make sure to take it into account
420                 self.safety_context = closure_visitor.safety_context;
421             }
422             ExprKind::Field { lhs, .. } => {
423                 let lhs = &self.thir[lhs];
424                 if let ty::Adt(adt_def, _) = lhs.ty.kind() && adt_def.is_union() {
425                     if let Some((assigned_ty, assignment_span)) = self.assignment_info {
426                         if assigned_ty.needs_drop(self.tcx, self.param_env) {
427                             // This would be unsafe, but should be outright impossible since we reject such unions.
428                             self.tcx.sess.delay_span_bug(assignment_span, format!("union fields that need dropping should be impossible: {assigned_ty}"));
429                         }
430                     } else {
431                         self.requires_unsafe(expr.span, AccessToUnionField);
432                     }
433                 }
434             }
435             ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
436                 let lhs = &self.thir[lhs];
437                 // First, check whether we are mutating a layout constrained field
438                 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
439                 visit::walk_expr(&mut visitor, lhs);
440                 if visitor.found {
441                     self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
442                 }
443
444                 // Second, check for accesses to union fields
445                 // don't have any special handling for AssignOp since it causes a read *and* write to lhs
446                 if matches!(expr.kind, ExprKind::Assign { .. }) {
447                     self.assignment_info = Some((lhs.ty, expr.span));
448                     visit::walk_expr(self, lhs);
449                     self.assignment_info = None;
450                     visit::walk_expr(self, &self.thir()[rhs]);
451                     return; // we have already visited everything by now
452                 }
453             }
454             ExprKind::Borrow { borrow_kind, arg } => {
455                 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
456                 visit::walk_expr(&mut visitor, expr);
457                 if visitor.found {
458                     match borrow_kind {
459                         BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique
460                             if !self.thir[arg].ty.is_freeze(self.tcx, self.param_env) =>
461                         {
462                             self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
463                         }
464                         BorrowKind::Mut { .. } => {
465                             self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
466                         }
467                         BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {}
468                     }
469                 }
470             }
471             ExprKind::Let { expr: expr_id, .. } => {
472                 let let_expr = &self.thir[expr_id];
473                 if let ty::Adt(adt_def, _) = let_expr.ty.kind() && adt_def.is_union() {
474                     self.requires_unsafe(expr.span, AccessToUnionField);
475                 }
476             }
477             _ => {}
478         }
479         visit::walk_expr(self, expr);
480     }
481 }
482
483 #[derive(Clone, Copy)]
484 enum SafetyContext {
485     Safe,
486     BuiltinUnsafeBlock,
487     UnsafeFn,
488     UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
489 }
490
491 #[derive(Clone, Copy)]
492 enum BodyUnsafety {
493     /// The body is not unsafe.
494     Safe,
495     /// The body is an unsafe function. The span points to
496     /// the signature of the function.
497     Unsafe(Span),
498 }
499
500 impl BodyUnsafety {
501     /// Returns whether the body is unsafe.
502     fn is_unsafe(&self) -> bool {
503         matches!(self, BodyUnsafety::Unsafe(_))
504     }
505
506     /// If the body is unsafe, returns the `Span` of its signature.
507     fn unsafe_fn_sig_span(self) -> Option<Span> {
508         match self {
509             BodyUnsafety::Unsafe(span) => Some(span),
510             BodyUnsafety::Safe => None,
511         }
512     }
513 }
514
515 #[derive(Clone, Copy, PartialEq)]
516 enum UnsafeOpKind {
517     CallToUnsafeFunction(Option<DefId>),
518     UseOfInlineAssembly,
519     InitializingTypeWith,
520     UseOfMutableStatic,
521     UseOfExternStatic,
522     DerefOfRawPointer,
523     AccessToUnionField,
524     MutationOfLayoutConstrainedField,
525     BorrowOfLayoutConstrainedField,
526     CallToFunctionWith(DefId),
527 }
528
529 use UnsafeOpKind::*;
530
531 impl UnsafeOpKind {
532     pub fn simple_description(&self) -> &'static str {
533         match self {
534             CallToUnsafeFunction(..) => "call to unsafe function",
535             UseOfInlineAssembly => "use of inline assembly",
536             InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
537             UseOfMutableStatic => "use of mutable static",
538             UseOfExternStatic => "use of extern static",
539             DerefOfRawPointer => "dereference of raw pointer",
540             AccessToUnionField => "access to union field",
541             MutationOfLayoutConstrainedField => "mutation of layout constrained field",
542             BorrowOfLayoutConstrainedField => {
543                 "borrow of layout constrained field with interior mutability"
544             }
545             CallToFunctionWith(..) => "call to function with `#[target_feature]`",
546         }
547     }
548
549     pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
550         match self {
551             CallToUnsafeFunction(did) => (
552                 if let Some(did) = did {
553                     Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
554                 } else {
555                     Cow::Borrowed(self.simple_description())
556                 },
557                 "consult the function's documentation for information on how to avoid undefined \
558                  behavior",
559             ),
560             UseOfInlineAssembly => (
561                 Cow::Borrowed(self.simple_description()),
562                 "inline assembly is entirely unchecked and can cause undefined behavior",
563             ),
564             InitializingTypeWith => (
565                 Cow::Borrowed(self.simple_description()),
566                 "initializing a layout restricted type's field with a value outside the valid \
567                  range is undefined behavior",
568             ),
569             UseOfMutableStatic => (
570                 Cow::Borrowed(self.simple_description()),
571                 "mutable statics can be mutated by multiple threads: aliasing violations or data \
572                  races will cause undefined behavior",
573             ),
574             UseOfExternStatic => (
575                 Cow::Borrowed(self.simple_description()),
576                 "extern statics are not controlled by the Rust type system: invalid data, \
577                  aliasing violations or data races will cause undefined behavior",
578             ),
579             DerefOfRawPointer => (
580                 Cow::Borrowed(self.simple_description()),
581                 "raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
582                  and cause data races: all of these are undefined behavior",
583             ),
584             AccessToUnionField => (
585                 Cow::Borrowed(self.simple_description()),
586                 "the field may not be properly initialized: using uninitialized data will cause \
587                  undefined behavior",
588             ),
589             MutationOfLayoutConstrainedField => (
590                 Cow::Borrowed(self.simple_description()),
591                 "mutating layout constrained fields cannot statically be checked for valid values",
592             ),
593             BorrowOfLayoutConstrainedField => (
594                 Cow::Borrowed(self.simple_description()),
595                 "references to fields of layout constrained fields lose the constraints. Coupled \
596                  with interior mutability, the field can be changed to invalid values",
597             ),
598             CallToFunctionWith(did) => (
599                 Cow::from(format!(
600                     "call to function `{}` with `#[target_feature]`",
601                     tcx.def_path_str(*did)
602                 )),
603                 "can only be called if the required target features are available",
604             ),
605         }
606     }
607 }
608
609 pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) {
610     // THIR unsafeck is gated under `-Z thir-unsafeck`
611     if !tcx.sess.opts.unstable_opts.thir_unsafeck {
612         return;
613     }
614
615     // Closures are handled by their owner, if it has a body
616     if tcx.is_closure(def.did.to_def_id()) {
617         let hir = tcx.hir();
618         let owner = hir.enclosing_body_owner(hir.local_def_id_to_hir_id(def.did));
619         tcx.ensure().thir_check_unsafety(owner);
620         return;
621     }
622
623     let Ok((thir, expr)) = tcx.thir_body(def) else {
624         return
625     };
626     let thir = &thir.borrow();
627     // If `thir` is empty, a type error occurred, skip this body.
628     if thir.exprs.is_empty() {
629         return;
630     }
631
632     let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
633     let body_unsafety = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(BodyUnsafety::Safe, |fn_sig| {
634         if fn_sig.header.unsafety == hir::Unsafety::Unsafe {
635             BodyUnsafety::Unsafe(fn_sig.span)
636         } else {
637             BodyUnsafety::Safe
638         }
639     });
640     let body_target_features = &tcx.body_codegen_attrs(def.did.to_def_id()).target_features;
641     let safety_context =
642         if body_unsafety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe };
643     let mut visitor = UnsafetyVisitor {
644         tcx,
645         thir,
646         safety_context,
647         hir_context: hir_id,
648         body_unsafety,
649         body_target_features,
650         assignment_info: None,
651         in_union_destructure: false,
652         param_env: tcx.param_env(def.did),
653         inside_adt: false,
654     };
655     visitor.visit_expr(&thir[expr]);
656 }
657
658 pub(crate) fn thir_check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
659     if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
660         tcx.thir_check_unsafety_for_const_arg(def)
661     } else {
662         check_unsafety(tcx, ty::WithOptConstParam::unknown(def_id))
663     }
664 }
665
666 pub(crate) fn thir_check_unsafety_for_const_arg<'tcx>(
667     tcx: TyCtxt<'tcx>,
668     (did, param_did): (LocalDefId, DefId),
669 ) {
670     check_unsafety(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
671 }