1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::match_def_path;
3 use if_chain::if_chain;
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for usage of invalid atomic
13 /// ordering in atomic loads/stores/exchanges/updates and
16 /// ### Why is this bad?
17 /// Using an invalid atomic ordering
18 /// will cause a panic at run-time.
22 /// # use std::sync::atomic::{self, AtomicU8, Ordering};
24 /// let x = AtomicU8::new(0);
26 /// // Bad: `Release` and `AcqRel` cannot be used for `load`.
27 /// let _ = x.load(Ordering::Release);
28 /// let _ = x.load(Ordering::AcqRel);
30 /// // Bad: `Acquire` and `AcqRel` cannot be used for `store`.
31 /// x.store(1, Ordering::Acquire);
32 /// x.store(2, Ordering::AcqRel);
34 /// // Bad: `Relaxed` cannot be used as a fence's ordering.
35 /// atomic::fence(Ordering::Relaxed);
36 /// atomic::compiler_fence(Ordering::Relaxed);
38 /// // Bad: `Release` and `AcqRel` are both always invalid
39 /// // for the failure ordering (the last arg).
40 /// let _ = x.compare_exchange(1, 2, Ordering::SeqCst, Ordering::Release);
41 /// let _ = x.compare_exchange_weak(2, 3, Ordering::AcqRel, Ordering::AcqRel);
43 /// // Bad: The failure ordering is not allowed to be
44 /// // stronger than the success order, and `SeqCst` is
45 /// // stronger than `Relaxed`.
46 /// let _ = x.fetch_update(Ordering::Relaxed, Ordering::SeqCst, |val| Some(val + val));
48 pub INVALID_ATOMIC_ORDERING,
50 "usage of invalid atomic ordering in atomic operations and memory fences"
53 declare_lint_pass!(AtomicOrdering => [INVALID_ATOMIC_ORDERING]);
55 const ATOMIC_TYPES: [&str; 12] = [
70 fn type_is_atomic(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
71 if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.typeck_results().expr_ty(expr).kind() {
74 .any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty]))
80 fn match_ordering_def_path(cx: &LateContext<'_>, did: DefId, orderings: &[&str]) -> bool {
83 .any(|ordering| match_def_path(cx, did, &["core", "sync", "atomic", "Ordering", ordering]))
86 fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
88 if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind;
89 let method = method_path.ident.name.as_str();
90 if type_is_atomic(cx, &args[0]);
91 if method == "load" || method == "store";
92 let ordering_arg = if method == "load" { &args[1] } else { &args[2] };
93 if let ExprKind::Path(ref ordering_qpath) = ordering_arg.kind;
94 if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id();
96 if method == "load" &&
97 match_ordering_def_path(cx, ordering_def_id, &["Release", "AcqRel"]) {
100 INVALID_ATOMIC_ORDERING,
102 "atomic loads cannot have `Release` and `AcqRel` ordering",
104 "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`"
106 } else if method == "store" &&
107 match_ordering_def_path(cx, ordering_def_id, &["Acquire", "AcqRel"]) {
110 INVALID_ATOMIC_ORDERING,
112 "atomic stores cannot have `Acquire` and `AcqRel` ordering",
114 "consider using ordering modes `Release`, `SeqCst` or `Relaxed`"
121 fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) {
123 if let ExprKind::Call(func, args) = expr.kind;
124 if let ExprKind::Path(ref func_qpath) = func.kind;
125 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
126 if ["fence", "compiler_fence"]
128 .any(|func| match_def_path(cx, def_id, &["core", "sync", "atomic", func]));
129 if let ExprKind::Path(ref ordering_qpath) = &args[0].kind;
130 if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, args[0].hir_id).opt_def_id();
131 if match_ordering_def_path(cx, ordering_def_id, &["Relaxed"]);
135 INVALID_ATOMIC_ORDERING,
137 "memory fences cannot have `Relaxed` ordering",
139 "consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`"
145 fn opt_ordering_defid(cx: &LateContext<'_>, ord_arg: &Expr<'_>) -> Option<DefId> {
146 if let ExprKind::Path(ref ord_qpath) = ord_arg.kind {
147 cx.qpath_res(ord_qpath, ord_arg.hir_id).opt_def_id()
153 fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
155 if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind;
156 let method = method_path.ident.name.as_str();
157 if type_is_atomic(cx, &args[0]);
158 if method == "compare_exchange" || method == "compare_exchange_weak" || method == "fetch_update";
159 let (success_order_arg, failure_order_arg) = if method == "fetch_update" {
164 if let Some(fail_ordering_def_id) = opt_ordering_defid(cx, failure_order_arg);
166 // Helper type holding on to some checking and error reporting data. Has
167 // - (success ordering name,
168 // - list of failure orderings forbidden by the success order,
169 // - suggestion message)
170 type OrdLintInfo = (&'static str, &'static [&'static str], &'static str);
171 let relaxed: OrdLintInfo = ("Relaxed", &["SeqCst", "Acquire"], "ordering mode `Relaxed`");
172 let acquire: OrdLintInfo = ("Acquire", &["SeqCst"], "ordering modes `Acquire` or `Relaxed`");
173 let seq_cst: OrdLintInfo = ("SeqCst", &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`");
174 let release = ("Release", relaxed.1, relaxed.2);
175 let acqrel = ("AcqRel", acquire.1, acquire.2);
176 let search = [relaxed, acquire, seq_cst, release, acqrel];
178 let success_lint_info = opt_ordering_defid(cx, success_order_arg)
179 .and_then(|success_ord_def_id| -> Option<OrdLintInfo> {
182 .find(|(ordering, ..)| {
183 match_def_path(cx, success_ord_def_id,
184 &["core", "sync", "atomic", "Ordering", ordering])
189 if match_ordering_def_path(cx, fail_ordering_def_id, &["Release", "AcqRel"]) {
190 // If we don't know the success order is, use what we'd suggest
191 // if it were maximally permissive.
192 let suggested = success_lint_info.unwrap_or(seq_cst).2;
195 INVALID_ATOMIC_ORDERING,
196 failure_order_arg.span,
198 "{}'s failure ordering may not be `Release` or `AcqRel`",
202 &format!("consider using {} instead", suggested),
204 } else if let Some((success_ord_name, bad_ords_given_success, suggested)) = success_lint_info {
205 if match_ordering_def_path(cx, fail_ordering_def_id, bad_ords_given_success) {
208 INVALID_ATOMIC_ORDERING,
209 failure_order_arg.span,
211 "{}'s failure ordering may not be stronger than the success ordering of `{}`",
216 &format!("consider using {} instead", suggested),
224 impl<'tcx> LateLintPass<'tcx> for AtomicOrdering {
225 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
226 check_atomic_load_store(cx, expr);
227 check_memory_fence(cx, expr);
228 check_atomic_compare_exchange(cx, expr);