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