Skip to main content

rustc_lint/
types.rs

1use std::iter;
2
3use rustc_abi::{BackendRepr, TagEncoding, Variants, WrappingRange};
4use rustc_ast as ast;
5use rustc_hir as hir;
6use rustc_hir::{Expr, ExprKind, HirId, LangItem, find_attr};
7use rustc_middle::bug;
8use rustc_middle::ty::layout::{LayoutOf, SizeSkeleton};
9use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
10use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
11use rustc_span::{DUMMY_SP, Span, Symbol, sym};
12use tracing::debug;
13
14mod improper_ctypes; // these files do the implementation for ImproperCTypesDefinitions,ImproperCTypesDeclarations
15pub(crate) use improper_ctypes::ImproperCTypesLint;
16
17use crate::lints::{
18    AmbiguousWidePointerComparisons, AmbiguousWidePointerComparisonsAddrMetadataSuggestion,
19    AmbiguousWidePointerComparisonsAddrSuggestion, AmbiguousWidePointerComparisonsCastSuggestion,
20    AmbiguousWidePointerComparisonsExpectSuggestion, AtomicOrderingFence, AtomicOrderingLoad,
21    AtomicOrderingStore, InvalidAtomicOrderingDiag, InvalidNanComparisons,
22    InvalidNanComparisonsSuggestion, UnpredictableFunctionPointerComparisons,
23    UnpredictableFunctionPointerComparisonsSuggestion, UnusedComparisons,
24    VariantSizeDifferencesDiag,
25};
26use crate::{LateContext, LateLintPass, LintContext};
27
28mod literal;
29use literal::{int_ty_range, lint_literal, uint_ty_range};
30
31#[doc = r" The `unused_comparisons` lint detects comparisons made useless by"]
#[doc = r" limits of the types involved."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn foo(x: u8) {"]
#[doc = r"     x >= 0;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" A useless comparison may indicate a mistake, and should be fixed or"]
#[doc = r" removed."]
static UNUSED_COMPARISONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNUSED_COMPARISONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "comparisons made useless by limits of the types involved",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
32    /// The `unused_comparisons` lint detects comparisons made useless by
33    /// limits of the types involved.
34    ///
35    /// ### Example
36    ///
37    /// ```rust
38    /// fn foo(x: u8) {
39    ///     x >= 0;
40    /// }
41    /// ```
42    ///
43    /// {{produces}}
44    ///
45    /// ### Explanation
46    ///
47    /// A useless comparison may indicate a mistake, and should be fixed or
48    /// removed.
49    UNUSED_COMPARISONS,
50    Warn,
51    "comparisons made useless by limits of the types involved"
52}
53
54#[doc =
r" The `overflowing_literals` lint detects literals out of range for their type."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" let x: u8 = 1000;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" It is usually a mistake to use a literal that overflows its type"]
#[doc = r" Change either the literal or its type such that the literal is"]
#[doc = r" within the range of its type."]
static OVERFLOWING_LITERALS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "OVERFLOWING_LITERALS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "literal out of range for its type",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
55    /// The `overflowing_literals` lint detects literals out of range for their type.
56    ///
57    /// ### Example
58    ///
59    /// ```rust,compile_fail
60    /// let x: u8 = 1000;
61    /// ```
62    ///
63    /// {{produces}}
64    ///
65    /// ### Explanation
66    ///
67    /// It is usually a mistake to use a literal that overflows its type
68    /// Change either the literal or its type such that the literal is
69    /// within the range of its type.
70    OVERFLOWING_LITERALS,
71    Deny,
72    "literal out of range for its type"
73}
74
75#[doc =
r" The `variant_size_differences` lint detects enums with widely varying"]
#[doc = r" variant sizes."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(variant_size_differences)]"]
#[doc = r" enum En {"]
#[doc = r"     V0(u8),"]
#[doc = r"     VBig([u8; 1024]),"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" It can be a mistake to add a variant to an enum that is much larger"]
#[doc =
r" than the other variants, bloating the overall size required for all"]
#[doc = r" variants. This can impact performance and memory usage. This is"]
#[doc = r" triggered if one variant is more than 3 times larger than the"]
#[doc = r" second-largest variant."]
#[doc = r""]
#[doc =
r" Consider placing the large variant's contents on the heap (for example"]
#[doc = r" via [`Box`]) to keep the overall size of the enum itself down."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and may not be"#]
#[doc = r" an actual problem. Decisions about this should be guided with"]
#[doc = r" profiling and benchmarking."]
#[doc = r""]
#[doc = r" [`Box`]: https://doc.rust-lang.org/std/boxed/index.html"]
static VARIANT_SIZE_DIFFERENCES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "VARIANT_SIZE_DIFFERENCES",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects enums with widely varying variant sizes",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
76    /// The `variant_size_differences` lint detects enums with widely varying
77    /// variant sizes.
78    ///
79    /// ### Example
80    ///
81    /// ```rust,compile_fail
82    /// #![deny(variant_size_differences)]
83    /// enum En {
84    ///     V0(u8),
85    ///     VBig([u8; 1024]),
86    /// }
87    /// ```
88    ///
89    /// {{produces}}
90    ///
91    /// ### Explanation
92    ///
93    /// It can be a mistake to add a variant to an enum that is much larger
94    /// than the other variants, bloating the overall size required for all
95    /// variants. This can impact performance and memory usage. This is
96    /// triggered if one variant is more than 3 times larger than the
97    /// second-largest variant.
98    ///
99    /// Consider placing the large variant's contents on the heap (for example
100    /// via [`Box`]) to keep the overall size of the enum itself down.
101    ///
102    /// This lint is "allow" by default because it can be noisy, and may not be
103    /// an actual problem. Decisions about this should be guided with
104    /// profiling and benchmarking.
105    ///
106    /// [`Box`]: https://doc.rust-lang.org/std/boxed/index.html
107    VARIANT_SIZE_DIFFERENCES,
108    Allow,
109    "detects enums with widely varying variant sizes"
110}
111
112#[doc =
r" The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN`"]
#[doc = r" as one of the operand."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" let a = 2.3f32;"]
#[doc = r" if a == f32::NAN {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" NaN does not compare meaningfully to anything – not"]
#[doc = r" even itself – so those comparisons are always false."]
static INVALID_NAN_COMPARISONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INVALID_NAN_COMPARISONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects invalid floating point NaN comparisons",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
113    /// The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN`
114    /// as one of the operand.
115    ///
116    /// ### Example
117    ///
118    /// ```rust
119    /// let a = 2.3f32;
120    /// if a == f32::NAN {}
121    /// ```
122    ///
123    /// {{produces}}
124    ///
125    /// ### Explanation
126    ///
127    /// NaN does not compare meaningfully to anything – not
128    /// even itself – so those comparisons are always false.
129    INVALID_NAN_COMPARISONS,
130    Warn,
131    "detects invalid floating point NaN comparisons"
132}
133
134#[doc = r" The `ambiguous_wide_pointer_comparisons` lint checks comparison"]
#[doc = r" of `*const/*mut ?Sized` as the operands."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" # struct A;"]
#[doc = r" # struct B;"]
#[doc = r""]
#[doc = r" # trait T {}"]
#[doc = r" # impl T for A {}"]
#[doc = r" # impl T for B {}"]
#[doc = r""]
#[doc = r" let ab = (A, B);"]
#[doc = r" let a = &ab.0 as *const dyn T;"]
#[doc = r" let b = &ab.1 as *const dyn T;"]
#[doc = r""]
#[doc = r" let _ = a == b;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The comparison includes metadata which may not be expected."]
static AMBIGUOUS_WIDE_POINTER_COMPARISONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "AMBIGUOUS_WIDE_POINTER_COMPARISONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects ambiguous wide pointer comparisons",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
135    /// The `ambiguous_wide_pointer_comparisons` lint checks comparison
136    /// of `*const/*mut ?Sized` as the operands.
137    ///
138    /// ### Example
139    ///
140    /// ```rust
141    /// # struct A;
142    /// # struct B;
143    ///
144    /// # trait T {}
145    /// # impl T for A {}
146    /// # impl T for B {}
147    ///
148    /// let ab = (A, B);
149    /// let a = &ab.0 as *const dyn T;
150    /// let b = &ab.1 as *const dyn T;
151    ///
152    /// let _ = a == b;
153    /// ```
154    ///
155    /// {{produces}}
156    ///
157    /// ### Explanation
158    ///
159    /// The comparison includes metadata which may not be expected.
160    AMBIGUOUS_WIDE_POINTER_COMPARISONS,
161    Warn,
162    "detects ambiguous wide pointer comparisons"
163}
164
165#[doc =
r" The `unpredictable_function_pointer_comparisons` lint checks comparison"]
#[doc = r" of function pointer as the operands."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn a() {}"]
#[doc = r" fn b() {}"]
#[doc = r""]
#[doc = r" let f: fn() = a;"]
#[doc = r" let g: fn() = b;"]
#[doc = r""]
#[doc = r" let _ = f == g;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Function pointers comparisons do not produce meaningful result since"]
#[doc =
r" they are never guaranteed to be unique and could vary between different"]
#[doc =
r" code generation units. Furthermore, different functions could have the"]
#[doc = r" same address after being merged together."]
static UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects unpredictable function pointer comparisons",
            is_externally_loaded: false,
            report_in_external_macro: true,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
