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