Skip to content

Commit 7547a4d

Browse files
committed
New Lint: Pass small trivially copyable objects by value
Fixes #1680 Hardcoded for 64-bit "trivial" size for now
1 parent 0c23112 commit 7547a4d

14 files changed

+269
-9
lines changed

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ pub mod suspicious_trait_impl;
196196
pub mod swap;
197197
pub mod temporary_assignment;
198198
pub mod transmute;
199+
pub mod trivially_copy_pass_by_ref;
199200
pub mod types;
200201
pub mod unicode;
201202
pub mod unsafe_removed_from_name;
@@ -399,6 +400,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
399400
reg.register_late_lint_pass(box large_enum_variant::LargeEnumVariant::new(conf.enum_variant_size_threshold));
400401
reg.register_late_lint_pass(box explicit_write::Pass);
401402
reg.register_late_lint_pass(box needless_pass_by_value::NeedlessPassByValue);
403+
reg.register_late_lint_pass(box trivially_copy_pass_by_ref::TriviallyCopyPassByRef);
402404
reg.register_early_lint_pass(box literal_representation::LiteralDigitGrouping);
403405
reg.register_early_lint_pass(box literal_representation::LiteralRepresentation::new(
404406
conf.literal_representation_threshold
@@ -672,6 +674,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
672674
transmute::TRANSMUTE_PTR_TO_REF,
673675
transmute::USELESS_TRANSMUTE,
674676
transmute::WRONG_TRANSMUTE,
677+
trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF,
675678
types::ABSURD_EXTREME_COMPARISONS,
676679
types::BORROWED_BOX,
677680
types::BOX_VEC,
@@ -916,6 +919,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
916919
methods::SINGLE_CHAR_PATTERN,
917920
misc::CMP_OWNED,
918921
mutex_atomic::MUTEX_ATOMIC,
922+
trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF,
919923
types::BOX_VEC,
920924
vec::USELESS_VEC,
921925
]);
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
use rustc::hir::*;
2+
use rustc::hir::map::*;
3+
use rustc::hir::intravisit::FnKind;
4+
use rustc::lint::*;
5+
use rustc::ty::TypeVariants;
6+
use rustc_target::spec::abi::Abi;
7+
use rustc_target::abi::LayoutOf;
8+
use syntax::ast::NodeId;
9+
use syntax_pos::Span;
10+
use crate::utils::{in_macro, is_copy, is_self, span_lint_and_sugg, snippet};
11+
12+
/// **What it does:** Checks for functions taking arguments by reference, where
13+
/// the argument type is `Copy` and small enough to be more efficient to always
14+
/// pass by value.
15+
///
16+
/// **Why is this bad?** In many calling conventions instances of structs will
17+
/// be passed through registers if they fit into two or less general purpose
18+
/// registers.
19+
///
20+
/// **Example:**
21+
/// ```rust
22+
/// fn foo(v: &u32) {
23+
/// assert_eq!(v, 42);
24+
/// }
25+
/// // should be
26+
/// fn foo(v: u32) {
27+
/// assert_eq!(v, 42);
28+
/// }
29+
/// ```
30+
declare_clippy_lint! {
31+
pub TRIVIALLY_COPY_PASS_BY_REF,
32+
perf,
33+
"functions taking small copyable arguments by reference"
34+
}
35+
36+
pub struct TriviallyCopyPassByRef;
37+
38+
impl LintPass for TriviallyCopyPassByRef {
39+
fn get_lints(&self) -> LintArray {
40+
lint_array![TRIVIALLY_COPY_PASS_BY_REF]
41+
}
42+
}
43+
44+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef {
45+
fn check_fn(
46+
&mut self,
47+
cx: &LateContext<'a, 'tcx>,
48+
kind: FnKind<'tcx>,
49+
decl: &'tcx FnDecl,
50+
body: &'tcx Body,
51+
span: Span,
52+
node_id: NodeId,
53+
) {
54+
if in_macro(span) {
55+
return;
56+
}
57+
58+
match kind {
59+
FnKind::ItemFn(.., abi, _, attrs) => {
60+
if abi != Abi::Rust {
61+
return;
62+
}
63+
for a in attrs {
64+
if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
65+
return;
66+
}
67+
}
68+
},
69+
FnKind::Method(..) => (),
70+
_ => return,
71+
}
72+
73+
// Exclude non-inherent impls
74+
if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
75+
if matches!(item.node, ItemImpl(_, _, _, _, Some(_), _, _) |
76+
ItemTrait(..))
77+
{
78+
return;
79+
}
80+
}
81+
82+
let fn_def_id = cx.tcx.hir.local_def_id(node_id);
83+
84+
let fn_sig = cx.tcx.fn_sig(fn_def_id);
85+
let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
86+
87+
for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
88+
// All spans generated from a proc-macro invocation are the same...
89+
if span == input.span {
90+
return;
91+
}
92+
93+
if_chain! {
94+
if let TypeVariants::TyRef(_, ty, Mutability::MutImmutable) = ty.sty;
95+
if is_copy(cx, ty);
96+
if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
97+
if size < 16;
98+
if let Ty_::TyRptr(_, MutTy { ty: ref decl_ty, .. }) = input.node;
99+
then {
100+
let value_type = if is_self(arg) {
101+
"self".into()
102+
} else {
103+
snippet(cx, decl_ty.span, "_").into()
104+
};
105+
span_lint_and_sugg(
106+
cx,
107+
TRIVIALLY_COPY_PASS_BY_REF,
108+
input.span,
109+
"this argument is passed by reference, but would be more efficient if passed by value",
110+
"consider passing by value instead",
111+
value_type);
112+
}
113+
}
114+
}
115+
}
116+
}

