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::{
19 do_dataflow, BitDenotation, BottomValue, DataflowResults, DataflowResultsCursor, DebugFormatted, GenKillSet,
21 use rustc_session::{declare_lint_pass, declare_tool_lint};
22 use rustc_span::source_map::{BytePos, Span};
23 use std::convert::TryFrom;
25 macro_rules! unwrap_or_continue {
34 declare_clippy_lint! {
35 /// **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned
36 /// value that is going to be dropped without further use.
38 /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
39 /// allocations and deallocations generated by redundant `clone()`s.
41 /// **Known problems:**
43 /// False-negatives: analysis performed by this lint is conservative and limited.
47 /// # use std::path::Path;
48 /// # #[derive(Clone)]
51 /// # fn new() -> Self { Foo {} }
53 /// # fn call(x: Foo) {}
55 /// let x = Foo::new();
57 /// call(x.clone()); // this can just pass `x`
60 /// ["lorem", "ipsum"].join(" ").to_string();
62 /// Path::new("/a/b").join("c").to_path_buf();
66 "`clone()` of an owned value that is going to be dropped immediately"
69 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
72 #[allow(clippy::too_many_lines)]
75 cx: &LateContext<'a, 'tcx>,
82 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
83 let mir = cx.tcx.optimized_mir(def_id);
84 let mir_read_only = mir.unwrap_read_only();
86 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
87 let maybe_storage_live_result = do_dataflow(
93 MaybeStorageLive::new(mir),
94 |bd, p| DebugFormatted::new(&bd.body.local_decls[p]),
96 let mut possible_borrower = {
97 let mut vis = PossibleBorrowerVisitor::new(cx, mir);
98 vis.visit_body(mir_read_only);
99 vis.into_map(cx, maybe_storage_live_result)
102 for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
103 let terminator = bbdata.terminator();
105 if terminator.source_info.span.from_expansion() {
110 if terminator.successors().any(|s| *s == bb) {
114 let (fn_def_id, arg, arg_ty, _) = 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) && match_type(cx, arg_ty, &paths::STRING));
120 let from_deref = !from_borrow
121 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
122 || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
124 if !from_borrow && !from_deref {
128 // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
129 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
131 let loc = mir::Location {
133 statement_index: bbdata.statements.len(),
137 let local = if from_borrow {
138 // `res = clone(arg)` can be turned into `res = move arg;`
139 // if `arg` is the only borrow of `cloned` at this point.
141 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
147 // `arg` is a reference as it is `.deref()`ed in the previous block.
148 // Look into the predecessor block and find out the source of deref.
150 let ps = mir_read_only.predecessors_for(bb);
154 let pred_terminator = mir[ps[0]].terminator();
156 // receiver of the `deref()` call
157 let pred_arg = if_chain! {
158 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
159 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
160 if res.local == cloned;
161 if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
162 if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
163 || match_type(cx, pred_arg_ty, &paths::OS_STRING);
171 let (local, cannot_move_out) =
172 unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
173 let loc = mir::Location {
175 statement_index: mir.basic_blocks()[bb].statements.len(),
178 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
179 // at the last statement:
182 // pred_arg = &local;
183 // cloned = deref(pred_arg);
185 // StorageDead(pred_arg);
186 // res = to_path_buf(cloned);
188 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
195 // `local` cannot be moved out if it is used later
196 let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
198 if tdata.terminator().successors().any(|s| *s == bb) {
202 let mut vis = LocalUseVisitor {
204 used_other_than_drop: false,
206 vis.visit_basic_block_data(tbb, tdata);
207 vis.used_other_than_drop
211 let span = terminator.source_info.span;
212 let scope = terminator.source_info.scope;
213 let node = mir.source_scopes[scope]
216 .assert_crate_local()
220 if let Some(snip) = snippet_opt(cx, span);
221 if let Some(dot) = snip.rfind('.');
223 let sugg_span = span.with_lo(
224 span.lo() + BytePos(u32::try_from(dot).unwrap())
226 let mut app = Applicability::MaybeIncorrect;
228 let mut call_snip = &snip[dot + 1..];
229 // Machine applicable when `call_snip` looks like `foobar()`
230 if call_snip.ends_with("()") {
231 call_snip = call_snip[..call_snip.len()-2].trim();
232 if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
233 app = Applicability::MachineApplicable;
237 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
245 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
246 "this value is dropped without further use",
250 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
258 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
259 fn is_call_with_ref_arg<'tcx>(
260 cx: &LateContext<'_, 'tcx>,
261 mir: &'tcx mir::Body<'tcx>,
262 kind: &'tcx mir::TerminatorKind<'tcx>,
263 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
265 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
267 if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
268 if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind;
269 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
270 if !is_copy(cx, inner_ty);
272 Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
279 type CannotMoveOut = bool;
281 /// Finds the first `to = (&)from`, and returns
282 /// ``Some((from, whether `from` cannot be moved out))``.
283 fn find_stmt_assigns_to<'tcx>(
284 cx: &LateContext<'_, 'tcx>,
285 mir: &mir::Body<'tcx>,
286 to_local: mir::Local,
289 ) -> Option<(mir::Local, CannotMoveOut)> {
290 let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
291 if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
292 return if *local == to_local { Some(v) } else { None };
298 match (by_ref, &*rvalue) {
299 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
300 base_local_and_movability(cx, mir, *place)
302 (false, mir::Rvalue::Ref(_, _, place)) => {
303 if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
304 base_local_and_movability(cx, mir, *place)
313 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
314 /// if it is already a `Local`.
316 /// Also reports whether given `place` cannot be moved out.
317 fn base_local_and_movability<'tcx>(
318 cx: &LateContext<'_, 'tcx>,
319 mir: &mir::Body<'tcx>,
320 place: mir::Place<'tcx>,
321 ) -> Option<(mir::Local, CannotMoveOut)> {
322 use rustc::mir::PlaceRef;
324 // Dereference. You cannot move things out from a borrowed value.
325 let mut deref = false;
326 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
327 let mut field = false;
329 let PlaceRef { local, mut projection } = place.as_ref();
330 while let [base @ .., elem] = projection {
332 deref |= matches!(elem, mir::ProjectionElem::Deref);
333 field |= matches!(elem, mir::ProjectionElem::Field(..))
334 && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
337 Some((*local, deref || field))
340 struct LocalUseVisitor {
342 used_other_than_drop: bool,
345 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
346 fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
347 let statements = &data.statements;
348 for (statement_index, statement) in statements.iter().enumerate() {
349 self.visit_statement(statement, mir::Location { block, statement_index });
351 // Once flagged, skip remaining statements
352 if self.used_other_than_drop {
357 self.visit_terminator(
361 statement_index: statements.len(),
366 fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
368 PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
372 if *local == self.local {
373 self.used_other_than_drop = true;
378 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
379 #[derive(Copy, Clone)]
380 struct MaybeStorageLive<'a, 'tcx> {
381 body: &'a mir::Body<'tcx>,
384 impl<'a, 'tcx> MaybeStorageLive<'a, 'tcx> {
385 fn new(body: &'a mir::Body<'tcx>) -> Self {
386 MaybeStorageLive { body }
390 impl<'a, 'tcx> BitDenotation<'tcx> for MaybeStorageLive<'a, 'tcx> {
391 type Idx = mir::Local;
392 fn name() -> &'static str {
395 fn bits_per_block(&self) -> usize {
396 self.body.local_decls.len()
399 fn start_block_effect(&self, on_entry: &mut BitSet<mir::Local>) {
400 for arg in self.body.args_iter() {
401 on_entry.insert(arg);
405 fn statement_effect(&self, trans: &mut GenKillSet<mir::Local>, loc: mir::Location) {
406 let stmt = &self.body[loc.block].statements[loc.statement_index];
409 mir::StatementKind::StorageLive(l) => trans.gen(l),
410 mir::StatementKind::StorageDead(l) => trans.kill(l),
415 fn terminator_effect(&self, _trans: &mut GenKillSet<mir::Local>, _loc: mir::Location) {}
417 fn propagate_call_return(
419 _in_out: &mut BitSet<mir::Local>,
420 _call_bb: mir::BasicBlock,
421 _dest_bb: mir::BasicBlock,
422 _dest_place: &mir::Place<'tcx>,
424 // Nothing to do when a call returns successfully
428 impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> {
430 const BOTTOM_VALUE: bool = false;
433 /// Collects the possible borrowers of each local.
434 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
435 /// possible borrowers of `a`.
436 struct PossibleBorrowerVisitor<'a, 'tcx> {
437 possible_borrower: TransitiveRelation<mir::Local>,
438 body: &'a mir::Body<'tcx>,
439 cx: &'a LateContext<'a, 'tcx>,
442 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
443 fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
445 possible_borrower: TransitiveRelation::default(),
453 cx: &LateContext<'a, 'tcx>,
454 maybe_live: DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>,
455 ) -> PossibleBorrower<'a, 'tcx> {
456 let mut map = FxHashMap::default();
457 for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
458 if is_copy(cx, self.body.local_decls[row].ty) {
462 let borrowers = self.possible_borrower.reachable_from(&row);
463 if !borrowers.is_empty() {
464 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
465 for &c in borrowers {
466 if c != mir::Local::from_usize(0) {
477 let bs = BitSet::new_empty(self.body.local_decls.len());
480 maybe_live: DataflowResultsCursor::new(maybe_live, self.body),
481 bitset: (bs.clone(), bs),
486 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
487 fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
488 let lhs = place.local;
490 mir::Rvalue::Ref(_, _, borrowed) => {
491 self.possible_borrower.add(borrowed.local, lhs);
494 if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
497 rvalue_locals(other, |rhs| {
499 self.possible_borrower.add(rhs, lhs);
506 fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
507 if let mir::TerminatorKind::Call {
509 destination: Some((mir::Place { local: dest, .. }, _)),
513 // If the call returns something with lifetimes,
514 // let's conservatively assume the returned value contains lifetime of all the arguments.
515 // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
516 if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
522 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
523 self.possible_borrower.add(p.local, *dest);
532 struct ContainsRegion;
534 impl TypeVisitor<'_> for ContainsRegion {
535 fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
540 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
541 use rustc::mir::Rvalue::*;
543 let mut visit_op = |op: &mir::Operand<'_>| match op {
544 mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
549 Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
550 Aggregate(_, ops) => ops.iter().for_each(visit_op),
551 BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
559 /// Result of `PossibleBorrowerVisitor`.
560 struct PossibleBorrower<'a, 'tcx> {
561 /// Mapping `Local -> its possible borrowers`
562 map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
563 maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>,
564 // Caches to avoid allocation of `BitSet` on every query
565 bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
568 impl PossibleBorrower<'_, '_> {
569 /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
570 fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
571 self.maybe_live.seek(at);
573 self.bitset.0.clear();
574 let maybe_live = &mut self.maybe_live;
575 if let Some(bitset) = self.map.get(&borrowed) {
576 for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
577 self.bitset.0.insert(b);
583 self.bitset.1.clear();
585 self.bitset.1.insert(*b);
588 self.bitset.0 == self.bitset.1