1 //! A pass that promotes borrows of constant rvalues.
3 //! The rvalues considered constant are trees of temps,
4 //! each with exactly one initialization, and holding
5 //! a constant value with no interior mutability.
6 //! They are placed into a new MIR constant body in
7 //! `promoted` and the borrow rvalue is replaced with
8 //! a `Literal::Promoted` using the index into `promoted`
9 //! of that constant MIR.
11 //! This pass assumes that every use is dominated by an
12 //! initialization and can otherwise silence errors, if
13 //! move analysis runs after promotion on broken MIR.
16 use rustc_middle::mir::traversal::ReversePostorder;
17 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
18 use rustc_middle::mir::*;
19 use rustc_middle::ty::cast::CastTy;
20 use rustc_middle::ty::subst::InternalSubsts;
21 use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable};
24 use rustc_index::vec::{Idx, IndexVec};
27 use std::{cmp, iter, mem};
29 use crate::transform::check_consts::{is_lang_special_const_fn, qualifs, ConstCx};
30 use crate::transform::MirPass;
32 /// A `MirPass` for promotion.
34 /// Promotion is the extraction of promotable temps into separate MIR bodies so they can have
35 /// `'static` lifetime.
37 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
38 /// newly created `Constant`.
40 pub struct PromoteTemps<'tcx> {
41 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
44 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
45 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
46 // There's not really any point in promoting errorful MIR.
48 // This does not include MIR that failed const-checking, which we still try to promote.
49 if body.return_ty().references_error() {
50 tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
54 if body.source.promoted.is_some() {
58 let mut rpo = traversal::reverse_postorder(body);
59 let ccx = ConstCx::new(tcx, body);
60 let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
62 let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
64 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
65 self.promoted_fragments.set(promoted);
69 /// State of a temporary during collection and promotion.
70 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
72 /// No references to this temp.
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 },
78 /// Any other combination of assignments/uses.
80 /// This temp was part of an rvalue which got extracted
81 /// during promotion and needs cleanup.
86 pub fn is_promotable(&self) -> bool {
87 debug!("is_promotable: self={:?}", self);
88 matches!(self, TempState::Defined { .. })
92 /// A "root candidate" for promotion, which will become the
93 /// returned value in a promoted MIR, unless it's a subset
94 /// of a larger candidate.
95 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
97 /// Borrow of a constant temporary, candidate for lifetime extension.
102 fn source_info(&self, body: &Body<'_>) -> SourceInfo {
104 Candidate::Ref(location) => *body.source_info(*location),
109 struct Collector<'a, 'tcx> {
110 ccx: &'a ConstCx<'a, 'tcx>,
111 temps: IndexVec<Local, TempState>,
112 candidates: Vec<Candidate>,
115 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
116 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
117 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
118 // We're only interested in temporaries and the return place
119 match self.ccx.body.local_kind(index) {
120 LocalKind::Temp | LocalKind::ReturnPointer => {}
121 LocalKind::Arg | LocalKind::Var => return,
124 // Ignore drops, if the temp gets promoted,
125 // then it's constant and thus drop is noop.
126 // Non-uses are also irrelevant.
127 if context.is_drop() || !context.is_use() {
129 "visit_local: context.is_drop={:?} context.is_use={:?}",
136 let temp = &mut self.temps[index];
137 debug!("visit_local: temp={:?}", temp);
138 if *temp == TempState::Undefined {
140 PlaceContext::MutatingUse(MutatingUseContext::Store)
141 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
142 *temp = TempState::Defined { location, uses: 0 };
145 _ => { /* mark as unpromotable below */ }
147 } else if let TempState::Defined { ref mut uses, .. } = *temp {
148 // We always allow borrows, even mutable ones, as we need
149 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
150 let allowed_use = match context {
151 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
152 | PlaceContext::NonMutatingUse(_) => true,
153 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
155 debug!("visit_local: allowed_use={:?}", allowed_use);
160 /* mark as unpromotable below */
162 *temp = TempState::Unpromotable;
165 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
166 self.super_rvalue(rvalue, location);
170 self.candidates.push(Candidate::Ref(location));
177 pub fn collect_temps_and_candidates(
178 ccx: &ConstCx<'mir, 'tcx>,
179 rpo: &mut ReversePostorder<'_, 'tcx>,
180 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
181 let mut collector = Collector {
182 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
186 for (bb, data) in rpo {
187 collector.visit_basic_block_data(bb, data);
189 (collector.temps, collector.candidates)
192 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
194 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
195 struct Validator<'a, 'tcx> {
196 ccx: &'a ConstCx<'a, 'tcx>,
197 temps: &'a IndexVec<Local, TempState>,
200 impl std::ops::Deref for Validator<'a, 'tcx> {
201 type Target = ConstCx<'a, 'tcx>;
203 fn deref(&self) -> &Self::Target {
210 impl<'tcx> Validator<'_, 'tcx> {
211 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
213 Candidate::Ref(loc) => {
214 let statement = &self.body[loc.block].statements[loc.statement_index];
215 match &statement.kind {
216 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
217 // We can only promote interior borrows of promotable temps (non-temps
218 // don't get promoted anyway).
219 self.validate_local(place.local)?;
221 // The reference operation itself must be promotable.
222 // (Needs to come after `validate_local` to avoid ICEs.)
223 self.validate_ref(*kind, place)?;
225 // We do not check all the projections (they do not get promoted anyway),
226 // but we do stay away from promoting anything involving a dereference.
227 if place.projection.contains(&ProjectionElem::Deref) {
228 return Err(Unpromotable);
231 // We cannot promote things that need dropping, since the promoted value
232 // would not get dropped.
233 if self.qualif_local::<qualifs::NeedsNonConstDrop>(place.local) {
234 return Err(Unpromotable);
245 // FIXME(eddyb) maybe cache this?
246 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
247 if let TempState::Defined { location: loc, .. } = self.temps[local] {
248 let num_stmts = self.body[loc.block].statements.len();
250 if loc.statement_index < num_stmts {
251 let statement = &self.body[loc.block].statements[loc.statement_index];
252 match &statement.kind {
253 StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
255 &mut |l| self.qualif_local::<Q>(l),
260 statement.source_info.span,
261 "{:?} is not an assignment",
267 let terminator = self.body[loc.block].terminator();
268 match &terminator.kind {
269 TerminatorKind::Call { .. } => {
270 let return_ty = self.body.local_decls[local].ty;
271 Q::in_any_value_of_ty(&self.ccx, return_ty)
274 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
279 let span = self.body.local_decls[local].source_info.span;
280 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
284 // FIXME(eddyb) maybe cache this?
285 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
286 if let TempState::Defined { location: loc, .. } = self.temps[local] {
287 let block = &self.body[loc.block];
288 let num_stmts = block.statements.len();
290 if loc.statement_index < num_stmts {
291 let statement = &block.statements[loc.statement_index];
292 match &statement.kind {
293 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
296 statement.source_info.span,
297 "{:?} is not an assignment",
303 let terminator = block.terminator();
304 match &terminator.kind {
305 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
306 TerminatorKind::Yield { .. } => Err(Unpromotable),
308 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
317 fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
318 match place.last_projection() {
319 None => self.validate_local(place.local),
320 Some((place_base, elem)) => {
321 // Validate topmost projection, then recurse.
323 ProjectionElem::Deref => {
324 let mut promotable = false;
325 // We need to make sure this is a `Deref` of a local with no further projections.
326 // Discussion can be found at
327 // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
328 if let Some(local) = place_base.as_local() {
329 // This is a special treatment for cases like *&STATIC where STATIC is a
330 // global static variable.
331 // This pattern is generated only when global static variables are directly
332 // accessed and is qualified for promotion safely.
333 if let TempState::Defined { location, .. } = self.temps[local] {
334 let def_stmt = self.body[location.block]
336 .get(location.statement_index);
337 if let Some(Statement {
339 StatementKind::Assign(box (
341 Rvalue::Use(Operand::Constant(c)),
346 if let Some(did) = c.check_static_ptr(self.tcx) {
347 // Evaluating a promoted may not read statics except if it got
348 // promoted from a static (this is a CTFE check). So we
349 // can only promote static accesses inside statics.
350 if let Some(hir::ConstContext::Static(..)) = self.const_kind
352 if !self.tcx.is_thread_local_static(did) {
361 return Err(Unpromotable);
364 ProjectionElem::Downcast(..) => {
365 return Err(Unpromotable);
368 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
370 ProjectionElem::Index(local) => {
371 let mut promotable = false;
372 // Only accept if we can predict the index and are indexing an array.
374 if let TempState::Defined { location: loc, .. } = self.temps[local] {
375 let block = &self.body[loc.block];
376 if loc.statement_index < block.statements.len() {
377 let statement = &block.statements[loc.statement_index];
378 match &statement.kind {
379 StatementKind::Assign(box (
381 Rvalue::Use(Operand::Constant(c)),
382 )) => c.literal.try_eval_usize(self.tcx, self.param_env),
391 if let Some(idx) = val {
392 // Determine the type of the thing we are indexing.
393 let ty = place_base.ty(self.body, self.tcx).ty;
395 ty::Array(_, len) => {
396 // It's an array; determine its length.
397 if let Some(len) = len.try_eval_usize(self.tcx, self.param_env)
399 // If the index is in-bounds, go ahead.
409 return Err(Unpromotable);
412 self.validate_local(local)?;
415 ProjectionElem::Field(..) => {
416 let base_ty = place_base.ty(self.body, self.tcx).ty;
417 if base_ty.is_union() {
418 // No promotion of union field accesses.
419 return Err(Unpromotable);
424 self.validate_place(place_base)
429 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
431 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
433 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
434 // `validate_rvalue` upon access.
435 Operand::Constant(c) => {
436 if let Some(def_id) = c.check_static_ptr(self.tcx) {
437 // Only allow statics (not consts) to refer to other statics.
438 // FIXME(eddyb) does this matter at all for promotion?
439 // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
440 // and in `const` this cannot occur anyway. The only concern is that we might
441 // promote even `let x = &STATIC` which would be useless, but this applies to
442 // promotion inside statics as well.
443 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
445 return Err(Unpromotable);
448 let is_thread_local = self.tcx.is_thread_local_static(def_id);
450 return Err(Unpromotable);
459 fn validate_ref(&self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
461 // Reject these borrow types just to be safe.
462 // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase.
463 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
465 BorrowKind::Shared => {
466 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
467 if has_mut_interior {
468 return Err(Unpromotable);
472 BorrowKind::Mut { .. } => {
473 let ty = place.ty(self.body, self.tcx).ty;
475 // In theory, any zero-sized value could be borrowed
476 // mutably without consequences. However, only &mut []
477 // is allowed right now.
478 if let ty::Array(_, len) = ty.kind() {
479 match len.try_eval_usize(self.tcx, self.param_env) {
481 _ => return Err(Unpromotable),
484 return Err(Unpromotable);
492 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
494 Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => {
495 self.validate_operand(operand)?;
498 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
499 self.validate_place(place.as_ref())?
502 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
504 Rvalue::Cast(kind, operand, cast_ty) => {
505 if matches!(kind, CastKind::Misc) {
506 let operand_ty = operand.ty(self.body, self.tcx);
507 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
508 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
509 if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
510 // ptr-to-int casts are not possible in consts and thus not promotable
511 return Err(Unpromotable);
513 // int-to-ptr casts are fine, they just use the integer value at pointer type.
516 self.validate_operand(operand)?;
519 Rvalue::NullaryOp(op, _) => match op {
520 NullOp::Box => return Err(Unpromotable),
522 NullOp::AlignOf => {}
525 Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),
527 Rvalue::UnaryOp(op, operand) => {
529 // These operations can never fail.
530 UnOp::Neg | UnOp::Not => {}
533 self.validate_operand(operand)?;
536 Rvalue::BinaryOp(op, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(op, box (lhs, rhs)) => {
538 let lhs_ty = lhs.ty(self.body, self.tcx);
540 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs_ty.kind() {
541 // Raw and fn pointer operations are not allowed inside consts and thus not promotable.
552 return Err(Unpromotable);
556 BinOp::Div | BinOp::Rem => {
557 if lhs_ty.is_integral() {
558 // Integer division: the RHS must be a non-zero const.
559 let const_val = match rhs {
560 Operand::Constant(c) => {
561 c.literal.try_eval_bits(self.tcx, self.param_env, lhs_ty)
566 Some(x) if x != 0 => {} // okay
567 _ => return Err(Unpromotable), // value not known or 0 -- not okay
571 // The remaining operations can never fail.
589 self.validate_operand(lhs)?;
590 self.validate_operand(rhs)?;
593 Rvalue::AddressOf(_, place) => {
594 // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
595 // no problem, only using it is.
596 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
598 let base_ty = place_base.ty(self.body, self.tcx).ty;
599 if let ty::Ref(..) = base_ty.kind() {
600 return self.validate_place(place_base);
603 return Err(Unpromotable);
606 Rvalue::Ref(_, kind, place) => {
607 // Special-case reborrows to be more like a copy of the reference.
608 let mut place_simplified = place.as_ref();
609 if let Some((place_base, ProjectionElem::Deref)) =
610 place_simplified.last_projection()
612 let base_ty = place_base.ty(self.body, self.tcx).ty;
613 if let ty::Ref(..) = base_ty.kind() {
614 place_simplified = place_base;
618 self.validate_place(place_simplified)?;
620 // Check that the reference is fine (using the original place!).
621 // (Needs to come after `validate_place` to avoid ICEs.)
622 self.validate_ref(*kind, place)?;
625 Rvalue::Aggregate(_, operands) => {
627 self.validate_operand(o)?;
637 callee: &Operand<'tcx>,
638 args: &[Operand<'tcx>],
639 ) -> Result<(), Unpromotable> {
640 let fn_ty = callee.ty(self.body, self.tcx);
642 // Inside const/static items, we promote all (eligible) function calls.
643 // Everywhere else, we require `#[rustc_promotable]` on the callee.
644 let promote_all_const_fn = matches!(
646 Some(hir::ConstContext::Static(_) | hir::ConstContext::Const)
648 if !promote_all_const_fn {
649 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
650 // Never promote runtime `const fn` calls of
651 // functions without `#[rustc_promotable]`.
652 if !self.tcx.is_promotable_const_fn(def_id) {
653 return Err(Unpromotable);
658 let is_const_fn = match *fn_ty.kind() {
659 ty::FnDef(def_id, _) => {
660 self.tcx.is_const_fn_raw(def_id) || is_lang_special_const_fn(self.tcx, def_id)
665 return Err(Unpromotable);
668 self.validate_operand(callee)?;
670 self.validate_operand(arg)?;
677 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
678 pub fn validate_candidates(
679 ccx: &ConstCx<'_, '_>,
680 temps: &IndexVec<Local, TempState>,
681 candidates: &[Candidate],
682 ) -> Vec<Candidate> {
683 let validator = Validator { ccx, temps };
688 .filter(|&candidate| validator.validate_candidate(candidate).is_ok())
692 struct Promoter<'a, 'tcx> {
694 source: &'a mut Body<'tcx>,
695 promoted: Body<'tcx>,
696 temps: &'a mut IndexVec<Local, TempState>,
697 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
699 /// If true, all nested temps are also kept in the
700 /// source MIR, not moved to the promoted MIR.
704 impl<'a, 'tcx> Promoter<'a, 'tcx> {
705 fn new_block(&mut self) -> BasicBlock {
706 let span = self.promoted.span;
707 self.promoted.basic_blocks_mut().push(BasicBlockData {
709 terminator: Some(Terminator {
710 source_info: SourceInfo::outermost(span),
711 kind: TerminatorKind::Return,
717 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
718 let last = self.promoted.basic_blocks().last().unwrap();
719 let data = &mut self.promoted[last];
720 data.statements.push(Statement {
721 source_info: SourceInfo::outermost(span),
722 kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
726 fn is_temp_kind(&self, local: Local) -> bool {
727 self.source.local_kind(local) == LocalKind::Temp
730 /// Copies the initialization of this temp to the
731 /// promoted MIR, recursing through temps.
732 fn promote_temp(&mut self, temp: Local) -> Local {
733 let old_keep_original = self.keep_original;
734 let loc = match self.temps[temp] {
735 TempState::Defined { location, uses } if uses > 0 => {
737 self.keep_original = true;
742 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
745 if !self.keep_original {
746 self.temps[temp] = TempState::PromotedOut;
749 let num_stmts = self.source[loc.block].statements.len();
750 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
751 self.source.local_decls[temp].ty,
752 self.source.local_decls[temp].source_info.span,
755 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
757 // First, take the Rvalue or Call out of the source MIR,
758 // or duplicate it, depending on keep_original.
759 if loc.statement_index < num_stmts {
760 let (mut rvalue, source_info) = {
761 let statement = &mut self.source[loc.block].statements[loc.statement_index];
762 let rhs = match statement.kind {
763 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
766 statement.source_info.span,
767 "{:?} is not an assignment",
774 if self.keep_original {
777 let unit = Rvalue::Use(Operand::Constant(Box::new(Constant {
778 span: statement.source_info.span,
780 literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit).into(),
782 mem::replace(rhs, unit)
784 statement.source_info,
788 self.visit_rvalue(&mut rvalue, loc);
789 self.assign(new_temp, rvalue, source_info.span);
791 let terminator = if self.keep_original {
792 self.source[loc.block].terminator().clone()
794 let terminator = self.source[loc.block].terminator_mut();
795 let target = match terminator.kind {
796 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
798 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
802 source_info: terminator.source_info,
803 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
807 match terminator.kind {
808 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
809 self.visit_operand(&mut func, loc);
810 for arg in &mut args {
811 self.visit_operand(arg, loc);
814 let last = self.promoted.basic_blocks().last().unwrap();
815 let new_target = self.new_block();
817 *self.promoted[last].terminator_mut() = Terminator {
818 kind: TerminatorKind::Call {
822 destination: Some((Place::from(new_temp), new_target)),
826 source_info: SourceInfo::outermost(terminator.source_info.span),
831 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
836 self.keep_original = old_keep_original;
840 fn promote_candidate(
842 candidate: Candidate,
843 next_promoted_id: usize,
844 ) -> Option<Body<'tcx>> {
845 let def = self.source.source.with_opt_param();
847 let promoted = &mut self.promoted;
848 let promoted_id = Promoted::new(next_promoted_id);
850 let mut promoted_operand = |ty, span| {
851 promoted.span = span;
852 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
854 Operand::Constant(Box::new(Constant {
858 .mk_const(ty::Const {
860 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
862 substs_: Some(InternalSubsts::for_item(
866 if let ty::GenericParamDefKind::Lifetime = param.kind {
867 tcx.lifetimes.re_erased.into()
869 tcx.mk_param_from_def(param)
873 promoted: Some(promoted_id),
879 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
881 Candidate::Ref(loc) => {
882 let statement = &mut blocks[loc.block].statements[loc.statement_index];
883 match statement.kind {
884 StatementKind::Assign(box (
886 Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
888 // Use the underlying local for this (necessarily interior) borrow.
889 let ty = local_decls.local_decls()[place.local].ty;
890 let span = statement.source_info.span;
892 let ref_ty = tcx.mk_ref(
893 tcx.lifetimes.re_erased,
894 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
897 *region = tcx.lifetimes.re_erased;
899 let mut projection = vec![PlaceElem::Deref];
900 projection.extend(place.projection);
901 place.projection = tcx.intern_place_elems(&projection);
903 // Create a temp to hold the promoted reference.
904 // This is because `*r` requires `r` to be a local,
905 // otherwise we would use the `promoted` directly.
906 let mut promoted_ref = LocalDecl::new(ref_ty, span);
907 promoted_ref.source_info = statement.source_info;
908 let promoted_ref = local_decls.push(promoted_ref);
909 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
911 let promoted_ref_statement = Statement {
912 source_info: statement.source_info,
913 kind: StatementKind::Assign(Box::new((
914 Place::from(promoted_ref),
915 Rvalue::Use(promoted_operand(ref_ty, span)),
918 self.extra_statements.push((loc, promoted_ref_statement));
921 tcx.lifetimes.re_erased,
924 local: mem::replace(&mut place.local, promoted_ref),
925 projection: List::empty(),
935 assert_eq!(self.new_block(), START_BLOCK);
938 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
941 let span = self.promoted.span;
942 self.assign(RETURN_PLACE, rvalue, span);
947 /// Replaces all temporaries with their promoted counterparts.
948 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
949 fn tcx(&self) -> TyCtxt<'tcx> {
953 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
954 if self.is_temp_kind(*local) {
955 *local = self.promote_temp(*local);
960 pub fn promote_candidates<'tcx>(
961 body: &mut Body<'tcx>,
963 mut temps: IndexVec<Local, TempState>,
964 candidates: Vec<Candidate>,
965 ) -> IndexVec<Promoted, Body<'tcx>> {
966 // Visit candidates in reverse, in case they're nested.
967 debug!("promote_candidates({:?})", candidates);
969 let mut promotions = IndexVec::new();
971 let mut extra_statements = vec![];
972 for candidate in candidates.into_iter().rev() {
974 Candidate::Ref(Location { block, statement_index }) => {
975 if let StatementKind::Assign(box (place, _)) =
976 &body[block].statements[statement_index].kind
978 if let Some(local) = place.as_local() {
979 if temps[local] == TempState::PromotedOut {
988 // Declare return place local so that `mir::Body::new` doesn't complain.
989 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
991 let mut scope = body.source_scopes[candidate.source_info(body).scope].clone();
992 scope.parent_scope = None;
994 let promoted = Body::new(
996 body.source, // `promoted` gets filled in below
998 IndexVec::from_elem_n(scope, 1),
1004 body.generator_kind(),
1007 let promoter = Promoter {
1012 extra_statements: &mut extra_statements,
1013 keep_original: false,
1016 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1017 if let Some(mut promoted) = promoter.promote_candidate(candidate, promotions.len()) {
1018 promoted.source.promoted = Some(promotions.next_index());
1019 promotions.push(promoted);
1023 // Insert each of `extra_statements` before its indicated location, which
1024 // has to be done in reverse location order, to not invalidate the rest.
1025 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1026 for (loc, statement) in extra_statements {
1027 body[loc.block].statements.insert(loc.statement_index, statement);
1030 // Eliminate assignments to, and drops of promoted temps.
1031 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1032 for block in body.basic_blocks_mut() {
1033 block.statements.retain(|statement| match &statement.kind {
1034 StatementKind::Assign(box (place, _)) => {
1035 if let Some(index) = place.as_local() {
1041 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1046 let terminator = block.terminator_mut();
1047 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1048 if let Some(index) = place.as_local() {
1049 if promoted(index) {
1050 terminator.kind = TerminatorKind::Goto { target: *target };
1059 /// This function returns `true` if the function being called in the array
1060 /// repeat expression is a `const` function.
1061 pub fn is_const_fn_in_array_repeat_expression<'tcx>(
1062 ccx: &ConstCx<'_, 'tcx>,
1063 place: &Place<'tcx>,
1066 match place.as_local() {
1067 // rule out cases such as: `let my_var = some_fn(); [my_var; N]`
1068 Some(local) if body.local_decls[local].is_user_variable() => return false,
1069 None => return false,
1073 for block in body.basic_blocks() {
1074 if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) =
1077 if let Operand::Constant(box Constant { literal, .. }) = func {
1078 if let ty::FnDef(def_id, _) = *literal.ty().kind() {
1079 if let Some((destination_place, _)) = destination {
1080 if destination_place == place {
1081 if ccx.tcx.is_const_fn(def_id) {