Skip to main content

rustc_const_eval/check_consts/
check.rs

1//! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
2
3use std::borrow::Cow;
4use std::num::NonZero;
5use std::ops::Deref;
6use std::{assert_matches, mem};
7
8use rustc_errors::{Diag, ErrorGuaranteed};
9use rustc_hir::attrs::lang_items::LangItem;
10use rustc_hir::def::DefKind;
11use rustc_hir::def_id::DefId;
12use rustc_hir::{self as hir, find_attr};
13use rustc_index::bit_set::DenseBitSet;
14use rustc_infer::infer::TyCtxtInferExt;
15use rustc_middle::mir::visit::Visitor;
16use rustc_middle::mir::*;
17use rustc_middle::span_bug;
18use rustc_middle::ty::adjustment::PointerCoercion;
19use rustc_middle::ty::{self, Ty, TypeVisitableExt};
20use rustc_mir_dataflow::Analysis;
21use rustc_mir_dataflow::impls::{MaybeStorageLive, always_storage_live_locals};
22use rustc_span::{Span, Symbol, sym};
23use rustc_trait_selection::traits::{
24    Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
25};
26use tracing::{instrument, trace};
27
28use super::ops::{self, NonConstOp, Status};
29use super::qualifs::{self, HasMutInterior, NeedsDrop, NeedsNonConstDrop};
30use super::resolver::FlowSensitiveAnalysis;
31use super::{ConstCx, Qualif};
32use crate::check_consts::is_fn_or_trait_safe_to_expose_on_stable;
33use crate::diagnostics;
34
35type QualifResults<'mir, 'tcx, Q> =
36    rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'tcx, Q>>;
37
38#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstConditionsHold { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConstConditionsHold { }
#[automatically_derived]
impl ::core::clone::Clone for ConstConditionsHold {
    #[inline]
    fn clone(&self) -> ConstConditionsHold { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ConstConditionsHold { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ConstConditionsHold {
    #[inline]
    fn eq(&self, other: &ConstConditionsHold) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ConstConditionsHold {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ConstConditionsHold {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConstConditionsHold::Yes => "Yes",
                ConstConditionsHold::No => "No",
            })
    }
}Debug)]
39enum ConstConditionsHold {
40    Yes,
41    No,
42}
43
44#[derive(#[automatically_derived]
impl<'mir, 'tcx> ::core::default::Default for Qualifs<'mir, 'tcx> {
    #[inline]
    fn default() -> Qualifs<'mir, 'tcx> {
        Qualifs {
            has_mut_interior: ::core::default::Default::default(),
            needs_drop: ::core::default::Default::default(),
            needs_non_const_drop: ::core::default::Default::default(),
        }
    }
}Default)]
45pub(crate) struct Qualifs<'mir, 'tcx> {
46    has_mut_interior: Option<QualifResults<'mir, 'tcx, HasMutInterior>>,
47    needs_drop: Option<QualifResults<'mir, 'tcx, NeedsDrop>>,
48    needs_non_const_drop: Option<QualifResults<'mir, 'tcx, NeedsNonConstDrop>>,
49}
50
51impl<'mir, 'tcx> Qualifs<'mir, 'tcx> {
52    /// Does `Q` hold for the `local` at the given `Location`?
53    ///
54    /// Only updates the cursor if absolutely necessary.
55    fn in_local<Q: Qualif>(
56        qualif_results: &mut Option<QualifResults<'mir, 'tcx, Q>>,
57        ccx: &'mir ConstCx<'mir, 'tcx>,
58        local: Local,
59        location: Location,
60    ) -> bool {
61        let ty = ccx.body.local_decls[local].ty;
62        // Peeking into opaque types causes cycles if the current function declares said opaque
63        // type. Thus we avoid short circuiting on the type and instead run the more expensive
64        // analysis that looks at the actual usage within this function.
65        if !ty.has_opaque_types() && !Q::in_any_value_of_ty(ccx, ty) {
66            return false;
67        }
68
69        let qualif_results = qualif_results.get_or_insert_with(|| {
70            let ConstCx { tcx, body, .. } = *ccx;
71
72            FlowSensitiveAnalysis::new(ccx)
73                .iterate_to_fixpoint(tcx, body, None)
74                .into_results_cursor(body)
75        });
76
77        qualif_results.seek_before_primary_effect(location);
78        qualif_results.get().contains(local)
79    }
80
81    fn in_return_place(
82        &mut self,
83        ccx: &'mir ConstCx<'mir, 'tcx>,
84        tainted_by_errors: Option<ErrorGuaranteed>,
85    ) -> ConstQualifs {
86        // FIXME(explicit_tail_calls): uhhhh I think we can return without return now, does it change anything
87
88        // Find the `Return` terminator if one exists.
89        //
90        // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
91        // qualifs for the return type.
92        let return_block = ccx
93            .body
94            .basic_blocks
95            .iter_enumerated()
96            .find(|(_, block)| #[allow(non_exhaustive_omitted_patterns)] match block.terminator().kind {
    TerminatorKind::Return => true,
    _ => false,
}matches!(block.terminator().kind, TerminatorKind::Return))
97            .map(|(bb, _)| bb);
98
99        let Some(return_block) = return_block else {
100            return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty(), tainted_by_errors);
101        };
102
103        let return_loc = ccx.body.terminator_loc(return_block);
104
105        ConstQualifs {
106            needs_drop: Self::in_local(&mut self.needs_drop, ccx, RETURN_PLACE, return_loc),
107            needs_non_const_drop: Self::in_local(
108                &mut self.needs_non_const_drop,
109                ccx,
110                RETURN_PLACE,
111                return_loc,
112            ),
113            has_mut_interior: Self::in_local(
114                &mut self.has_mut_interior,
115                ccx,
116                RETURN_PLACE,
117                return_loc,
118            ),
119            tainted_by_errors,
120        }
121    }
122}
123
124pub struct Checker<'mir, 'tcx> {
125    ccx: &'mir ConstCx<'mir, 'tcx>,
126    qualifs: Qualifs<'mir, 'tcx>,
127
128    /// The span of the current statement.
129    span: Span,
130
131    /// A set that stores for each local whether it is "transient", i.e. guaranteed to be dead
132    /// when this MIR body returns.
133    transient_locals: Option<DenseBitSet<Local>>,
134
135    error_emitted: Option<ErrorGuaranteed>,
136    secondary_errors: Vec<Diag<'tcx>>,
137}
138
139impl<'mir, 'tcx> Deref for Checker<'mir, 'tcx> {
140    type Target = ConstCx<'mir, 'tcx>;
141
142    fn deref(&self) -> &Self::Target {
143        self.ccx
144    }
145}
146
147impl<'mir, 'tcx> Checker<'mir, 'tcx> {
148    pub fn new(ccx: &'mir ConstCx<'mir, 'tcx>) -> Self {
149        Checker {
150            span: ccx.body.span,
151            ccx,
152            qualifs: Default::default(),
153            transient_locals: None,
154            error_emitted: None,
155            secondary_errors: Vec::new(),
156        }
157    }
158
159    pub fn check_body(&mut self) {
160        let ConstCx { tcx, body, .. } = *self.ccx;
161        let def_id = self.ccx.def_id();
162
163        // `async` functions cannot be `const fn`. This is checked during AST lowering, so there's
164        // no need to emit duplicate errors here.
165        if self.ccx.is_async() || body.coroutine.is_some() {
166            tcx.dcx().span_delayed_bug(body.span, "`async` functions cannot be `const fn`");
167            return;
168        }
169
170        if !{
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcDoNotConstCheck) {
171            self.visit_body(body);
172        }
173
174        // If we got through const-checking without emitting any "primary" errors, emit any
175        // "secondary" errors if they occurred. Otherwise, cancel the "secondary" errors.
176        let secondary_errors = mem::take(&mut self.secondary_errors);
177        if self.error_emitted.is_none() {
178            for error in secondary_errors {
179                self.error_emitted = Some(error.emit());
180            }
181        } else {
182            if !self.tcx.dcx().has_errors().is_some() {
    ::core::panicking::panic("assertion failed: self.tcx.dcx().has_errors().is_some()")
};assert!(self.tcx.dcx().has_errors().is_some());
183            for error in secondary_errors {
184                error.cancel();
185            }
186        }
187    }
188
189    fn local_is_transient(&mut self, local: Local) -> bool {
190        let ccx = self.ccx;
191        self.transient_locals
192            .get_or_insert_with(|| {
193                // A local is "transient" if it is guaranteed dead at all `Return`.
194                // So first compute the say of "maybe live" locals at each program point.
195                let always_live_locals = &always_storage_live_locals(&ccx.body);
196                let mut maybe_storage_live =
197                    MaybeStorageLive::new(Cow::Borrowed(always_live_locals))
198                        .iterate_to_fixpoint(ccx.tcx, &ccx.body, None)
199                        .into_results_cursor(&ccx.body);
200
201                // And then check all `Return` in the MIR, and if a local is "maybe live" at a
202                // `Return` then it is definitely not transient.
203                let mut transient = DenseBitSet::new_filled(ccx.body.local_decls.len());
204                // Make sure to only visit reachable blocks, the dataflow engine can ICE otherwise.
205                for (bb, data) in traversal::reachable(&ccx.body) {
206                    if data.terminator().kind == TerminatorKind::Return {
207                        let location = ccx.body.terminator_loc(bb);
208                        maybe_storage_live.seek_after_primary_effect(location);
209                        // If a local may be live here, it is definitely not transient.
210                        transient.subtract(maybe_storage_live.get());
211                    }
212                }
213
214                transient
215            })
216            .contains(local)
217    }
218
219    pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
220        self.qualifs.in_return_place(self.ccx, self.error_emitted)
221    }
222
223    /// Emits an error if an expression cannot be evaluated in the current context.
224    pub fn check_op(&mut self, op: impl NonConstOp<'tcx>) {
225        self.check_op_spanned(op, self.span);
226    }
227
228    /// Emits an error at the given `span` if an expression cannot be evaluated in the current
229    /// context.
230    pub fn check_op_spanned<O: NonConstOp<'tcx>>(&mut self, op: O, span: Span) {
231        let gate = match op.status_in_item(self.ccx) {
232            Status::Unstable {
233                gate,
234                safe_to_expose_on_stable,
235                is_function_call,
236                gate_already_checked,
237            } if gate_already_checked || self.tcx.features().enabled(gate) => {
238                if gate_already_checked {
239                    if !!safe_to_expose_on_stable {
    {
        ::core::panicking::panic_fmt(format_args!("setting `gate_already_checked` without `safe_to_expose_on_stable` makes no sense"));
    }
};assert!(
240                        !safe_to_expose_on_stable,
241                        "setting `gate_already_checked` without `safe_to_expose_on_stable` makes no sense"
242                    );
243                }
244                // Generally this is allowed since the feature gate is enabled -- except
245                // if this function wants to be safe-to-expose-on-stable.
246                if !safe_to_expose_on_stable
247                    && self.enforce_recursive_const_stability()
248                    && !super::rustc_allow_const_fn_unstable(self.tcx, self.def_id(), gate)
249                {
250                    emit_unstable_in_stable_exposed_error(self.ccx, span, gate, is_function_call);
251                }
252
253                return;
254            }
255
256            Status::Unstable { gate, .. } => Some(gate),
257            Status::Forbidden => None,
258        };
259
260        if self.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
261            self.tcx.sess.miri_unleashed_feature(span, gate);
262            return;
263        }
264
265        let err = op.build_error(self.ccx, span);
266        if !err.is_error() {
    ::core::panicking::panic("assertion failed: err.is_error()")
};assert!(err.is_error());
267
268        match op.importance() {
269            ops::DiagImportance::Primary => {
270                let reported = err.emit();
271                self.error_emitted = Some(reported);
272            }
273
274            ops::DiagImportance::Secondary => {
275                self.secondary_errors.push(err);
276                self.tcx.dcx().span_delayed_bug(
277                    span,
278                    "compilation must fail when there is a secondary const checker error",
279                );
280            }
281        }
282    }
283
284    fn check_static(&mut self, def_id: DefId, span: Span) {
285        if self.tcx.is_thread_local_static(def_id) {
286            self.tcx.dcx().span_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`");
287        }
288        if let Some(def_id) = def_id.as_local()
289            && let Err(guar) = self.tcx.ensure_result().check_well_formed(hir::OwnerId { def_id })
290        {
291            self.error_emitted = Some(guar);
292        }
293    }
294
295    /// Returns whether this place can possibly escape the evaluation of the current const/static
296    /// initializer. The check assumes that all already existing pointers and references point to
297    /// non-escaping places.
298    fn place_may_escape(&mut self, place: &Place<'_>) -> bool {
299        let is_transient = match self.const_kind() {
300            // In a const fn all borrows are transient or point to the places given via
301            // references in the arguments (so we already checked them with
302            // TransientMutBorrow/MutBorrow as appropriate).
303            // The borrow checker guarantees that no new non-transient borrows are created.
304            // NOTE: Once we have heap allocations during CTFE we need to figure out
305            // how to prevent `const fn` to create long-lived allocations that point
306            // to mutable memory.
307            hir::ConstContext::ConstFn => true,
308            _ => {
309                // For indirect places, we are not creating a new permanent borrow, it's just as
310                // transient as the already existing one.
311                // Locals with StorageDead do not live beyond the evaluation and can
312                // thus safely be borrowed without being able to be leaked to the final
313                // value of the constant.
314                // Note: This is only sound if every local that has a `StorageDead` has a
315                // `StorageDead` in every control flow path leading to a `return` terminator.
316                // If anything slips through, there's no safety net -- safe code can create
317                // references to variants of `!Freeze` enums as long as that variant is `Freeze`, so
318                // interning can't protect us here. (There *is* a safety net for mutable references
319                // though, interning will ICE if we miss something here.)
320                place.is_indirect() || self.local_is_transient(place.local)
321            }
322        };
323        // Transient places cannot possibly escape because the place doesn't exist any more at the
324        // end of evaluation.
325        !is_transient
326    }
327
328    /// Returns whether there are const-conditions.
329    fn revalidate_conditional_constness(
330        &mut self,
331        callee: DefId,
332        callee_args: ty::GenericArgsRef<'tcx>,
333        call_span: Span,
334    ) -> Option<ConstConditionsHold> {
335        let tcx = self.tcx;
336        if !tcx.is_conditionally_const(callee) {
337            return None;
338        }
339
340        let const_conditions = tcx.const_conditions(callee).instantiate(tcx, callee_args);
341        if const_conditions.is_empty() {
342            return None;
343        }
344
345        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(self.body.typing_env(tcx));
346        let ocx = ObligationCtxt::new(&infcx);
347
348        let body_id = self.body.source.def_id().expect_local();
349        let host_polarity = match self.const_kind() {
350            hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
351            hir::ConstContext::Static(_) | hir::ConstContext::Const { .. } => {
352                ty::BoundConstness::Const
353            }
354        };
355        let const_conditions = const_conditions.into_iter().map(|(c, s)| {
356            (ocx.normalize(&ObligationCause::misc(call_span, body_id), param_env, c), s)
357        });
358        ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, span)| {
359            Obligation::new(
360                tcx,
361                ObligationCause::new(
362                    call_span,
363                    body_id,
364                    ObligationCauseCode::WhereClause(callee, span),
365                ),
366                param_env,
367                trait_ref.to_host_effect_clause(tcx, host_polarity),
368            )
369        }));
370
371        let errors = ocx.evaluate_obligations_error_on_ambiguity();
372        if errors.no_errors() {
373            Some(ConstConditionsHold::Yes)
374        } else {
375            tcx.dcx()
376                .span_delayed_bug(call_span, "this should have reported a [const] error in HIR");
377            Some(ConstConditionsHold::No)
378        }
379    }
380
381    pub fn check_drop_terminator(
382        &mut self,
383        dropped_place: Place<'tcx>,
384        location: Location,
385        terminator_span: Span,
386    ) {
387        let ty_of_dropped_place = dropped_place.ty(self.body, self.tcx).ty;
388
389        let needs_drop = if let Some(local) = dropped_place.as_local() {
390            Qualifs::in_local(&mut self.qualifs.needs_drop, self.ccx, local, location)
391        } else {
392            qualifs::NeedsDrop::in_any_value_of_ty(self.ccx, ty_of_dropped_place)
393        };
394        // If this type doesn't need a drop at all, then there's nothing to enforce.
395        if !needs_drop {
396            return;
397        }
398
399        let mut err_span = self.span;
400        let needs_non_const_drop = if let Some(local) = dropped_place.as_local() {
401            // Use the span where the local was declared as the span of the drop error.
402            err_span = self.body.local_decls[local].source_info.span;
403            Qualifs::in_local(&mut self.qualifs.needs_non_const_drop, self.ccx, local, location)
404        } else {
405            qualifs::NeedsNonConstDrop::in_any_value_of_ty(self.ccx, ty_of_dropped_place)
406        };
407
408        self.check_op_spanned(
409            ops::LiveDrop {
410                dropped_at: terminator_span,
411                dropped_ty: ty_of_dropped_place,
412                needs_non_const_drop,
413            },
414            err_span,
415        );
416    }
417
418    /// Check the const stability of the given item (fn or trait).
419    fn check_callee_stability(&mut self, def_id: DefId) {
420        match self.tcx.lookup_const_stability(def_id) {
421            Some(hir::ConstStability { level: hir::StabilityLevel::Stable { .. }, .. }) => {
422                // All good.
423            }
424            None => {
425                // This doesn't need a separate const-stability check -- const-stability equals
426                // regular stability, and regular stability is checked separately.
427                // However, we *do* have to worry about *recursive* const stability.
428                if self.enforce_recursive_const_stability()
429                    && !is_fn_or_trait_safe_to_expose_on_stable(self.tcx, def_id)
430                {
431                    self.dcx().emit_err(diagnostics::UnmarkedConstItemExposed {
432                        span: self.span,
433                        def_path: self.tcx.def_path_str(def_id),
434                    });
435                }
436            }
437            Some(hir::ConstStability {
438                level: hir::StabilityLevel::Unstable { implied_by: implied_feature, issue, .. },
439                feature,
440                ..
441            }) => {
442                // An unstable const fn/trait with a feature gate.
443                let callee_safe_to_expose_on_stable =
444                    is_fn_or_trait_safe_to_expose_on_stable(self.tcx, def_id);
445
446                // We only honor `span.allows_unstable` aka `#[allow_internal_unstable]` if
447                // the callee is safe to expose, to avoid bypassing recursive stability.
448                // This is not ideal since it means the user sees an error, not the macro
449                // author, but that's also the case if one forgets to set
450                // `#[allow_internal_unstable]` in the first place. Note that this cannot be
451                // integrated in the check below since we want to enforce
452                // `callee_safe_to_expose_on_stable` even if
453                // `!self.enforce_recursive_const_stability()`.
454                if (self.span.allows_unstable(feature)
455                    || implied_feature.is_some_and(|f| self.span.allows_unstable(f)))
456                    && callee_safe_to_expose_on_stable
457                {
458                    return;
459                }
460
461                // We can't use `check_op` to check whether the feature is enabled because
462                // the logic is a bit different than elsewhere: local functions don't need
463                // the feature gate, and there might be an "implied" gate that also suffices
464                // to allow this.
465                let feature_enabled = def_id.is_local()
466                    || self.tcx.features().enabled(feature)
467                    || implied_feature.is_some_and(|f| self.tcx.features().enabled(f))
468                    || {
469                        // When we're compiling the compiler itself we may pull in
470                        // crates from crates.io, but those crates may depend on other
471                        // crates also pulled in from crates.io. We want to ideally be
472                        // able to compile everything without requiring upstream
473                        // modifications, so in the case that this looks like a
474                        // `rustc_private` crate (e.g., a compiler crate) and we also have
475                        // the `-Z force-unstable-if-unmarked` flag present (we're
476                        // compiling a compiler crate), then let this missing feature
477                        // annotation slide.
478                        // This matches what we do in `eval_stability_allow_unstable` for
479                        // regular stability.
480                        feature == sym::rustc_private
481                            && issue == NonZero::new(27812)
482                            && self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
483                    };
484                // Even if the feature is enabled, we still need check_op to double-check
485                // this if the callee is not safe to expose on stable.
486                if !feature_enabled || !callee_safe_to_expose_on_stable {
487                    self.check_op(ops::CallUnstable {
488                        def_id,
489                        feature,
490                        feature_enabled,
491                        safe_to_expose_on_stable: callee_safe_to_expose_on_stable,
492                        is_function_call: self.tcx.def_kind(def_id) != DefKind::Trait,
493                    });
494                }
495            }
496        }
497    }
498}
499
500impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
501    fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
502        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs:502",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(502u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("visit_basic_block_data: bb={0:?} is_cleanup={1:?}",
                                                    bb, block.is_cleanup) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
