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::ty::adjustment::PointerCoercion;
18use rustc_middle::ty::{self, Ty, TypeVisitableExt};
19use rustc_mir_dataflow::Analysis;
20use rustc_mir_dataflow::impls::{MaybeStorageLive, always_storage_live_locals};
21use rustc_span::{Span, Symbol, span_bug, sym};
22use rustc_trait_selection::traits::{
23    Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
24};
25use tracing::{instrument, trace};
26
27use super::ops::{self, NonConstOp, Status};
28use super::qualifs::{self, HasMutInterior, NeedsDrop, NeedsNonConstDrop};
29use super::resolver::FlowSensitiveAnalysis;
30use super::{ConstCx, Qualif};
31use crate::check_consts::is_fn_or_trait_safe_to_expose_on_stable;
32use crate::diagnostics;
33
34type QualifResults<'mir, 'tcx, Q> =
35    rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'tcx, Q>>;
36
37#[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 { }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)]
38enum ConstConditionsHold {
39    Yes,
40    No,
41}
42
43#[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)]
44pub(crate) struct Qualifs<'mir, 'tcx> {
45    has_mut_interior: Option<QualifResults<'mir, 'tcx, HasMutInterior>>,
46    needs_drop: Option<QualifResults<'mir, 'tcx, NeedsDrop>>,
47    needs_non_const_drop: Option<QualifResults<'mir, 'tcx, NeedsNonConstDrop>>,
48}
49
50impl<'mir, 'tcx> Qualifs<'mir, 'tcx> {
51    /// Does `Q` hold for the `local` at the given `Location`?
52    ///
53    /// Only updates the cursor if absolutely necessary.
54    fn in_local<Q: Qualif>(
55        qualif_results: &mut Option<QualifResults<'mir, 'tcx, Q>>,
56        ccx: &'mir ConstCx<'mir, 'tcx>,
57        local: Local,
58        location: Location,
59    ) -> bool {
60        let ty = ccx.body.local_decls[local].ty;
61        // Peeking into opaque types causes cycles if the current function declares said opaque
62        // type. Thus we avoid short circuiting on the type and instead run the more expensive
63        // analysis that looks at the actual usage within this function.
64        if !ty.has_opaque_types() && !Q::in_any_value_of_ty(ccx, ty) {
65            return false;
66        }
67
68        let qualif_results = qualif_results.get_or_insert_with(|| {
69            let ConstCx { tcx, body, .. } = *ccx;
70
71            FlowSensitiveAnalysis::new(ccx)
72                .iterate_to_fixpoint(tcx, body, None)
73                .into_results_cursor(body)
74        });
75
76        qualif_results.seek_before_primary_effect(location);
77        qualif_results.get().contains(local)
78    }
79
80    fn in_return_place(
81        &mut self,
82        ccx: &'mir ConstCx<'mir, 'tcx>,
83        tainted_by_errors: Option<ErrorGuaranteed>,
84    ) -> ConstQualifs {
85        // FIXME(explicit_tail_calls): uhhhh I think we can return without return now, does it change anything
86
87        // Find the `Return` terminator if one exists.
88        //
89        // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
90        // qualifs for the return type.
91        let return_block = ccx
92            .body
93            .basic_blocks
94            .iter_enumerated()
95            .find(|(_, block)| #[allow(non_exhaustive_omitted_patterns)] match block.terminator().kind {
    TerminatorKind::Return => true,
    _ => false,
}matches!(block.terminator().kind, TerminatorKind::Return))
96            .map(|(bb, _)| bb);
97
98        let Some(return_block) = return_block else {
99            return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty(), tainted_by_errors);
100        };
101
102        let return_loc = ccx.body.terminator_loc(return_block);
103
104        ConstQualifs {
105            needs_drop: Self::in_local(&mut self.needs_drop, ccx, RETURN_PLACE, return_loc),
106            needs_non_const_drop: Self::in_local(
107                &mut self.needs_non_const_drop,
108                ccx,
109                RETURN_PLACE,
110                return_loc,
111            ),
112            has_mut_interior: Self::in_local(
113                &mut self.has_mut_interior,
114                ccx,
115                RETURN_PLACE,
116                return_loc,
117            ),
118            tainted_by_errors,
119        }
120    }
121}
122
123pub struct Checker<'mir, 'tcx> {
124    ccx: &'mir ConstCx<'mir, 'tcx>,
125    qualifs: Qualifs<'mir, 'tcx>,
126
127    /// The span of the current statement.
128    span: Span,
129
130    /// A set that stores for each local whether it is "transient", i.e. guaranteed to be dead
131    /// when this MIR body returns.
132    transient_locals: Option<DenseBitSet<Local>>,
133
134    error_emitted: Option<ErrorGuaranteed>,
135    secondary_errors: Vec<Diag<'tcx>>,
136}
137
138impl<'mir, 'tcx> Deref for Checker<'mir, 'tcx> {
139    type Target = ConstCx<'mir, 'tcx>;
140
141    fn deref(&self) -> &Self::Target {
142        self.ccx
143    }
144}
145
146impl<'mir, 'tcx> Checker<'mir, 'tcx> {
147    pub fn new(ccx: &'mir ConstCx<'mir, 'tcx>) -> Self {
148        Checker {
149            span: ccx.body.span,
150            ccx,
151            qualifs: Default::default(),
152            transient_locals: None,
153            error_emitted: None,
154            secondary_errors: Vec::new(),
155        }
156    }
157
158    pub fn check_body(&mut self) {
159        let ConstCx { tcx, body, .. } = *self.ccx;
160        let def_id = self.ccx.def_id();
161
162        // `async` functions cannot be `const fn`. This is checked during AST lowering, so there's
163        // no need to emit duplicate errors here.
164        if self.ccx.is_async() || body.coroutine.is_some() {
165            tcx.dcx().span_delayed_bug(body.span, "`async` functions cannot be `const fn`");
166            return;
167        }
168
169        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) {
170            self.visit_body(body);
171        }
172
173        // If we got through const-checking without emitting any "primary" errors, emit any
174        // "secondary" errors if they occurred. Otherwise, cancel the "secondary" errors.
175        let secondary_errors = mem::take(&mut self.secondary_errors);
176        if self.error_emitted.is_none() {
177            for error in secondary_errors {
178                self.error_emitted = Some(error.emit());
179            }
180        } else {
181            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());
182            for error in secondary_errors {
183                error.cancel();
184            }
185        }
186    }
187
188    fn local_is_transient(&mut self, local: Local) -> bool {
189        let ccx = self.ccx;
190        self.transient_locals
191            .get_or_insert_with(|| {
192                // A local is "transient" if it is guaranteed dead at all `Return`.
193                // So first compute the say of "maybe live" locals at each program point.
194                let always_live_locals = &always_storage_live_locals(&ccx.body);
195                let mut maybe_storage_live =
196                    MaybeStorageLive::new(Cow::Borrowed(always_live_locals))
197                        .iterate_to_fixpoint(ccx.tcx, &ccx.body, None)
198                        .into_results_cursor(&ccx.body);
199
200                // And then check all `Return` in the MIR, and if a local is "maybe live" at a
201                // `Return` then it is definitely not transient.
202                let mut transient = DenseBitSet::new_filled(ccx.body.local_decls.len());
203                // Make sure to only visit reachable blocks, the dataflow engine can ICE otherwise.
204                for (bb, data) in traversal::reachable(&ccx.body) {
205                    if data.terminator().kind == TerminatorKind::Return {
206                        let location = ccx.body.terminator_loc(bb);
207                        maybe_storage_live.seek_after_primary_effect(location);
208                        // If a local may be live here, it is definitely not transient.
209                        transient.subtract(maybe_storage_live.get());
210                    }
211                }
212
213                transient
214            })
215            .contains(local)
216    }
217
218    pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
219        self.qualifs.in_return_place(self.ccx, self.error_emitted)
220    }
221
222    /// Emits an error if an expression cannot be evaluated in the current context.
223    pub fn check_op(&mut self, op: impl NonConstOp<'tcx>) {
224        self.check_op_spanned(op, self.span);
225    }
226
227    /// Emits an error at the given `span` if an expression cannot be evaluated in the current
228    /// context.
229    pub fn check_op_spanned<O: NonConstOp<'tcx>>(&mut self, op: O, span: Span) {
230        let gate = match op.status_in_item(self.ccx) {
231            Status::Unstable {
232                gate,
233                safe_to_expose_on_stable,
234                is_function_call,
235                gate_already_checked,
236            } if gate_already_checked || self.tcx.features().enabled(gate) => {
237                if gate_already_checked {
238                    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!(
239                        !safe_to_expose_on_stable,
240                        "setting `gate_already_checked` without `safe_to_expose_on_stable` makes no sense"
241                    );
242                }
243                // Generally this is allowed since the feature gate is enabled -- except
244                // if this function wants to be safe-to-expose-on-stable.
245                if !safe_to_expose_on_stable
246                    && self.enforce_recursive_const_stability()
247                    && !super::rustc_allow_const_fn_unstable(self.tcx, self.def_id(), gate)
248                {
249                    // Avoid suggesting to add `rustc_const_unstable` if the attribute is already
250                    // present. Need to directly check raw attributes as
251                    // `tcx.lookup_const_stability` also includes inherited stability.
252                    let already_unstable = {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(self.def_id(),
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcConstStability {
                            stability, .. }) if stability.is_const_unstable() => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, self.def_id(), RustcConstStability { stability, .. } if stability.is_const_unstable());
253                    emit_unstable_in_stable_exposed_error(
254                        self.ccx,
255                        span,
256                        gate,
257                        is_function_call,
258                        already_unstable,
259                    );
260                }
261
262                return;
263            }
264
265            Status::Unstable { gate, .. } => Some(gate),
266            Status::Forbidden => None,
267        };
268
269        if self.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
270            self.tcx.sess.miri_unleashed_feature(span, gate);
271            return;
272        }
273
274        let err = op.build_error(self.ccx, span);
275        if !err.is_error() {
    ::core::panicking::panic("assertion failed: err.is_error()")
};assert!(err.is_error());
276
277        match op.importance() {
278            ops::DiagImportance::Primary => {
279                let reported = err.emit();
280                self.error_emitted = Some(reported);
281            }
282
283            ops::DiagImportance::Secondary => {
284                self.secondary_errors.push(err);
285                self.tcx.dcx().span_delayed_bug(
286                    span,
287                    "compilation must fail when there is a secondary const checker error",
288                );
289            }
290        }
291    }
292
293    fn check_static(&mut self, def_id: DefId, span: Span) {
294        if self.tcx.is_thread_local_static(def_id) {
295            self.tcx.dcx().span_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`");
296        }
297        if let Some(def_id) = def_id.as_local()
298            && let Err(guar) = self.tcx.ensure_result().check_well_formed(hir::OwnerId { def_id })
299        {
300            self.error_emitted = Some(guar);
301        }
302    }
303
304    /// Returns whether this place can possibly escape the evaluation of the current const/static
305    /// initializer. The check assumes that all already existing pointers and references point to
306    /// non-escaping places.
307    fn place_may_escape(&mut self, place: &Place<'_>) -> bool {
308        let is_transient = match self.const_kind() {
309            // In a const fn all borrows are transient or point to the places given via
310            // references in the arguments (so we already checked them with
311            // TransientMutBorrow/MutBorrow as appropriate).
312            // The borrow checker guarantees that no new non-transient borrows are created.
313            // NOTE: Once we have heap allocations during CTFE we need to figure out
314            // how to prevent `const fn` to create long-lived allocations that point
315            // to mutable memory.
316            hir::ConstContext::ConstFn => true,
317            _ => {
318                // For indirect places, we are not creating a new permanent borrow, it's just as
319                // transient as the already existing one.
320                // Locals with StorageDead do not live beyond the evaluation and can
321                // thus safely be borrowed without being able to be leaked to the final
322                // value of the constant.
323                // Note: This is only sound if every local that has a `StorageDead` has a
324                // `StorageDead` in every control flow path leading to a `return` terminator.
325                // If anything slips through, there's no safety net -- safe code can create
326                // references to variants of `!Freeze` enums as long as that variant is `Freeze`, so
327                // interning can't protect us here. (There *is* a safety net for mutable references
328                // though, interning will ICE if we miss something here.)
329                place.is_indirect() || self.local_is_transient(place.local)
330            }
331        };
332        // Transient places cannot possibly escape because the place doesn't exist any more at the
333        // end of evaluation.
334        !is_transient
335    }
336
337    /// Returns whether there are const-conditions.
338    fn revalidate_conditional_constness(
339        &mut self,
340        callee: DefId,
341        callee_args: ty::GenericArgsRef<'tcx>,
342        call_span: Span,
343    ) -> Option<ConstConditionsHold> {
344        let tcx = self.tcx;
345        if !tcx.is_conditionally_const(callee) {
346            return None;
347        }
348
349        let const_conditions = tcx.const_conditions(callee).instantiate(tcx, callee_args);
350        if const_conditions.is_empty() {
351            return None;
352        }
353
354        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(self.body.typing_env(tcx));
355        let ocx = ObligationCtxt::new(&infcx);
356
357        let body_id = self.body.source.def_id().expect_local();
358        let host_polarity = match self.const_kind() {
359            hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
360            hir::ConstContext::Static(_) | hir::ConstContext::Const { .. } => {
361                ty::BoundConstness::Const
362            }
363        };
364        let const_conditions = const_conditions.into_iter().map(|(c, s)| {
365            (ocx.normalize(&ObligationCause::misc(call_span, body_id), param_env, c), s)
366        });
367        ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, span)| {
368            Obligation::new(
369                tcx,
370                ObligationCause::new(
371                    call_span,
372                    body_id,
373                    ObligationCauseCode::WhereClause(callee, span),
374                ),
375                param_env,
376                trait_ref.to_host_effect_clause(tcx, host_polarity),
377            )
378        }));
379
380        let errors = ocx.evaluate_obligations_error_on_ambiguity();
381        if errors.no_errors() {
382            Some(ConstConditionsHold::Yes)
383        } else {
384            tcx.dcx()
385                .span_delayed_bug(call_span, "this should have reported a [const] error in HIR");
386            Some(ConstConditionsHold::No)
387        }
388    }
389
390    pub fn check_drop_terminator(
391        &mut self,
392        dropped_place: Place<'tcx>,
393        location: Location,
394        terminator_span: Span,
395    ) {
396        let ty_of_dropped_place = dropped_place.ty(self.body, self.tcx).ty;
397
398        let needs_drop = if let Some(local) = dropped_place.as_local() {
399            Qualifs::in_local(&mut self.qualifs.needs_drop, self.ccx, local, location)
400        } else {
401            qualifs::NeedsDrop::in_any_value_of_ty(self.ccx, ty_of_dropped_place)
402        };
403        // If this type doesn't need a drop at all, then there's nothing to enforce.
404        if !needs_drop {
405            return;
406        }
407
408        let mut err_span = self.span;
409        let needs_non_const_drop = if let Some(local) = dropped_place.as_local() {
410            // Use the span where the local was declared as the span of the drop error.
411            err_span = self.body.local_decls[local].source_info.span;
412            Qualifs::in_local(&mut self.qualifs.needs_non_const_drop, self.ccx, local, location)
413        } else {
414            qualifs::NeedsNonConstDrop::in_any_value_of_ty(self.ccx, ty_of_dropped_place)
415        };
416
417        self.check_op_spanned(
418            ops::LiveDrop {
419                dropped_at: terminator_span,
420                dropped_ty: ty_of_dropped_place,
421                needs_non_const_drop,
422            },
423            err_span,
424        );
425    }
426
427    /// Check the const stability of the given item (fn or trait).
428    fn check_callee_stability(&mut self, def_id: DefId) {
429        match self.tcx.lookup_const_stability(def_id) {
430            Some(hir::ConstStability { level: hir::StabilityLevel::Stable { .. }, .. }) => {
431                // All good.
432            }
433            None => {
434                // This doesn't need a separate const-stability check -- const-stability equals
435                // regular stability, and regular stability is checked separately.
436                // However, we *do* have to worry about *recursive* const stability.
437                if self.enforce_recursive_const_stability()
438                    && !is_fn_or_trait_safe_to_expose_on_stable(self.tcx, def_id)
439                {
440                    self.dcx().emit_err(diagnostics::UnmarkedConstItemExposed {
441                        span: self.span,
442                        def_path: self.tcx.def_path_str(def_id),
443                    });
444                }
445            }
446            Some(hir::ConstStability {
447                level: hir::StabilityLevel::Unstable { implied_by: implied_feature, issue, .. },
448                feature,
449                ..
450            }) => {
451                // An unstable const fn/trait with a feature gate.
452                let callee_safe_to_expose_on_stable =
453                    is_fn_or_trait_safe_to_expose_on_stable(self.tcx, def_id);
454
455                // We only honor `span.allows_unstable` aka `#[allow_internal_unstable]` if
456                // the callee is safe to expose, to avoid bypassing recursive stability.
457                // This is not ideal since it means the user sees an error, not the macro
458                // author, but that's also the case if one forgets to set
459                // `#[allow_internal_unstable]` in the first place. Note that this cannot be
460                // integrated in the check below since we want to enforce
461                // `callee_safe_to_expose_on_stable` even if
462                // `!self.enforce_recursive_const_stability()`.
463                if (self.span.allows_unstable(feature)
464                    || implied_feature.is_some_and(|f| self.span.allows_unstable(f)))
465                    && callee_safe_to_expose_on_stable
466                {
467                    return;
468                }
469
470                // We can't use `check_op` to check whether the feature is enabled because
471                // the logic is a bit different than elsewhere: local functions don't need
472                // the feature gate, and there might be an "implied" gate that also suffices
473                // to allow this.
474                let feature_enabled = def_id.is_local()
475                    || self.tcx.features().enabled(feature)
476                    || implied_feature.is_some_and(|f| self.tcx.features().enabled(f))
477                    || {
478                        // When we're compiling the compiler itself we may pull in
479                        // crates from crates.io, but those crates may depend on other
480                        // crates also pulled in from crates.io. We want to ideally be
481                        // able to compile everything without requiring upstream
482                        // modifications, so in the case that this looks like a
483                        // `rustc_private` crate (e.g., a compiler crate) and we also have
484                        // the `-Z force-unstable-if-unmarked` flag present (we're
485                        // compiling a compiler crate), then let this missing feature
486                        // annotation slide.
487                        // This matches what we do in `eval_stability_allow_unstable` for
488                        // regular stability.
489                        feature == sym::rustc_private
490                            && issue == NonZero::new(27812)
491                            && self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
492                    };
493                // Even if the feature is enabled, we still need check_op to double-check
494                // this if the callee is not safe to expose on stable.
495                if !feature_enabled || !callee_safe_to_expose_on_stable {
496                    self.check_op(ops::CallUnstable {
497                        def_id,
498                        feature,
499                        feature_enabled,
500                        safe_to_expose_on_stable: callee_safe_to_expose_on_stable,
501                        is_function_call: self.tcx.def_kind(def_id) != DefKind::Trait,
502                    });
503                }
504            }
505        }
506    }
507}
508
509impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
510    fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
511        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs:511",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(511u32),
                        ::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);
