]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
152a98c0c1aa2e0a93d3356da6a6aaa4764b59e7
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 use rustc::hir::map::Map;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
4 use rustc::mir::*;
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit;
13 use rustc_hir::Node;
14 use rustc_span::symbol::{sym, Symbol};
15
16 use std::ops::Bound;
17
18 use crate::const_eval::{is_const_fn, is_min_const_fn};
19 use crate::util;
20
21 pub struct UnsafetyChecker<'a, 'tcx> {
22     body: &'a Body<'tcx>,
23     const_context: bool,
24     min_const_fn: bool,
25     violations: Vec<UnsafetyViolation>,
26     source_info: SourceInfo,
27     tcx: TyCtxt<'tcx>,
28     param_env: ty::ParamEnv<'tcx>,
29     /// Mark an `unsafe` block as used, so we don't lint it.
30     used_unsafe: FxHashSet<hir::HirId>,
31     inherited_blocks: Vec<(hir::HirId, bool)>,
32 }
33
34 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
35     fn new(
36         const_context: bool,
37         min_const_fn: bool,
38         body: &'a Body<'tcx>,
39         tcx: TyCtxt<'tcx>,
40         param_env: ty::ParamEnv<'tcx>,
41     ) -> Self {
42         // sanity check
43         if min_const_fn {
44             assert!(const_context);
45         }
46         Self {
47             body,
48             const_context,
49             min_const_fn,
50             violations: vec![],
51             source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
52             tcx,
53             param_env,
54             used_unsafe: Default::default(),
55             inherited_blocks: vec![],
56         }
57     }
58 }
59
60 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
61     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
62         self.source_info = terminator.source_info;
63         match terminator.kind {
64             TerminatorKind::Goto { .. }
65             | TerminatorKind::SwitchInt { .. }
66             | TerminatorKind::Drop { .. }
67             | TerminatorKind::Yield { .. }
68             | TerminatorKind::Assert { .. }
69             | TerminatorKind::DropAndReplace { .. }
70             | TerminatorKind::GeneratorDrop
71             | TerminatorKind::Resume
72             | TerminatorKind::Abort
73             | TerminatorKind::Return
74             | TerminatorKind::Unreachable
75             | TerminatorKind::FalseEdges { .. }
76             | TerminatorKind::FalseUnwind { .. } => {
77                 // safe (at least as emitted during MIR construction)
78             }
79
80             TerminatorKind::Call { ref func, .. } => {
81                 let func_ty = func.ty(self.body, self.tcx);
82                 let sig = func_ty.fn_sig(self.tcx);
83                 if let hir::Unsafety::Unsafe = sig.unsafety() {
84                     self.require_unsafe(
85                         "call to unsafe function",
86                         "consult the function's documentation for information on how to avoid \
87                          undefined behavior",
88                         UnsafetyViolationKind::GeneralAndConstFn,
89                     )
90                 }
91             }
92         }
93         self.super_terminator(terminator, location);
94     }
95
96     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
97         self.source_info = statement.source_info;
98         match statement.kind {
99             StatementKind::Assign(..)
100             | StatementKind::FakeRead(..)
101             | StatementKind::SetDiscriminant { .. }
102             | StatementKind::StorageLive(..)
103             | StatementKind::StorageDead(..)
104             | StatementKind::Retag { .. }
105             | StatementKind::AscribeUserType(..)
106             | StatementKind::Nop => {
107                 // safe (at least as emitted during MIR construction)
108             }
109
110             StatementKind::InlineAsm { .. } => self.require_unsafe(
111                 "use of inline assembly",
112                 "inline assembly is entirely unchecked and can cause undefined behavior",
113                 UnsafetyViolationKind::General,
114             ),
115         }
116         self.super_statement(statement, location);
117     }
118
119     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
120         match rvalue {
121             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
122                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
123                 &AggregateKind::Adt(ref def, ..) => {
124                     match self.tcx.layout_scalar_valid_range(def.did) {
125                         (Bound::Unbounded, Bound::Unbounded) => {}
126                         _ => self.require_unsafe(
127                             "initializing type with `rustc_layout_scalar_valid_range` attr",
128                             "initializing a layout restricted type's field with a value \
129                                 outside the valid range is undefined behavior",
130                             UnsafetyViolationKind::GeneralAndConstFn,
131                         ),
132                     }
133                 }
134                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
135                     let UnsafetyCheckResult { violations, unsafe_blocks } =
136                         self.tcx.unsafety_check_result(def_id);
137                     self.register_violations(&violations, &unsafe_blocks);
138                 }
139             },
140             // casting pointers to ints is unsafe in const fn because the const evaluator cannot
141             // possibly know what the result of various operations like `address / 2` would be
142             // pointers during const evaluation have no integral address, only an abstract one
143             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
144                 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
145             {
146                 let operand_ty = operand.ty(self.body, self.tcx);
147                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
148                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
149                 match (cast_in, cast_out) {
150                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
151                         self.require_unsafe(
152                             "cast of pointer to int",
153                             "casting pointers to integers in constants",
154                             UnsafetyViolationKind::General,
155                         );
156                     }
157                     _ => {}
158                 }
159             }
160             // raw pointer and fn pointer operations are unsafe as it is not clear whether one
161             // pointer would be "less" or "equal" to another, because we cannot know where llvm
162             // or the linker will place various statics in memory. Without this information the
163             // result of a comparison of addresses would differ between runtime and compile-time.
164             Rvalue::BinaryOp(_, ref lhs, _)
165                 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
166             {
167                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
168                     self.require_unsafe(
169                         "pointer operation",
170                         "operations on pointers in constants",
171                         UnsafetyViolationKind::General,
172                     );
173                 }
174             }
175             _ => {}
176         }
177         self.super_rvalue(rvalue, location);
178     }
179
180     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
181         // prevent
182         // * `&mut x.field`
183         // * `x.field = y;`
184         // * `&x.field` if `field`'s type has interior mutability
185         // because either of these would allow modifying the layout constrained field and
186         // insert values that violate the layout constraints.
187         if context.is_mutating_use() || context.is_borrow() {
188             self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
189         }
190
191         for (i, elem) in place.projection.iter().enumerate() {
192             let proj_base = &place.projection[..i];
193
194             if context.is_borrow() {
195                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
196                     let source_info = self.source_info;
197                     let lint_root = self.body.source_scopes[source_info.scope]
198                         .local_data
199                         .as_ref()
200                         .assert_crate_local()
201                         .lint_root;
202                     self.require_unsafe(
203                         "borrow of packed field",
204                         "fields of packed structs might be misaligned: dereferencing a \
205                         misaligned pointer or even just creating a misaligned reference \
206                         is undefined behavior",
207                         UnsafetyViolationKind::BorrowPacked(lint_root),
208                     );
209                 }
210             }
211             let old_source_info = self.source_info;
212             if let [] = proj_base {
213                 let decl = &self.body.local_decls[place.local];
214                 if decl.internal {
215                     if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
216                         if self.tcx.is_mutable_static(def_id) {
217                             self.require_unsafe(
218                                 "use of mutable static",
219                                 "mutable statics can be mutated by multiple threads: aliasing \
220                             violations or data races will cause undefined behavior",
221                                 UnsafetyViolationKind::General,
222                             );
223                             return;
224                         } else if self.tcx.is_foreign_item(def_id) {
225                             self.require_unsafe(
226                                 "use of extern static",
227                                 "extern statics are not controlled by the Rust type system: \
228                             invalid data, aliasing violations or data races will cause \
229                             undefined behavior",
230                                 UnsafetyViolationKind::General,
231                             );
232                             return;
233                         }
234                     } else {
235                         // Internal locals are used in the `move_val_init` desugaring.
236                         // We want to check unsafety against the source info of the
237                         // desugaring, rather than the source info of the RHS.
238                         self.source_info = self.body.local_decls[place.local].source_info;
239                     }
240                 }
241             }
242             let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
243             match base_ty.kind {
244                 ty::RawPtr(..) => self.require_unsafe(
245                     "dereference of raw pointer",
246                     "raw pointers may be NULL, dangling or unaligned; they can violate \
247                          aliasing rules and cause data races: all of these are undefined \
248                          behavior",
249                     UnsafetyViolationKind::General,
250                 ),
251                 ty::Adt(adt, _) => {
252                     if adt.is_union() {
253                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
254                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
255                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
256                         {
257                             let elem_ty = match elem {
258                                 ProjectionElem::Field(_, ty) => ty,
259                                 _ => span_bug!(
260                                     self.source_info.span,
261                                     "non-field projection {:?} from union?",
262                                     place
263                                 ),
264                             };
265                             if !elem_ty.is_copy_modulo_regions(
266                                 self.tcx,
267                                 self.param_env,
268                                 self.source_info.span,
269                             ) {
270                                 self.require_unsafe(
271                                     "assignment to non-`Copy` union field",
272                                     "the previous content of the field will be dropped, which \
273                                      causes undefined behavior if the field was not properly \
274                                      initialized",
275                                     UnsafetyViolationKind::GeneralAndConstFn,
276                                 )
277                             } else {
278                                 // write to non-move union, safe
279                             }
280                         } else {
281                             self.require_unsafe(
282                                 "access to union field",
283                                 "the field may not be properly initialized: using \
284                                  uninitialized data will cause undefined behavior",
285                                 UnsafetyViolationKind::GeneralAndConstFn,
286                             )
287                         }
288                     }
289                 }
290                 _ => {}
291             }
292             self.source_info = old_source_info;
293         }
294     }
295 }
296
297 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
298     fn require_unsafe(
299         &mut self,
300         description: &'static str,
301         details: &'static str,
302         kind: UnsafetyViolationKind,
303     ) {
304         let source_info = self.source_info;
305         self.register_violations(
306             &[UnsafetyViolation {
307                 source_info,
308                 description: Symbol::intern(description),
309                 details: Symbol::intern(details),
310                 kind,
311             }],
312             &[],
313         );
314     }
315
316     fn register_violations(
317         &mut self,
318         violations: &[UnsafetyViolation],
319         unsafe_blocks: &[(hir::HirId, bool)],
320     ) {
321         let safety = self.body.source_scopes[self.source_info.scope]
322             .local_data
323             .as_ref()
324             .assert_crate_local()
325             .safety;
326         let within_unsafe = match safety {
327             // `unsafe` blocks are required in safe code
328             Safety::Safe => {
329                 for violation in violations {
330                     let mut violation = *violation;
331                     match violation.kind {
332                         UnsafetyViolationKind::GeneralAndConstFn
333                         | UnsafetyViolationKind::General => {}
334                         UnsafetyViolationKind::BorrowPacked(_) => {
335                             if self.min_const_fn {
336                                 // const fns don't need to be backwards compatible and can
337                                 // emit these violations as a hard error instead of a backwards
338                                 // compat lint
339                                 violation.kind = UnsafetyViolationKind::General;
340                             }
341                         }
342                     }
343                     if !self.violations.contains(&violation) {
344                         self.violations.push(violation)
345                     }
346                 }
347                 false
348             }
349             // `unsafe` function bodies allow unsafe without additional unsafe blocks
350             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
351             Safety::ExplicitUnsafe(hir_id) => {
352                 // mark unsafe block as used if there are any unsafe operations inside
353                 if !violations.is_empty() {
354                     self.used_unsafe.insert(hir_id);
355                 }
356                 // only some unsafety is allowed in const fn
357                 if self.min_const_fn {
358                     for violation in violations {
359                         match violation.kind {
360                             // these unsafe things are stable in const fn
361                             UnsafetyViolationKind::GeneralAndConstFn => {}
362                             // these things are forbidden in const fns
363                             UnsafetyViolationKind::General
364                             | UnsafetyViolationKind::BorrowPacked(_) => {
365                                 let mut violation = *violation;
366                                 // const fns don't need to be backwards compatible and can
367                                 // emit these violations as a hard error instead of a backwards
368                                 // compat lint
369                                 violation.kind = UnsafetyViolationKind::General;
370                                 if !self.violations.contains(&violation) {
371                                     self.violations.push(violation)
372                                 }
373                             }
374                         }
375                     }
376                 }
377                 true
378             }
379         };
380         self.inherited_blocks.extend(
381             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
382         );
383     }
384     fn check_mut_borrowing_layout_constrained_field(
385         &mut self,
386         place: &Place<'tcx>,
387         is_mut_use: bool,
388     ) {
389         let mut cursor = place.projection.as_ref();
390         while let &[ref proj_base @ .., elem] = cursor {
391             cursor = proj_base;
392
393             match elem {
394                 // Modifications behind a dereference don't affect the value of
395                 // the pointer.
396                 ProjectionElem::Deref => return,
397                 ProjectionElem::Field(..) => {
398                     let ty =
399                         Place::ty_from(place.local, proj_base, &self.body.local_decls, self.tcx).ty;
400                     match ty.kind {
401                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
402                             (Bound::Unbounded, Bound::Unbounded) => {}
403                             _ => {
404                                 let (description, details) = if is_mut_use {
405                                     (
406                                         "mutation of layout constrained field",
407                                         "mutating layout constrained fields cannot statically be \
408                                         checked for valid values",
409                                     )
410
411                                 // Check `is_freeze` as late as possible to avoid cycle errors
412                                 // with opaque types.
413                                 } else if !place.ty(self.body, self.tcx).ty.is_freeze(
414                                     self.tcx,
415                                     self.param_env,
416                                     self.source_info.span,
417                                 ) {
418                                     (
419                                         "borrow of layout constrained field with interior \
420                                         mutability",
421                                         "references to fields of layout constrained fields \
422                                         lose the constraints. Coupled with interior mutability, \
423                                         the field can be changed to invalid values",
424                                     )
425                                 } else {
426                                     continue;
427                                 };
428                                 self.require_unsafe(
429                                     description,
430                                     details,
431                                     UnsafetyViolationKind::GeneralAndConstFn,
432                                 );
433                             }
434                         },
435                         _ => {}
436                     }
437                 }
438                 _ => {}
439             }
440         }
441     }
442 }
443
444 pub(crate) fn provide(providers: &mut Providers<'_>) {
445     *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
446 }
447
448 struct UnusedUnsafeVisitor<'a> {
449     used_unsafe: &'a FxHashSet<hir::HirId>,
450     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
451 }
452
453 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
454     type Map = Map<'tcx>;
455
456     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
457         intravisit::NestedVisitorMap::None
458     }
459
460     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
461         intravisit::walk_block(self, block);
462
463         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
464             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
465         }
466     }
467 }
468
469 fn check_unused_unsafe(
470     tcx: TyCtxt<'_>,
471     def_id: DefId,
472     used_unsafe: &FxHashSet<hir::HirId>,
473     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
474 ) {
475     let body_id =
476         tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
477
478     let body_id = match body_id {
479         Some(body) => body,
480         None => {
481             debug!("check_unused_unsafe({:?}) - no body found", def_id);
482             return;
483         }
484     };
485     let body = tcx.hir().body(body_id);
486     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
487
488     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
489     intravisit::Visitor::visit_body(&mut visitor, body);
490 }
491
492 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
493     debug!("unsafety_violations({:?})", def_id);
494
495     // N.B., this borrow is valid because all the consumers of
496     // `mir_built` force this.
497     let body = &tcx.mir_built(def_id).borrow();
498
499     let param_env = tcx.param_env(def_id);
500
501     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
502     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
503         hir::BodyOwnerKind::Closure => (false, false),
504         hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
505         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
506     };
507     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
508     // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
509     // recompute it here.
510     let body = body.unwrap_read_only();
511     checker.visit_body(body);
512
513     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
514     UnsafetyCheckResult {
515         violations: checker.violations.into(),
516         unsafe_blocks: checker.inherited_blocks.into(),
517     }
518 }
519
520 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
521     let lint_hir_id = tcx
522         .hir()
523         .as_local_hir_id(def_id)
524         .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
525
526     tcx.struct_span_lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), |lint| {
527         // FIXME: when we make this a hard error, this should have its
528         // own error code.
529         let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
530             "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
531              type or const parameters (error E0133)"
532                 .to_string()
533         } else {
534             "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
535              does not derive Copy (error E0133)"
536                 .to_string()
537         };
538         lint.build(&message).emit()
539     });
540 }
541
542 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
543 fn is_enclosed(
544     tcx: TyCtxt<'_>,
545     used_unsafe: &FxHashSet<hir::HirId>,
546     id: hir::HirId,
547 ) -> Option<(String, hir::HirId)> {
548     let parent_id = tcx.hir().get_parent_node(id);
549     if parent_id != id {
550         if used_unsafe.contains(&parent_id) {
551             Some(("block".to_string(), parent_id))
552         } else if let Some(Node::Item(&hir::Item {
553             kind: hir::ItemKind::Fn(ref sig, _, _), ..
554         })) = tcx.hir().find(parent_id)
555         {
556             match sig.header.unsafety {
557                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
558                 hir::Unsafety::Normal => None,
559             }
560         } else {
561             is_enclosed(tcx, used_unsafe, parent_id)
562         }
563     } else {
564         None
565     }
566 }
567
568 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
569     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
570     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
571         let msg = "unnecessary `unsafe` block";
572         let mut db = lint.build(msg);
573         db.span_label(span, msg);
574         if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
575             db.span_label(
576                 tcx.sess.source_map().def_span(tcx.hir().span(id)),
577                 format!("because it's nested under this `unsafe` {}", kind),
578             );
579         }
580         db.emit();
581     });
582 }
583
584 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
585     debug!("builtin_derive_def_id({:?})", def_id);
586     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
587         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
588             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
589             Some(impl_def_id)
590         } else {
591             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
592             None
593         }
594     } else {
595         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
596         None
597     }
598 }
599
600 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
601     debug!("check_unsafety({:?})", def_id);
602
603     // closures are handled by their parent fn.
604     if tcx.is_closure(def_id) {
605         return;
606     }
607
608     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
609
610     for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
611         // Report an error.
612         match kind {
613             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
614                 struct_span_err!(
615                     tcx.sess,
616                     source_info.span,
617                     E0133,
618                     "{} is unsafe and requires unsafe function or block",
619                     description
620                 )
621                 .span_label(source_info.span, &*description.as_str())
622                 .note(&details.as_str())
623                 .emit();
624             }
625             UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
626                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
627                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
628                 } else {
629                     tcx.struct_span_lint_hir(
630                         SAFE_PACKED_BORROWS,
631                         lint_hir_id,
632                         source_info.span,
633                         |lint| {
634                             lint.build(&format!(
635                                 "{} is unsafe and requires unsafe function or block (error E0133)",
636                                 description
637                             ))
638                             .note(&details.as_str())
639                             .emit()
640                         },
641                     )
642                 }
643             }
644         }
645     }
646
647     let mut unsafe_blocks: Vec<_> = unsafe_blocks.iter().collect();
648     unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
649     let used_unsafe: FxHashSet<_> =
650         unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
651     for &(block_id, is_used) in unsafe_blocks {
652         if !is_used {
653             report_unused_unsafe(tcx, &used_unsafe, block_id);
654         }
655     }
656 }