1 use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::{has_drop, is_copy, is_type_diagnostic_item, walk_ptrs_ty_depth};
4 use clippy_utils::{fn_has_unsatisfiable_preds, match_def_path, paths};
5 use if_chain::if_chain;
6 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_hir::{def_id, Body, FnDecl, HirId};
10 use rustc_index::bit_set::{BitSet, HybridBitSet};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::mir::{
14 visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
16 use rustc_middle::ty::{self, fold::TypeVisitor, Ty};
17 use rustc_mir::dataflow::{Analysis, AnalysisDomain, GenKill, GenKillAnalysis, ResultsCursor};
18 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 use rustc_span::source_map::{BytePos, Span};
21 use std::convert::TryFrom;
22 use std::ops::ControlFlow;
24 macro_rules! unwrap_or_continue {
33 declare_clippy_lint! {
34 /// **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned
35 /// value that is going to be dropped without further use.
37 /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
38 /// allocations and deallocations generated by redundant `clone()`s.
40 /// **Known problems:**
42 /// False-negatives: analysis performed by this lint is conservative and limited.
46 /// # use std::path::Path;
47 /// # #[derive(Clone)]
50 /// # fn new() -> Self { Foo {} }
52 /// # fn call(x: Foo) {}
54 /// let x = Foo::new();
56 /// call(x.clone()); // this can just pass `x`
59 /// ["lorem", "ipsum"].join(" ").to_string();
61 /// Path::new("/a/b").join("c").to_path_buf();
65 "`clone()` of an owned value that is going to be dropped immediately"
68 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
70 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
71 #[allow(clippy::too_many_lines)]
74 cx: &LateContext<'tcx>,
81 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
83 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
84 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
88 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
90 let maybe_storage_live_result = MaybeStorageLive
91 .into_engine(cx.tcx, mir)
92 .pass_name("redundant_clone")
93 .iterate_to_fixpoint()
94 .into_results_cursor(mir);
95 let mut possible_borrower = {
96 let mut vis = PossibleBorrowerVisitor::new(cx, mir);
98 vis.into_map(cx, maybe_storage_live_result)
101 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
102 let terminator = bbdata.terminator();
104 if terminator.source_info.span.from_expansion() {
109 if terminator.successors().any(|s| *s == bb) {
113 let (fn_def_id, arg, arg_ty, clone_ret) =
114 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
116 let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
117 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
118 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD)
119 && is_type_diagnostic_item(cx, arg_ty, sym::string_type));
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 if let ty::Adt(def, _) = arg_ty.kind() {
130 if match_def_path(cx, def.did, &paths::MEM_MANUALLY_DROP) {
135 // `{ arg = &cloned; clone(move arg); }` or `{ arg = &cloned; to_path_buf(arg); }`
136 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
138 let loc = mir::Location {
140 statement_index: bbdata.statements.len(),
143 // `Local` to be cloned, and a local of `clone` call's destination
144 let (local, ret_local) = if from_borrow {
145 // `res = clone(arg)` can be turned into `res = move arg;`
146 // if `arg` is the only borrow of `cloned` at this point.
148 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
154 // `arg` is a reference as it is `.deref()`ed in the previous block.
155 // Look into the predecessor block and find out the source of deref.
157 let ps = &mir.predecessors()[bb];
161 let pred_terminator = mir[ps[0]].terminator();
163 // receiver of the `deref()` call
164 let (pred_arg, deref_clone_ret) = if_chain! {
165 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
166 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
168 if cx.tcx.is_diagnostic_item(sym::deref_method, pred_fn_def_id);
169 if is_type_diagnostic_item(cx, pred_arg_ty, sym::PathBuf)
170 || is_type_diagnostic_item(cx, pred_arg_ty, sym::OsString);
178 let (local, cannot_move_out) =
179 unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
180 let loc = mir::Location {
182 statement_index: mir.basic_blocks()[bb].statements.len(),
185 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
186 // at the last statement:
189 // pred_arg = &local;
190 // cloned = deref(pred_arg);
192 // StorageDead(pred_arg);
193 // res = to_path_buf(cloned);
195 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
199 (local, deref_clone_ret)
202 let clone_usage = if local == ret_local {
205 cloned_consume_or_mutate_loc: None,
206 clone_consumed_or_mutated: true,
209 let clone_usage = visit_clone_usage(local, ret_local, mir, bb);
210 if clone_usage.cloned_used && clone_usage.clone_consumed_or_mutated {
211 // cloned value is used, and the clone is modified or moved
213 } else if let Some(loc) = clone_usage.cloned_consume_or_mutate_loc {
214 // cloned value is mutated, and the clone is alive.
215 if possible_borrower.is_alive_at(ret_local, loc) {
222 let span = terminator.source_info.span;
223 let scope = terminator.source_info.scope;
224 let node = mir.source_scopes[scope]
227 .assert_crate_local()
231 if let Some(snip) = snippet_opt(cx, span);
232 if let Some(dot) = snip.rfind('.');
234 let sugg_span = span.with_lo(
235 span.lo() + BytePos(u32::try_from(dot).unwrap())
237 let mut app = Applicability::MaybeIncorrect;
239 let call_snip = &snip[dot + 1..];
240 // Machine applicable when `call_snip` looks like `foobar()`
241 if let Some(call_snip) = call_snip.strip_suffix("()").map(str::trim) {
242 if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
243 app = Applicability::MachineApplicable;
247 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
248 diag.span_suggestion(
254 if clone_usage.cloned_used {
257 "cloned value is neither consumed nor mutated",
261 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
262 "this value is dropped without further use",
267 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
274 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
275 fn is_call_with_ref_arg<'tcx>(
276 cx: &LateContext<'tcx>,
277 mir: &'tcx mir::Body<'tcx>,
278 kind: &'tcx mir::TerminatorKind<'tcx>,
279 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
281 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
283 if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
284 if let ty::FnDef(def_id, _) = *func.ty(&*mir, cx.tcx).kind();
285 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
286 if !is_copy(cx, inner_ty);
288 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
295 type CannotMoveOut = bool;
297 /// Finds the first `to = (&)from`, and returns
298 /// ``Some((from, whether `from` cannot be moved out))``.
299 fn find_stmt_assigns_to<'tcx>(
300 cx: &LateContext<'tcx>,
301 mir: &mir::Body<'tcx>,
302 to_local: mir::Local,
305 ) -> Option<(mir::Local, CannotMoveOut)> {
306 let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
307 if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
308 return if *local == to_local { Some(v) } else { None };
314 match (by_ref, &*rvalue) {
315 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
316 Some(base_local_and_movability(cx, mir, *place))
318 (false, mir::Rvalue::Ref(_, _, place)) => {
319 if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
320 Some(base_local_and_movability(cx, mir, *place))
329 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
330 /// if it is already a `Local`.
332 /// Also reports whether given `place` cannot be moved out.
333 fn base_local_and_movability<'tcx>(
334 cx: &LateContext<'tcx>,
335 mir: &mir::Body<'tcx>,
336 place: mir::Place<'tcx>,
337 ) -> (mir::Local, CannotMoveOut) {
338 use rustc_middle::mir::PlaceRef;
340 // Dereference. You cannot move things out from a borrowed value.
341 let mut deref = false;
342 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
343 let mut field = false;
344 // If projection is a slice index then clone can be removed only if the
345 // underlying type implements Copy
346 let mut slice = false;
348 let PlaceRef { local, mut projection } = place.as_ref();
349 while let [base @ .., elem] = projection {
351 deref |= matches!(elem, mir::ProjectionElem::Deref);
352 field |= matches!(elem, mir::ProjectionElem::Field(..))
353 && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
354 slice |= matches!(elem, mir::ProjectionElem::Index(..))
355 && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
358 (local, deref || field || slice)
363 /// Whether the cloned value is used after the clone.
365 /// The first location where the cloned value is consumed or mutated, if any.
366 cloned_consume_or_mutate_loc: Option<mir::Location>,
367 /// Whether the clone value is mutated.
368 clone_consumed_or_mutated: bool,
370 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
376 impl<'tcx> mir::visit::Visitor<'tcx> for V {
377 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
378 let statements = &data.statements;
379 for (statement_index, statement) in statements.iter().enumerate() {
380 self.visit_statement(statement, mir::Location { block, statement_index });
383 self.visit_terminator(
387 statement_index: statements.len(),
392 fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, loc: mir::Location) {
393 let local = place.local;
395 if local == self.cloned
398 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_)
401 self.result.cloned_used = true;
402 self.result.cloned_consume_or_mutate_loc = self.result.cloned_consume_or_mutate_loc.or_else(|| {
405 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
406 | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
410 } else if local == self.clone {
412 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
413 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
414 self.result.clone_consumed_or_mutated = true;
422 let init = CloneUsage {
424 cloned_consume_or_mutate_loc: None,
425 // Consider non-temporary clones consumed.
426 // TODO: Actually check for mutation of non-temporaries.
427 clone_consumed_or_mutated: mir.local_kind(clone) != mir::LocalKind::Temp,
429 traversal::ReversePostorder::new(mir, bb)
431 .fold(init, |usage, (tbb, tdata)| {
433 if (usage.cloned_used && usage.clone_consumed_or_mutated) ||
435 tdata.terminator().successors().any(|s| *s == bb)
439 clone_consumed_or_mutated: true,
449 v.visit_basic_block_data(tbb, tdata);
454 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
455 #[derive(Copy, Clone)]
456 struct MaybeStorageLive;
458 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
459 type Domain = BitSet<mir::Local>;
460 const NAME: &'static str = "maybe_storage_live";
462 fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
464 BitSet::new_empty(body.local_decls.len())
467 fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
468 for arg in body.args_iter() {
474 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
475 type Idx = mir::Local;
477 fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
479 mir::StatementKind::StorageLive(l) => trans.gen(l),
480 mir::StatementKind::StorageDead(l) => trans.kill(l),
485 fn terminator_effect(
487 _trans: &mut impl GenKill<Self::Idx>,
488 _terminator: &mir::Terminator<'tcx>,
493 fn call_return_effect(
495 _in_out: &mut impl GenKill<Self::Idx>,
496 _block: mir::BasicBlock,
497 _func: &mir::Operand<'tcx>,
498 _args: &[mir::Operand<'tcx>],
499 _return_place: mir::Place<'tcx>,
501 // Nothing to do when a call returns successfully
505 /// Collects the possible borrowers of each local.
506 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
507 /// possible borrowers of `a`.
508 struct PossibleBorrowerVisitor<'a, 'tcx> {
509 possible_borrower: TransitiveRelation<mir::Local>,
510 body: &'a mir::Body<'tcx>,
511 cx: &'a LateContext<'tcx>,
514 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
515 fn new(cx: &'a LateContext<'tcx>, body: &'a mir::Body<'tcx>) -> Self {
517 possible_borrower: TransitiveRelation::default(),
525 cx: &LateContext<'tcx>,
526 maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
527 ) -> PossibleBorrowerMap<'a, 'tcx> {
528 let mut map = FxHashMap::default();
529 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
530 if is_copy(cx, self.body.local_decls[row].ty) {
534 let borrowers = self.possible_borrower.reachable_from(&row);
535 if !borrowers.is_empty() {
536 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
537 for &c in borrowers {
538 if c != mir::Local::from_usize(0) {
549 let bs = BitSet::new_empty(self.body.local_decls.len());
550 PossibleBorrowerMap {
553 bitset: (bs.clone(), bs),
558 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
559 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
560 let lhs = place.local;
562 mir::Rvalue::Ref(_, _, borrowed) => {
563 self.possible_borrower.add(borrowed.local, lhs);
567 .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
572 rvalue_locals(other, |rhs| {
574 self.possible_borrower.add(rhs, lhs);
581 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
582 if let mir::TerminatorKind::Call {
584 destination: Some((mir::Place { local: dest, .. }, _)),
588 // If the call returns something with lifetimes,
589 // let's conservatively assume the returned value contains lifetime of all the arguments.
590 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
591 if ContainsRegion.visit_ty(self.body.local_decls[*dest].ty).is_continue() {
597 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
598 self.possible_borrower.add(p.local, *dest);
600 mir::Operand::Constant(..) => (),
607 struct ContainsRegion;
609 impl TypeVisitor<'_> for ContainsRegion {
612 fn visit_region(&mut self, _: ty::Region<'_>) -> ControlFlow<Self::BreakTy> {
617 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
618 use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
620 let mut visit_op = |op: &mir::Operand<'_>| match op {
621 mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
622 mir::Operand::Constant(..) => (),
626 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
627 Aggregate(_, ops) => ops.iter().for_each(visit_op),
628 BinaryOp(_, box (lhs, rhs)) | CheckedBinaryOp(_, box (lhs, rhs)) => {
636 /// Result of `PossibleBorrowerVisitor`.
637 struct PossibleBorrowerMap<'a, 'tcx> {
638 /// Mapping `Local -> its possible borrowers`
639 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
640 maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
641 // Caches to avoid allocation of `BitSet` on every query
642 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
645 impl PossibleBorrowerMap<'_, '_> {
646 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
647 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
648 self.maybe_live.seek_after_primary_effect(at);
650 self.bitset.0.clear();
651 let maybe_live = &mut self.maybe_live;
652 if let Some(bitset) = self.map.get(&borrowed) {
653 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
654 self.bitset.0.insert(b);
660 self.bitset.1.clear();
662 self.bitset.1.insert(*b);
665 self.bitset.0 == self.bitset.1
668 fn is_alive_at(&mut self, local: mir::Local, at: mir::Location) -> bool {
669 self.maybe_live.seek_after_primary_effect(at);
670 self.maybe_live.contains(local)