166    /// The `unpredictable_function_pointer_comparisons` lint checks comparison
167    /// of function pointer as the operands.
168    ///
169    /// ### Example
170    ///
171    /// ```rust
172    /// fn a() {}
173    /// fn b() {}
174    ///
175    /// let f: fn() = a;
176    /// let g: fn() = b;
177    ///
178    /// let _ = f == g;
179    /// ```
180    ///
181    /// {{produces}}
182    ///
183    /// ### Explanation
184    ///
185    /// Function pointers comparisons do not produce meaningful result since
186    /// they are never guaranteed to be unique and could vary between different
187    /// code generation units. Furthermore, different functions could have the
188    /// same address after being merged together.
189    UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
190    Warn,
191    "detects unpredictable function pointer comparisons",
192    report_in_external_macro
193}
194
195#[derive(#[automatically_derived]
impl ::core::marker::Copy for TypeLimits { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TypeLimits {
    #[inline]
    fn clone(&self) -> TypeLimits {
        let _: ::core::clone::AssertParamIsClone<Option<NegationInfo>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::default::Default for TypeLimits {
    #[inline]
    fn default() -> TypeLimits {
        TypeLimits {
            last_visited_negation: ::core::default::Default::default(),
        }
    }
}Default)]
196pub(crate) struct TypeLimits {
197    last_visited_negation: Option<NegationInfo>,
198}
199
200#[derive(#[automatically_derived]
impl ::core::marker::Copy for NegationInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NegationInfo {
    #[inline]
    fn clone(&self) -> NegationInfo {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<hir::HirId>;
        *self
    }
}Clone)]
201struct NegationInfo {
202    /// A negation expression (a `rustc_hir::ExprKind::Unary`)
203    negation_span: Span,
204    /// The operand of the negation expression.
205    negated_id: hir::HirId,
206}
207
208impl ::rustc_lint_defs::LintPass for TypeLimits {
    fn name(&self) -> &'static str { "TypeLimits" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
                        INVALID_NAN_COMPARISONS, AMBIGUOUS_WIDE_POINTER_COMPARISONS,
                        UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS]))
    }
}
impl TypeLimits {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
                        INVALID_NAN_COMPARISONS, AMBIGUOUS_WIDE_POINTER_COMPARISONS,
                        UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS]))
    }
}impl_lint_pass!(TypeLimits => [
209    UNUSED_COMPARISONS,
210    OVERFLOWING_LITERALS,
211    INVALID_NAN_COMPARISONS,
212    AMBIGUOUS_WIDE_POINTER_COMPARISONS,
213    UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS
214]);
215
216impl TypeLimits {
217    pub(crate) fn new() -> TypeLimits {
218        TypeLimits { last_visited_negation: None }
219    }
220}
221
222fn lint_nan<'tcx>(
223    cx: &LateContext<'tcx>,
224    e: &'tcx hir::Expr<'tcx>,
225    binop: hir::BinOpKind,
226    l: &'tcx hir::Expr<'tcx>,
227    r: &'tcx hir::Expr<'tcx>,
228) {
229    fn is_nan(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
230        let expr = expr.peel_blocks().peel_borrows();
231        match expr.kind {
232            ExprKind::Path(qpath) => {
233                let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id()
234                else {
235                    return false;
236                };
237
238                #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
    {
    Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan) => true,
    _ => false,
}matches!(
239                    cx.tcx.get_diagnostic_name(def_id),
240                    Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan)
241                )
242            }
243            _ => false,
244        }
245    }
246
247    fn eq_ne(
248        e: &hir::Expr<'_>,
249        l: &hir::Expr<'_>,
250        r: &hir::Expr<'_>,
251        f: impl FnOnce(Span, Span) -> InvalidNanComparisonsSuggestion,
252    ) -> InvalidNanComparisons {
253        let suggestion = if let Some(l_span) = l.span.find_ancestor_inside(e.span)
254            && let Some(r_span) = r.span.find_ancestor_inside(e.span)
255        {
256            f(l_span, r_span)
257        } else {
258            InvalidNanComparisonsSuggestion::Spanless
259        };
260
261        InvalidNanComparisons::EqNe { suggestion }
262    }
263
264    let lint = match binop {
265        hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, l) => {
266            eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
267                nan_plus_binop: l_span.until(r_span),
268                float: r_span.shrink_to_hi(),
269                neg: (binop == hir::BinOpKind::Ne).then(|| r_span.shrink_to_lo()),
270            })
271        }
272        hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, r) => {
273            eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
274                nan_plus_binop: l_span.shrink_to_hi().to(r_span),
275                float: l_span.shrink_to_hi(),
276                neg: (binop == hir::BinOpKind::Ne).then(|| l_span.shrink_to_lo()),
277            })
278        }
279        hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Gt | hir::BinOpKind::Ge
280            if is_nan(cx, l) || is_nan(cx, r) =>
281        {
282            InvalidNanComparisons::LtLeGtGe
283        }
284        _ => return,
285    };
286
287    cx.emit_span_lint(INVALID_NAN_COMPARISONS, e.span, lint);
288}
289
290#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComparisonOp {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ComparisonOp::BinOp(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "BinOp",
                    &__self_0),
            ComparisonOp::Other =>
                ::core::fmt::Formatter::write_str(f, "Other"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ComparisonOp {
    #[inline]
    fn eq(&self, other: &ComparisonOp) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ComparisonOp::BinOp(__self_0), ComparisonOp::BinOp(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::marker::Copy for ComparisonOp { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ComparisonOp {
    #[inline]
    fn clone(&self) -> ComparisonOp {
        let _: ::core::clone::AssertParamIsClone<hir::BinOpKind>;
        *self
    }
}Clone)]
291enum ComparisonOp {
292    BinOp(hir::BinOpKind),
293    Other,
294}
295
296fn lint_wide_pointer<'tcx>(
297    cx: &LateContext<'tcx>,
298    e: &'tcx hir::Expr<'tcx>,
299    cmpop: ComparisonOp,
300    l: &'tcx hir::Expr<'tcx>,
301    r: &'tcx hir::Expr<'tcx>,
302) {
303    let ptr_unsized = |mut ty: Ty<'tcx>| -> Option<(
304        /* number of refs */ usize,
305        /* modifiers */ String,
306        /* is dyn */ bool,
307    )> {
308        let mut refs = 0;
309        // here we remove any "implicit" references and count the number
310        // of them to correctly suggest the right number of deref
311        while let ty::Ref(_, inner_ty, _) = ty.kind() {
312            ty = *inner_ty;
313            refs += 1;
314        }
315
316        // get the inner type of a pointer (or akin)
317        let mut modifiers = String::new();
318        ty = match ty.kind() {
319            ty::RawPtr(ty, _) => *ty,
320            ty::Adt(def, args) if cx.tcx.is_diagnostic_item(sym::NonNull, def.did()) => {
321                modifiers.push_str(".as_ptr()");
322                args.type_at(0)
323            }
324            _ => return None,
325        };
326
327        (!ty.is_sized(cx.tcx, cx.typing_env()))
328            .then(|| (refs, modifiers, #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Dynamic(_, _) => true,
    _ => false,
}matches!(ty.kind(), ty::Dynamic(_, _))))
329    };
330
331    // the left and right operands can have references, remove any explicit references
332    let l = l.peel_borrows();
333    let r = r.peel_borrows();
334
335    let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else {
336        return;
337    };
338    let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else {
339        return;
340    };
341
342    let Some((l_ty_refs, l_modifiers, l_inner_ty_is_dyn)) = ptr_unsized(l_ty) else {
343        return;
344    };
345    let Some((r_ty_refs, r_modifiers, r_inner_ty_is_dyn)) = ptr_unsized(r_ty) else {
346        return;
347    };
348
349    let (Some(l_span), Some(r_span)) =
350        (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
351    else {
352        return cx.emit_span_lint(
353            AMBIGUOUS_WIDE_POINTER_COMPARISONS,
354            e.span,
355            AmbiguousWidePointerComparisons::Spanless,
356        );
357    };
358
359    let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
360    let is_eq_ne = #[allow(non_exhaustive_omitted_patterns)] match cmpop {
    ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne) => true,
    _ => false,
}matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne));
361    let is_dyn_comparison = l_inner_ty_is_dyn && r_inner_ty_is_dyn;
362    let via_method_call = #[allow(non_exhaustive_omitted_patterns)] match &e.kind {
    ExprKind::MethodCall(..) | ExprKind::Call(..) => true,
    _ => false,
}matches!(&e.kind, ExprKind::MethodCall(..) | ExprKind::Call(..));
363
364    let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
365    let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
366    let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
367
368    let deref_left = &*"*".repeat(l_ty_refs);
369    let deref_right = &*"*".repeat(r_ty_refs);
370
371    let l_modifiers = &*l_modifiers;
372    let r_modifiers = &*r_modifiers;
373
374    cx.emit_span_lint(
375        AMBIGUOUS_WIDE_POINTER_COMPARISONS,
376        e.span,
377        if is_eq_ne {
378            AmbiguousWidePointerComparisons::SpanfulEq {
379                addr_metadata_suggestion: (!is_dyn_comparison).then(|| {
380                    AmbiguousWidePointerComparisonsAddrMetadataSuggestion {
381                        ne,
382                        deref_left,
383                        deref_right,
384                        l_modifiers,
385                        r_modifiers,
386                        left,
387                        middle,
388                        right,
389                    }
390                }),
391                addr_suggestion: AmbiguousWidePointerComparisonsAddrSuggestion {
392                    ne,
393                    deref_left,
394                    deref_right,
395                    l_modifiers,
396                    r_modifiers,
397                    left,
398                    middle,
399                    right,
400                },
401            }
402        } else {
403            AmbiguousWidePointerComparisons::SpanfulCmp {
404                cast_suggestion: AmbiguousWidePointerComparisonsCastSuggestion {
405                    deref_left,
406                    deref_right,
407                    l_modifiers,
408                    r_modifiers,
409                    paren_left: if l_ty_refs != 0 { ")" } else { "" },
410                    paren_right: if r_ty_refs != 0 { ")" } else { "" },
411                    left_before: (l_ty_refs != 0).then_some(l_span.shrink_to_lo()),
412                    left_after: l_span.shrink_to_hi(),
413                    right_before: (r_ty_refs != 0).then_some(r_span.shrink_to_lo()),
414                    right_after: r_span.shrink_to_hi(),
415                },
416                expect_suggestion: AmbiguousWidePointerComparisonsExpectSuggestion {
417                    paren_left: if via_method_call { "" } else { "(" },
418                    paren_right: if via_method_call { "" } else { ")" },
419                    before: e.span.shrink_to_lo(),
420                    after: e.span.shrink_to_hi(),
421                },
422            }
423        },
424    );
425}
426
427fn lint_fn_pointer<'tcx>(
428    cx: &LateContext<'tcx>,
429    e: &'tcx hir::Expr<'tcx>,
430    cmpop: ComparisonOp,
431    l: &'tcx hir::Expr<'tcx>,
432    r: &'tcx hir::Expr<'tcx>,
433) {
434    let peel_refs = |mut ty: Ty<'tcx>| -> (Ty<'tcx>, usize) {
435        let mut refs = 0;
436
437        while let ty::Ref(_, inner_ty, _) = ty.kind() {
438            ty = *inner_ty;
439            refs += 1;
440        }
441
442        (ty, refs)
443    };
444
445    // Left and right operands can have borrows, remove them
446    let l = l.peel_borrows();
447    let r = r.peel_borrows();
448
449    let Some(l_ty) = cx.typeck_results().expr_ty_opt(l) else { return };
450    let Some(r_ty) = cx.typeck_results().expr_ty_opt(r) else { return };
451
452    // Remove any references as `==` will deref through them (and count the
453    // number of references removed, for latter).
454    let (l_ty, l_ty_refs) = peel_refs(l_ty);
455    let (r_ty, r_ty_refs) = peel_refs(r_ty);
456
457    if l_ty.is_fn() && r_ty.is_fn() {
458        // both operands are function pointers, fallthrough
459    } else if let ty::Adt(l_def, l_args) = l_ty.kind()
460        && let ty::Adt(r_def, r_args) = r_ty.kind()
461        && cx.tcx.is_lang_item(l_def.did(), LangItem::Option)
462        && cx.tcx.is_lang_item(r_def.did(), LangItem::Option)
463        && let Some(l_some_arg) = l_args.get(0)
464        && let Some(r_some_arg) = r_args.get(0)
465        && l_some_arg.expect_ty().is_fn()
466        && r_some_arg.expect_ty().is_fn()
467    {
468        // both operands are `Option<{function ptr}>`
469        return cx.emit_span_lint(
470            UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
471            e.span,
472            UnpredictableFunctionPointerComparisons::Warn,
473        );
474    } else {
475        // types are not function pointers, nothing to do
476        return;
477    }
478
479    // Let's try to suggest `ptr::fn_addr_eq` if/when possible.
480
481    let is_eq_ne = #[allow(non_exhaustive_omitted_patterns)] match cmpop {
    ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne) => true,
    _ => false,
}matches!(cmpop, ComparisonOp::BinOp(hir::BinOpKind::Eq | hir::BinOpKind::Ne));
482
483    if !is_eq_ne {
484        // Neither `==` nor `!=`, we can't suggest `ptr::fn_addr_eq`, just show the warning.
485        return cx.emit_span_lint(
486            UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
487            e.span,
488            UnpredictableFunctionPointerComparisons::Warn,
489        );
490    }
491
492    let (Some(l_span), Some(r_span)) =
493        (l.span.find_ancestor_inside(e.span), r.span.find_ancestor_inside(e.span))
494    else {
495        // No appropriate spans for the left and right operands, just show the warning.
496        return cx.emit_span_lint(
497            UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
498            e.span,
499            UnpredictableFunctionPointerComparisons::Warn,
500        );
501    };
502
503    let ne = if cmpop == ComparisonOp::BinOp(hir::BinOpKind::Ne) { "!" } else { "" };
504
505    // `ptr::fn_addr_eq` only works with raw pointer, deref any references.
506    let deref_left = &*"*".repeat(l_ty_refs);
507    let deref_right = &*"*".repeat(r_ty_refs);
508
509    let left = e.span.shrink_to_lo().until(l_span.shrink_to_lo());
510    let middle = l_span.shrink_to_hi().until(r_span.shrink_to_lo());
511    let right = r_span.shrink_to_hi().until(e.span.shrink_to_hi());
512
513    let sugg =
514        // We only check for a right cast as `FnDef` == `FnPtr` is not possible,
515        // only `FnPtr == FnDef` is possible.
516        if !r_ty.is_fn_ptr() {
517            let fn_sig = r_ty.fn_sig(cx.tcx);
518
519            UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEqWithCast {
520                ne,
521                fn_sig,
522                deref_left,
523                deref_right,
524                left,
525                middle,
526                right,
527            }
528        } else {
529            UnpredictableFunctionPointerComparisonsSuggestion::FnAddrEq {
530                ne,
531                deref_left,
532                deref_right,
533                left,
534                middle,
535                right,
536            }
537        };
538
539    cx.emit_span_lint(
540        UNPREDICTABLE_FUNCTION_POINTER_COMPARISONS,
541        e.span,
542        UnpredictableFunctionPointerComparisons::Suggestion { sugg },
543    );
544}
545
546impl<'tcx> LateLintPass<'tcx> for TypeLimits {
547    fn check_lit(
548        &mut self,
549        cx: &LateContext<'tcx>,
550        hir_id: HirId,
551        lit: hir::Lit,
552        is_negated_pat: bool,
553    ) {
554        let surrounding_negation = if is_negated_pat {
555            // In this case, lit.span refers to a `rustc_hir::hir::PatExprKind::Lit`,
556            // which includes the minus sign in front.
557            Some(lit.span)
558        } else if let Some(negation_info) = self.last_visited_negation
559            && negation_info.negated_id == hir_id
560        {
561            Some(negation_info.negation_span)
562        } else {
563            None
564        };
565        lint_literal(cx, hir_id, lit.span, &lit, surrounding_negation);
566    }
567
568    fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) {
569        match e.kind {
570            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
571                self.last_visited_negation =
572                    Some(NegationInfo { negation_span: e.span, negated_id: expr.hir_id });
573            }
574            hir::ExprKind::Binary(binop, ref l, ref r) => {
575                if is_comparison(binop.node) {
576                    if !check_limits(cx, binop.node, l, r) {
577                        cx.emit_span_lint(UNUSED_COMPARISONS, e.span, UnusedComparisons);
578                    } else {
579                        lint_nan(cx, e, binop.node, l, r);
580                        let cmpop = ComparisonOp::BinOp(binop.node);
581                        lint_wide_pointer(cx, e, cmpop, l, r);
582                        lint_fn_pointer(cx, e, cmpop, l, r);
583                    }
584                }
585            }
586            hir::ExprKind::Call(path, [l, r])
587                if let ExprKind::Path(ref qpath) = path.kind
588                    && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
589                    && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
590                    && let Some(cmpop) = diag_item_cmpop(diag_item) =>
591            {
592                lint_wide_pointer(cx, e, cmpop, l, r);
593                lint_fn_pointer(cx, e, cmpop, l, r);
594            }
595            hir::ExprKind::MethodCall(_, l, [r], _)
596                if let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
597                    && let Some(diag_item) = cx.tcx.get_diagnostic_name(def_id)
598                    && let Some(cmpop) = diag_item_cmpop(diag_item) =>
599            {
600                lint_wide_pointer(cx, e, cmpop, l, r);
601                lint_fn_pointer(cx, e, cmpop, l, r);
602            }
603            _ => {}
604        };
605
606        fn is_valid<T: PartialOrd>(binop: hir::BinOpKind, v: T, min: T, max: T) -> bool {
607            match binop {
608                hir::BinOpKind::Lt => v > min && v <= max,
609                hir::BinOpKind::Le => v >= min && v < max,
610                hir::BinOpKind::Gt => v >= min && v < max,
611                hir::BinOpKind::Ge => v > min && v <= max,
612                hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max,
613                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
614            }
615        }
616
617        fn rev_binop(binop: hir::BinOpKind) -> hir::BinOpKind {
618            match binop {
619                hir::BinOpKind::Lt => hir::BinOpKind::Gt,
620                hir::BinOpKind::Le => hir::BinOpKind::Ge,
621                hir::BinOpKind::Gt => hir::BinOpKind::Lt,
622                hir::BinOpKind::Ge => hir::BinOpKind::Le,
623                _ => binop,
624            }
625        }
626
627        fn check_limits(
628            cx: &LateContext<'_>,
629            binop: hir::BinOpKind,
630            l: &hir::Expr<'_>,
631            r: &hir::Expr<'_>,
632        ) -> bool {
633            let (lit, expr, swap) = match (&l.kind, &r.kind) {
634                (&hir::ExprKind::Lit(_), _) => (l, r, true),
635                (_, &hir::ExprKind::Lit(_)) => (r, l, false),
636                _ => return true,
637            };
638            // Normalize the binop so that the literal is always on the RHS in
639            // the comparison
640            let norm_binop = if swap { rev_binop(binop) } else { binop };
641            match *cx.typeck_results().node_type(expr.hir_id).kind() {
642                ty::Int(int_ty) => {
643                    let (min, max) = int_ty_range(int_ty);
644                    let lit_val: i128 = match lit.kind {
645                        hir::ExprKind::Lit(li) => match li.node {
646                            ast::LitKind::Int(
647                                v,
648                                ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed,
649                            ) => v.get() as i128,
650                            _ => return true,
651                        },
652                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
653                    };
654                    is_valid(norm_binop, lit_val, min, max)
655                }
656                ty::Uint(uint_ty) => {
657                    let (min, max): (u128, u128) = uint_ty_range(uint_ty);
658                    let lit_val: u128 = match lit.kind {
659                        hir::ExprKind::Lit(li) => match li.node {
660                            ast::LitKind::Int(v, _) => v.get(),
661                            _ => return true,
662                        },
663                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
664                    };
665                    is_valid(norm_binop, lit_val, min, max)
666                }
667                _ => true,
668            }
669        }
670
671        fn is_comparison(binop: hir::BinOpKind) -> bool {
672            #[allow(non_exhaustive_omitted_patterns)] match binop {
    hir::BinOpKind::Eq | hir::BinOpKind::Lt | hir::BinOpKind::Le |
        hir::BinOpKind::Ne | hir::BinOpKind::Ge | hir::BinOpKind::Gt => true,
    _ => false,
}matches!(
673                binop,
674                hir::BinOpKind::Eq
675                    | hir::BinOpKind::Lt
676                    | hir::BinOpKind::Le
677                    | hir::BinOpKind::Ne
678                    | hir::BinOpKind::Ge
679                    | hir::BinOpKind::Gt
680            )
681        }
682
683        fn diag_item_cmpop(diag_item: Symbol) -> Option<ComparisonOp> {
684            Some(match diag_item {
685                sym::cmp_ord_max => ComparisonOp::Other,
686                sym::cmp_ord_min => ComparisonOp::Other,
687                sym::ord_cmp_method => ComparisonOp::Other,
688                sym::cmp_partialeq_eq => ComparisonOp::BinOp(hir::BinOpKind::Eq),
689                sym::cmp_partialeq_ne => ComparisonOp::BinOp(hir::BinOpKind::Ne),
690                sym::cmp_partialord_cmp => ComparisonOp::Other,
691                sym::cmp_partialord_ge => ComparisonOp::BinOp(hir::BinOpKind::Ge),
692                sym::cmp_partialord_gt => ComparisonOp::BinOp(hir::BinOpKind::Gt),
693                sym::cmp_partialord_le => ComparisonOp::BinOp(hir::BinOpKind::Le),
694                sym::cmp_partialord_lt => ComparisonOp::BinOp(hir::BinOpKind::Lt),
695                _ => return None,
696            })
697        }
698    }
699}
700
701pub(crate) fn nonnull_optimization_guaranteed<'tcx>(
702    tcx: TyCtxt<'tcx>,
703    def: ty::AdtDef<'tcx>,
704) -> bool {
705    {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(def.did(), &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_hir::attrs::AttributeKind::*;
                    let i: &::rustc_hir::Attribute = i;
                    match i {
                        ::rustc_hir::Attribute::Parsed(RustcNonnullOptimizationGuaranteed)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def.did(), RustcNonnullOptimizationGuaranteed)
706}
707
708/// `repr(transparent)` structs can have a single non-1-ZST field, this function returns that
709/// field.
710pub(crate) fn transparent_newtype_field<'a, 'tcx>(
711    tcx: TyCtxt<'tcx>,
712    variant: &'a ty::VariantDef,
713) -> Option<&'a ty::FieldDef> {
714    let typing_env = ty::TypingEnv::non_body_analysis(tcx, variant.def_id);
715    variant.fields.iter().find(|field| {
716        let field_ty = tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
717        let is_1zst =
718            tcx.layout_of(typing_env.as_query_input(field_ty)).is_ok_and(|layout| layout.is_1zst());
719        !is_1zst
720    })
721}
722
723/// Is type known to be non-null?
724fn ty_is_known_nonnull<'tcx>(
725    tcx: TyCtxt<'tcx>,
726    typing_env: ty::TypingEnv<'tcx>,
727    ty: Ty<'tcx>,
728) -> bool {
729    let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
730
731    match ty.kind() {
732        ty::FnPtr(..) => true,
733        ty::Ref(..) => true,
734        ty::Adt(def, _) if def.is_box() => true,
735        ty::Adt(def, args) if def.repr().transparent() && !def.is_union() => {
736            let marked_non_null = nonnull_optimization_guaranteed(tcx, *def);
737
738            if marked_non_null {
739                return true;
740            }
741
742            // `UnsafeCell` and `UnsafePinned` have their niche hidden.
743            if def.is_unsafe_cell() || def.is_unsafe_pinned() {
744                return false;
745            }
746
747            def.variants().iter().filter_map(|variant| transparent_newtype_field(tcx, variant)).any(
748                |field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, args).skip_norm_wip()),
749            )
750        }
751        ty::Pat(base, pat) => {
752            ty_is_known_nonnull(tcx, typing_env, *base)
753                || pat_ty_is_known_nonnull(tcx, typing_env, *pat)
754        }
755        _ => false,
756    }
757}
758
759fn pat_ty_is_known_nonnull<'tcx>(
760    tcx: TyCtxt<'tcx>,
761    typing_env: ty::TypingEnv<'tcx>,
762    pat: ty::Pattern<'tcx>,
763) -> bool {
764    try {
765        match *pat {
766            ty::PatternKind::Range { start, end } => {
767                let start = start.try_to_value()?.try_to_bits(tcx, typing_env)?;
768                let end = end.try_to_value()?.try_to_bits(tcx, typing_env)?;
769
770                // This also works for negative numbers, as we just need
771                // to ensure we aren't wrapping over zero.
772                start > 0 && end >= start
773            }
774            ty::PatternKind::NotNull => true,
775            ty::PatternKind::Or(patterns) => {
776                patterns.iter().all(|pat| pat_ty_is_known_nonnull(tcx, typing_env, pat))
777            }
778        }
779    }
780    .unwrap_or_default()
781}
782
783/// Given a non-null scalar (or transparent) type `ty`, return the nullable version of that type.
784/// If the type passed in was not scalar, returns None.
785fn get_nullable_type<'tcx>(
786    tcx: TyCtxt<'tcx>,
787    typing_env: ty::TypingEnv<'tcx>,
788    ty: Ty<'tcx>,
789) -> Option<Ty<'tcx>> {
790    let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
791
792    Some(match *ty.kind() {
793        ty::Adt(field_def, field_args) => {
794            let inner_field_ty = {
795                let mut first_non_zst_ty =
796                    field_def.variants().iter().filter_map(|v| transparent_newtype_field(tcx, v));
797                if true {
    {
        match (&first_non_zst_ty.clone().count(), &1) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("Wrong number of fields for transparent type")));
                }
            }
        }
    };
};debug_assert_eq!(
798                    first_non_zst_ty.clone().count(),
799                    1,
800                    "Wrong number of fields for transparent type"
801                );
802                first_non_zst_ty
803                    .next_back()
804                    .expect("No non-zst fields in transparent type.")
805                    .ty(tcx, field_args)
806                    .skip_norm_wip()
807            };
808            return get_nullable_type(tcx, typing_env, inner_field_ty);
809        }
810        ty::Pat(base, ..) => return get_nullable_type(tcx, typing_env, base),
811        ty::Int(_) | ty::Uint(_) | ty::Char | ty::RawPtr(..) => ty,
812        // As these types are always non-null, the nullable equivalent of
813        // `Option<T>` of these types are their raw pointer counterparts.
814        ty::Ref(_region, ty, mutbl) => Ty::new_ptr(tcx, ty, mutbl),
815        // There is no nullable equivalent for Rust's function pointers,
816        // you must use an `Option<fn(..) -> _>` to represent it.
817        ty::FnPtr(..) => ty,
818        // We should only ever reach this case if `ty_is_known_nonnull` is
819        // extended to other types.
820        ref unhandled => {
821            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:821",
                        "rustc_lint::types", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
                        ::tracing_core::__macro_support::Option::Some(821u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_nullable_type: Unhandled scalar kind: {0:?} while checking {1:?}",
                                                    unhandled, ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
822                "get_nullable_type: Unhandled scalar kind: {:?} while checking {:?}",
823                unhandled, ty
824            );
825            return None;
826        }
827    })
828}
829
830/// A type is niche-optimization candidate iff:
831/// - Is a zero-sized type with alignment 1 (a “1-ZST”).
832/// - Is either a struct/tuple with no fields, or an enum with no variants.
833/// - Does not have the `#[non_exhaustive]` attribute.
834fn is_niche_optimization_candidate<'tcx>(
835    tcx: TyCtxt<'tcx>,
836    typing_env: ty::TypingEnv<'tcx>,
837    ty: Ty<'tcx>,
838) -> bool {
839    if tcx.layout_of(typing_env.as_query_input(ty)).is_ok_and(|layout| !layout.is_1zst()) {
840        return false;
841    }
842
843    match ty.kind() {
844        ty::Adt(ty_def, _) => {
845            let non_exhaustive = ty_def.is_variant_list_non_exhaustive();
846            let empty = (ty_def.is_struct() && ty_def.non_enum_variant().fields.is_empty())
847                || (ty_def.is_enum() && ty_def.variants().is_empty());
848
849            !non_exhaustive && empty
850        }
851        ty::Tuple(tys) => tys.is_empty(),
852        _ => false,
853    }
854}
855
856/// Check if this enum can be safely exported based on the "nullable pointer optimization". If it
857/// can, return the type that `ty` can be safely converted to, otherwise return `None`.
858/// Currently restricted to function pointers, boxes, references, `core::num::NonZero`,
859/// `core::ptr::NonNull`, and `#[repr(transparent)]` newtypes.
860pub(crate) fn repr_nullable_ptr<'tcx>(
861    tcx: TyCtxt<'tcx>,
862    typing_env: ty::TypingEnv<'tcx>,
863    ty: Ty<'tcx>,
864) -> Option<Ty<'tcx>> {
865    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:865",
                        "rustc_lint::types", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
                        ::tracing_core::__macro_support::Option::Some(865u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("is_repr_nullable_ptr(tcx, ty = {0:?})",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("is_repr_nullable_ptr(tcx, ty = {:?})", ty);
866    match ty.kind() {
867        ty::Adt(ty_def, args) => {
868            let field_ty = match &ty_def.variants().raw[..] {
869                [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) {
870                    ([], [field]) | ([field], []) => field.ty(tcx, args).skip_norm_wip(),
871                    ([field1], [field2]) => {
872                        let ty1 = field1.ty(tcx, args).skip_norm_wip();
873                        let ty2 = field2.ty(tcx, args).skip_norm_wip();
874
875                        if is_niche_optimization_candidate(tcx, typing_env, ty1) {
876                            ty2
877                        } else if is_niche_optimization_candidate(tcx, typing_env, ty2) {
878                            ty1
879                        } else {
880                            return None;
881                        }
882                    }
883                    _ => return None,
884                },
885                _ => return None,
886            };
887
888            if !ty_is_known_nonnull(tcx, typing_env, field_ty) {
889                return None;
890            }
891
892            // At this point, the field's type is known to be nonnull and the parent enum is Option-like.
893            // If the computed size for the field and the enum are different, the nonnull optimization isn't
894            // being applied (and we've got a problem somewhere).
895            let compute_size_skeleton =
896                |t| SizeSkeleton::compute(t, tcx, typing_env, DUMMY_SP).ok();
897            if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) {
898                ::rustc_middle::util::bug::bug_fmt(format_args!("improper_ctypes: Option nonnull optimization not applied?"));bug!("improper_ctypes: Option nonnull optimization not applied?");
899            }
900
901            // Return the nullable type this Option-like enum can be safely represented with.
902            let field_ty_layout = tcx.layout_of(typing_env.as_query_input(field_ty));
903            if field_ty_layout.is_err() && !field_ty.has_non_region_param() {
904                ::rustc_middle::util::bug::bug_fmt(format_args!("should be able to compute the layout of non-polymorphic type"));bug!("should be able to compute the layout of non-polymorphic type");
905            }
906
907            let field_ty_abi = &field_ty_layout.ok()?.backend_repr;
908            if let BackendRepr::Scalar(field_ty_scalar) = field_ty_abi {
909                match field_ty_scalar.valid_range(&tcx) {
910                    WrappingRange { start: 0, end }
911                        if end == field_ty_scalar.size(&tcx).unsigned_int_max() - 1 =>
912                    {
913                        return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
914                            "known non-null scalar type should have a nullable representation",
915                        ));
916                    }
917                    WrappingRange { start: 1, .. } => {
918                        return Some(get_nullable_type(tcx, typing_env, field_ty).expect(
919                            "known non-null scalar type should have a nullable representation",
920                        ));
921                    }
922                    WrappingRange { start, end } => {
923                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unhandled start and end range: ({0}, {1})", start,
                end)));
}unreachable!("Unhandled start and end range: ({}, {})", start, end)
924                    }
925                };
926            }
927            None
928        }
929        ty::Pat(base, pat) => get_nullable_type_from_pat(tcx, typing_env, *base, *pat),
930        _ => None,
931    }
932}
933
934fn get_nullable_type_from_pat<'tcx>(
935    tcx: TyCtxt<'tcx>,
936    typing_env: ty::TypingEnv<'tcx>,
937    base: Ty<'tcx>,
938    pat: ty::Pattern<'tcx>,
939) -> Option<Ty<'tcx>> {
940    match *pat {
941        ty::PatternKind::NotNull | ty::PatternKind::Range { .. } => {
942            get_nullable_type(tcx, typing_env, base)
943        }
944        ty::PatternKind::Or(patterns) => {
945            let first = get_nullable_type_from_pat(tcx, typing_env, base, patterns[0])?;
946            for &pat in &patterns[1..] {
947                {
    match (&first, &get_nullable_type_from_pat(tcx, typing_env, base, pat)?) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(first, get_nullable_type_from_pat(tcx, typing_env, base, pat)?);
948            }
949            Some(first)
950        }
951    }
952}
953
954pub struct VariantSizeDifferences;
#[automatically_derived]
impl ::core::marker::Copy for VariantSizeDifferences { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VariantSizeDifferences { }
#[automatically_derived]
impl ::core::clone::Clone for VariantSizeDifferences {
    #[inline]
    fn clone(&self) -> VariantSizeDifferences { *self }
}
impl ::rustc_lint_defs::LintPass for VariantSizeDifferences {
    fn name(&self) -> &'static str { "VariantSizeDifferences" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [VARIANT_SIZE_DIFFERENCES]))
    }
}
impl VariantSizeDifferences {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [VARIANT_SIZE_DIFFERENCES]))
    }
}declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]);
955
956impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences {
957    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
958        if let hir::ItemKind::Enum(_, _, ref enum_definition) = it.kind {
959            let t = cx.tcx.type_of(it.owner_id).instantiate_identity().skip_norm_wip();
960            let ty = cx.tcx.erase_and_anonymize_regions(t);
961            let Ok(layout) = cx.layout_of(ty) else { return };
962            let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, variants, .. } =
963                &layout.variants
964            else {
965                return;
966            };
967
968            let tag_size = tag.size(&cx.tcx).bytes();
969
970            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:970",
                        "rustc_lint::types", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
                        ::tracing_core::__macro_support::Option::Some(970u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("enum `{0}` is {1} bytes large with layout:\n{2:#?}",
                                                    t, layout.size.bytes(), layout) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
971                "enum `{}` is {} bytes large with layout:\n{:#?}",
972                t,
973                layout.size.bytes(),
974                layout
975            );
976
977            let (largest, slargest, largest_index) = iter::zip(enum_definition.variants, variants)
978                .map(|(variant, variant_layout)| {
979                    // Subtract the size of the enum tag.
980                    let bytes = variant_layout.size.bytes().saturating_sub(tag_size);
981
982                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/types.rs:982",
                        "rustc_lint::types", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/types.rs"),
                        ::tracing_core::__macro_support::Option::Some(982u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::types"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("- variant `{0}` is {1} bytes large",
                                                    variant.ident, bytes) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("- variant `{}` is {} bytes large", variant.ident, bytes);
983                    bytes
984                })
985                .enumerate()
986                .fold((0, 0, 0), |(l, s, li), (idx, size)| {
987                    if size > l {
988                        (size, l, idx)
989                    } else if size > s {
990                        (l, size, li)
991                    } else {
992                        (l, s, li)
993                    }
994                });
995
996            // We only warn if the largest variant is at least thrice as large as
997            // the second-largest.
998            if largest > slargest * 3 && slargest > 0 {
999                cx.emit_span_lint(
1000                    VARIANT_SIZE_DIFFERENCES,
1001                    enum_definition.variants[largest_index].span,
1002                    VariantSizeDifferencesDiag { largest },
1003                );
1004            }
1005        }
1006    }
1007}
1008
1009#[doc = r" The `invalid_atomic_ordering` lint detects passing an `Ordering`"]
#[doc = r" to an atomic operation that does not support that ordering."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # use core::sync::atomic::{AtomicU8, Ordering};"]
#[doc = r" let atom = AtomicU8::new(0);"]
#[doc = r" let value = atom.load(Ordering::Release);"]
#[doc = r" # let _ = value;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Some atomic operations are only supported for a subset of the"]
#[doc =
r" `atomic::Ordering` variants. Passing an unsupported variant will cause"]
#[doc =
r" an unconditional panic at runtime, which is detected by this lint."]
#[doc = r""]
#[doc =
r" This lint will trigger in the following cases: (where `AtomicType` is an"]
#[doc = r" atomic type from `core::sync::atomic`, such as `AtomicBool`,"]
#[doc = r" `AtomicPtr`, `AtomicUsize`, or any of the other integer atomics)."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Acquire` or `Ordering::AcqRel` to"]
#[doc = r"   `AtomicType::store`."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Release` or `Ordering::AcqRel` to"]
#[doc = r"   `AtomicType::load`."]
#[doc = r""]
#[doc = r" - Passing `Ordering::Relaxed` to `core::sync::atomic::fence` or"]
#[doc = r"   `core::sync::atomic::compiler_fence`."]
#[doc = r""]
#[doc =
r" - Passing `Ordering::Release` or `Ordering::AcqRel` as the failure"]
#[doc = r"   ordering for any of `AtomicType::compare_exchange`,"]
#[doc = r"   `AtomicType::compare_exchange_weak`, `AtomicType::update`, or"]
#[doc = r"   `AtomicType::try_update`."]
static INVALID_ATOMIC_ORDERING: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INVALID_ATOMIC_ORDERING",
            default_level: ::rustc_lint_defs::Deny,
            desc: "usage of invalid atomic ordering in atomic operations and memory fences",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1010    /// The `invalid_atomic_ordering` lint detects passing an `Ordering`
