Skip to main content

rustc_mir_transform/
promote_consts.rs

1//! A pass that promotes borrows of constant rvalues.
2//!
3//! The rvalues considered constant are trees of temps, each with exactly one
4//! initialization, and holding a constant value with no interior mutability.
5//! They are placed into a new MIR constant body in `promoted` and the borrow
6//! rvalue is replaced with a `Literal::Promoted` using the index into
7//! `promoted` of that constant MIR.
8//!
9//! This pass assumes that every use is dominated by an initialization and can
10//! otherwise silence errors, if move analysis runs after promotion on broken
11//! MIR.
12
13use std::cell::Cell;
14use std::{assert_matches, cmp, iter, mem};
15
16use either::{Left, Right};
17use rustc_const_eval::check_consts::{ConstCx, qualifs};
18use rustc_data_structures::fx::FxHashSet;
19use rustc_hir as hir;
20use rustc_hir::def::DefKind;
21use rustc_index::{IndexSlice, IndexVec};
22use rustc_middle::mir;
23use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
24use rustc_middle::mir::*;
25use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
26use rustc_span::{Span, Spanned, bug, span_bug};
27use tracing::{debug, instrument};
28
29use crate::PassPolicy;
30
31/// A `MirPass` for promotion.
32///
33/// Promotion is the extraction of promotable temps into separate MIR bodies so they can have
34/// `'static` lifetime.
35///
36/// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
37/// newly created `Constant`.
38#[derive(Default)]
39pub(super) struct PromoteTemps<'tcx> {
40    // Must use `Cell` because `run_pass` takes `&self`, not `&mut self`.
41    pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
42}
43
44impl<'tcx> crate::MirPass<'tcx> for PromoteTemps<'tcx> {
45    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
46        // There's not really any point in promoting errorful MIR.
47        //
48        // This does not include MIR that failed const-checking, which we still try to promote.
49        if let Err(_) = body.return_ty().error_reported() {
50            debug!("PromoteTemps: MIR had errors");
51            return;
52        }
53        if body.source.promoted.is_some() {
54            return;
55        }
56
57        let ccx = ConstCx::new(tcx, body);
58        let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx);
59
60        let promotable_candidates = validate_candidates(&ccx, &mut temps, all_candidates);
61
62        let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
63        self.promoted_fragments.set(promoted);
64    }
65
66    fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
67        // Implements promotion by extracting eligible values into separate constant MIR bodies.
68        PassPolicy::Required
69    }
70}
71
72/// State of a temporary during collection and promotion.
73#[derive(Copy, Clone, PartialEq, Eq, Debug)]
74enum TempState {
75    /// No references to this temp.
76    Undefined,
77    /// One direct assignment and any number of direct uses.
78    /// A borrow of this temp is promotable if the assigned
79    /// value is qualified as constant.
80    Defined { location: Location, uses: usize, valid: Result<(), ()> },
81    /// Any other combination of assignments/uses.
82    Unpromotable,
83    /// This temp was part of an rvalue which got extracted
84    /// during promotion and needs cleanup.
85    PromotedOut,
86}
87
88/// A "root candidate" for promotion, which will become the
89/// returned value in a promoted MIR, unless it's a subset
90/// of a larger candidate.
91#[derive(Copy, Clone, PartialEq, Eq, Debug)]
92struct Candidate {
93    location: Location,
94}
95
96struct Collector<'a, 'tcx> {
97    ccx: &'a ConstCx<'a, 'tcx>,
98    temps: IndexVec<Local, TempState>,
99    candidates: Vec<Candidate>,
100}
101
102impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
103    #[instrument(level = "debug", skip(self))]
104    fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
105        // We're only interested in temporaries and the return place
106        match self.ccx.body.local_kind(index) {
107            LocalKind::Arg => return,
108            LocalKind::Temp if self.ccx.body.local_decls[index].is_user_variable() => return,
109            LocalKind::ReturnPointer | LocalKind::Temp => {}
110        }
111
112        // Ignore drops, if the temp gets promoted,
113        // then it's constant and thus drop is noop.
114        // Non-uses are also irrelevant.
115        if context.is_drop() || !context.is_use() {
116            debug!(is_drop = context.is_drop(), is_use = context.is_use());
117            return;
118        }
119
120        let temp = &mut self.temps[index];
121        debug!(?temp);
122        *temp = match *temp {
123            TempState::Undefined => match context {
124                PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {
125                    TempState::Defined { location, uses: 0, valid: Err(()) }
126                }
127                _ => TempState::Unpromotable,
128            },
129            TempState::Defined { ref mut uses, .. } => {
130                // We always allow borrows, even mutable ones, as we need
131                // to promote mutable borrows of some ZSTs e.g., `&mut []`.
132                let allowed_use = match context {
133                    PlaceContext::MutatingUse(MutatingUseContext::Borrow)
134                    | PlaceContext::NonMutatingUse(_) => true,
135                    PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
136                };
137                debug!(?allowed_use);
138                if allowed_use {
139                    *uses += 1;
140                    return;
141                }
142                TempState::Unpromotable
143            }
144            TempState::Unpromotable | TempState::PromotedOut => TempState::Unpromotable,
145        };
146        debug!(?temp);
147    }
148
149    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
150        self.super_rvalue(rvalue, location);
151
152        if let Rvalue::Ref(..) = *rvalue {
153            self.candidates.push(Candidate { location });
154        }
155    }
156}
157
158fn collect_temps_and_candidates<'tcx>(
159    ccx: &ConstCx<'_, 'tcx>,
160) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
161    let mut collector = Collector {
162        temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
163        candidates: vec![],
164        ccx,
165    };
166    for (bb, data) in traversal::reverse_postorder(ccx.body) {
167        collector.visit_basic_block_data(bb, data);
168    }
169    (collector.temps, collector.candidates)
170}
171
172/// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
173///
174/// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
175struct Validator<'a, 'tcx> {
176    ccx: &'a ConstCx<'a, 'tcx>,
177    temps: &'a mut IndexSlice<Local, TempState>,
178    /// For backwards compatibility, we are promoting function calls in `const`/`static`
179    /// initializers. But we want to avoid evaluating code that might panic and that otherwise would
180    /// not have been evaluated, so we only promote such calls in basic blocks that are guaranteed
181    /// to execute. In other words, we only promote such calls in basic blocks that are definitely
182    /// not dead code. Here we cache the result of computing that set of basic blocks.
183    promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
184}
185
186impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
187    type Target = ConstCx<'a, 'tcx>;
188
189    fn deref(&self) -> &Self::Target {
190        self.ccx
191    }
192}
193
194struct Unpromotable;
195
196impl<'tcx> Validator<'_, 'tcx> {
197    fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
198        let Left(statement) = self.body.stmt_at(candidate.location) else { bug!() };
199        let Some((_, Rvalue::Ref(_, kind, place))) = statement.kind.as_assign() else { bug!() };
200
201        // We can only promote interior borrows of promotable temps (non-temps
202        // don't get promoted anyway).
203        self.validate_local(place.local)?;
204
205        // The reference operation itself must be promotable.
206        // (Needs to come after `validate_local` to avoid ICEs.)
207        self.validate_ref(*kind, place)?;
208
209        // We do not check all the projections (they do not get promoted anyway),
210        // but we do stay away from promoting anything involving a dereference.
211        if place.projection.contains(&ProjectionElem::Deref) {
212            return Err(Unpromotable);
213        }
214
215        Ok(())
216    }
217
218    // FIXME(eddyb) maybe cache this?
219    fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
220        let TempState::Defined { location: loc, .. } = self.temps[local] else {
221            return false;
222        };
223
224        let stmt_or_term = self.body.stmt_at(loc);
225        match stmt_or_term {
226            Left(statement) => {
227                let Some((_, rhs)) = statement.kind.as_assign() else {
228                    span_bug!(statement.source_info.span, "{:?} is not an assignment", statement)
229                };
230                qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.qualif_local::<Q>(l), rhs)
231            }
232            Right(terminator) => {
233                assert_matches!(terminator.kind, TerminatorKind::Call { .. });
234                let return_ty = self.body.local_decls[local].ty;
235                Q::in_any_value_of_ty(self.ccx, return_ty)
236            }
237        }
238    }
239
240    fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
241        let TempState::Defined { location: loc, uses, valid } = self.temps[local] else {
242            return Err(Unpromotable);
243        };
244
245        // We cannot promote things that need dropping, since the promoted value would not get
246        // dropped.
247        if self.qualif_local::<qualifs::NeedsDrop>(local) {
248            return Err(Unpromotable);
249        }
250
251        if valid.is_ok() {
252            return Ok(());
253        }
254
255        let ok = {
256            let stmt_or_term = self.body.stmt_at(loc);
257            match stmt_or_term {
258                Left(statement) => {
259                    let Some((_, rhs)) = statement.kind.as_assign() else {
260                        span_bug!(
261                            statement.source_info.span,
262                            "{:?} is not an assignment",
263                            statement
264                        )
265                    };
266                    self.validate_rvalue(rhs)
267                }
268                Right(terminator) => match &terminator.kind {
269                    TerminatorKind::Call { func, args, .. } => {
270                        self.validate_call(func, args, loc.block)
271                    }
272                    TerminatorKind::Yield { .. } => Err(Unpromotable),
273                    kind => {
274                        span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
275                    }
276                },
277            }
278        };
279
280        self.temps[local] = match ok {
281            Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
282            Err(_) => TempState::Unpromotable,
283        };
284
285        ok
286    }
287
288    fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
289        let Some((place_base, elem)) = place.last_projection() else {
290            return self.validate_local(place.local);
291        };
292
293        // Validate topmost projection, then recurse.
294        match elem {
295            // Recurse directly.
296            ProjectionElem::ConstantIndex { .. }
297            | ProjectionElem::Subslice { .. }
298            | ProjectionElem::UnwrapUnsafeBinder(_) => {}
299
300            // Never recurse.
301            ProjectionElem::PhantomDeref
302            | ProjectionElem::OpaqueCast(..)
303            | ProjectionElem::Downcast(..) => {
304                return Err(Unpromotable);
305            }
306
307            ProjectionElem::Deref => {
308                // When a static is used by-value, that gets desugared to `*STATIC_ADDR`,
309                // and we need to be able to promote this. So check if this deref matches
310                // that specific pattern.
311
312                // We need to make sure this is a `Deref` of a local with no further projections.
313                // Discussion can be found at
314                // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
315                if let Some(local) = place_base.as_local()
316                    && let TempState::Defined { location, .. } = self.temps[local]
317                    && let Left(def_stmt) = self.body.stmt_at(location)
318                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = def_stmt.kind.as_assign()
319                    && let Some(did) = c.check_static_ptr(self.tcx)
320                    // Evaluating a promoted may not read statics except if it got
321                    // promoted from a static (this is a CTFE check). So we
322                    // can only promote static accesses inside statics.
323                    && let Some(hir::ConstContext::Static(..)) = self.const_kind
324                    && !self.tcx.is_thread_local_static(did)
325                    // Extern statics can never be read by CTFE, even inside a static.
326                    && !self.tcx.is_foreign_item(did)
327                {
328                    // Recurse.
329                } else {
330                    return Err(Unpromotable);
331                }
332            }
333            ProjectionElem::Index(local) => {
334                // Only accept if we can predict the index and are indexing an array.
335                if let TempState::Defined { location: loc, .. } = self.temps[local]
336                    && let Left(statement) =  self.body.stmt_at(loc)
337                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = statement.kind.as_assign()
338                    && self.should_evaluate_for_promotion_checks(c.const_)
339                    && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
340                    // Determine the type of the thing we are indexing.
341                    && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
342                    // It's an array; determine its length.
343                    && let Some(len) = len.try_to_target_usize(self.tcx)
344                    // If the index is in-bounds, go ahead.
345                    && idx < len
346                {
347                    self.validate_local(local)?;
348                    // Recurse.
349                } else {
350                    return Err(Unpromotable);
351                }
352            }
353
354            ProjectionElem::Field(..) => {
355                let base_ty = place_base.ty(self.body, self.tcx).ty;
356                if base_ty.is_union() {
357                    // No promotion of union field accesses.
358                    return Err(Unpromotable);
359                }
360            }
361        }
362
363        self.validate_place(place_base)
364    }
365
366    fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
367        match operand {
368            Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
369
370            // `RuntimeChecks` behaves different in const-eval and runtime MIR,
371            // so we do not promote it.
372            Operand::RuntimeChecks(_) => Err(Unpromotable),
373
374            // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
375            // `validate_rvalue` upon access.
376            Operand::Constant(c) => {
377                if let Some(def_id) = c.check_static_ptr(self.tcx) {
378                    // Only allow statics (not consts) to refer to other statics.
379                    // FIXME(eddyb) does this matter at all for promotion?
380                    // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
381                    // and in `const` this cannot occur anyway. The only concern is that we might
382                    // promote even `let x = &STATIC` which would be useless, but this applies to
383                    // promotion inside statics as well.
384                    let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
385                    if !is_static {
386                        return Err(Unpromotable);
387                    }
388
389                    let is_thread_local = self.tcx.is_thread_local_static(def_id);
390                    if is_thread_local {
391                        return Err(Unpromotable);
392                    }
393                }
394
395                Ok(())
396            }
397        }
398    }
399
400    fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
401        match kind {
402            // Reject these borrow types just to be safe.
403            // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a
404            // usecase.
405            BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
406                return Err(Unpromotable);
407            }
408
409            BorrowKind::Shared => {
410                let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
411                if has_mut_interior {
412                    return Err(Unpromotable);
413                }
414            }
415
416            // FIXME: consider changing this to only promote &mut [] for default borrows,
417            // also forbidding two phase borrows
418            BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
419                let ty = place.ty(self.body, self.tcx).ty;
420
421                // In theory, any zero-sized value could be borrowed
422                // mutably without consequences. However, only &mut []
423                // is allowed right now.
424                let ty::Array(_, len) = ty.kind() else { return Err(Unpromotable) };
425                let Some(0) = len.try_to_target_usize(self.tcx) else { return Err(Unpromotable) };
426            }
427        }
428
429        Ok(())
430    }
431
432    fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
433        match rvalue {
434            Rvalue::Use(_operand, WithRetag::No) => {
435                // This shouldn't actually happen, but just to be safe: we'll later add the promoted
436                // with retagging, so don't promote anything that didn't already have retagging.
437                return Err(Unpromotable);
438            }
439            Rvalue::Use(operand, _)
440            | Rvalue::Repeat(operand, _)
441            | Rvalue::WrapUnsafeBinder(operand, _) => {
442                self.validate_operand(operand)?;
443            }
444            Rvalue::CopyForDeref(place) => {
445                let op = &Operand::Copy(*place);
446                self.validate_operand(op)?
447            }
448
449            Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
450
451            Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
452
453            // ptr-to-int casts are not possible in consts and thus not promotable
454            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
455
456            // all other casts including int-to-ptr casts are fine, they just use the integer value
457            // at pointer type.
458            Rvalue::Cast(_, operand, _) => {
459                self.validate_operand(operand)?;
460            }
461
462            Rvalue::UnaryOp(op, operand) => {
463                match op {
464                    // These operations can never fail.
465                    UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
466                }
467
468                self.validate_operand(operand)?;
469            }
470
471            Rvalue::BinaryOp(op, (lhs, rhs)) => {
472                let op = *op;
473                let lhs_ty = lhs.ty(self.body, self.tcx);
474
475                if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
476                    // Raw and fn pointer operations are not allowed inside consts and thus not
477                    // promotable.
478                    assert_matches!(
479                        op,
480                        BinOp::Eq
481                            | BinOp::Ne
482                            | BinOp::Le
483                            | BinOp::Lt
484                            | BinOp::Ge
485                            | BinOp::Gt
486                            | BinOp::Offset
487                    );
488                    return Err(Unpromotable);
489                }
490
491                match op {
492                    BinOp::Div | BinOp::Rem => {
493                        if lhs_ty.is_integral() {
494                            let sz = lhs_ty.primitive_size(self.tcx);
495                            // Integer division: the RHS must be a non-zero const.
496                            let rhs_val = if let Operand::Constant(rhs_c) = rhs
497                                && self.should_evaluate_for_promotion_checks(rhs_c.const_)
498                                && let Some(rhs_val) =
499                                    rhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
500                                // for the zero test, int vs uint does not matter
501                                && rhs_val.to_uint(sz) != 0
502                            {
503                                rhs_val
504                            } else {
505                                // value not known or 0 -- not okay
506                                return Err(Unpromotable);
507                            };
508                            // Furthermore, for signed division, we also have to exclude `int::MIN /
509                            // -1`.
510                            if lhs_ty.is_signed() && rhs_val.to_int(sz) == -1 {
511                                // The RHS is -1, so we have to be careful. But is the LHS int::MIN?
512                                if let Operand::Constant(lhs_c) = lhs
513                                    && self.should_evaluate_for_promotion_checks(lhs_c.const_)
514                                    && let Some(lhs_val) =
515                                        lhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
516                                    && let lhs_min = sz.signed_int_min()
517                                    && lhs_val.to_int(sz) != lhs_min
518                                {
519                                    // okay
520                                } else {
521                                    // value not known or int::MIN -- not okay
522                                    return Err(Unpromotable);
523                                }
524                            }
525                        }
526                    }
527                    // The remaining operations can never fail.
528                    BinOp::Eq
529                    | BinOp::Ne
530                    | BinOp::Le
531                    | BinOp::Lt
532                    | BinOp::Ge
533                    | BinOp::Gt
534                    | BinOp::Cmp
535                    | BinOp::Offset
536                    | BinOp::Add
537                    | BinOp::AddUnchecked
538                    | BinOp::AddWithOverflow
539                    | BinOp::Sub
540                    | BinOp::SubUnchecked
541                    | BinOp::SubWithOverflow
542                    | BinOp::Mul
543                    | BinOp::MulUnchecked
544                    | BinOp::MulWithOverflow
545                    | BinOp::BitXor
546                    | BinOp::BitAnd
547                    | BinOp::BitOr
548                    | BinOp::Shl
549                    | BinOp::ShlUnchecked
550                    | BinOp::Shr
551                    | BinOp::ShrUnchecked => {}
552                }
553
554                self.validate_operand(lhs)?;
555                self.validate_operand(rhs)?;
556            }
557
558            Rvalue::RawPtr(_, place) => {
559                // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
560                // no problem, only using it is.
561                if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
562                {
563                    let base_ty = place_base.ty(self.body, self.tcx).ty;
564                    if let ty::Ref(..) = base_ty.kind() {
565                        return self.validate_place(place_base);
566                    }
567                }
568                return Err(Unpromotable);
569            }
570
571            Rvalue::Ref(_, kind, place) => {
572                // Special-case reborrows to be more like a copy of the reference.
573                let mut place_simplified = place.as_ref();
574                if let Some((place_base, ProjectionElem::Deref)) =
575                    place_simplified.last_projection()
576                {
577                    let base_ty = place_base.ty(self.body, self.tcx).ty;
578                    if let ty::Ref(..) = base_ty.kind() {
579                        place_simplified = place_base;
580                    }
581                }
582
583                self.validate_place(place_simplified)?;
584
585                // Check that the reference is fine (using the original place!).
586                // (Needs to come after `validate_place` to avoid ICEs.)
587                self.validate_ref(*kind, place)?;
588            }
589
590            Rvalue::Reborrow(..) => return Err(Unpromotable),
591
592            Rvalue::Aggregate(_, operands) => {
593                for o in operands {
594                    self.validate_operand(o)?;
595                }
596            }
597        }
598
599        Ok(())
600    }
601
602    /// Computes the sets of blocks of this MIR that are definitely going to be executed
603    /// if the function returns successfully. That makes it safe to promote calls in them
604    /// that might fail.
605    fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
606        let mut safe_blocks = FxHashSet::default();
607        let mut safe_block = START_BLOCK;
608        loop {
609            safe_blocks.insert(safe_block);
610            // Let's see if we can find another safe block.
611            safe_block = match body.basic_blocks[safe_block].terminator().kind {
612                TerminatorKind::Goto { target, .. } => target,
613                TerminatorKind::Call { target: Some(target), .. }
614                | TerminatorKind::Drop { target, .. } => {
615                    // This calls a function or the destructor. `target` does not get executed if
616                    // the callee loops or panics. But in both cases the const already fails to
617                    // evaluate, so we are fine considering `target` a safe block for promotion.
618                    target
619                }
620                TerminatorKind::Assert { target, .. } => {
621                    // Similar to above, we only consider successful execution.
622                    target
623                }
624                _ => {
625                    // No next safe block.
626                    break;
627                }
628            };
629        }
630        safe_blocks
631    }
632
633    /// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
634    /// We use this to avoid promoting operations that can fail in dead code.
635    fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
636        let body = self.body;
637        let safe_blocks =
638            self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
639        safe_blocks.contains(&block)
640    }
641
642    fn validate_call(
643        &mut self,
644        callee: &Operand<'tcx>,
645        args: &[Spanned<Operand<'tcx>>],
646        block: BasicBlock,
647    ) -> Result<(), Unpromotable> {
648        // Validate the operands. If they fail, there's no question -- we cannot promote.
649        self.validate_operand(callee)?;
650        for arg in args {
651            self.validate_operand(&arg.node)?;
652        }
653
654        // Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
655        // accept them at this point.
656        let fn_ty = callee.ty(self.body, self.tcx);
657        if let ty::FnDef(def_id, _) = *fn_ty.kind() {
658            if self.tcx.is_promotable_const_fn(def_id) {
659                return Ok(());
660            }
661        }
662
663        // Ideally, we'd stop here and reject the rest.
664        // But for backward compatibility, we have to accept some promotion in const/static
665        // initializers. Inline consts are explicitly excluded, they are more recent so we have no
666        // backwards compatibility reason to allow more promotion inside of them.
667        let promote_all_fn = matches!(
668            self.const_kind,
669            Some(
670                hir::ConstContext::Static(_)
671                    | hir::ConstContext::Const { allow_const_fn_promotion: true }
672            )
673        );
674        if !promote_all_fn {
675            return Err(Unpromotable);
676        }
677        // Make sure the callee is a `const fn`.
678        let is_const_fn = match *fn_ty.kind() {
679            ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
680            _ => false,
681        };
682        if !is_const_fn {
683            return Err(Unpromotable);
684        }
685        // The problem is, this may promote calls to functions that panic.
686        // We don't want to introduce compilation errors if there's a panic in a call in dead code.
687        // So we ensure that this is not dead code.
688        if !self.is_promotion_safe_block(block) {
689            return Err(Unpromotable);
690        }
691        // This passed all checks, so let's accept.
692        Ok(())
693    }
694
695    /// Can we try to evaluate a given constant at this point in compilation? Attempting to evaluate
696    /// a const block before borrow-checking will result in a query cycle (#150464).
697    fn should_evaluate_for_promotion_checks(&self, constant: Const<'tcx>) -> bool {
698        match constant {
699            // `Const::Ty` is always a `ConstKind::Param` right now and that can never be turned
700            // into a mir value for promotion
701            // FIXME(mgca): do we want uses of type_const to be normalized during promotion?
702            Const::Ty(..) => false,
703            Const::Val(..) => true,
704            // Evaluating a MIR constant requires borrow-checking it. For inline consts, as of
705            // #138499, this means borrow-checking its typeck root. Since borrow-checking the
706            // typeck root requires promoting its constants, trying to evaluate an inline const here
707            // will result in a query cycle. To avoid the cycle, we can't evaluate const blocks yet.
708            // Other kinds of unevaluated's can cause query cycles too when they arise from
709            // self-reference in user code; e.g. evaluating a constant can require evaluating a
710            // const function that uses that constant, again requiring evaluation of the constant.
711            // However, this form of cycle renders both the constant and function unusable in
712            // general, so we don't need to special-case it here.
713            Const::Unevaluated(uc, _) => {
714                self.tcx.def_kind(uc.def) != DefKind::AnonConst
715                    || self.tcx.anon_const_kind(uc.def) != ty::AnonConstKind::NonTypeSystemInline
716            }
717        }
718    }
719}
720
721fn validate_candidates(
722    ccx: &ConstCx<'_, '_>,
723    temps: &mut IndexSlice<Local, TempState>,
724    mut candidates: Vec<Candidate>,
725) -> Vec<Candidate> {
726    let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
727
728    candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
729    candidates
730}
731
732struct Promoter<'a, 'tcx> {
733    tcx: TyCtxt<'tcx>,
734    source: &'a mut Body<'tcx>,
735    promoted: Body<'tcx>,
736    temps: &'a mut IndexVec<Local, TempState>,
737    extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
738
739    /// Used to assemble the required_consts list while building the promoted.
740    required_consts: Vec<ConstOperand<'tcx>>,
741
742    /// If true, all nested temps are also kept in the
743    /// source MIR, not moved to the promoted MIR.
744    keep_original: bool,
745
746    /// If true, add the new const (the promoted) to the required_consts of the parent MIR.
747    /// This is initially false and then set by the visitor when it encounters a `Call` terminator.
748    add_to_required: bool,
749}
750
751impl<'a, 'tcx> Promoter<'a, 'tcx> {
752    fn new_block(&mut self) -> BasicBlock {
753        let span = self.promoted.span;
754        self.promoted.basic_blocks_mut().push(BasicBlockData::new(
755            Some(Terminator {
756                source_info: SourceInfo::outermost(span),
757                kind: TerminatorKind::Return,
758            }),
759            false,
760        ))
761    }
762
763    fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
764        let last = self.promoted.basic_blocks.last_index().unwrap();
765        let data = &mut self.promoted[last];
766        data.statements.push(Statement::new(
767            SourceInfo::outermost(span),
768            StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
769        ));
770    }
771
772    fn is_temp_kind(&self, local: Local) -> bool {
773        self.source.local_kind(local) == LocalKind::Temp
774    }
775
776    /// Copies the initialization of this temp to the
777    /// promoted MIR, recursing through temps.
778    fn promote_temp(&mut self, temp: Local) -> Local {
779        let old_keep_original = self.keep_original;
780        let loc = match self.temps[temp] {
781            TempState::Defined { location, uses, .. } if uses > 0 => {
782                if uses > 1 {
783                    self.keep_original = true;
784                }
785                location
786            }
787            state => {
788                span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
789            }
790        };
791        if !self.keep_original {
792            self.temps[temp] = TempState::PromotedOut;
793        }
794
795        let num_stmts = self.source[loc.block].statements.len();
796        let new_temp = self.promoted.local_decls.push(LocalDecl::new(
797            self.source.local_decls[temp].ty,
798            self.source.local_decls[temp].source_info.span,
799        ));
800
801        debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
802
803        // First, take the Rvalue or Call out of the source MIR,
804        // or duplicate it, depending on keep_original.
805        if loc.statement_index < num_stmts {
806            let (mut rvalue, source_info) = {
807                let statement = &mut self.source[loc.block].statements[loc.statement_index];
808                let StatementKind::Assign((_, rhs)) = &mut statement.kind else {
809                    span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
810                };
811
812                (
813                    if self.keep_original {
814                        rhs.clone()
815                    } else {
816                        let unit = Rvalue::Use(
817                            Operand::Constant(Box::new(ConstOperand {
818                                span: statement.source_info.span,
819                                user_ty: None,
820                                const_: Const::zero_sized(self.tcx.types.unit),
821                            })),
822                            WithRetag::Yes,
823                        );
824                        mem::replace(rhs, unit)
825                    },
826                    statement.source_info,
827                )
828            };
829
830            self.visit_rvalue(&mut rvalue, loc);
831            self.assign(new_temp, rvalue, source_info.span);
832        } else {
833            let terminator = if self.keep_original {
834                self.source[loc.block].terminator().clone()
835            } else {
836                let terminator = self.source[loc.block].terminator_mut();
837                let target = match &terminator.kind {
838                    TerminatorKind::Call { target: Some(target), .. } => *target,
839                    kind => {
840                        span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
841                    }
842                };
843                Terminator {
844                    source_info: terminator.source_info,
845                    kind: mem::replace(&mut terminator.kind, TerminatorKind::goto(target)),
846                }
847            };
848
849            match terminator.kind {
850                TerminatorKind::Call {
851                    mut func, mut args, call_source: desugar, fn_span, ..
852                } => {
853                    // This promoted involves a function call, so it may fail to evaluate. Let's
854                    // make sure it is added to `required_consts` so that failure cannot get lost.
855                    self.add_to_required = true;
856
857                    self.visit_operand(&mut func, loc);
858                    for arg in &mut args {
859                        self.visit_operand(&mut arg.node, loc);
860                    }
861
862                    let last = self.promoted.basic_blocks.last_index().unwrap();
863                    let new_target = self.new_block();
864
865                    *self.promoted[last].terminator_mut() = Terminator {
866                        kind: TerminatorKind::Call {
867                            func,
868                            args,
869                            unwind: UnwindAction::Continue,
870                            destination: Place::from(new_temp),
871                            target: Some(new_target),
872                            call_source: desugar,
873                            fn_span,
874                        },
875                        source_info: SourceInfo::outermost(terminator.source_info.span),
876                        ..terminator
877                    };
878                }
879                kind => {
880                    span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
881                }
882            };
883        };
884
885        self.keep_original = old_keep_original;
886        new_temp
887    }
888
889    fn promote_candidate(
890        mut self,
891        candidate: Candidate,
892        next_promoted_index: Promoted,
893    ) -> Body<'tcx> {
894        let def = self.source.source.def_id();
895        let (mut rvalue, promoted_op) = {
896            let promoted = &mut self.promoted;
897            let tcx = self.tcx;
898            let mut promoted_operand = |ty, span| {
899                promoted.span = span;
900                promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
901                let args =
902                    tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
903                let uneval =
904                    mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
905
906                ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
907            };
908
909            let blocks = self.source.basic_blocks.as_mut();
910            let local_decls = &mut self.source.local_decls;
911            let loc = candidate.location;
912            let statement = &mut blocks[loc.block].statements[loc.statement_index];
913            let StatementKind::Assign((_, Rvalue::Ref(region, borrow_kind, place))) =
914                &mut statement.kind
915            else {
916                bug!()
917            };
918
919            // Use the underlying local for this (necessarily interior) borrow.
920            debug_assert!(region.is_erased());
921            let ty = local_decls[place.local].ty;
922            let span = statement.source_info.span;
923
924            let ref_ty =
925                Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
926
927            let mut projection = vec![PlaceElem::Deref];
928            projection.extend(place.projection);
929            place.projection = tcx.mk_place_elems(&projection);
930
931            // Create a temp to hold the promoted reference.
932            // This is because `*r` requires `r` to be a local,
933            // otherwise we would use the `promoted` directly.
934            let mut promoted_ref = LocalDecl::new(ref_ty, span);
935            promoted_ref.source_info = statement.source_info;
936            let promoted_ref = local_decls.push(promoted_ref);
937            assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
938
939            let promoted_operand = promoted_operand(ref_ty, span);
940            let promoted_ref_statement = Statement::new(
941                statement.source_info,
942                StatementKind::Assign(Box::new((
943                    Place::from(promoted_ref),
944                    // We can retag here because we wouldn't promote non-retagged values (they get
945                    // rejected in validate_rvalue).
946                    Rvalue::Use(Operand::Constant(Box::new(promoted_operand)), WithRetag::Yes),
947                ))),
948            );
949            self.extra_statements.push((loc, promoted_ref_statement));
950
951            (
952                Rvalue::Ref(
953                    tcx.lifetimes.re_erased,
954                    *borrow_kind,
955                    Place {
956                        local: mem::replace(&mut place.local, promoted_ref),
957                        projection: List::empty(),
958                    },
959                ),
960                promoted_operand,
961            )
962        };
963
964        assert_eq!(self.new_block(), START_BLOCK);
965        self.visit_rvalue(
966            &mut rvalue,
967            Location { block: START_BLOCK, statement_index: usize::MAX },
968        );
969
970        let span = self.promoted.span;
971        self.assign(RETURN_PLACE, rvalue, span);
972
973        // Now that we did promotion, we know whether we'll want to add this to `required_consts` of
974        // the surrounding MIR body.
975        if self.add_to_required {
976            self.source.required_consts.as_mut().unwrap().push(promoted_op);
977        }
978
979        self.promoted.set_required_consts(self.required_consts);
980
981        self.promoted
982    }
983}
984
985/// Replaces all temporaries with their promoted counterparts.
986impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
987    fn tcx(&self) -> TyCtxt<'tcx> {
988        self.tcx
989    }
990
991    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
992        if self.is_temp_kind(*local) {
993            *local = self.promote_temp(*local);
994        }
995    }
996
997    fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
998        if constant.const_.is_required_const() {
999            self.required_consts.push(*constant);
1000        }
1001
1002        // Skipping `super_constant` as the visitor is otherwise only looking for locals.
1003    }
1004}
1005
1006fn promote_candidates<'tcx>(
1007    body: &mut Body<'tcx>,
1008    tcx: TyCtxt<'tcx>,
1009    mut temps: IndexVec<Local, TempState>,
1010    candidates: Vec<Candidate>,
1011) -> IndexVec<Promoted, Body<'tcx>> {
1012    // Visit candidates in reverse, in case they're nested.
1013    debug!(promote_candidates = ?candidates);
1014
1015    // eagerly fail fast
1016    if candidates.is_empty() {
1017        return IndexVec::new();
1018    }
1019
1020    let mut promotions = IndexVec::new();
1021
1022    let mut extra_statements = vec![];
1023    for candidate in candidates.into_iter().rev() {
1024        let Location { block, statement_index } = candidate.location;
1025        if let StatementKind::Assign((place, _)) = &body[block].statements[statement_index].kind
1026            && let Some(local) = place.as_local()
1027        {
1028            if temps[local] == TempState::PromotedOut {
1029                // Already promoted.
1030                continue;
1031            }
1032        }
1033
1034        // Declare return place local so that `mir::Body::new` doesn't complain.
1035        let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1036
1037        let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1038        scope.parent_scope = None;
1039
1040        let mut promoted = Body::new(
1041            body.source, // `promoted` gets filled in below
1042            IndexVec::new(),
1043            IndexVec::from_elem_n(scope, 1),
1044            initial_locals,
1045            IndexVec::new(),
1046            0,
1047            vec![],
1048            body.span,
1049            None,
1050            body.tainted_by_errors,
1051        );
1052        promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1053
1054        let promoter = Promoter {
1055            promoted,
1056            tcx,
1057            source: body,
1058            temps: &mut temps,
1059            extra_statements: &mut extra_statements,
1060            keep_original: false,
1061            add_to_required: false,
1062            required_consts: Vec::new(),
1063        };
1064
1065        let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1066        promoted.source.promoted = Some(promotions.next_index());
1067        promotions.push(promoted);
1068    }
1069
1070    // Insert each of `extra_statements` before its indicated location, which
1071    // has to be done in reverse location order, to not invalidate the rest.
1072    extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1073    for (loc, statement) in extra_statements {
1074        body[loc.block].statements.insert(loc.statement_index, statement);
1075    }
1076
1077    // Eliminate assignments to, and drops of promoted temps.
1078    let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1079    for block in body.basic_blocks_mut() {
1080        block.retain_statements(|statement| match &statement.kind {
1081            StatementKind::Assign((place, _)) => {
1082                if let Some(index) = place.as_local() {
1083                    !promoted(index)
1084                } else {
1085                    true
1086                }
1087            }
1088            StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1089                !promoted(*index)
1090            }
1091            _ => true,
1092        });
1093        let terminator = block.terminator_mut();
1094        if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1095            && let Some(index) = place.as_local()
1096        {
1097            if promoted(index) {
1098                terminator.kind = TerminatorKind::goto(*target);
1099            }
1100        }
1101    }
1102
1103    promotions
1104}