512
513        // We don't const-check basic blocks on the cleanup path since we never unwind during
514        // const-eval: a panic causes an immediate compile error. In other words, cleanup blocks
515        // are unreachable during const-eval.
516        //
517        // We can't be more conservative (e.g., by const-checking cleanup blocks anyways) because
518        // locals that would never be dropped during normal execution are sometimes dropped during
519        // unwinding, which means backwards-incompatible live-drop errors.
520        if block.is_cleanup {
521            return;
522        }
523
524        self.super_basic_block_data(bb, block);
525    }
526
527    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
528        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs:528",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(528u32),
                        ::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);
529
530        self.super_rvalue(rvalue, location);
531
532        match rvalue {
533            Rvalue::ThreadLocalRef(_) => self.check_op(ops::ThreadLocalAccess),
534
535            Rvalue::Use(..)
536            | Rvalue::CopyForDeref(..)
537            | Rvalue::Repeat(..)
538            | Rvalue::Discriminant(..) => {}
539
540            Rvalue::Aggregate(kind, ..) => {
541                if let AggregateKind::Coroutine(def_id, ..) = kind.as_ref()
542                    && let Some(coroutine_kind) = self.tcx.coroutine_kind(*def_id)
543                {
544                    self.check_op(ops::Coroutine(coroutine_kind));
545                }
546            }
547
548            Rvalue::Ref(_, BorrowKind::Mut { .. }, place)
549            | Rvalue::RawPtr(RawPtrKind::Mut, place) => {
550                // Inside mutable statics, we allow arbitrary mutable references.
551                // We've allowed `static mut FOO = &mut [elements];` for a long time (the exact
552                // reasons why are lost to history), and there is no reason to restrict that to
553                // arrays and slices.
554                let is_allowed =
555                    self.const_kind() == hir::ConstContext::Static(hir::Mutability::Mut);
556
557                if !is_allowed && self.place_may_escape(place) {
558                    self.check_op(ops::EscapingMutBorrow);
559                }
560            }
561
562            Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Fake(_), place)
563            | Rvalue::RawPtr(RawPtrKind::Const, place) => {
564                let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
565                    self.ccx,
566                    &mut |local| {
567                        Qualifs::in_local(
568                            &mut self.qualifs.has_mut_interior,
569                            self.ccx,
570                            local,
571                            location,
572                        )
573                    },
574                    place.as_ref(),
575                );
576
577                if borrowed_place_has_mut_interior && self.place_may_escape(place) {
578                    self.check_op(ops::EscapingCellBorrow);
579                }
580            }
581
582            Rvalue::Reborrow(..) => {
583                // FIXME(reborrow): figure out if this is relevant at all.
584            }
585
586            Rvalue::RawPtr(RawPtrKind::FakeForPtrMetadata, place) => {
587                // These are only inserted for slice length, so the place must already be indirect.
588                // This implies we do not have to worry about whether the borrow escapes.
589                if !place.is_indirect() {
590                    self.tcx.dcx().span_delayed_bug(
591                        self.body.source_info(location).span,
592                        "fake borrows are always indirect",
593                    );
594                }
595            }
596
597            Rvalue::Cast(
598                CastKind::IntToInt
599                | CastKind::FloatToInt
600                | CastKind::FloatToFloat
601                | CastKind::IntToFloat
602                | CastKind::PtrToPtr
603                | CastKind::FnPtrToPtr
604                | CastKind::Transmute
605                | CastKind::BoxDerefTransmute
606                | CastKind::PointerCoercion(
607                    PointerCoercion::MutToConstPointer
608                    | PointerCoercion::ArrayToPointer
609                    | PointerCoercion::UnsafeFnPointer
610                    | PointerCoercion::ClosureFnPointer(_)
611                    | PointerCoercion::ReifyFnPointer(_)
612                    | PointerCoercion::Unsize,
613                    _,
614                ),
615                _,
616                _,
617            ) => {
618                // Operations that are fully supported by const-eval.
619            }
620            // Special checks for special casts
621            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
622                self.check_op(ops::RawPtrToIntCast);
623            }
624            Rvalue::Cast(CastKind::PointerWithExposedProvenance, _, _) => {
625                // Since no pointer can ever get exposed (rejected above), this is easy to support.
626            }
627            Rvalue::Cast(kind @ CastKind::Subtype, _, _) => {
628                bug_impl(Some(self.span),
    format_args!("invalid CastKind for this MIR phase: {0:?}", kind),
    Location::caller());span_bug!(self.span, "invalid CastKind for this MIR phase: {kind:?}");
629            }
630
631            Rvalue::UnaryOp(op, operand) => {
632                let ty = operand.ty(self.body, self.tcx);
633                match op {
634                    UnOp::Not | UnOp::Neg => {
635                        if is_int_bool_float_or_char(ty) {
636                            // Int, bool, float, and char operations are fine.
637                        } else {
638                            bug_impl(Some(self.span),
    format_args!("non-primitive type in `Rvalue::UnaryOp{0:?}`: {1:?}", op,
        ty), Location::caller());span_bug!(
639                                self.span,
640                                "non-primitive type in `Rvalue::UnaryOp{op:?}`: {ty:?}",
641                            );
642                        }
643                    }
644                    UnOp::PtrMetadata => {
645                        // Getting the metadata from a pointer is always const.
646                        // We already validated the type is valid in the validator.
647                    }
648                }
649            }
650
651            Rvalue::BinaryOp(op, (lhs, rhs)) => {
652                let lhs_ty = lhs.ty(self.body, self.tcx);
653                let rhs_ty = rhs.ty(self.body, self.tcx);
654
655                if is_int_bool_float_or_char(lhs_ty) && is_int_bool_float_or_char(rhs_ty) {
656                    // Int, bool, float, and char operations are fine.
657                } else if lhs_ty.is_fn_ptr() || lhs_ty.is_raw_ptr() {
658                    {
    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!(
659                        op,
660                        BinOp::Eq
661                            | BinOp::Ne
662                            | BinOp::Le
663                            | BinOp::Lt
664                            | BinOp::Ge
665                            | BinOp::Gt
666                            | BinOp::Offset
667                    );
668
669                    self.check_op(ops::RawPtrComparison);
670                } else {
671                    bug_impl(Some(self.span),
    format_args!("non-primitive type in `Rvalue::BinaryOp`: {0:?} ⚬ {1:?}",
        lhs_ty, rhs_ty), Location::caller());span_bug!(
672                        self.span,
673                        "non-primitive type in `Rvalue::BinaryOp`: {:?} ⚬ {:?}",
674                        lhs_ty,
675                        rhs_ty
676                    );
677                }
678            }
679
680            Rvalue::WrapUnsafeBinder(..) => {
681                // Unsafe binders are always trivial to create.
682            }
683        }
684    }
685
686    fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
687        self.super_operand(op, location);
688        if let Operand::Constant(c) = op
689            && let Some(def_id) = c.check_static_ptr(self.tcx)
690        {
691            self.check_static(def_id, self.span);
692        }
693    }
694
695    fn visit_source_info(&mut self, source_info: &SourceInfo) {
696        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs:696",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(696u32),
                        ::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);