503
504        // We don't const-check basic blocks on the cleanup path since we never unwind during
505        // const-eval: a panic causes an immediate compile error. In other words, cleanup blocks
506        // are unreachable during const-eval.
507        //
508        // We can't be more conservative (e.g., by const-checking cleanup blocks anyways) because
509        // locals that would never be dropped during normal execution are sometimes dropped during
510        // unwinding, which means backwards-incompatible live-drop errors.
511        if block.is_cleanup {
512            return;
513        }
514
515        self.super_basic_block_data(bb, block);
516    }
517
518    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
519        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs:519",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(519u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("visit_rvalue: rvalue={0:?} location={1:?}",
                                                    rvalue, location) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
520
521        self.super_rvalue(rvalue, location);
522
523        match rvalue {
524            Rvalue::ThreadLocalRef(_) => self.check_op(ops::ThreadLocalAccess),
525
526            Rvalue::Use(..)
527            | Rvalue::CopyForDeref(..)
528            | Rvalue::Repeat(..)
529            | Rvalue::Discriminant(..) => {}
530
531            Rvalue::Aggregate(kind, ..) => {
532                if let AggregateKind::Coroutine(def_id, ..) = kind.as_ref()
533                    && let Some(coroutine_kind) = self.tcx.coroutine_kind(*def_id)
534                {
535                    self.check_op(ops::Coroutine(coroutine_kind));
536                }
537            }
538
539            Rvalue::Ref(_, BorrowKind::Mut { .. }, place)
540            | Rvalue::RawPtr(RawPtrKind::Mut, place) => {
541                // Inside mutable statics, we allow arbitrary mutable references.
542                // We've allowed `static mut FOO = &mut [elements];` for a long time (the exact
543                // reasons why are lost to history), and there is no reason to restrict that to
544                // arrays and slices.
545                let is_allowed =
546                    self.const_kind() == hir::ConstContext::Static(hir::Mutability::Mut);
547
548                if !is_allowed && self.place_may_escape(place) {
549                    self.check_op(ops::EscapingMutBorrow);
550                }
551            }
552
553            Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Fake(_), place)
554            | Rvalue::RawPtr(RawPtrKind::Const, place) => {
555                let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
556                    self.ccx,
557                    &mut |local| {
558                        Qualifs::in_local(
559                            &mut self.qualifs.has_mut_interior,
560                            self.ccx,
561                            local,
562                            location,
563                        )
564                    },
565                    place.as_ref(),
566                );
567
568                if borrowed_place_has_mut_interior && self.place_may_escape(place) {
569                    self.check_op(ops::EscapingCellBorrow);
570                }
571            }
572
573            Rvalue::Reborrow(..) => {
574                // FIXME(reborrow): figure out if this is relevant at all.
575            }
576
577            Rvalue::RawPtr(RawPtrKind::FakeForPtrMetadata, place) => {
578                // These are only inserted for slice length, so the place must already be indirect.
579                // This implies we do not have to worry about whether the borrow escapes.
580                if !place.is_indirect() {
581                    self.tcx.dcx().span_delayed_bug(
582                        self.body.source_info(location).span,
583                        "fake borrows are always indirect",
584                    );
585                }
586            }
587
588            Rvalue::Cast(
589                CastKind::IntToInt
590                | CastKind::FloatToInt
591                | CastKind::FloatToFloat
592                | CastKind::IntToFloat
593                | CastKind::PtrToPtr
594                | CastKind::FnPtrToPtr
595                | CastKind::Transmute
596                | CastKind::BoxDerefTransmute
597                | CastKind::PointerCoercion(
598                    PointerCoercion::MutToConstPointer
599                    | PointerCoercion::ArrayToPointer
600                    | PointerCoercion::UnsafeFnPointer
601                    | PointerCoercion::ClosureFnPointer(_)
602                    | PointerCoercion::ReifyFnPointer(_)
603                    | PointerCoercion::Unsize,
604                    _,
605                ),
606                _,
607                _,
608            ) => {
609                // Operations that are fully supported by const-eval.
610            }
611            // Special checks for special casts
612            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
613                self.check_op(ops::RawPtrToIntCast);
614            }
615            Rvalue::Cast(CastKind::PointerWithExposedProvenance, _, _) => {
616                // Since no pointer can ever get exposed (rejected above), this is easy to support.
617            }
618            Rvalue::Cast(kind @ CastKind::Subtype, _, _) => {
619                ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("invalid CastKind for this MIR phase: {0:?}", kind));span_bug!(self.span, "invalid CastKind for this MIR phase: {kind:?}");
620            }
621
622            Rvalue::UnaryOp(op, operand) => {
623                let ty = operand.ty(self.body, self.tcx);
624                match op {
625                    UnOp::Not | UnOp::Neg => {
626                        if is_int_bool_float_or_char(ty) {
627                            // Int, bool, float, and char operations are fine.
628                        } else {
629                            ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("non-primitive type in `Rvalue::UnaryOp{0:?}`: {1:?}", op,
        ty));span_bug!(
630                                self.span,
631                                "non-primitive type in `Rvalue::UnaryOp{op:?}`: {ty:?}",
632                            );
633                        }
634                    }
635                    UnOp::PtrMetadata => {
636                        // Getting the metadata from a pointer is always const.
637                        // We already validated the type is valid in the validator.
638                    }
639                }
640            }
641
642            Rvalue::BinaryOp(op, (lhs, rhs)) => {
643                let lhs_ty = lhs.ty(self.body, self.tcx);
644                let rhs_ty = rhs.ty(self.body, self.tcx);
645
646                if is_int_bool_float_or_char(lhs_ty) && is_int_bool_float_or_char(rhs_ty) {
647                    // Int, bool, float, and char operations are fine.
648                } else if lhs_ty.is_fn_ptr() || lhs_ty.is_raw_ptr() {
649                    {
    match op {
        BinOp::Eq | BinOp::Ne | BinOp::Le | BinOp::Lt | BinOp::Ge | BinOp::Gt
            | BinOp::Offset => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BinOp::Eq | BinOp::Ne | BinOp::Le | BinOp::Lt | BinOp::Ge | BinOp::Gt |\nBinOp::Offset",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
650                        op,
651                        BinOp::Eq
652                            | BinOp::Ne
653                            | BinOp::Le
654                            | BinOp::Lt
655                            | BinOp::Ge
656                            | BinOp::Gt
657                            | BinOp::Offset
658                    );
659
660                    self.check_op(ops::RawPtrComparison);
661                } else {
662                    ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("non-primitive type in `Rvalue::BinaryOp`: {0:?} ⚬ {1:?}",
        lhs_ty, rhs_ty));span_bug!(
663                        self.span,
664                        "non-primitive type in `Rvalue::BinaryOp`: {:?} ⚬ {:?}",
665                        lhs_ty,
666                        rhs_ty
667                    );
668                }
669            }
670
671            Rvalue::WrapUnsafeBinder(..) => {
672                // Unsafe binders are always trivial to create.
673            }
674        }
675    }
676
677    fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
678        self.super_operand(op, location);
679        if let Operand::Constant(c) = op
680            && let Some(def_id) = c.check_static_ptr(self.tcx)
681        {
682            self.check_static(def_id, self.span);
683        }
684    }
685
686    fn visit_source_info(&mut self, source_info: &SourceInfo) {
687        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs:687",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(687u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("visit_source_info: source_info={0:?}",
                                                    source_info) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("visit_source_info: source_info={:?}", source_info);
