1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
14 use crate::rustc::hir;
15 use crate::rustc::hir::*;
16 use crate::rustc::hir::intravisit::FnKind;
17 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
18 use crate::rustc::{declare_tool_lint, lint_array};
19 use if_chain::if_chain;
20 use crate::rustc::ty::TyKind;
21 use crate::rustc::session::config::Config as SessionConfig;
22 use crate::rustc_target::spec::abi::Abi;
23 use crate::rustc_target::abi::LayoutOf;
24 use crate::syntax::ast::NodeId;
25 use crate::syntax_pos::Span;
26 use crate::utils::{in_macro, is_copy, is_self, span_lint_and_sugg, snippet};
28 /// **What it does:** Checks for functions taking arguments by reference, where
29 /// the argument type is `Copy` and small enough to be more efficient to always
32 /// **Why is this bad?** In many calling conventions instances of structs will
33 /// be passed through registers if they fit into two or less general purpose
36 /// **Known problems:** This lint is target register size dependent, it is
37 /// limited to 32-bit to try and reduce portability problems between 32 and
38 /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
39 /// will be different.
41 /// The configuration option `trivial_copy_size_limit` can be set to override
42 /// this limit for a project.
44 /// This lint attempts to allow passing arguments by reference if a reference
45 /// to that argument is returned. This is implemented by comparing the lifetime
46 /// of the argument and return value for equality. However, this can cause
47 /// false positives in cases involving multiple lifetimes that are bounded by
53 /// assert_eq!(v, 42);
57 /// assert_eq!(v, 42);
60 declare_clippy_lint! {
61 pub TRIVIALLY_COPY_PASS_BY_REF,
63 "functions taking small copyable arguments by reference"
66 pub struct TriviallyCopyPassByRef {
70 impl TriviallyCopyPassByRef {
71 pub fn new(limit: Option<u64>, target: &SessionConfig) -> Self {
72 let limit = limit.unwrap_or_else(|| {
73 let bit_width = target.usize_ty.bit_width().expect("usize should have a width") as u64;
74 // Cap the calculated bit width at 32-bits to reduce
75 // portability problems between 32 and 64-bit targets
76 let bit_width = cmp::min(bit_width, 32);
77 let byte_width = bit_width / 8;
78 // Use a limit of 2 times the register bit width
85 impl LintPass for TriviallyCopyPassByRef {
86 fn get_lints(&self) -> LintArray {
87 lint_array![TRIVIALLY_COPY_PASS_BY_REF]
91 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TriviallyCopyPassByRef {
94 cx: &LateContext<'a, 'tcx>,
106 FnKind::ItemFn(.., header, _, attrs) => {
107 if header.abi != Abi::Rust {
111 if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
116 FnKind::Method(..) => (),
120 // Exclude non-inherent impls
121 if let Some(Node::Item(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
122 if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
129 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
131 let fn_sig = cx.tcx.fn_sig(fn_def_id);
132 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
134 // Use lifetimes to determine if we're returning a reference to the
135 // argument. In that case we can't switch to pass-by-value as the
136 // argument will not live long enough.
137 let output_lts = match fn_sig.output().sty {
138 TyKind::Ref(output_lt, _, _) => vec![output_lt],
139 TyKind::Adt(_, substs) => substs.regions().collect(),
143 for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
144 // All spans generated from a proc-macro invocation are the same...
145 if span == input.span {
150 if let TyKind::Ref(input_lt, ty, Mutability::MutImmutable) = ty.sty;
151 if !output_lts.contains(&input_lt);
153 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
154 if size <= self.limit;
155 if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.node;
157 let value_type = if is_self(arg) {
160 snippet(cx, decl_ty.span, "_").into()
164 TRIVIALLY_COPY_PASS_BY_REF,
166 "this argument is passed by reference, but would be more efficient if passed by value",
167 "consider passing by value instead",