1use std::assert_matches::assert_matches;
14use std::cell::Cell;
15use std::{cmp, iter, mem};
16
17use either::{Left, Right};
18use rustc_const_eval::check_consts::{ConstCx, qualifs};
19use rustc_data_structures::fx::FxHashSet;
20use rustc_hir as hir;
21use rustc_index::{Idx, IndexSlice, IndexVec};
22use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
23use rustc_middle::mir::*;
24use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
25use rustc_middle::{bug, mir, span_bug};
26use rustc_span::Span;
27use rustc_span::source_map::Spanned;
28use tracing::{debug, instrument};
29
30#[derive(Default)]
38pub(super) struct PromoteTemps<'tcx> {
39 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
41}
42
43impl<'tcx> crate::MirPass<'tcx> for PromoteTemps<'tcx> {
44 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
45 if let Err(_) = body.return_ty().error_reported() {
49 debug!("PromoteTemps: MIR had errors");
50 return;
51 }
52 if body.source.promoted.is_some() {
53 return;
54 }
55
56 let ccx = ConstCx::new(tcx, body);
57 let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx);
58
59 let promotable_candidates = validate_candidates(&ccx, &mut temps, all_candidates);
60
61 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
62 self.promoted_fragments.set(promoted);
63 }
64
65 fn is_required(&self) -> bool {
66 true
67 }
68}
69
70#[derive(Copy, Clone, PartialEq, Eq, Debug)]
72enum TempState {
73 Undefined,
75 Defined { location: Location, uses: usize, valid: Result<(), ()> },
79 Unpromotable,
81 PromotedOut,
84}
85
86#[derive(Copy, Clone, PartialEq, Eq, Debug)]
90struct Candidate {
91 location: Location,
92}
93
94struct Collector<'a, 'tcx> {
95 ccx: &'a ConstCx<'a, 'tcx>,
96 temps: IndexVec<Local, TempState>,
97 candidates: Vec<Candidate>,
98}
99
100impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
101 #[instrument(level = "debug", skip(self))]
102 fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
103 match self.ccx.body.local_kind(index) {
105 LocalKind::Arg => return,
106 LocalKind::Temp if self.ccx.body.local_decls[index].is_user_variable() => return,
107 LocalKind::ReturnPointer | LocalKind::Temp => {}
108 }
109
110 if context.is_drop() || !context.is_use() {
114 debug!(is_drop = context.is_drop(), is_use = context.is_use());
115 return;
116 }
117
118 let temp = &mut self.temps[index];
119 debug!(?temp);
120 *temp = match *temp {
121 TempState::Undefined => match context {
122 PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {
123 TempState::Defined { location, uses: 0, valid: Err(()) }
124 }
125 _ => TempState::Unpromotable,
126 },
127 TempState::Defined { ref mut uses, .. } => {
128 let allowed_use = match context {
131 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
132 | PlaceContext::NonMutatingUse(_) => true,
133 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
134 };
135 debug!(?allowed_use);
136 if allowed_use {
137 *uses += 1;
138 return;
139 }
140 TempState::Unpromotable
141 }
142 TempState::Unpromotable | TempState::PromotedOut => TempState::Unpromotable,
143 };
144 debug!(?temp);
145 }
146
147 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
148 self.super_rvalue(rvalue, location);
149
150 if let Rvalue::Ref(..) = *rvalue {
151 self.candidates.push(Candidate { location });
152 }
153 }
154}
155
156fn collect_temps_and_candidates<'tcx>(
157 ccx: &ConstCx<'_, 'tcx>,
158) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
159 let mut collector = Collector {
160 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
161 candidates: vec![],
162 ccx,
163 };
164 for (bb, data) in traversal::reverse_postorder(ccx.body) {
165 collector.visit_basic_block_data(bb, data);
166 }
167 (collector.temps, collector.candidates)
168}
169
170struct Validator<'a, 'tcx> {
174 ccx: &'a ConstCx<'a, 'tcx>,
175 temps: &'a mut IndexSlice<Local, TempState>,
176 promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
182}
183
184impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
185 type Target = ConstCx<'a, 'tcx>;
186
187 fn deref(&self) -> &Self::Target {
188 self.ccx
189 }
190}
191
192struct Unpromotable;
193
194impl<'tcx> Validator<'_, 'tcx> {
195 fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
196 let Left(statement) = self.body.stmt_at(candidate.location) else { bug!() };
197 let Some((_, Rvalue::Ref(_, kind, place))) = statement.kind.as_assign() else { bug!() };
198
199 self.validate_local(place.local)?;
202
203 self.validate_ref(*kind, place)?;
206
207 if place.projection.contains(&ProjectionElem::Deref) {
210 return Err(Unpromotable);
211 }
212
213 Ok(())
214 }
215
216 fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
218 let TempState::Defined { location: loc, .. } = self.temps[local] else {
219 return false;
220 };
221
222 let stmt_or_term = self.body.stmt_at(loc);
223 match stmt_or_term {
224 Left(statement) => {
225 let Some((_, rhs)) = statement.kind.as_assign() else {
226 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement)
227 };
228 qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.qualif_local::<Q>(l), rhs)
229 }
230 Right(terminator) => {
231 assert_matches!(terminator.kind, TerminatorKind::Call { .. });
232 let return_ty = self.body.local_decls[local].ty;
233 Q::in_any_value_of_ty(self.ccx, return_ty)
234 }
235 }
236 }
237
238 fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
239 let TempState::Defined { location: loc, uses, valid } = self.temps[local] else {
240 return Err(Unpromotable);
241 };
242
243 if self.qualif_local::<qualifs::NeedsDrop>(local) {
246 return Err(Unpromotable);
247 }
248
249 if valid.is_ok() {
250 return Ok(());
251 }
252
253 let ok = {
254 let stmt_or_term = self.body.stmt_at(loc);
255 match stmt_or_term {
256 Left(statement) => {
257 let Some((_, rhs)) = statement.kind.as_assign() else {
258 span_bug!(
259 statement.source_info.span,
260 "{:?} is not an assignment",
261 statement
262 )
263 };
264 self.validate_rvalue(rhs)
265 }
266 Right(terminator) => match &terminator.kind {
267 TerminatorKind::Call { func, args, .. } => {
268 self.validate_call(func, args, loc.block)
269 }
270 TerminatorKind::Yield { .. } => Err(Unpromotable),
271 kind => {
272 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
273 }
274 },
275 }
276 };
277
278 self.temps[local] = match ok {
279 Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
280 Err(_) => TempState::Unpromotable,
281 };
282
283 ok
284 }
285
286 fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
287 let Some((place_base, elem)) = place.last_projection() else {
288 return self.validate_local(place.local);
289 };
290
291 match elem {
293 ProjectionElem::ConstantIndex { .. }
295 | ProjectionElem::Subtype(_)
296 | ProjectionElem::Subslice { .. }
297 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
298
299 ProjectionElem::OpaqueCast(..) | ProjectionElem::Downcast(..) => {
301 return Err(Unpromotable);
302 }
303
304 ProjectionElem::Deref => {
305 if let Some(local) = place_base.as_local()
313 && let TempState::Defined { location, .. } = self.temps[local]
314 && let Left(def_stmt) = self.body.stmt_at(location)
315 && let Some((_, Rvalue::Use(Operand::Constant(c)))) = def_stmt.kind.as_assign()
316 && let Some(did) = c.check_static_ptr(self.tcx)
317 && let Some(hir::ConstContext::Static(..)) = self.const_kind
321 && !self.tcx.is_thread_local_static(did)
322 {
323 } else {
325 return Err(Unpromotable);
326 }
327 }
328 ProjectionElem::Index(local) => {
329 if let TempState::Defined { location: loc, .. } = self.temps[local]
331 && let Left(statement) = self.body.stmt_at(loc)
332 && let Some((_, Rvalue::Use(Operand::Constant(c)))) = statement.kind.as_assign()
333 && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
334 && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
336 && let Some(len) = len.try_to_target_usize(self.tcx)
338 && idx < len
340 {
341 self.validate_local(local)?;
342 } else {
344 return Err(Unpromotable);
345 }
346 }
347
348 ProjectionElem::Field(..) => {
349 let base_ty = place_base.ty(self.body, self.tcx).ty;
350 if base_ty.is_union() {
351 return Err(Unpromotable);
353 }
354 }
355 }
356
357 self.validate_place(place_base)
358 }
359
360 fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
361 match operand {
362 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
363
364 Operand::Constant(c) => {
367 if let Some(def_id) = c.check_static_ptr(self.tcx) {
368 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
375 if !is_static {
376 return Err(Unpromotable);
377 }
378
379 let is_thread_local = self.tcx.is_thread_local_static(def_id);
380 if is_thread_local {
381 return Err(Unpromotable);
382 }
383 }
384
385 Ok(())
386 }
387 }
388 }
389
390 fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
391 match kind {
392 BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
396 return Err(Unpromotable);
397 }
398
399 BorrowKind::Shared => {
400 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
401 if has_mut_interior {
402 return Err(Unpromotable);
403 }
404 }
405
406 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
409 let ty = place.ty(self.body, self.tcx).ty;
410
411 if let ty::Array(_, len) = ty.kind() {
415 match len.try_to_target_usize(self.tcx) {
416 Some(0) => {}
417 _ => return Err(Unpromotable),
418 }
419 } else {
420 return Err(Unpromotable);
421 }
422 }
423 }
424
425 Ok(())
426 }
427
428 fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
429 match rvalue {
430 Rvalue::Use(operand)
431 | Rvalue::Repeat(operand, _)
432 | Rvalue::WrapUnsafeBinder(operand, _) => {
433 self.validate_operand(operand)?;
434 }
435 Rvalue::CopyForDeref(place) => {
436 let op = &Operand::Copy(*place);
437 self.validate_operand(op)?
438 }
439
440 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
441 self.validate_place(place.as_ref())?
442 }
443
444 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
445
446 Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
448
449 Rvalue::Cast(_, operand, _) => {
452 self.validate_operand(operand)?;
453 }
454
455 Rvalue::NullaryOp(op, _) => match op {
456 NullOp::SizeOf => {}
457 NullOp::AlignOf => {}
458 NullOp::OffsetOf(_) => {}
459 NullOp::UbChecks => {}
460 NullOp::ContractChecks => {}
461 },
462
463 Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),
464
465 Rvalue::UnaryOp(op, operand) => {
466 match op {
467 UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
469 }
470
471 self.validate_operand(operand)?;
472 }
473
474 Rvalue::BinaryOp(op, box (lhs, rhs)) => {
475 let op = *op;
476 let lhs_ty = lhs.ty(self.body, self.tcx);
477
478 if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
479 assert_matches!(
482 op,
483 BinOp::Eq
484 | BinOp::Ne
485 | BinOp::Le
486 | BinOp::Lt
487 | BinOp::Ge
488 | BinOp::Gt
489 | BinOp::Offset
490 );
491 return Err(Unpromotable);
492 }
493
494 match op {
495 BinOp::Div | BinOp::Rem => {
496 if lhs_ty.is_integral() {
497 let sz = lhs_ty.primitive_size(self.tcx);
498 let rhs_val = match rhs {
500 Operand::Constant(c) => {
501 c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
502 }
503 _ => None,
504 };
505 match rhs_val.map(|x| x.to_uint(sz)) {
506 Some(x) if x != 0 => {} _ => return Err(Unpromotable), }
510 if lhs_ty.is_signed() {
513 match rhs_val.map(|x| x.to_int(sz)) {
514 Some(-1) | None => {
515 let lhs_val = match lhs {
518 Operand::Constant(c) => c
519 .const_
520 .try_eval_scalar_int(self.tcx, self.typing_env),
521 _ => None,
522 };
523 let lhs_min = sz.signed_int_min();
524 match lhs_val.map(|x| x.to_int(sz)) {
525 Some(x) if x != lhs_min => {}
527
528 _ => return Err(Unpromotable),
530 }
531 }
532 _ => {}
533 }
534 }
535 }
536 }
537 BinOp::Eq
539 | BinOp::Ne
540 | BinOp::Le
541 | BinOp::Lt
542 | BinOp::Ge
543 | BinOp::Gt
544 | BinOp::Cmp
545 | BinOp::Offset
546 | BinOp::Add
547 | BinOp::AddUnchecked
548 | BinOp::AddWithOverflow
549 | BinOp::Sub
550 | BinOp::SubUnchecked
551 | BinOp::SubWithOverflow
552 | BinOp::Mul
553 | BinOp::MulUnchecked
554 | BinOp::MulWithOverflow
555 | BinOp::BitXor
556 | BinOp::BitAnd
557 | BinOp::BitOr
558 | BinOp::Shl
559 | BinOp::ShlUnchecked
560 | BinOp::Shr
561 | BinOp::ShrUnchecked => {}
562 }
563
564 self.validate_operand(lhs)?;
565 self.validate_operand(rhs)?;
566 }
567
568 Rvalue::RawPtr(_, place) => {
569 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
572 {
573 let base_ty = place_base.ty(self.body, self.tcx).ty;
574 if let ty::Ref(..) = base_ty.kind() {
575 return self.validate_place(place_base);
576 }
577 }
578 return Err(Unpromotable);
579 }
580
581 Rvalue::Ref(_, kind, place) => {
582 let mut place_simplified = place.as_ref();
584 if let Some((place_base, ProjectionElem::Deref)) =
585 place_simplified.last_projection()
586 {
587 let base_ty = place_base.ty(self.body, self.tcx).ty;
588 if let ty::Ref(..) = base_ty.kind() {
589 place_simplified = place_base;
590 }
591 }
592
593 self.validate_place(place_simplified)?;
594
595 self.validate_ref(*kind, place)?;
598 }
599
600 Rvalue::Aggregate(_, operands) => {
601 for o in operands {
602 self.validate_operand(o)?;
603 }
604 }
605 }
606
607 Ok(())
608 }
609
610 fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
614 let mut safe_blocks = FxHashSet::default();
615 let mut safe_block = START_BLOCK;
616 loop {
617 safe_blocks.insert(safe_block);
618 safe_block = match body.basic_blocks[safe_block].terminator().kind {
620 TerminatorKind::Goto { target } => target,
621 TerminatorKind::Call { target: Some(target), .. }
622 | TerminatorKind::Drop { target, .. } => {
623 target
627 }
628 TerminatorKind::Assert { target, .. } => {
629 target
631 }
632 _ => {
633 break;
635 }
636 };
637 }
638 safe_blocks
639 }
640
641 fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
644 let body = self.body;
645 let safe_blocks =
646 self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
647 safe_blocks.contains(&block)
648 }
649
650 fn validate_call(
651 &mut self,
652 callee: &Operand<'tcx>,
653 args: &[Spanned<Operand<'tcx>>],
654 block: BasicBlock,
655 ) -> Result<(), Unpromotable> {
656 self.validate_operand(callee)?;
658 for arg in args {
659 self.validate_operand(&arg.node)?;
660 }
661
662 let fn_ty = callee.ty(self.body, self.tcx);
665 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
666 if self.tcx.is_promotable_const_fn(def_id) {
667 return Ok(());
668 }
669 }
670
671 let promote_all_fn = matches!(
676 self.const_kind,
677 Some(hir::ConstContext::Static(_) | hir::ConstContext::Const { inline: false })
678 );
679 if !promote_all_fn {
680 return Err(Unpromotable);
681 }
682 let is_const_fn = match *fn_ty.kind() {
684 ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
685 _ => false,
686 };
687 if !is_const_fn {
688 return Err(Unpromotable);
689 }
690 if !self.is_promotion_safe_block(block) {
694 return Err(Unpromotable);
695 }
696 Ok(())
698 }
699}
700
701fn validate_candidates(
702 ccx: &ConstCx<'_, '_>,
703 temps: &mut IndexSlice<Local, TempState>,
704 mut candidates: Vec<Candidate>,
705) -> Vec<Candidate> {
706 let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
707
708 candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
709 candidates
710}
711
712struct Promoter<'a, 'tcx> {
713 tcx: TyCtxt<'tcx>,
714 source: &'a mut Body<'tcx>,
715 promoted: Body<'tcx>,
716 temps: &'a mut IndexVec<Local, TempState>,
717 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
718
719 required_consts: Vec<ConstOperand<'tcx>>,
721
722 keep_original: bool,
725
726 add_to_required: bool,
729}
730
731impl<'a, 'tcx> Promoter<'a, 'tcx> {
732 fn new_block(&mut self) -> BasicBlock {
733 let span = self.promoted.span;
734 self.promoted.basic_blocks_mut().push(BasicBlockData {
735 statements: vec![],
736 terminator: Some(Terminator {
737 source_info: SourceInfo::outermost(span),
738 kind: TerminatorKind::Return,
739 }),
740 is_cleanup: false,
741 })
742 }
743
744 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
745 let last = self.promoted.basic_blocks.last_index().unwrap();
746 let data = &mut self.promoted[last];
747 data.statements.push(Statement {
748 source_info: SourceInfo::outermost(span),
749 kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
750 });
751 }
752
753 fn is_temp_kind(&self, local: Local) -> bool {
754 self.source.local_kind(local) == LocalKind::Temp
755 }
756
757 fn promote_temp(&mut self, temp: Local) -> Local {
760 let old_keep_original = self.keep_original;
761 let loc = match self.temps[temp] {
762 TempState::Defined { location, uses, .. } if uses > 0 => {
763 if uses > 1 {
764 self.keep_original = true;
765 }
766 location
767 }
768 state => {
769 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
770 }
771 };
772 if !self.keep_original {
773 self.temps[temp] = TempState::PromotedOut;
774 }
775
776 let num_stmts = self.source[loc.block].statements.len();
777 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
778 self.source.local_decls[temp].ty,
779 self.source.local_decls[temp].source_info.span,
780 ));
781
782 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
783
784 if loc.statement_index < num_stmts {
787 let (mut rvalue, source_info) = {
788 let statement = &mut self.source[loc.block].statements[loc.statement_index];
789 let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else {
790 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
791 };
792
793 (
794 if self.keep_original {
795 rhs.clone()
796 } else {
797 let unit = Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
798 span: statement.source_info.span,
799 user_ty: None,
800 const_: Const::zero_sized(self.tcx.types.unit),
801 })));
802 mem::replace(rhs, unit)
803 },
804 statement.source_info,
805 )
806 };
807
808 self.visit_rvalue(&mut rvalue, loc);
809 self.assign(new_temp, rvalue, source_info.span);
810 } else {
811 let terminator = if self.keep_original {
812 self.source[loc.block].terminator().clone()
813 } else {
814 let terminator = self.source[loc.block].terminator_mut();
815 let target = match &terminator.kind {
816 TerminatorKind::Call { target: Some(target), .. } => *target,
817 kind => {
818 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
819 }
820 };
821 Terminator {
822 source_info: terminator.source_info,
823 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
824 }
825 };
826
827 match terminator.kind {
828 TerminatorKind::Call {
829 mut func, mut args, call_source: desugar, fn_span, ..
830 } => {
831 self.add_to_required = true;
834
835 self.visit_operand(&mut func, loc);
836 for arg in &mut args {
837 self.visit_operand(&mut arg.node, loc);
838 }
839
840 let last = self.promoted.basic_blocks.last_index().unwrap();
841 let new_target = self.new_block();
842
843 *self.promoted[last].terminator_mut() = Terminator {
844 kind: TerminatorKind::Call {
845 func,
846 args,
847 unwind: UnwindAction::Continue,
848 destination: Place::from(new_temp),
849 target: Some(new_target),
850 call_source: desugar,
851 fn_span,
852 },
853 source_info: SourceInfo::outermost(terminator.source_info.span),
854 ..terminator
855 };
856 }
857 kind => {
858 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
859 }
860 };
861 };
862
863 self.keep_original = old_keep_original;
864 new_temp
865 }
866
867 fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Body<'tcx> {
868 let def = self.source.source.def_id();
869 let (mut rvalue, promoted_op) = {
870 let promoted = &mut self.promoted;
871 let promoted_id = Promoted::new(next_promoted_id);
872 let tcx = self.tcx;
873 let mut promoted_operand = |ty, span| {
874 promoted.span = span;
875 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
876 let args = tcx.erase_regions(GenericArgs::identity_for_item(tcx, def));
877 let uneval = mir::UnevaluatedConst { def, args, promoted: Some(promoted_id) };
878
879 ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
880 };
881
882 let blocks = self.source.basic_blocks.as_mut();
883 let local_decls = &mut self.source.local_decls;
884 let loc = candidate.location;
885 let statement = &mut blocks[loc.block].statements[loc.statement_index];
886 let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) =
887 &mut statement.kind
888 else {
889 bug!()
890 };
891
892 debug_assert!(region.is_erased());
894 let ty = local_decls[place.local].ty;
895 let span = statement.source_info.span;
896
897 let ref_ty =
898 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
899
900 let mut projection = vec![PlaceElem::Deref];
901 projection.extend(place.projection);
902 place.projection = tcx.mk_place_elems(&projection);
903
904 let mut promoted_ref = LocalDecl::new(ref_ty, span);
908 promoted_ref.source_info = statement.source_info;
909 let promoted_ref = local_decls.push(promoted_ref);
910 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
911
912 let promoted_operand = promoted_operand(ref_ty, span);
913 let promoted_ref_statement = Statement {
914 source_info: statement.source_info,
915 kind: StatementKind::Assign(Box::new((
916 Place::from(promoted_ref),
917 Rvalue::Use(Operand::Constant(Box::new(promoted_operand))),
918 ))),
919 };
920 self.extra_statements.push((loc, promoted_ref_statement));
921
922 (
923 Rvalue::Ref(
924 tcx.lifetimes.re_erased,
925 *borrow_kind,
926 Place {
927 local: mem::replace(&mut place.local, promoted_ref),
928 projection: List::empty(),
929 },
930 ),
931 promoted_operand,
932 )
933 };
934
935 assert_eq!(self.new_block(), START_BLOCK);
936 self.visit_rvalue(
937 &mut rvalue,
938 Location { block: START_BLOCK, statement_index: usize::MAX },
939 );
940
941 let span = self.promoted.span;
942 self.assign(RETURN_PLACE, rvalue, span);
943
944 if self.add_to_required {
947 self.source.required_consts.as_mut().unwrap().push(promoted_op);
948 }
949
950 self.promoted.set_required_consts(self.required_consts);
951
952 self.promoted
953 }
954}
955
956impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
958 fn tcx(&self) -> TyCtxt<'tcx> {
959 self.tcx
960 }
961
962 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
963 if self.is_temp_kind(*local) {
964 *local = self.promote_temp(*local);
965 }
966 }
967
968 fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
969 if constant.const_.is_required_const() {
970 self.required_consts.push(*constant);
971 }
972
973 }
975}
976
977fn promote_candidates<'tcx>(
978 body: &mut Body<'tcx>,
979 tcx: TyCtxt<'tcx>,
980 mut temps: IndexVec<Local, TempState>,
981 candidates: Vec<Candidate>,
982) -> IndexVec<Promoted, Body<'tcx>> {
983 debug!(promote_candidates = ?candidates);
985
986 if candidates.is_empty() {
988 return IndexVec::new();
989 }
990
991 let mut promotions = IndexVec::new();
992
993 let mut extra_statements = vec![];
994 for candidate in candidates.into_iter().rev() {
995 let Location { block, statement_index } = candidate.location;
996 if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind
997 {
998 if let Some(local) = place.as_local() {
999 if temps[local] == TempState::PromotedOut {
1000 continue;
1002 }
1003 }
1004 }
1005
1006 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1008
1009 let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1010 scope.parent_scope = None;
1011
1012 let mut promoted = Body::new(
1013 body.source, IndexVec::new(),
1015 IndexVec::from_elem_n(scope, 1),
1016 initial_locals,
1017 IndexVec::new(),
1018 0,
1019 vec![],
1020 body.span,
1021 None,
1022 body.tainted_by_errors,
1023 );
1024 promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1025
1026 let promoter = Promoter {
1027 promoted,
1028 tcx,
1029 source: body,
1030 temps: &mut temps,
1031 extra_statements: &mut extra_statements,
1032 keep_original: false,
1033 add_to_required: false,
1034 required_consts: Vec::new(),
1035 };
1036
1037 let mut promoted = promoter.promote_candidate(candidate, promotions.len());
1038 promoted.source.promoted = Some(promotions.next_index());
1039 promotions.push(promoted);
1040 }
1041
1042 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1045 for (loc, statement) in extra_statements {
1046 body[loc.block].statements.insert(loc.statement_index, statement);
1047 }
1048
1049 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1051 for block in body.basic_blocks_mut() {
1052 block.statements.retain(|statement| match &statement.kind {
1053 StatementKind::Assign(box (place, _)) => {
1054 if let Some(index) = place.as_local() {
1055 !promoted(index)
1056 } else {
1057 true
1058 }
1059 }
1060 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1061 !promoted(*index)
1062 }
1063 _ => true,
1064 });
1065 let terminator = block.terminator_mut();
1066 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1067 if let Some(index) = place.as_local() {
1068 if promoted(index) {
1069 terminator.kind = TerminatorKind::Goto { target: *target };
1070 }
1071 }
1072 }
1073 }
1074
1075 promotions
1076}