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