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