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