688        self.span = source_info.span;
689    }
690
691    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
692        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs:692",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(692u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("visit_statement: statement={0:?} location={1:?}",
                                                    statement, location) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("visit_statement: statement={:?} location={:?}", statement, location);
693
694        self.super_statement(statement, location);
695
696        match statement.kind {
697            StatementKind::Assign(..)
698            | StatementKind::SetDiscriminant { .. }
699            | StatementKind::FakeRead(..)
700            | StatementKind::StorageLive(_)
701            | StatementKind::StorageDead(_)
702            | StatementKind::PlaceMention(..)
703            | StatementKind::AscribeUserType(..)
704            | StatementKind::Coverage(..)
705            | StatementKind::Intrinsic(..)
706            | StatementKind::ConstEvalCounter
707            | StatementKind::BackwardIncompatibleDropHint { .. }
708            | StatementKind::Nop => {}
709        }
710    }
711
712    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_terminator",
                                    "rustc_const_eval::check_consts::check",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                                    ::tracing_core::__macro_support::Option::Some(712u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("terminator")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("terminator");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terminator)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_terminator(terminator, location);
            match &terminator.kind {
                TerminatorKind::Call { func, args, fn_span, .. } |
                    TerminatorKind::TailCall { func, args, fn_span, .. } => {
                    let call_source =
                        match terminator.kind {
                            TerminatorKind::Call { call_source, .. } => call_source,
                            TerminatorKind::TailCall { .. } => CallSource::Normal,
                            _ =>
                                ::core::panicking::panic("internal error: entered unreachable code"),
                        };
                    let ConstCx { tcx, body, .. } = *self.ccx;
                    let fn_ty = func.ty(body, tcx);
                    let (callee, fn_args) =
                        match *fn_ty.kind() {
                            ty::FnDef(def_id, fn_args) =>
                                (def_id, fn_args.no_bound_vars().unwrap()),
                            ty::FnPtr(..) => {
                                self.check_op(ops::FnCallIndirect);
                                return;
                            }
                            _ => {
                                ::rustc_middle::util::bug::span_bug_fmt(terminator.source_info.span,
                                    format_args!("invalid callee of type {0:?}", fn_ty))
                            }
                        };
                    let has_const_conditions =
                        self.revalidate_conditional_constness(callee, fn_args,
                            *fn_span);
                    if let Some(trait_did) = tcx.trait_of_assoc(callee) {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs:751",
                                                "rustc_const_eval::check_consts::check",
                                                ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_const_eval/src/check_consts/check.rs"),
                                                ::tracing_core::__macro_support::Option::Some(751u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::check"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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!("attempting to call a trait method")
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let is_const =
                            #[allow(non_exhaustive_omitted_patterns)] match tcx.constness(callee)
                                {
                                hir::Constness::Const { always: false } => true,
                                _ => false,
                            };
                        if is_const &&
                                has_const_conditions == Some(ConstConditionsHold::Yes) {
                            self.check_op(ops::ConditionallyConstCall {
                                    callee,
                                    args: fn_args,
                                    span: *fn_span,
                                    call_source,
                                });
                            self.check_callee_stability(trait_did);
                        } else {
                            self.check_op(ops::FnCallNonConst {
                                    callee,
                                    args: fn_args,
                                    span: *fn_span,
                                    call_source,
                                });
                        }
                        return;
                    }
                    if has_const_conditions.is_some() {
                        self.check_op(ops::ConditionallyConstCall {
                                callee,
                                args: fn_args,
                                span: *fn_span,
                                call_source,
                            });
                    }
                    if self.tcx.fn_sig(callee).skip_binder().c_variadic() {
                        self.check_op(ops::FnCallCVariadic)
                    }
                    if tcx.is_lang_item(callee, LangItem::BeginPanic) {
                        match args[0].node.ty(&self.ccx.body.local_decls,
                                    tcx).kind() {
                            ty::Ref(_, ty, _) if ty.is_str() => {}
                            _ => self.check_op(ops::PanicNonStr),
                        }
                        return;
                    }
                    if tcx.is_lang_item(callee, LangItem::PanicDisplay) {
                        if let ty::Ref(_, ty, _) =
                                        args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() &&
                                    let ty::Ref(_, ty, _) = ty.kind() && ty.is_str()
                            {} else { self.check_op(ops::PanicNonStr); }
                        return;
                    }
                    if let Some(intrinsic) = tcx.intrinsic(callee) {
                        if !tcx.is_const_fn(callee) {
                            self.check_op(ops::IntrinsicNonConst {
                                    name: intrinsic.name,
                                });
                            return;
                        }
                        let is_const_stable =
                            intrinsic.const_stable ||
                                (!intrinsic.must_be_overridden &&
                                        is_fn_or_trait_safe_to_expose_on_stable(tcx, callee));
                        match tcx.lookup_const_stability(callee) {
                            None => {
                                if !is_const_stable &&
                                        self.enforce_recursive_const_stability() {
                                    self.dcx().emit_err(diagnostics::UnmarkedIntrinsicExposed {
                                            span: self.span,
                                            def_path: self.tcx.def_path_str(callee),
                                        });
                                }
                            }
                            Some(hir::ConstStability {
                                level: hir::StabilityLevel::Unstable { .. }, feature, .. })
                                => {
                                if self.span.allows_unstable(feature) && is_const_stable {
                                    return;
                                }
                                self.check_op(ops::IntrinsicUnstable {
                                        name: intrinsic.name,
                                        feature,
                                        const_stable_indirect: is_const_stable,
                                    });
                            }
                            Some(hir::ConstStability {
                                level: hir::StabilityLevel::Stable { .. }, .. }) => {}
                        }
                        return;
                    }
                    if !tcx.is_const_fn(callee) {
                        self.check_op(ops::FnCallNonConst {
                                callee,
                                args: fn_args,
                                span: *fn_span,
                                call_source,
                            });
                        return;
                    }
                    self.check_callee_stability(callee);
                }
                TerminatorKind::Drop { place: dropped_place, .. } => {
                    if super::post_drop_elaboration::checking_enabled(self.ccx)
                        {
                        return;
                    }
                    self.check_drop_terminator(*dropped_place, location,
                        terminator.source_info.span);
                }
                TerminatorKind::InlineAsm { .. } =>
                    self.check_op(ops::InlineAsm),
                TerminatorKind::Yield { .. } => {
                    self.check_op(ops::Coroutine(self.tcx.coroutine_kind(self.body.source.def_id()).expect("Only expected to have a yield in a coroutine")));
                }
                TerminatorKind::CoroutineDrop => {
                    ::rustc_middle::util::bug::span_bug_fmt(self.body.source_info(location).span,
                        format_args!("We should not encounter TerminatorKind::CoroutineDrop after coroutine transform"));
                }
                TerminatorKind::UnwindTerminate(_) => {
                    ::rustc_middle::util::bug::span_bug_fmt(self.span,
                        format_args!("`Terminate` terminator outside of cleanup block"))
                }
                TerminatorKind::Assert { .. } | TerminatorKind::FalseEdge { ..
                    } | TerminatorKind::FalseUnwind { .. } |
                    TerminatorKind::Goto { .. } | TerminatorKind::UnwindResume |
                    TerminatorKind::Return | TerminatorKind::SwitchInt { .. } |
                    TerminatorKind::Unreachable => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
713    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
714        self.super_terminator(terminator, location);
715
716        match &terminator.kind {
717            TerminatorKind::Call { func, args, fn_span, .. }
718            | TerminatorKind::TailCall { func, args, fn_span, .. } => {
719                let call_source = match terminator.kind {
720                    TerminatorKind::Call { call_source, .. } => call_source,
721                    TerminatorKind::TailCall { .. } => CallSource::Normal,
722                    _ => unreachable!(),
723                };
724
725                let ConstCx { tcx, body, .. } = *self.ccx;
726
727                let fn_ty = func.ty(body, tcx);
728
729                let (callee, fn_args) = match *fn_ty.kind() {
730                    ty::FnDef(def_id, fn_args) => (def_id, fn_args.no_bound_vars().unwrap()),
731
732                    ty::FnPtr(..) => {
733                        self.check_op(ops::FnCallIndirect);
734                        // We can get here without an error in miri-unleashed mode... might as well
735                        // skip the rest of the checks as well then.
736                        return;
737                    }
738                    _ => {
739                        span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
740                    }
741                };
742
743                let has_const_conditions =
744                    self.revalidate_conditional_constness(callee, fn_args, *fn_span);
745
746                // Attempting to call a trait method?
747                if let Some(trait_did) = tcx.trait_of_assoc(callee) {
748                    // We can't determine the actual callee (the underlying impl of the trait) here, so we have
749                    // to do different checks than usual.
750
751                    trace!("attempting to call a trait method");
752                    let is_const =
753                        matches!(tcx.constness(callee), hir::Constness::Const { always: false });
754
755                    // Only consider a trait to be const if the const conditions hold.
756                    // Otherwise, it's really misleading to call something "conditionally"
757                    // const when it's very obviously not conditionally const.
758                    if is_const && has_const_conditions == Some(ConstConditionsHold::Yes) {
759                        // Trait calls are always conditionally-const.
760                        self.check_op(ops::ConditionallyConstCall {
761                            callee,
762                            args: fn_args,
763                            span: *fn_span,
764                            call_source,
765                        });
766                        self.check_callee_stability(trait_did);
767                    } else {
768                        // Not even a const trait.
769                        self.check_op(ops::FnCallNonConst {
770                            callee,
771                            args: fn_args,
772                            span: *fn_span,
773                            call_source,
774                        });
775                    }
776                    // That's all we can check here.
777                    return;
778                }
779
780                // Even if we know the callee, ensure we can use conditionally-const calls.
781                if has_const_conditions.is_some() {
782                    self.check_op(ops::ConditionallyConstCall {
783                        callee,
784                        args: fn_args,
785                        span: *fn_span,
786                        call_source,
787                    });
788                }
789
790                if self.tcx.fn_sig(callee).skip_binder().c_variadic() {
791                    self.check_op(ops::FnCallCVariadic)
792                }
793
794                // At this point, we are calling a function, `callee`, whose `DefId` is known...
795
796                // `begin_panic` and `panic_display` functions accept generic
797                // types other than str. Check to enforce that only str can be used in
798                // const-eval.
799
800                // const-eval of the `begin_panic` fn assumes the argument is `&str`
801                if tcx.is_lang_item(callee, LangItem::BeginPanic) {
802                    match args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() {
803                        ty::Ref(_, ty, _) if ty.is_str() => {}
804                        _ => self.check_op(ops::PanicNonStr),
805                    }
806                    // Allow this call, skip all the checks below.
807                    return;
808                }
809
810                // const-eval of `panic_display` assumes the argument is `&&str`
811                if tcx.is_lang_item(callee, LangItem::PanicDisplay) {
812                    if let ty::Ref(_, ty, _) =
813                        args[0].node.ty(&self.ccx.body.local_decls, tcx).kind()
814                        && let ty::Ref(_, ty, _) = ty.kind()
815                        && ty.is_str()
816                    {
817                    } else {
818                        self.check_op(ops::PanicNonStr);
819                    }
820                    // Allow this call, skip all the checks below.
821                    return;
822                }
823
824                // Intrinsics are language primitives, not regular calls, so treat them separately.
825                if let Some(intrinsic) = tcx.intrinsic(callee) {
826                    if !tcx.is_const_fn(callee) {
827                        // Non-const intrinsic.
828                        self.check_op(ops::IntrinsicNonConst { name: intrinsic.name });
829                        // If we allowed this, we're in miri-unleashed mode, so we might
830                        // as well skip the remaining checks.
831                        return;
832                    }
833                    // We use `intrinsic.const_stable` to determine if this can be safely exposed to
834                    // stable code, rather than `const_stable_indirect`. This is to make
835                    // `#[rustc_const_stable_indirect]` an attribute that is always safe to add.
836                    // We also ask is_safe_to_expose_on_stable_const_fn; this determines whether the intrinsic
837                    // fallback body is safe to expose on stable.
838                    let is_const_stable = intrinsic.const_stable
839                        || (!intrinsic.must_be_overridden
840                            && is_fn_or_trait_safe_to_expose_on_stable(tcx, callee));
841                    match tcx.lookup_const_stability(callee) {
842                        None => {
843                            // This doesn't need a separate const-stability check -- const-stability equals
844                            // regular stability, and regular stability is checked separately.
845                            // However, we *do* have to worry about *recursive* const stability.
846                            if !is_const_stable && self.enforce_recursive_const_stability() {
847                                self.dcx().emit_err(diagnostics::UnmarkedIntrinsicExposed {
848                                    span: self.span,
849                                    def_path: self.tcx.def_path_str(callee),
850                                });
851                            }
852                        }
853                        Some(hir::ConstStability {
854                            level: hir::StabilityLevel::Unstable { .. },
855                            feature,
856                            ..
857                        }) => {
858                            // We only honor `span.allows_unstable` aka `#[allow_internal_unstable]`
859                            // if the callee is safe to expose, to avoid bypassing recursive stability.
860                            // This is not ideal since it means the user sees an error, not the macro
861                            // author, but that's also the case if one forgets to set
862                            // `#[allow_internal_unstable]` in the first place.
863                            if self.span.allows_unstable(feature) && is_const_stable {
864                                return;
865                            }
866
867                            self.check_op(ops::IntrinsicUnstable {
868                                name: intrinsic.name,
869                                feature,
870                                const_stable_indirect: is_const_stable,
871                            });
872                        }
873                        Some(hir::ConstStability {
874                            level: hir::StabilityLevel::Stable { .. },
875                            ..
876                        }) => {
877                            // All good. Note that a `#[rustc_const_stable]` intrinsic (meaning it
878                            // can be *directly* invoked from stable const code) does not always
879                            // have the `#[rustc_intrinsic_const_stable_indirect]` attribute (which controls
880                            // exposing an intrinsic indirectly); we accept this call anyway.
881                        }
882                    }
883                    // This completes the checks for intrinsics.
884                    return;
885                }
886
887                if !tcx.is_const_fn(callee) {
888                    self.check_op(ops::FnCallNonConst {
889                        callee,
890                        args: fn_args,
891                        span: *fn_span,
892                        call_source,
893                    });
894                    // If we allowed this, we're in miri-unleashed mode, so we might
895                    // as well skip the remaining checks.
896                    return;
897                }
898
899                // Finally, stability for regular function calls -- this is the big one.
900                self.check_callee_stability(callee);
901            }
902
903            // Forbid all `Drop` terminators unless the place being dropped is a local with no
904            // projections that cannot be `NeedsNonConstDrop`.
905            TerminatorKind::Drop { place: dropped_place, .. } => {
906                // If we are checking live drops after drop-elaboration, don't emit duplicate
907                // errors here.
908                if super::post_drop_elaboration::checking_enabled(self.ccx) {
909                    return;
910                }
911
912                self.check_drop_terminator(*dropped_place, location, terminator.source_info.span);
913            }
914
915            TerminatorKind::InlineAsm { .. } => self.check_op(ops::InlineAsm),
916
917            TerminatorKind::Yield { .. } => {
918                self.check_op(ops::Coroutine(
919                    self.tcx
920                        .coroutine_kind(self.body.source.def_id())
921                        .expect("Only expected to have a yield in a coroutine"),
922                ));
923            }
924
925            TerminatorKind::CoroutineDrop => {
926                span_bug!(
927                    self.body.source_info(location).span,
928                    "We should not encounter TerminatorKind::CoroutineDrop after coroutine transform"
929                );
930            }
931
932            TerminatorKind::UnwindTerminate(_) => {
933                // Cleanup blocks are skipped for const checking (see `visit_basic_block_data`).
934                span_bug!(self.span, "`Terminate` terminator outside of cleanup block")
935            }
936
937            TerminatorKind::Assert { .. }
938            | TerminatorKind::FalseEdge { .. }
939            | TerminatorKind::FalseUnwind { .. }
940            | TerminatorKind::Goto { .. }
941            | TerminatorKind::UnwindResume
942            | TerminatorKind::Return
943            | TerminatorKind::SwitchInt { .. }
944            | TerminatorKind::Unreachable => {}
945        }
946    }
947}
948
949fn is_int_bool_float_or_char(ty: Ty<'_>) -> bool {
950    ty.is_bool() || ty.is_integral() || ty.is_char() || ty.is_floating_point()
951}
952
953fn emit_unstable_in_stable_exposed_error(
954    ccx: &ConstCx<'_, '_>,
955    span: Span,
956    gate: Symbol,
957    is_function_call: bool,
958) -> ErrorGuaranteed {
959    let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo();
960
961    ccx.dcx().emit_err(diagnostics::UnstableInStableExposed {
962        gate: gate.to_string(),
963        span,
964        attr_span,
965        is_function_call,
966        is_function_call2: is_function_call,
967    })
968}