2 has_drop, is_copy, match_def_path, match_type, paths, snippet_opt, span_lint_hir, span_lint_hir_and_then,
5 use if_chain::if_chain;
7 use rustc::declare_lint_pass;
8 use rustc::hir::intravisit::FnKind;
9 use rustc::hir::{def_id, Body, FnDecl, HirId};
10 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 visit::{MutatingUseContext, PlaceContext, Visitor as _},
15 use rustc::ty::{self, fold::TypeVisitor, Ty};
16 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
17 use rustc_errors::Applicability;
18 use rustc_index::bit_set::{BitSet, HybridBitSet};
19 use rustc_mir::dataflow::{
20 do_dataflow, BitDenotation, BottomValue, DataflowResults, DataflowResultsCursor, DebugFormatted, GenKillSet,
22 use rustc_session::declare_tool_lint;
23 use std::convert::TryFrom;
24 use syntax::source_map::{BytePos, Span};
26 macro_rules! unwrap_or_continue {
35 declare_clippy_lint! {
36 /// **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned
37 /// value that is going to be dropped without further use.
39 /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
40 /// allocations and deallocations generated by redundant `clone()`s.
42 /// **Known problems:**
44 /// False-negatives: analysis performed by this lint is conservative and limited.
48 /// # use std::path::Path;
49 /// # #[derive(Clone)]
52 /// # fn new() -> Self { Foo {} }
54 /// # fn call(x: Foo) {}
56 /// let x = Foo::new();
58 /// call(x.clone()); // this can just pass `x`
61 /// ["lorem", "ipsum"].join(" ").to_string();
63 /// Path::new("/a/b").join("c").to_path_buf();
67 "`clone()` of an owned value that is going to be dropped immediately"
70 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
73 #[allow(clippy::too_many_lines)]
76 cx: &LateContext<'a, 'tcx>,
83 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
84 let mir = cx.tcx.optimized_mir(def_id);
85 let mir_read_only = mir.unwrap_read_only();
87 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
88 let maybe_storage_live_result = do_dataflow(
94 MaybeStorageLive::new(mir),
95 |bd, p| DebugFormatted::new(&bd.body.local_decls[p]),
97 let mut possible_borrower = {
98 let mut vis = PossibleBorrowerVisitor::new(cx, mir);
99 vis.visit_body(mir_read_only);
100 vis.into_map(cx, maybe_storage_live_result)
103 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
104 let terminator = bbdata.terminator();
106 if terminator.source_info.span.from_expansion() {
111 if terminator.successors().any(|s| *s == bb) {
115 let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
117 let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
118 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
119 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD) && match_type(cx, arg_ty, &paths::STRING));
121 let from_deref = !from_borrow
122 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
123 || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
125 if !from_borrow && !from_deref {
129 // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
130 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
132 let loc = mir::Location {
134 statement_index: bbdata.statements.len(),
138 let local = if from_borrow {
139 // `res = clone(arg)` can be turned into `res = move arg;`
140 // if `arg` is the only borrow of `cloned` at this point.
142 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
148 // `arg` is a reference as it is `.deref()`ed in the previous block.
149 // Look into the predecessor block and find out the source of deref.
151 let ps = mir_read_only.predecessors_for(bb);
155 let pred_terminator = mir[ps[0]].terminator();
157 // receiver of the `deref()` call
158 let pred_arg = if_chain! {
159 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
160 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
161 if res.base == mir::PlaceBase::Local(cloned);
162 if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
163 if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
164 || match_type(cx, pred_arg_ty, &paths::OS_STRING);
172 let (local, cannot_move_out) =
173 unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
174 let loc = mir::Location {
176 statement_index: mir.basic_blocks()[bb].statements.len(),
179 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
180 // at the last statement:
183 // pred_arg = &local;
184 // cloned = deref(pred_arg);
186 // StorageDead(pred_arg);
187 // res = to_path_buf(cloned);
189 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
196 // `local` cannot be moved out if it is used later
197 let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
199 if tdata.terminator().successors().any(|s| *s == bb) {
203 let mut vis = LocalUseVisitor {
205 used_other_than_drop: false,
207 vis.visit_basic_block_data(tbb, tdata);
208 vis.used_other_than_drop
212 let span = terminator.source_info.span;
213 let scope = terminator.source_info.scope;
214 let node = mir.source_scopes[scope]
217 .assert_crate_local()
221 if let Some(snip) = snippet_opt(cx, span);
222 if let Some(dot) = snip.rfind('.');
224 let sugg_span = span.with_lo(
225 span.lo() + BytePos(u32::try_from(dot).unwrap())
227 let mut app = Applicability::MaybeIncorrect;
229 let mut call_snip = &snip[dot + 1..];
230 // Machine applicable when `call_snip` looks like `foobar()`
231 if call_snip.ends_with("()") {
232 call_snip = call_snip[..call_snip.len()-2].trim();
233 if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
234 app = Applicability::MachineApplicable;
238 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
246 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
247 "this value is dropped without further use",
251 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
259 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
260 fn is_call_with_ref_arg<'tcx>(
261 cx: &LateContext<'_, 'tcx>,
262 mir: &'tcx mir::Body<'tcx>,
263 kind: &'tcx mir::TerminatorKind<'tcx>,
264 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
266 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
268 if let mir::Operand::Move(mir::Place { base: mir::PlaceBase::Local(local), .. }) = &args[0];
269 if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind;
270 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
271 if !is_copy(cx, inner_ty);
273 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
280 type CannotMoveOut = bool;
282 /// Finds the first `to = (&)from`, and returns
283 /// ``Some((from, whether `from` cannot be moved out))``.
284 fn find_stmt_assigns_to<'tcx>(
285 cx: &LateContext<'_, 'tcx>,
286 mir: &mir::Body<'tcx>,
287 to_local: mir::Local,
290 ) -> Option<(mir::Local, CannotMoveOut)> {
291 let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
292 if let mir::StatementKind::Assign(box (
294 base: mir::PlaceBase::Local(local),
300 return if *local == to_local { Some(v) } else { None };
306 match (by_ref, &*rvalue) {
307 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
308 base_local_and_movability(cx, mir, place)
314 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
315 /// if it is already a `Local`.
317 /// Also reports whether given `place` cannot be moved out.
318 fn base_local_and_movability<'tcx>(
319 cx: &LateContext<'_, 'tcx>,
320 mir: &mir::Body<'tcx>,
321 place: &mir::Place<'tcx>,
322 ) -> Option<(mir::Local, CannotMoveOut)> {
323 use rustc::mir::PlaceRef;
325 // Dereference. You cannot move things out from a borrowed value.
326 let mut deref = false;
327 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
328 let mut field = false;
334 if let mir::PlaceBase::Local(local) = place_base {
335 while let [base @ .., elem] = projection {
337 deref |= matches!(elem, mir::ProjectionElem::Deref);
338 field |= matches!(elem, mir::ProjectionElem::Field(..))
341 mir::Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty,
345 Some((*local, deref || field))
351 struct LocalUseVisitor {
353 used_other_than_drop: bool,
356 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
357 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
358 let statements = &data.statements;
359 for (statement_index, statement) in statements.iter().enumerate() {
360 self.visit_statement(statement, mir::Location { block, statement_index });
362 // Once flagged, skip remaining statements
363 if self.used_other_than_drop {
368 self.visit_terminator(
372 statement_index: statements.len(),
377 fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
379 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
383 if *local == self.local {
384 self.used_other_than_drop = true;
389 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
390 #[derive(Copy, Clone)]
391 struct MaybeStorageLive<'a, 'tcx> {
392 body: &'a mir::Body<'tcx>,
395 impl<'a, 'tcx> MaybeStorageLive<'a, 'tcx> {
396 fn new(body: &'a mir::Body<'tcx>) -> Self {
397 MaybeStorageLive { body }
401 impl<'a, 'tcx> BitDenotation<'tcx> for MaybeStorageLive<'a, 'tcx> {
402 type Idx = mir::Local;
403 fn name() -> &'static str {
406 fn bits_per_block(&self) -> usize {
407 self.body.local_decls.len()
410 fn start_block_effect(&self, on_entry: &mut BitSet<mir::Local>) {
411 for arg in self.body.args_iter() {
412 on_entry.insert(arg);
416 fn statement_effect(&self, trans: &mut GenKillSet<mir::Local>, loc: mir::Location) {
417 let stmt = &self.body[loc.block].statements[loc.statement_index];
420 mir::StatementKind::StorageLive(l) => trans.gen(l),
421 mir::StatementKind::StorageDead(l) => trans.kill(l),
426 fn terminator_effect(&self, _trans: &mut GenKillSet<mir::Local>, _loc: mir::Location) {}
428 fn propagate_call_return(
430 _in_out: &mut BitSet<mir::Local>,
431 _call_bb: mir::BasicBlock,
432 _dest_bb: mir::BasicBlock,
433 _dest_place: &mir::Place<'tcx>,
435 // Nothing to do when a call returns successfully
439 impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> {
441 const BOTTOM_VALUE: bool = false;
444 /// Collects the possible borrowers of each local.
445 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
446 /// possible borrowers of `a`.
447 struct PossibleBorrowerVisitor<'a, 'tcx> {
448 possible_borrower: TransitiveRelation<mir::Local>,
449 body: &'a mir::Body<'tcx>,
450 cx: &'a LateContext<'a, 'tcx>,
453 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
454 fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
456 possible_borrower: TransitiveRelation::default(),
464 cx: &LateContext<'a, 'tcx>,
465 maybe_live: DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>,
466 ) -> PossibleBorrower<'a, 'tcx> {
467 let mut map = FxHashMap::default();
468 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
469 if is_copy(cx, self.body.local_decls[row].ty) {
473 let borrowers = self.possible_borrower.reachable_from(&row);
474 if !borrowers.is_empty() {
475 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
476 for &c in borrowers {
477 if c != mir::Local::from_usize(0) {
488 let bs = BitSet::new_empty(self.body.local_decls.len());
491 maybe_live: DataflowResultsCursor::new(maybe_live, self.body),
492 bitset: (bs.clone(), bs),
497 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
498 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
499 if let mir::PlaceBase::Local(lhs) = place.base {
501 mir::Rvalue::Ref(_, _, borrowed) => {
502 if let mir::PlaceBase::Local(borrowed_local) = borrowed.base {
503 self.possible_borrower.add(borrowed_local, lhs);
507 if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
510 rvalue_locals(other, |rhs| {
512 self.possible_borrower.add(rhs, lhs);
520 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
521 if let mir::TerminatorKind::Call {
526 base: mir::PlaceBase::Local(dest),
534 // If the call returns something with lifetimes,
535 // let's conservatively assume the returned value contains lifetime of all the arguments.
536 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
537 if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
543 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
544 if let mir::PlaceBase::Local(arg) = p.base {
545 self.possible_borrower.add(arg, *dest);
555 struct ContainsRegion;
557 impl TypeVisitor<'_> for ContainsRegion {
558 fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
563 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
564 use rustc::mir::Rvalue::*;
566 let mut visit_op = |op: &mir::Operand<'_>| match op {
567 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
568 if let mir::PlaceBase::Local(l) = p.base {
576 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
577 Aggregate(_, ops) => ops.iter().for_each(visit_op),
578 BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
586 /// Result of `PossibleBorrowerVisitor`.
587 struct PossibleBorrower<'a, 'tcx> {
588 /// Mapping `Local -> its possible borrowers`
589 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
590 maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>,
591 // Caches to avoid allocation of `BitSet` on every query
592 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
595 impl PossibleBorrower<'_, '_> {
596 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
597 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
598 self.maybe_live.seek(at);
600 self.bitset.0.clear();
601 let maybe_live = &mut self.maybe_live;
602 if let Some(bitset) = self.map.get(&borrowed) {
603 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
604 self.bitset.0.insert(b);
610 self.bitset.1.clear();
612 self.bitset.1.insert(*b);
615 self.bitset.0 == self.bitset.1