1 use crate::utils::{match_def_path, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_hir::def_id::DefId;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// **What it does:** Checks for usage of invalid atomic
11 /// ordering in atomic loads/stores/exchanges/updates and
14 /// **Why is this bad?** Using an invalid atomic ordering
15 /// will cause a panic at run-time.
17 /// **Known problems:** None.
21 /// # use std::sync::atomic::{self, AtomicU8, Ordering};
23 /// let x = AtomicU8::new(0);
25 /// // Bad: `Release` and `AcqRel` cannot be used for `load`.
26 /// let _ = x.load(Ordering::Release);
27 /// let _ = x.load(Ordering::AcqRel);
29 /// // Bad: `Acquire` and `AcqRel` cannot be used for `store`.
30 /// x.store(1, Ordering::Acquire);
31 /// x.store(2, Ordering::AcqRel);
33 /// // Bad: `Relaxed` cannot be used as a fence's ordering.
34 /// atomic::fence(Ordering::Relaxed);
35 /// atomic::compiler_fence(Ordering::Relaxed);
37 /// // Bad: `Release` and `AcqRel` are both always invalid
38 /// // for the failure ordering (the last arg).
39 /// let _ = x.compare_exchange(1, 2, Ordering::SeqCst, Ordering::Release);
40 /// let _ = x.compare_exchange_weak(2, 3, Ordering::AcqRel, Ordering::AcqRel);
42 /// // Bad: The failure ordering is not allowed to be
43 /// // stronger than the success order, and `SeqCst` is
44 /// // stronger than `Relaxed`.
45 /// let _ = x.fetch_update(Ordering::Relaxed, Ordering::SeqCst, |val| Some(val + val));
47 pub INVALID_ATOMIC_ORDERING,
49 "usage of invalid atomic ordering in atomic operations and memory fences"
52 declare_lint_pass!(AtomicOrdering => [INVALID_ATOMIC_ORDERING]);
54 const ATOMIC_TYPES: [&str; 12] = [
69 fn type_is_atomic(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
70 if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.typeck_results().expr_ty(expr).kind() {
73 .any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty]))
79 fn match_ordering_def_path(cx: &LateContext<'_>, did: DefId, orderings: &[&str]) -> bool {
82 .any(|ordering| match_def_path(cx, did, &["core", "sync", "atomic", "Ordering", ordering]))
85 fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
87 if let ExprKind::MethodCall(ref method_path, _, args, _) = &expr.kind;
88 let method = method_path.ident.name.as_str();
89 if type_is_atomic(cx, &args[0]);
90 if method == "load" || method == "store";
91 let ordering_arg = if method == "load" { &args[1] } else { &args[2] };
92 if let ExprKind::Path(ref ordering_qpath) = ordering_arg.kind;
93 if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id();
95 if method == "load" &&
96 match_ordering_def_path(cx, ordering_def_id, &["Release", "AcqRel"]) {
99 INVALID_ATOMIC_ORDERING,
101 "atomic loads cannot have `Release` and `AcqRel` ordering",
103 "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`"
105 } else if method == "store" &&
106 match_ordering_def_path(cx, ordering_def_id, &["Acquire", "AcqRel"]) {
109 INVALID_ATOMIC_ORDERING,
111 "atomic stores cannot have `Acquire` and `AcqRel` ordering",
113 "consider using ordering modes `Release`, `SeqCst` or `Relaxed`"
120 fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) {
122 if let ExprKind::Call(ref func, ref args) = expr.kind;
123 if let ExprKind::Path(ref func_qpath) = func.kind;
124 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
125 if ["fence", "compiler_fence"]
127 .any(|func| match_def_path(cx, def_id, &["core", "sync", "atomic", func]));
128 if let ExprKind::Path(ref ordering_qpath) = &args[0].kind;
129 if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, args[0].hir_id).opt_def_id();
130 if match_ordering_def_path(cx, ordering_def_id, &["Relaxed"]);
134 INVALID_ATOMIC_ORDERING,
136 "memory fences cannot have `Relaxed` ordering",
138 "consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`"
144 fn opt_ordering_defid(cx: &LateContext<'_>, ord_arg: &Expr<'_>) -> Option<DefId> {
145 if let ExprKind::Path(ref ord_qpath) = ord_arg.kind {
146 cx.qpath_res(ord_qpath, ord_arg.hir_id).opt_def_id()
152 fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
154 if let ExprKind::MethodCall(ref method_path, _, args, _) = &expr.kind;
155 let method = method_path.ident.name.as_str();
156 if type_is_atomic(cx, &args[0]);
157 if method == "compare_exchange" || method == "compare_exchange_weak" || method == "fetch_update";
158 let (success_order_arg, failure_order_arg) = if method == "fetch_update" {
163 if let Some(fail_ordering_def_id) = opt_ordering_defid(cx, failure_order_arg);
165 // Helper type holding on to some checking and error reporting data. Has
166 // - (success ordering name,
167 // - list of failure orderings forbidden by the success order,
168 // - suggestion message)
169 type OrdLintInfo = (&'static str, &'static [&'static str], &'static str);
170 let relaxed: OrdLintInfo = ("Relaxed", &["SeqCst", "Acquire"], "ordering mode `Relaxed`");
171 let acquire: OrdLintInfo = ("Acquire", &["SeqCst"], "ordering modes `Acquire` or `Relaxed`");
172 let seq_cst: OrdLintInfo = ("SeqCst", &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`");
173 let release = ("Release", relaxed.1, relaxed.2);
174 let acqrel = ("AcqRel", acquire.1, acquire.2);
175 let search = [relaxed, acquire, seq_cst, release, acqrel];
177 let success_lint_info = opt_ordering_defid(cx, success_order_arg)
178 .and_then(|success_ord_def_id| -> Option<OrdLintInfo> {
181 .find(|(ordering, ..)| {
182 match_def_path(cx, success_ord_def_id,
183 &["core", "sync", "atomic", "Ordering", ordering])
188 if match_ordering_def_path(cx, fail_ordering_def_id, &["Release", "AcqRel"]) {
189 // If we don't know the success order is, use what we'd suggest
190 // if it were maximally permissive.
191 let suggested = success_lint_info.unwrap_or(seq_cst).2;
194 INVALID_ATOMIC_ORDERING,
195 failure_order_arg.span,
197 "{}'s failure ordering may not be `Release` or `AcqRel`",
201 &format!("consider using {} instead", suggested),
203 } else if let Some((success_ord_name, bad_ords_given_success, suggested)) = success_lint_info {
204 if match_ordering_def_path(cx, fail_ordering_def_id, bad_ords_given_success) {
207 INVALID_ATOMIC_ORDERING,
208 failure_order_arg.span,
210 "{}'s failure ordering may not be stronger than the success ordering of `{}`",
215 &format!("consider using {} instead", suggested),
223 impl<'tcx> LateLintPass<'tcx> for AtomicOrdering {
224 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
225 check_atomic_load_store(cx, expr);
226 check_memory_fence(cx, expr);
227 check_atomic_compare_exchange(cx, expr);