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;
9 visit::{MutatingUseContext, PlaceContext, Visitor as _},
11 use rustc::ty::{self, fold::TypeVisitor, Ty};
12 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
13 use rustc_errors::Applicability;
14 use rustc_hir::intravisit::FnKind;
15 use rustc_hir::{def_id, Body, FnDecl, HirId};
16 use rustc_index::bit_set::{BitSet, HybridBitSet};
17 use rustc_lint::{LateContext, LateLintPass};
18 use rustc_mir::dataflow::generic::{Analysis, AnalysisDomain, GenKill, GenKillAnalysis, ResultsCursor};
19 use rustc_mir::dataflow::BottomValue;
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::{BytePos, Span};
22 use std::convert::TryFrom;
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<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
71 #[allow(clippy::too_many_lines)]
74 cx: &LateContext<'a, 'tcx>,
81 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
82 let mir = cx.tcx.optimized_mir(def_id);
83 let mir_read_only = mir.unwrap_read_only();
85 let maybe_storage_live_result = MaybeStorageLive
86 .into_engine(cx.tcx, mir, def_id)
87 .iterate_to_fixpoint()
88 .into_results_cursor(mir);
89 let mut possible_borrower = {
90 let mut vis = PossibleBorrowerVisitor::new(cx, mir);
91 vis.visit_body(mir_read_only);
92 vis.into_map(cx, maybe_storage_live_result)
95 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
96 let terminator = bbdata.terminator();
98 if terminator.source_info.span.from_expansion() {
103 if terminator.successors().any(|s| *s == bb) {
107 let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
109 let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
110 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
111 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD) && match_type(cx, arg_ty, &paths::STRING));
113 let from_deref = !from_borrow
114 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
115 || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
117 if !from_borrow && !from_deref {
121 // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
122 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
124 let loc = mir::Location {
126 statement_index: bbdata.statements.len(),
130 let local = if from_borrow {
131 // `res = clone(arg)` can be turned into `res = move arg;`
132 // if `arg` is the only borrow of `cloned` at this point.
134 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
140 // `arg` is a reference as it is `.deref()`ed in the previous block.
141 // Look into the predecessor block and find out the source of deref.
143 let ps = mir_read_only.predecessors_for(bb);
147 let pred_terminator = mir[ps[0]].terminator();
149 // receiver of the `deref()` call
150 let pred_arg = if_chain! {
151 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
152 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
153 if res.local == cloned;
154 if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
155 if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
156 || match_type(cx, pred_arg_ty, &paths::OS_STRING);
164 let (local, cannot_move_out) =
165 unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
166 let loc = mir::Location {
168 statement_index: mir.basic_blocks()[bb].statements.len(),
171 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
172 // at the last statement:
175 // pred_arg = &local;
176 // cloned = deref(pred_arg);
178 // StorageDead(pred_arg);
179 // res = to_path_buf(cloned);
181 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
188 // `local` cannot be moved out if it is used later
189 let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
191 if tdata.terminator().successors().any(|s| *s == bb) {
195 let mut vis = LocalUseVisitor {
197 used_other_than_drop: false,
199 vis.visit_basic_block_data(tbb, tdata);
200 vis.used_other_than_drop
204 let span = terminator.source_info.span;
205 let scope = terminator.source_info.scope;
206 let node = mir.source_scopes[scope]
209 .assert_crate_local()
213 if let Some(snip) = snippet_opt(cx, span);
214 if let Some(dot) = snip.rfind('.');
216 let sugg_span = span.with_lo(
217 span.lo() + BytePos(u32::try_from(dot).unwrap())
219 let mut app = Applicability::MaybeIncorrect;
221 let mut call_snip = &snip[dot + 1..];
222 // Machine applicable when `call_snip` looks like `foobar()`
223 if call_snip.ends_with("()") {
224 call_snip = call_snip[..call_snip.len()-2].trim();
225 if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
226 app = Applicability::MachineApplicable;
230 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
238 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
239 "this value is dropped without further use",
243 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
251 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
252 fn is_call_with_ref_arg<'tcx>(
253 cx: &LateContext<'_, 'tcx>,
254 mir: &'tcx mir::Body<'tcx>,
255 kind: &'tcx mir::TerminatorKind<'tcx>,
256 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
258 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
260 if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
261 if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind;
262 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
263 if !is_copy(cx, inner_ty);
265 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
272 type CannotMoveOut = bool;
274 /// Finds the first `to = (&)from`, and returns
275 /// ``Some((from, whether `from` cannot be moved out))``.
276 fn find_stmt_assigns_to<'tcx>(
277 cx: &LateContext<'_, 'tcx>,
278 mir: &mir::Body<'tcx>,
279 to_local: mir::Local,
282 ) -> Option<(mir::Local, CannotMoveOut)> {
283 let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
284 if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
285 return if *local == to_local { Some(v) } else { None };
291 match (by_ref, &*rvalue) {
292 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
293 base_local_and_movability(cx, mir, *place)
295 (false, mir::Rvalue::Ref(_, _, place)) => {
296 if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
297 base_local_and_movability(cx, mir, *place)
306 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
307 /// if it is already a `Local`.
309 /// Also reports whether given `place` cannot be moved out.
310 fn base_local_and_movability<'tcx>(
311 cx: &LateContext<'_, 'tcx>,
312 mir: &mir::Body<'tcx>,
313 place: mir::Place<'tcx>,
314 ) -> Option<(mir::Local, CannotMoveOut)> {
315 use rustc::mir::PlaceRef;
317 // Dereference. You cannot move things out from a borrowed value.
318 let mut deref = false;
319 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
320 let mut field = false;
322 let PlaceRef { local, mut projection } = place.as_ref();
323 while let [base @ .., elem] = projection {
325 deref |= matches!(elem, mir::ProjectionElem::Deref);
326 field |= matches!(elem, mir::ProjectionElem::Field(..))
327 && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
330 Some((local, deref || field))
333 struct LocalUseVisitor {
335 used_other_than_drop: bool,
338 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
339 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
340 let statements = &data.statements;
341 for (statement_index, statement) in statements.iter().enumerate() {
342 self.visit_statement(statement, mir::Location { block, statement_index });
344 // Once flagged, skip remaining statements
345 if self.used_other_than_drop {
350 self.visit_terminator(
354 statement_index: statements.len(),
359 fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
361 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
365 if *local == self.local {
366 self.used_other_than_drop = true;
371 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
372 #[derive(Copy, Clone)]
373 struct MaybeStorageLive;
375 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
376 type Idx = mir::Local;
377 const NAME: &'static str = "maybe_storage_live";
379 fn bits_per_block(&self, body: &mir::Body<'tcx>) -> usize {
380 body.local_decls.len()
383 fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut BitSet<Self::Idx>) {
384 for arg in body.args_iter() {
390 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
391 fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
393 mir::StatementKind::StorageLive(l) => trans.gen(l),
394 mir::StatementKind::StorageDead(l) => trans.kill(l),
399 fn terminator_effect(
401 _trans: &mut impl GenKill<Self::Idx>,
402 _terminator: &mir::Terminator<'tcx>,
407 fn call_return_effect(
409 _in_out: &mut impl GenKill<Self::Idx>,
410 _block: mir::BasicBlock,
411 _func: &mir::Operand<'tcx>,
412 _args: &[mir::Operand<'tcx>],
413 _return_place: &mir::Place<'tcx>,
415 // Nothing to do when a call returns successfully
419 impl BottomValue for MaybeStorageLive {
421 const BOTTOM_VALUE: bool = false;
424 /// Collects the possible borrowers of each local.
425 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
426 /// possible borrowers of `a`.
427 struct PossibleBorrowerVisitor<'a, 'tcx> {
428 possible_borrower: TransitiveRelation<mir::Local>,
429 body: &'a mir::Body<'tcx>,
430 cx: &'a LateContext<'a, 'tcx>,
433 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
434 fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
436 possible_borrower: TransitiveRelation::default(),
444 cx: &LateContext<'a, 'tcx>,
445 maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
446 ) -> PossibleBorrowerMap<'a, 'tcx> {
447 let mut map = FxHashMap::default();
448 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
449 if is_copy(cx, self.body.local_decls[row].ty) {
453 let borrowers = self.possible_borrower.reachable_from(&row);
454 if !borrowers.is_empty() {
455 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
456 for &c in borrowers {
457 if c != mir::Local::from_usize(0) {
468 let bs = BitSet::new_empty(self.body.local_decls.len());
469 PossibleBorrowerMap {
472 bitset: (bs.clone(), bs),
477 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
478 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
479 let lhs = place.local;
481 mir::Rvalue::Ref(_, _, borrowed) => {
482 self.possible_borrower.add(borrowed.local, lhs);
485 if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
488 rvalue_locals(other, |rhs| {
490 self.possible_borrower.add(rhs, lhs);
497 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
498 if let mir::TerminatorKind::Call {
500 destination: Some((mir::Place { local: dest, .. }, _)),
504 // If the call returns something with lifetimes,
505 // let's conservatively assume the returned value contains lifetime of all the arguments.
506 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
507 if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
513 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
514 self.possible_borrower.add(p.local, *dest);
523 struct ContainsRegion;
525 impl TypeVisitor<'_> for ContainsRegion {
526 fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
531 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
532 use rustc::mir::Rvalue::*;
534 let mut visit_op = |op: &mir::Operand<'_>| match op {
535 mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
540 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
541 Aggregate(_, ops) => ops.iter().for_each(visit_op),
542 BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
550 /// Result of `PossibleBorrowerVisitor`.
551 struct PossibleBorrowerMap<'a, 'tcx> {
552 /// Mapping `Local -> its possible borrowers`
553 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
554 maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
555 // Caches to avoid allocation of `BitSet` on every query
556 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
559 impl PossibleBorrowerMap<'_, '_> {
560 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
561 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
562 self.maybe_live.seek_after(at);
564 self.bitset.0.clear();
565 let maybe_live = &mut self.maybe_live;
566 if let Some(bitset) = self.map.get(&borrowed) {
567 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
568 self.bitset.0.insert(b);
574 self.bitset.1.clear();
576 self.bitset.1.insert(*b);
579 self.bitset.0 == self.bitset.1