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