tests/ui/clone_on_copy_mut.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ pub fn dec_read_dec(i: &mut i32) -> i32 {
55
ret
66
}
77

8+
#[allow(trivially_copy_pass_by_ref)]
89
pub fn minus_1(i: &i32) -> i32 {
910
dec_read_dec(&mut i.clone())
1011
}

tests/ui/eta.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22

3-
#![allow(unknown_lints, unused, no_effect, redundant_closure_call, many_single_char_names, needless_pass_by_value, option_map_unit_fn)]
3+
#![allow(unknown_lints, unused, no_effect, redundant_closure_call, many_single_char_names, needless_pass_by_value, option_map_unit_fn, trivially_copy_pass_by_ref)]
44
#![warn(redundant_closure, needless_borrow)]
55

66
fn main() {

tests/ui/infinite_iter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![feature(iterator_for_each)]
22

33
use std::iter::repeat;
4-
4+
#[allow(trivially_copy_pass_by_ref)]
55
fn square_is_lower_64(x: &u32) -> bool { x * x < 64 }
66

77
#[allow(maybe_infinite_iter)]

tests/ui/infinite_loop.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
1+
#![allow(trivially_copy_pass_by_ref)]
22

33

44
fn fn_val(i: i32) -> i32 { unimplemented!() }

tests/ui/lifetimes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33

44
#![warn(needless_lifetimes, extra_unused_lifetimes)]
5-
#![allow(dead_code, needless_pass_by_value)]
5+
#![allow(dead_code, needless_pass_by_value, trivially_copy_pass_by_ref)]
66

77
fn distinct_lifetimes<'a, 'b>(_x: &'a u8, _y: &'b u8, _z: u8) { }
88

tests/ui/mut_from_ref.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22

3-
#![allow(unused)]
3+
#![allow(unused, trivially_copy_pass_by_ref)]
44
#![warn(mut_from_ref)]
55

66
struct Foo;

tests/ui/mut_reference.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22

33

4-
#![allow(unused_variables)]
4+
#![allow(unused_variables, trivially_copy_pass_by_ref)]
55

66
fn takes_an_immutable_reference(a: &i32) {}
77
fn takes_a_mutable_reference(a: &mut i32) {}

tests/ui/needless_borrow.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::borrow::Cow;
22

3-
3+
#[allow(trivially_copy_pass_by_ref)]
44
fn x(y: &i32) -> i32 {
55
*y
66
}

0 commit comments

Comments
 (0)