697        self.span = source_info.span;
698    }
699
700    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
701        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs:701",
                        "rustc_const_eval::check_consts::check",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(701u32),
                        ::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);
702
703        self.super_statement(statement, location);
704
705        match statement.kind {
706            StatementKind::Assign(..)
707            | StatementKind::SetDiscriminant { .. }
708            | StatementKind::FakeRead(..)
709            | StatementKind::StorageLive(_)
710            | StatementKind::StorageDead(_)
711            | StatementKind::PlaceMention(..)
712            | StatementKind::AscribeUserType(..)
713            | StatementKind::Coverage(..)
714            | StatementKind::Intrinsic(..)
715            | StatementKind::ConstEvalCounter
716            | StatementKind::BackwardIncompatibleDropHint { .. }
717            | StatementKind::Nop => {}
718        }
719    }
720
721    {}
#[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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                                    ::tracing_core::__macro_support::Option::Some(721u32),
                                    ::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;
                            }
                            _ => {
                                bug_impl(Some(terminator.source_info.span),
                                    format_args!("invalid callee of type {0:?}", fn_ty),
                                    Location::caller())
                            }
                        };
                    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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs:760",
                                                "rustc_const_eval::check_consts::check",
                                                ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/check.rs"),
                                                ::tracing_core::__macro_support::Option::Some(760u32),
                                                ::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 usable_fallback_body =
                            !intrinsic.must_be_overridden &&
                                !{
                                            {
                                                'done:
                                                    {
                                                    for i in
                                                        ::rustc_attr_ir::HasAttrs::get_attrs(callee, &self.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();
                        let const_stable_indirect =
                            is_fn_or_trait_safe_to_expose_on_stable(tcx, callee) &&
                                (usable_fallback_body || intrinsic.const_stable_indirect);
                        match tcx.lookup_const_stability(callee) {
                            None => {
                                if !const_stable_indirect &&
                                        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) &&
                                        const_stable_indirect {
                                    return;
                                }
                                self.check_op(ops::IntrinsicUnstable {
                                        name: intrinsic.name,
                                        feature,
                                        const_stable_indirect,
                                    });
                            }
                            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 => {
                    bug_impl(Some(self.body.source_info(location).span),
                        format_args!("We should not encounter TerminatorKind::CoroutineDrop after coroutine transform"),
                        Location::caller());
                }
                TerminatorKind::UnwindTerminate(_) => {
                    bug_impl(Some(self.span),
                        format_args!("`Terminate` terminator outside of cleanup block"),
                        Location::caller())
                }
                TerminatorKind::Assert { .. } | TerminatorKind::FalseEdge { ..
                    } | TerminatorKind::FalseUnwind { .. } |
                    TerminatorKind::Goto { .. } | TerminatorKind::UnwindResume |
                    TerminatorKind::Return | TerminatorKind::SwitchInt { .. } |
                    TerminatorKind::Unreachable => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
722    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
723        self.super_terminator(terminator, location);
724
725        match &terminator.kind {
726            TerminatorKind::Call { func, args, fn_span, .. }
727            | TerminatorKind::TailCall { func, args, fn_span, .. } => {
728                let call_source = match terminator.kind {
729                    TerminatorKind::Call { call_source, .. } => call_source,
730                    TerminatorKind::TailCall { .. } => CallSource::Normal,
731                    _ => unreachable!(),
732                };
733
734                let ConstCx { tcx, body, .. } = *self.ccx;
735
736                let fn_ty = func.ty(body, tcx);
737
738                let (callee, fn_args) = match *fn_ty.kind() {
739                    ty::FnDef(def_id, fn_args) => (def_id, fn_args.no_bound_vars().unwrap()),
740
741                    ty::FnPtr(..) => {
742                        self.check_op(ops::FnCallIndirect);
743                        // We can get here without an error in miri-unleashed mode... might as well
744                        // skip the rest of the checks as well then.
745                        return;
746                    }
747                    _ => {
748                        span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
749                    }
750                };
751
752                let has_const_conditions =
753                    self.revalidate_conditional_constness(callee, fn_args, *fn_span);
754
755                // Attempting to call a trait method?
756                if let Some(trait_did) = tcx.trait_of_assoc(callee) {
757                    // We can't determine the actual callee (the underlying impl of the trait) here, so we have
758                    // to do different checks than usual.
759
760                    trace!("attempting to call a trait method");
761                    let is_const =
762                        matches!(tcx.constness(callee), hir::Constness::Const { always: false });
763
764                    // Only consider a trait to be const if the const conditions hold.
765                    // Otherwise, it's really misleading to call something "conditionally"
766                    // const when it's very obviously not conditionally const.
767                    if is_const && has_const_conditions == Some(ConstConditionsHold::Yes) {
768                        // Trait calls are always conditionally-const.
769                        self.check_op(ops::ConditionallyConstCall {
770                            callee,
771                            args: fn_args,
772                            span: *fn_span,
773                            call_source,
774                        });
775                        self.check_callee_stability(trait_did);
776                    } else {
777                        // Not even a const trait.
778                        self.check_op(ops::FnCallNonConst {
779                            callee,
780                            args: fn_args,
781                            span: *fn_span,
782                            call_source,
783                        });
784                    }
785                    // That's all we can check here.
786                    return;
787                }
788
789                // Even if we know the callee, ensure we can use conditionally-const calls.
790                if has_const_conditions.is_some() {
791                    self.check_op(ops::ConditionallyConstCall {
792                        callee,
793                        args: fn_args,
794                        span: *fn_span,
795                        call_source,
796                    });
797                }
798
799                if self.tcx.fn_sig(callee).skip_binder().c_variadic() {
800                    self.check_op(ops::FnCallCVariadic)
801                }
802
803                // At this point, we are calling a function, `callee`, whose `DefId` is known...
804
805                // `begin_panic` and `panic_display` functions accept generic
806                // types other than str. Check to enforce that only str can be used in
807                // const-eval.
808
809                // const-eval of the `begin_panic` fn assumes the argument is `&str`
810                if tcx.is_lang_item(callee, LangItem::BeginPanic) {
811                    match args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() {
812                        ty::Ref(_, ty, _) if ty.is_str() => {}
813                        _ => self.check_op(ops::PanicNonStr),
814                    }
815                    // Allow this call, skip all the checks below.
816                    return;
817                }
818
819                // const-eval of `panic_display` assumes the argument is `&&str`
820                if tcx.is_lang_item(callee, LangItem::PanicDisplay) {
821                    if let ty::Ref(_, ty, _) =
822                        args[0].node.ty(&self.ccx.body.local_decls, tcx).kind()
823                        && let ty::Ref(_, ty, _) = ty.kind()
824                        && ty.is_str()
825                    {
826                    } else {
827                        self.check_op(ops::PanicNonStr);
828                    }
829                    // Allow this call, skip all the checks below.
830                    return;
831                }
832
833                // Intrinsics are language primitives, not regular calls, so treat them separately.
834                if let Some(intrinsic) = tcx.intrinsic(callee) {
835                    if !tcx.is_const_fn(callee) {
836                        // Non-const intrinsic.
837                        self.check_op(ops::IntrinsicNonConst { name: intrinsic.name });
838                        // If we allowed this, we're in miri-unleashed mode, so we might
839                        // as well skip the remaining checks.
840                        return;
841                    }
842                    // In addition to the usual check, we also require that the intrinsic either has
843                    // a fallback body, or the special `#[rustc_intrinsic_const_stable_indirect]`.
844                    let usable_fallback_body = !intrinsic.must_be_overridden
845                        && !find_attr!(self.tcx, callee, RustcDoNotConstCheck);
846                    let const_stable_indirect =
847                        is_fn_or_trait_safe_to_expose_on_stable(tcx, callee)
848                            && (usable_fallback_body || intrinsic.const_stable_indirect);
849                    match tcx.lookup_const_stability(callee) {
850                        None => {
851                            // This doesn't need a separate const-stability check -- const-stability equals
852                            // regular stability, and regular stability is checked separately.
853                            // However, we *do* have to worry about *recursive* const stability.
854                            if !const_stable_indirect && self.enforce_recursive_const_stability() {
855                                self.dcx().emit_err(diagnostics::UnmarkedIntrinsicExposed {
856                                    span: self.span,
857                                    def_path: self.tcx.def_path_str(callee),
858                                });
859                            }
860                        }
861                        Some(hir::ConstStability {
862                            level: hir::StabilityLevel::Unstable { .. },
863                            feature,
864                            ..
865                        }) => {
866                            // We only honor `span.allows_unstable` aka `#[allow_internal_unstable]`
867                            // if the callee is safe to expose, to avoid bypassing recursive stability.
868                            // This is not ideal since it means the user sees an error, not the macro
869                            // author, but that's also the case if one forgets to set
870                            // `#[allow_internal_unstable]` in the first place.
871                            if self.span.allows_unstable(feature) && const_stable_indirect {
872                                return;
873                            }
874
875                            self.check_op(ops::IntrinsicUnstable {
876                                name: intrinsic.name,
877                                feature,
878                                const_stable_indirect,
879                            });
880                        }
881                        Some(hir::ConstStability {
882                            level: hir::StabilityLevel::Stable { .. },
883                            ..
884                        }) => {
885                            // All good. Note that a `#[rustc_const_stable]` intrinsic (meaning it
886                            // can be *directly* invoked from stable const code) does not always
887                            // have the `#[rustc_intrinsic_const_stable_indirect]` attribute (which controls
888                            // exposing an intrinsic indirectly); we accept this call anyway.
889                        }
890                    }
891                    // This completes the checks for intrinsics.
892                    return;
893                }
894
895                if !tcx.is_const_fn(callee) {
896                    self.check_op(ops::FnCallNonConst {
897                        callee,
898                        args: fn_args,
899                        span: *fn_span,
900                        call_source,
901                    });
902                    // If we allowed this, we're in miri-unleashed mode, so we might
903                    // as well skip the remaining checks.
904                    return;
905                }
906
907                // Finally, stability for regular function calls -- this is the big one.
908                self.check_callee_stability(callee);
909            }
910
911            // Forbid all `Drop` terminators unless the place being dropped is a local with no
912            // projections that cannot be `NeedsNonConstDrop`.
913            TerminatorKind::Drop { place: dropped_place, .. } => {
914                // If we are checking live drops after drop-elaboration, don't emit duplicate
915                // errors here.
916                if super::post_drop_elaboration::checking_enabled(self.ccx) {
917                    return;
918                }
919
920                self.check_drop_terminator(*dropped_place, location, terminator.source_info.span);
921            }
922
923            TerminatorKind::InlineAsm { .. } => self.check_op(ops::InlineAsm),
924
925            TerminatorKind::Yield { .. } => {
926                self.check_op(ops::Coroutine(
927                    self.tcx
928                        .coroutine_kind(self.body.source.def_id())
929                        .expect("Only expected to have a yield in a coroutine"),
930                ));
931            }
932
933            TerminatorKind::CoroutineDrop => {
934                span_bug!(
935                    self.body.source_info(location).span,
936                    "We should not encounter TerminatorKind::CoroutineDrop after coroutine transform"
937                );
938            }
939
940            TerminatorKind::UnwindTerminate(_) => {
941                // Cleanup blocks are skipped for const checking (see `visit_basic_block_data`).
942                span_bug!(self.span, "`Terminate` terminator outside of cleanup block")
943            }
944
945            TerminatorKind::Assert { .. }
946            | TerminatorKind::FalseEdge { .. }
947            | TerminatorKind::FalseUnwind { .. }
948            | TerminatorKind::Goto { .. }
949            | TerminatorKind::UnwindResume
950            | TerminatorKind::Return
951            | TerminatorKind::SwitchInt { .. }
952            | TerminatorKind::Unreachable => {}
953        }
954    }
955}
956
957fn is_int_bool_float_or_char(ty: Ty<'_>) -> bool {
958    ty.is_bool() || ty.is_integral() || ty.is_char() || ty.is_floating_point()
959}
960
961fn emit_unstable_in_stable_exposed_error(
962    ccx: &ConstCx<'_, '_>,
963    span: Span,
964    gate: Symbol,
965    is_function_call: bool,
966    already_unstable: bool,
967) -> ErrorGuaranteed {
968    let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo();
969
970    ccx.dcx().emit_err(diagnostics::UnstableInStableExposed {
971        gate: gate.to_string(),
972        span,
973        suggest_const_unstable: (!already_unstable).then_some(attr_span),
974        is_function_call,
975        is_function_call2: is_function_call,
976    })
977}