1use std::cell::Cell;
14use std::{assert_matches, cmp, iter, mem};
15
16use either::{Left, Right};
17use rustc_const_eval::check_consts::{ConstCx, qualifs};
18use rustc_data_structures::fx::FxHashSet;
19use rustc_hir as hir;
20use rustc_hir::def::DefKind;
21use rustc_index::{IndexSlice, IndexVec};
22use rustc_middle::mir;
23use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
24use rustc_middle::mir::*;
25use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
26use rustc_span::{Span, Spanned, bug, span_bug};
27use tracing::{debug, instrument};
28
29use crate::PassPolicy;
30
31#[derive(Default)]
39pub(super) struct PromoteTemps<'tcx> {
40 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
42}
43
44impl<'tcx> crate::MirPass<'tcx> for PromoteTemps<'tcx> {
45 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
46 if let Err(_) = body.return_ty().error_reported() {
50 debug!("PromoteTemps: MIR had errors");
51 return;
52 }
53 if body.source.promoted.is_some() {
54 return;
55 }
56
57 let ccx = ConstCx::new(tcx, body);
58 let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx);
59
60 let promotable_candidates = validate_candidates(&ccx, &mut temps, all_candidates);
61
62 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
63 self.promoted_fragments.set(promoted);
64 }
65
66 fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
67 PassPolicy::Required
69 }
70}
71
72#[derive(Copy, Clone, PartialEq, Eq, Debug)]
74enum TempState {
75 Undefined,
77 Defined { location: Location, uses: usize, valid: Result<(), ()> },
81 Unpromotable,
83 PromotedOut,
86}
87
88#[derive(Copy, Clone, PartialEq, Eq, Debug)]
92struct Candidate {
93 location: Location,
94}
95
96struct Collector<'a, 'tcx> {
97 ccx: &'a ConstCx<'a, 'tcx>,
98 temps: IndexVec<Local, TempState>,
99 candidates: Vec<Candidate>,
100}
101
102impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
103 #[instrument(level = "debug", skip(self))]
104 fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
105 match self.ccx.body.local_kind(index) {
107 LocalKind::Arg => return,
108 LocalKind::Temp if self.ccx.body.local_decls[index].is_user_variable() => return,
109 LocalKind::ReturnPointer | LocalKind::Temp => {}
110 }
111
112 if context.is_drop() || !context.is_use() {
116 debug!(is_drop = context.is_drop(), is_use = context.is_use());
117 return;
118 }
119
120 let temp = &mut self.temps[index];
121 debug!(?temp);
122 *temp = match *temp {
123 TempState::Undefined => match context {
124 PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {
125 TempState::Defined { location, uses: 0, valid: Err(()) }
126 }
127 _ => TempState::Unpromotable,
128 },
129 TempState::Defined { ref mut uses, .. } => {
130 let allowed_use = match context {
133 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
134 | PlaceContext::NonMutatingUse(_) => true,
135 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
136 };
137 debug!(?allowed_use);
138 if allowed_use {
139 *uses += 1;
140 return;
141 }
142 TempState::Unpromotable
143 }
144 TempState::Unpromotable | TempState::PromotedOut => TempState::Unpromotable,
145 };
146 debug!(?temp);
147 }
148
149 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
150 self.super_rvalue(rvalue, location);
151
152 if let Rvalue::Ref(..) = *rvalue {
153 self.candidates.push(Candidate { location });
154 }
155 }
156}
157
158fn collect_temps_and_candidates<'tcx>(
159 ccx: &ConstCx<'_, 'tcx>,
160) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
161 let mut collector = Collector {
162 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
163 candidates: vec![],
164 ccx,
165 };
166 for (bb, data) in traversal::reverse_postorder(ccx.body) {
167 collector.visit_basic_block_data(bb, data);
168 }
169 (collector.temps, collector.candidates)
170}
171
172struct Validator<'a, 'tcx> {
176 ccx: &'a ConstCx<'a, 'tcx>,
177 temps: &'a mut IndexSlice<Local, TempState>,
178 promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
184}
185
186impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
187 type Target = ConstCx<'a, 'tcx>;
188
189 fn deref(&self) -> &Self::Target {
190 self.ccx
191 }
192}
193
194struct Unpromotable;
195
196impl<'tcx> Validator<'_, 'tcx> {
197 fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
198 let Left(statement) = self.body.stmt_at(candidate.location) else { bug!() };
199 let Some((_, Rvalue::Ref(_, kind, place))) = statement.kind.as_assign() else { bug!() };
200
201 self.validate_local(place.local)?;
204
205 self.validate_ref(*kind, place)?;
208
209 if place.projection.contains(&ProjectionElem::Deref) {
212 return Err(Unpromotable);
213 }
214
215 Ok(())
216 }
217
218 fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
220 let TempState::Defined { location: loc, .. } = self.temps[local] else {
221 return false;
222 };
223
224 let stmt_or_term = self.body.stmt_at(loc);
225 match stmt_or_term {
226 Left(statement) => {
227 let Some((_, rhs)) = statement.kind.as_assign() else {
228 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement)
229 };
230 qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.qualif_local::<Q>(l), rhs)
231 }
232 Right(terminator) => {
233 assert_matches!(terminator.kind, TerminatorKind::Call { .. });
234 let return_ty = self.body.local_decls[local].ty;
235 Q::in_any_value_of_ty(self.ccx, return_ty)
236 }
237 }
238 }
239
240 fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
241 let TempState::Defined { location: loc, uses, valid } = self.temps[local] else {
242 return Err(Unpromotable);
243 };
244
245 if self.qualif_local::<qualifs::NeedsDrop>(local) {
248 return Err(Unpromotable);
249 }
250
251 if valid.is_ok() {
252 return Ok(());
253 }
254
255 let ok = {
256 let stmt_or_term = self.body.stmt_at(loc);
257 match stmt_or_term {
258 Left(statement) => {
259 let Some((_, rhs)) = statement.kind.as_assign() else {
260 span_bug!(
261 statement.source_info.span,
262 "{:?} is not an assignment",
263 statement
264 )
265 };
266 self.validate_rvalue(rhs)
267 }
268 Right(terminator) => match &terminator.kind {
269 TerminatorKind::Call { func, args, .. } => {
270 self.validate_call(func, args, loc.block)
271 }
272 TerminatorKind::Yield { .. } => Err(Unpromotable),
273 kind => {
274 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
275 }
276 },
277 }
278 };
279
280 self.temps[local] = match ok {
281 Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
282 Err(_) => TempState::Unpromotable,
283 };
284
285 ok
286 }
287
288 fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
289 let Some((place_base, elem)) = place.last_projection() else {
290 return self.validate_local(place.local);
291 };
292
293 match elem {
295 ProjectionElem::ConstantIndex { .. }
297 | ProjectionElem::Subslice { .. }
298 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
299
300 ProjectionElem::PhantomDeref
302 | ProjectionElem::OpaqueCast(..)
303 | ProjectionElem::Downcast(..) => {
304 return Err(Unpromotable);
305 }
306
307 ProjectionElem::Deref => {
308 if let Some(local) = place_base.as_local()
316 && let TempState::Defined { location, .. } = self.temps[local]
317 && let Left(def_stmt) = self.body.stmt_at(location)
318 && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = def_stmt.kind.as_assign()
319 && let Some(did) = c.check_static_ptr(self.tcx)
320 && let Some(hir::ConstContext::Static(..)) = self.const_kind
324 && !self.tcx.is_thread_local_static(did)
325 && !self.tcx.is_foreign_item(did)
327 {
328 } else {
330 return Err(Unpromotable);
331 }
332 }
333 ProjectionElem::Index(local) => {
334 if let TempState::Defined { location: loc, .. } = self.temps[local]
336 && let Left(statement) = self.body.stmt_at(loc)
337 && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = statement.kind.as_assign()
338 && self.should_evaluate_for_promotion_checks(c.const_)
339 && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
340 && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
342 && let Some(len) = len.try_to_target_usize(self.tcx)
344 && idx < len
346 {
347 self.validate_local(local)?;
348 } else {
350 return Err(Unpromotable);
351 }
352 }
353
354 ProjectionElem::Field(..) => {
355 let base_ty = place_base.ty(self.body, self.tcx).ty;
356 if base_ty.is_union() {
357 return Err(Unpromotable);
359 }
360 }
361 }
362
363 self.validate_place(place_base)
364 }
365
366 fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
367 match operand {
368 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
369
370 Operand::RuntimeChecks(_) => Err(Unpromotable),
373
374 Operand::Constant(c) => {
377 if let Some(def_id) = c.check_static_ptr(self.tcx) {
378 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
385 if !is_static {
386 return Err(Unpromotable);
387 }
388
389 let is_thread_local = self.tcx.is_thread_local_static(def_id);
390 if is_thread_local {
391 return Err(Unpromotable);
392 }
393 }
394
395 Ok(())
396 }
397 }
398 }
399
400 fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
401 match kind {
402 BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
406 return Err(Unpromotable);
407 }
408
409 BorrowKind::Shared => {
410 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
411 if has_mut_interior {
412 return Err(Unpromotable);
413 }
414 }
415
416 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
419 let ty = place.ty(self.body, self.tcx).ty;
420
421 let ty::Array(_, len) = ty.kind() else { return Err(Unpromotable) };
425 let Some(0) = len.try_to_target_usize(self.tcx) else { return Err(Unpromotable) };
426 }
427 }
428
429 Ok(())
430 }
431
432 fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
433 match rvalue {
434 Rvalue::Use(_operand, WithRetag::No) => {
435 return Err(Unpromotable);
438 }
439 Rvalue::Use(operand, _)
440 | Rvalue::Repeat(operand, _)
441 | Rvalue::WrapUnsafeBinder(operand, _) => {
442 self.validate_operand(operand)?;
443 }
444 Rvalue::CopyForDeref(place) => {
445 let op = &Operand::Copy(*place);
446 self.validate_operand(op)?
447 }
448
449 Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
450
451 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
452
453 Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
455
456 Rvalue::Cast(_, operand, _) => {
459 self.validate_operand(operand)?;
460 }
461
462 Rvalue::UnaryOp(op, operand) => {
463 match op {
464 UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
466 }
467
468 self.validate_operand(operand)?;
469 }
470
471 Rvalue::BinaryOp(op, (lhs, rhs)) => {
472 let op = *op;
473 let lhs_ty = lhs.ty(self.body, self.tcx);
474
475 if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
476 assert_matches!(
479 op,
480 BinOp::Eq
481 | BinOp::Ne
482 | BinOp::Le
483 | BinOp::Lt
484 | BinOp::Ge
485 | BinOp::Gt
486 | BinOp::Offset
487 );
488 return Err(Unpromotable);
489 }
490
491 match op {
492 BinOp::Div | BinOp::Rem => {
493 if lhs_ty.is_integral() {
494 let sz = lhs_ty.primitive_size(self.tcx);
495 let rhs_val = if let Operand::Constant(rhs_c) = rhs
497 && self.should_evaluate_for_promotion_checks(rhs_c.const_)
498 && let Some(rhs_val) =
499 rhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
500 && rhs_val.to_uint(sz) != 0
502 {
503 rhs_val
504 } else {
505 return Err(Unpromotable);
507 };
508 if lhs_ty.is_signed() && rhs_val.to_int(sz) == -1 {
511 if let Operand::Constant(lhs_c) = lhs
513 && self.should_evaluate_for_promotion_checks(lhs_c.const_)
514 && let Some(lhs_val) =
515 lhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
516 && let lhs_min = sz.signed_int_min()
517 && lhs_val.to_int(sz) != lhs_min
518 {
519 } else {
521 return Err(Unpromotable);
523 }
524 }
525 }
526 }
527 BinOp::Eq
529 | BinOp::Ne
530 | BinOp::Le
531 | BinOp::Lt
532 | BinOp::Ge
533 | BinOp::Gt
534 | BinOp::Cmp
535 | BinOp::Offset
536 | BinOp::Add
537 | BinOp::AddUnchecked
538 | BinOp::AddWithOverflow
539 | BinOp::Sub
540 | BinOp::SubUnchecked
541 | BinOp::SubWithOverflow
542 | BinOp::Mul
543 | BinOp::MulUnchecked
544 | BinOp::MulWithOverflow
545 | BinOp::BitXor
546 | BinOp::BitAnd
547 | BinOp::BitOr
548 | BinOp::Shl
549 | BinOp::ShlUnchecked
550 | BinOp::Shr
551 | BinOp::ShrUnchecked => {}
552 }
553
554 self.validate_operand(lhs)?;
555 self.validate_operand(rhs)?;
556 }
557
558 Rvalue::RawPtr(_, place) => {
559 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
562 {
563 let base_ty = place_base.ty(self.body, self.tcx).ty;
564 if let ty::Ref(..) = base_ty.kind() {
565 return self.validate_place(place_base);
566 }
567 }
568 return Err(Unpromotable);
569 }
570
571 Rvalue::Ref(_, kind, place) => {
572 let mut place_simplified = place.as_ref();
574 if let Some((place_base, ProjectionElem::Deref)) =
575 place_simplified.last_projection()
576 {
577 let base_ty = place_base.ty(self.body, self.tcx).ty;
578 if let ty::Ref(..) = base_ty.kind() {
579 place_simplified = place_base;
580 }
581 }
582
583 self.validate_place(place_simplified)?;
584
585 self.validate_ref(*kind, place)?;
588 }
589
590 Rvalue::Reborrow(..) => return Err(Unpromotable),
591
592 Rvalue::Aggregate(_, operands) => {
593 for o in operands {
594 self.validate_operand(o)?;
595 }
596 }
597 }
598
599 Ok(())
600 }
601
602 fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
606 let mut safe_blocks = FxHashSet::default();
607 let mut safe_block = START_BLOCK;
608 loop {
609 safe_blocks.insert(safe_block);
610 safe_block = match body.basic_blocks[safe_block].terminator().kind {
612 TerminatorKind::Goto { target, .. } => target,
613 TerminatorKind::Call { target: Some(target), .. }
614 | TerminatorKind::Drop { target, .. } => {
615 target
619 }
620 TerminatorKind::Assert { target, .. } => {
621 target
623 }
624 _ => {
625 break;
627 }
628 };
629 }
630 safe_blocks
631 }
632
633 fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
636 let body = self.body;
637 let safe_blocks =
638 self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
639 safe_blocks.contains(&block)
640 }
641
642 fn validate_call(
643 &mut self,
644 callee: &Operand<'tcx>,
645 args: &[Spanned<Operand<'tcx>>],
646 block: BasicBlock,
647 ) -> Result<(), Unpromotable> {
648 self.validate_operand(callee)?;
650 for arg in args {
651 self.validate_operand(&arg.node)?;
652 }
653
654 let fn_ty = callee.ty(self.body, self.tcx);
657 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
658 if self.tcx.is_promotable_const_fn(def_id) {
659 return Ok(());
660 }
661 }
662
663 let promote_all_fn = matches!(
668 self.const_kind,
669 Some(
670 hir::ConstContext::Static(_)
671 | hir::ConstContext::Const { allow_const_fn_promotion: true }
672 )
673 );
674 if !promote_all_fn {
675 return Err(Unpromotable);
676 }
677 let is_const_fn = match *fn_ty.kind() {
679 ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
680 _ => false,
681 };
682 if !is_const_fn {
683 return Err(Unpromotable);
684 }
685 if !self.is_promotion_safe_block(block) {
689 return Err(Unpromotable);
690 }
691 Ok(())
693 }
694
695 fn should_evaluate_for_promotion_checks(&self, constant: Const<'tcx>) -> bool {
698 match constant {
699 Const::Ty(..) => false,
703 Const::Val(..) => true,
704 Const::Unevaluated(uc, _) => {
714 self.tcx.def_kind(uc.def) != DefKind::AnonConst
715 || self.tcx.anon_const_kind(uc.def) != ty::AnonConstKind::NonTypeSystemInline
716 }
717 }
718 }
719}
720
721fn validate_candidates(
722 ccx: &ConstCx<'_, '_>,
723 temps: &mut IndexSlice<Local, TempState>,
724 mut candidates: Vec<Candidate>,
725) -> Vec<Candidate> {
726 let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
727
728 candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
729 candidates
730}
731
732struct Promoter<'a, 'tcx> {
733 tcx: TyCtxt<'tcx>,
734 source: &'a mut Body<'tcx>,
735 promoted: Body<'tcx>,
736 temps: &'a mut IndexVec<Local, TempState>,
737 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
738
739 required_consts: Vec<ConstOperand<'tcx>>,
741
742 keep_original: bool,
745
746 add_to_required: bool,
749}
750
751impl<'a, 'tcx> Promoter<'a, 'tcx> {
752 fn new_block(&mut self) -> BasicBlock {
753 let span = self.promoted.span;
754 self.promoted.basic_blocks_mut().push(BasicBlockData::new(
755 Terminator { source_info: SourceInfo::outermost(span), kind: TerminatorKind::Return },
756 false,
757 ))
758 }
759
760 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
761 let last = self.promoted.basic_blocks.last_index().unwrap();
762 let data = &mut self.promoted[last];
763 data.statements.push(Statement::new(
764 SourceInfo::outermost(span),
765 StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
766 ));
767 }
768
769 fn is_temp_kind(&self, local: Local) -> bool {
770 self.source.local_kind(local) == LocalKind::Temp
771 }
772
773 fn promote_temp(&mut self, temp: Local) -> Local {
776 let old_keep_original = self.keep_original;
777 let loc = match self.temps[temp] {
778 TempState::Defined { location, uses, .. } if uses > 0 => {
779 if uses > 1 {
780 self.keep_original = true;
781 }
782 location
783 }
784 state => {
785 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
786 }
787 };
788 if !self.keep_original {
789 self.temps[temp] = TempState::PromotedOut;
790 }
791
792 let num_stmts = self.source[loc.block].statements.len();
793 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
794 self.source.local_decls[temp].ty,
795 self.source.local_decls[temp].source_info.span,
796 ));
797
798 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
799
800 if loc.statement_index < num_stmts {
803 let (mut rvalue, source_info) = {
804 let statement = &mut self.source[loc.block].statements[loc.statement_index];
805 let StatementKind::Assign((_, rhs)) = &mut statement.kind else {
806 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
807 };
808
809 (
810 if self.keep_original {
811 rhs.clone()
812 } else {
813 let unit = Rvalue::Use(
814 Operand::zero_sized_constant(
815 self.tcx.types.unit,
816 statement.source_info.span,
817 ),
818 WithRetag::Yes,
819 );
820 mem::replace(rhs, unit)
821 },
822 statement.source_info,
823 )
824 };
825
826 self.visit_rvalue(&mut rvalue, loc);
827 self.assign(new_temp, rvalue, source_info.span);
828 } else {
829 let terminator = if self.keep_original {
830 self.source[loc.block].terminator().clone()
831 } else {
832 let terminator = self.source[loc.block].terminator_mut();
833 let target = match &terminator.kind {
834 TerminatorKind::Call { target: Some(target), .. } => *target,
835 kind => {
836 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
837 }
838 };
839 Terminator {
840 source_info: terminator.source_info,
841 kind: mem::replace(&mut terminator.kind, TerminatorKind::goto(target)),
842 }
843 };
844
845 match terminator.kind {
846 TerminatorKind::Call {
847 mut func, mut args, call_source: desugar, fn_span, ..
848 } => {
849 self.add_to_required = true;
852
853 self.visit_operand(&mut func, loc);
854 for arg in &mut args {
855 self.visit_operand(&mut arg.node, loc);
856 }
857
858 let last = self.promoted.basic_blocks.last_index().unwrap();
859 let new_target = self.new_block();
860
861 *self.promoted[last].terminator_mut() = Terminator {
862 kind: TerminatorKind::Call {
863 func,
864 args,
865 unwind: UnwindAction::Continue,
866 destination: Place::from(new_temp),
867 target: Some(new_target),
868 call_source: desugar,
869 fn_span,
870 },
871 source_info: SourceInfo::outermost(terminator.source_info.span),
872 ..terminator
873 };
874 }
875 kind => {
876 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
877 }
878 };
879 };
880
881 self.keep_original = old_keep_original;
882 new_temp
883 }
884
885 fn promote_candidate(
886 mut self,
887 candidate: Candidate,
888 next_promoted_index: Promoted,
889 ) -> Body<'tcx> {
890 let def = self.source.source.def_id();
891 let (mut rvalue, promoted_op) = {
892 let promoted = &mut self.promoted;
893 let tcx = self.tcx;
894 let mut promoted_operand = |ty, span| {
895 promoted.span = span;
896 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
897 let args =
898 tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
899 let uneval =
900 mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
901
902 ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
903 };
904
905 let blocks = self.source.basic_blocks.as_mut();
906 let local_decls = &mut self.source.local_decls;
907 let loc = candidate.location;
908 let statement = &mut blocks[loc.block].statements[loc.statement_index];
909 let StatementKind::Assign((_, Rvalue::Ref(region, borrow_kind, place))) =
910 &mut statement.kind
911 else {
912 bug!()
913 };
914
915 debug_assert!(region.is_erased());
917 let ty = local_decls[place.local].ty;
918 let span = statement.source_info.span;
919
920 let ref_ty =
921 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
922
923 let mut projection = vec![PlaceElem::Deref];
924 projection.extend(place.projection);
925 place.projection = tcx.mk_place_elems(&projection);
926
927 let mut promoted_ref = LocalDecl::new(ref_ty, span);
931 promoted_ref.source_info = statement.source_info;
932 let promoted_ref = local_decls.push(promoted_ref);
933 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
934
935 let promoted_operand = promoted_operand(ref_ty, span);
936 let promoted_ref_statement = Statement::new(
937 statement.source_info,
938 StatementKind::Assign(Box::new((
939 Place::from(promoted_ref),
940 Rvalue::Use(Operand::Constant(Box::new(promoted_operand)), WithRetag::Yes),
943 ))),
944 );
945 self.extra_statements.push((loc, promoted_ref_statement));
946
947 (
948 Rvalue::Ref(
949 tcx.lifetimes.re_erased,
950 *borrow_kind,
951 Place {
952 local: mem::replace(&mut place.local, promoted_ref),
953 projection: List::empty(),
954 },
955 ),
956 promoted_operand,
957 )
958 };
959
960 assert_eq!(self.new_block(), START_BLOCK);
961 self.visit_rvalue(
962 &mut rvalue,
963 Location { block: START_BLOCK, statement_index: usize::MAX },
964 );
965
966 let span = self.promoted.span;
967 self.assign(RETURN_PLACE, rvalue, span);
968
969 if self.add_to_required {
972 self.source.required_consts.as_mut().unwrap().push(promoted_op);
973 }
974
975 self.promoted.set_required_consts(self.required_consts);
976
977 self.promoted
978 }
979}
980
981impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
983 fn tcx(&self) -> TyCtxt<'tcx> {
984 self.tcx
985 }
986
987 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
988 if self.is_temp_kind(*local) {
989 *local = self.promote_temp(*local);
990 }
991 }
992
993 fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
994 if constant.const_.is_required_const() {
995 self.required_consts.push(*constant);
996 }
997
998 }
1000}
1001
1002fn promote_candidates<'tcx>(
1003 body: &mut Body<'tcx>,
1004 tcx: TyCtxt<'tcx>,
1005 mut temps: IndexVec<Local, TempState>,
1006 candidates: Vec<Candidate>,
1007) -> IndexVec<Promoted, Body<'tcx>> {
1008 debug!(promote_candidates = ?candidates);
1010
1011 if candidates.is_empty() {
1013 return IndexVec::new();
1014 }
1015
1016 let mut promotions = IndexVec::new();
1017
1018 let mut extra_statements = vec![];
1019 for candidate in candidates.into_iter().rev() {
1020 let Location { block, statement_index } = candidate.location;
1021 if let StatementKind::Assign((place, _)) = &body[block].statements[statement_index].kind
1022 && let Some(local) = place.as_local()
1023 {
1024 if temps[local] == TempState::PromotedOut {
1025 continue;
1027 }
1028 }
1029
1030 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1032
1033 let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1034 scope.parent_scope = None;
1035
1036 let mut promoted = Body::new(
1037 body.source, IndexVec::new(),
1039 IndexVec::from_elem_n(scope, 1),
1040 initial_locals,
1041 IndexVec::new(),
1042 0,
1043 vec![],
1044 body.span,
1045 None,
1046 body.tainted_by_errors,
1047 );
1048 promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1049
1050 let promoter = Promoter {
1051 promoted,
1052 tcx,
1053 source: body,
1054 temps: &mut temps,
1055 extra_statements: &mut extra_statements,
1056 keep_original: false,
1057 add_to_required: false,
1058 required_consts: Vec::new(),
1059 };
1060
1061 let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1062 promoted.source.promoted = Some(promotions.next_index());
1063 promotions.push(promoted);
1064 }
1065
1066 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1069 for (loc, statement) in extra_statements {
1070 body[loc.block].statements.insert(loc.statement_index, statement);
1071 }
1072
1073 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1075 for block in body.basic_blocks_mut() {
1076 block.retain_statements(|statement| match &statement.kind {
1077 StatementKind::Assign((place, _)) => {
1078 if let Some(index) = place.as_local() {
1079 !promoted(index)
1080 } else {
1081 true
1082 }
1083 }
1084 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1085 !promoted(*index)
1086 }
1087 _ => true,
1088 });
1089 let terminator = block.terminator_mut();
1090 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1091 && let Some(index) = place.as_local()
1092 {
1093 if promoted(index) {
1094 terminator.kind = TerminatorKind::goto(*target);
1095 }
1096 }
1097 }
1098
1099 promotions
1100}