1011    /// to an atomic operation that does not support that ordering.
1012    ///
1013    /// ### Example
1014    ///
1015    /// ```rust,compile_fail
1016    /// # use core::sync::atomic::{AtomicU8, Ordering};
1017    /// let atom = AtomicU8::new(0);
1018    /// let value = atom.load(Ordering::Release);
1019    /// # let _ = value;
1020    /// ```
1021    ///
1022    /// {{produces}}
1023    ///
1024    /// ### Explanation
1025    ///
1026    /// Some atomic operations are only supported for a subset of the
1027    /// `atomic::Ordering` variants. Passing an unsupported variant will cause
1028    /// an unconditional panic at runtime, which is detected by this lint.
1029    ///
1030    /// This lint will trigger in the following cases: (where `AtomicType` is an
1031    /// atomic type from `core::sync::atomic`, such as `AtomicBool`,
1032    /// `AtomicPtr`, `AtomicUsize`, or any of the other integer atomics).
1033    ///
1034    /// - Passing `Ordering::Acquire` or `Ordering::AcqRel` to
1035    ///   `AtomicType::store`.
1036    ///
1037    /// - Passing `Ordering::Release` or `Ordering::AcqRel` to
1038    ///   `AtomicType::load`.
1039    ///
1040    /// - Passing `Ordering::Relaxed` to `core::sync::atomic::fence` or
1041    ///   `core::sync::atomic::compiler_fence`.
1042    ///
1043    /// - Passing `Ordering::Release` or `Ordering::AcqRel` as the failure
1044    ///   ordering for any of `AtomicType::compare_exchange`,
1045    ///   `AtomicType::compare_exchange_weak`, `AtomicType::update`, or
1046    ///   `AtomicType::try_update`.
1047    INVALID_ATOMIC_ORDERING,
1048    Deny,
1049    "usage of invalid atomic ordering in atomic operations and memory fences"
1050}
1051
1052pub struct InvalidAtomicOrdering;
#[automatically_derived]
impl ::core::marker::Copy for InvalidAtomicOrdering { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidAtomicOrdering { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidAtomicOrdering {
    #[inline]
    fn clone(&self) -> InvalidAtomicOrdering { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidAtomicOrdering {
    fn name(&self) -> &'static str { "InvalidAtomicOrdering" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_ATOMIC_ORDERING]))
    }
}
impl InvalidAtomicOrdering {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_ATOMIC_ORDERING]))
    }
}declare_lint_pass!(InvalidAtomicOrdering => [INVALID_ATOMIC_ORDERING]);
1053
1054impl InvalidAtomicOrdering {
1055    fn inherent_atomic_method_call<'hir>(
1056        cx: &LateContext<'_>,
1057        expr: &Expr<'hir>,
1058        recognized_names: &[Symbol], // used for fast path calculation
1059    ) -> Option<(Symbol, &'hir [Expr<'hir>])> {
1060        if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind
1061            && recognized_names.contains(&method_path.ident.name)
1062            && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
1063            // skip extension traits, only lint functions from the standard library
1064            && let Some(impl_did) = cx.tcx.inherent_impl_of_assoc(m_def_id)
1065            && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().ty_adt_def()
1066            && cx.tcx.is_diagnostic_item(sym::Atomic, adt.did())
1067        {
1068            return Some((method_path.ident.name, args));
1069        }
1070        None
1071    }
1072
1073    fn match_ordering(cx: &LateContext<'_>, ord_arg: &Expr<'_>) -> Option<Symbol> {
1074        let ExprKind::Path(ref ord_qpath) = ord_arg.kind else { return None };
1075        let did = cx.qpath_res(ord_qpath, ord_arg.hir_id).opt_def_id()?;
1076        let tcx = cx.tcx;
1077        let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering);
1078        let name = tcx.item_name(did);
1079        let parent = tcx.parent(did);
1080        [sym::Relaxed, sym::Release, sym::Acquire, sym::AcqRel, sym::SeqCst].into_iter().find(
1081            |&ordering| {
1082                name == ordering
1083                    && (Some(parent) == atomic_ordering
1084                            // needed in case this is a ctor, not a variant
1085                            || tcx.opt_parent(parent) == atomic_ordering)
1086            },
1087        )
1088    }
1089
1090    fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
1091        if let Some((method, args)) =
1092            Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store])
1093            && let Some((ordering_arg, invalid_ordering)) = match method {
1094                sym::load => Some((&args[0], sym::Release)),
1095                sym::store => Some((&args[1], sym::Acquire)),
1096                _ => None,
1097            }
1098            && let Some(ordering) = Self::match_ordering(cx, ordering_arg)
1099            && (ordering == invalid_ordering || ordering == sym::AcqRel)
1100        {
1101            if method == sym::load {
1102                cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingLoad);
1103            } else {
1104                cx.emit_span_lint(INVALID_ATOMIC_ORDERING, ordering_arg.span, AtomicOrderingStore);
1105            };
1106        }
1107    }
1108
1109    fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) {
1110        if let ExprKind::Call(func, args) = expr.kind
1111            && let ExprKind::Path(ref func_qpath) = func.kind
1112            && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
1113            && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
    {
    Some(sym::fence | sym::compiler_fence) => true,
    _ => false,
}matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence))
1114            && Self::match_ordering(cx, &args[0]) == Some(sym::Relaxed)
1115        {
1116            cx.emit_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, AtomicOrderingFence);
1117        }
1118    }
1119
1120    fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
1121        let Some((method, args)) = Self::inherent_atomic_method_call(
1122            cx,
1123            expr,
1124            &[
1125                sym::update,
1126                sym::try_update,
1127                sym::fetch_update,
1128                sym::compare_exchange,
1129                sym::compare_exchange_weak,
1130            ],
1131        ) else {
1132            return;
1133        };
1134
1135        let fail_order_arg = match method {
1136            sym::update | sym::try_update | sym::fetch_update => &args[1],
1137            sym::compare_exchange | sym::compare_exchange_weak => &args[3],
1138            _ => return,
1139        };
1140
1141        let Some(fail_ordering) = Self::match_ordering(cx, fail_order_arg) else { return };
1142
1143        if #[allow(non_exhaustive_omitted_patterns)] match fail_ordering {
    sym::Release | sym::AcqRel => true,
    _ => false,
}matches!(fail_ordering, sym::Release | sym::AcqRel) {
1144            cx.emit_span_lint(
1145                INVALID_ATOMIC_ORDERING,
1146                fail_order_arg.span,
1147                InvalidAtomicOrderingDiag { method, fail_order_arg_span: fail_order_arg.span },
1148            );
1149        }
1150    }
1151}
1152
1153impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering {
1154    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1155        Self::check_atomic_load_store(cx, expr);
1156        Self::check_memory_fence(cx, expr);
1157        Self::check_atomic_compare_exchange(cx, expr);
1158    }
1159}