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.
15 use rustc::hir::def_id::DefId;
17 use rustc::mir::visit::{PlaceContext, MutatingUseContext, MutVisitor, Visitor};
18 use rustc::mir::traversal::ReversePostorder;
19 use rustc::ty::{self, List, TyCtxt, TypeFoldable};
20 use rustc::ty::subst::InternalSubsts;
21 use rustc::ty::cast::CastTy;
22 use syntax::ast::LitKind;
23 use syntax::symbol::sym;
24 use syntax_pos::{Span, DUMMY_SP};
26 use rustc_index::vec::{IndexVec, Idx};
27 use rustc_target::spec::abi::Abi;
30 use std::{iter, mem, usize};
32 use crate::transform::{MirPass, MirSource};
33 use crate::transform::check_consts::{qualifs, Item, ConstKind, is_lang_panic_fn};
35 /// A `MirPass` for promotion.
37 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
38 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
40 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
41 /// newly created `StaticKind::Promoted`.
43 pub struct PromoteTemps<'tcx> {
44 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
47 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
48 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
49 // There's not really any point in promoting errorful MIR.
51 // This does not include MIR that failed const-checking, which we still try to promote.
52 if body.return_ty().references_error() {
53 tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
57 if src.promoted.is_some() {
61 let def_id = src.def_id();
63 let mut rpo = traversal::reverse_postorder(body);
64 let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
66 let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates);
68 let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
69 self.promoted_fragments.set(promoted);
73 /// State of a temporary during collection and promotion.
74 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
76 /// No references to this temp.
78 /// One direct assignment and any number of direct uses.
79 /// A borrow of this temp is promotable if the assigned
80 /// value is qualified as constant.
85 /// Any other combination of assignments/uses.
87 /// This temp was part of an rvalue which got extracted
88 /// during promotion and needs cleanup.
93 pub fn is_promotable(&self) -> bool {
94 debug!("is_promotable: self={:?}", self);
95 if let TempState::Defined { .. } = *self {
103 /// A "root candidate" for promotion, which will become the
104 /// returned value in a promoted MIR, unless it's a subset
105 /// of a larger candidate.
106 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
108 /// Borrow of a constant temporary.
111 /// Promotion of the `x` in `[x; 32]`.
114 /// Currently applied to function calls where the callee has the unstable
115 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
116 /// intrinsic. The intrinsic requires the arguments are indeed constant and
117 /// the attribute currently provides the semantic requirement that arguments
118 /// must be constant.
119 Argument { bb: BasicBlock, index: usize },
123 /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
124 fn forces_explicit_promotion(&self) -> bool {
127 Candidate::Repeat(_) => false,
128 Candidate::Argument { .. } => true,
133 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
134 let attrs = tcx.get_attrs(def_id);
135 let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
136 let mut ret = vec![];
137 for meta in attr.meta_item_list()? {
138 match meta.literal()?.kind {
139 LitKind::Int(a, _) => { ret.push(a as usize); }
146 struct Collector<'a, 'tcx> {
148 body: &'a Body<'tcx>,
149 temps: IndexVec<Local, TempState>,
150 candidates: Vec<Candidate>,
154 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
155 fn visit_local(&mut self,
157 context: PlaceContext,
158 location: Location) {
159 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
160 // We're only interested in temporaries and the return place
161 match self.body.local_kind(index) {
163 | LocalKind::ReturnPointer
170 // Ignore drops, if the temp gets promoted,
171 // then it's constant and thus drop is noop.
172 // Non-uses are also irrelevant.
173 if context.is_drop() || !context.is_use() {
175 "visit_local: context.is_drop={:?} context.is_use={:?}",
176 context.is_drop(), context.is_use(),
181 let temp = &mut self.temps[index];
182 debug!("visit_local: temp={:?}", temp);
183 if *temp == TempState::Undefined {
185 PlaceContext::MutatingUse(MutatingUseContext::Store) |
186 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
187 *temp = TempState::Defined {
193 _ => { /* mark as unpromotable below */ }
195 } else if let TempState::Defined { ref mut uses, .. } = *temp {
196 // We always allow borrows, even mutable ones, as we need
197 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
198 let allowed_use = context.is_borrow() || context.is_nonmutating_use();
199 debug!("visit_local: allowed_use={:?}", allowed_use);
204 /* mark as unpromotable below */
206 *temp = TempState::Unpromotable;
209 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
210 self.super_rvalue(rvalue, location);
214 self.candidates.push(Candidate::Ref(location));
216 Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
217 // FIXME(#49147) only promote the element when it isn't `Copy`
218 // (so that code that can copy it at runtime is unaffected).
219 self.candidates.push(Candidate::Repeat(location));
225 fn visit_terminator_kind(&mut self,
226 kind: &TerminatorKind<'tcx>,
227 location: Location) {
228 self.super_terminator_kind(kind, location);
230 if let TerminatorKind::Call { ref func, .. } = *kind {
231 if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
232 let fn_sig = self.tcx.fn_sig(def_id);
233 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
234 let name = self.tcx.item_name(def_id);
235 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
236 if name.as_str().starts_with("simd_shuffle") {
237 self.candidates.push(Candidate::Argument {
242 return; // Don't double count `simd_shuffle` candidates
246 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
247 for index in constant_args {
248 self.candidates.push(Candidate::Argument { bb: location.block, index });
255 fn visit_source_info(&mut self, source_info: &SourceInfo) {
256 self.span = source_info.span;
260 pub fn collect_temps_and_candidates(
263 rpo: &mut ReversePostorder<'_, 'tcx>,
264 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
265 let mut collector = Collector {
268 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
272 for (bb, data) in rpo {
273 collector.visit_basic_block_data(bb, data);
275 (collector.temps, collector.candidates)
278 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
280 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
281 struct Validator<'a, 'tcx> {
282 item: Item<'a, 'tcx>,
283 temps: &'a IndexVec<Local, TempState>,
285 /// Explicit promotion happens e.g. for constant arguments declared via
286 /// `rustc_args_required_const`.
287 /// Implicit promotion has almost the same rules, except that disallows `const fn`
288 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
289 /// a legitimate run-time operation into a failing compile-time operation
290 /// e.g. due to addresses being compared inside the function.
294 impl std::ops::Deref for Validator<'a, 'tcx> {
295 type Target = Item<'a, 'tcx>;
297 fn deref(&self) -> &Self::Target {
304 impl<'tcx> Validator<'_, 'tcx> {
305 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
307 Candidate::Ref(loc) => {
308 assert!(!self.explicit);
310 let statement = &self.body[loc.block].statements[loc.statement_index];
311 match &statement.kind {
312 StatementKind::Assign(box(_, Rvalue::Ref(_, kind, place))) => {
314 BorrowKind::Shared | BorrowKind::Mut { .. } => {}
316 // FIXME(eddyb) these aren't promoted here but *could*
317 // be promoted as part of a larger value because
318 // `validate_rvalue` doesn't check them, need to
319 // figure out what is the intended behavior.
320 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
323 // We can only promote interior borrows of promotable temps (non-temps
324 // don't get promoted anyway).
325 let base = match place.base {
326 PlaceBase::Local(local) => local,
327 _ => return Err(Unpromotable),
329 self.validate_local(base)?;
331 if place.projection.contains(&ProjectionElem::Deref) {
332 return Err(Unpromotable);
335 let mut has_mut_interior =
336 self.qualif_local::<qualifs::HasMutInterior>(base);
337 // HACK(eddyb) this should compute the same thing as
338 // `<HasMutInterior as Qualif>::in_projection` from
339 // `check_consts::qualifs` but without recursion.
340 if has_mut_interior {
341 // This allows borrowing fields which don't have
342 // `HasMutInterior`, from a type that does, e.g.:
343 // `let _: &'static _ = &(Cell::new(1), 2).1;`
344 let mut place_projection = &place.projection[..];
345 // FIXME(eddyb) use a forward loop instead of a reverse one.
346 while let [proj_base @ .., elem] = place_projection {
347 // FIXME(eddyb) this is probably excessive, with
348 // the exception of `union` member accesses.
350 Place::ty_from(&place.base, proj_base, self.body, self.tcx)
351 .projection_ty(self.tcx, elem)
353 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
354 has_mut_interior = false;
358 place_projection = proj_base;
362 // FIXME(eddyb) this duplicates part of `validate_rvalue`.
363 if has_mut_interior {
364 return Err(Unpromotable);
366 if self.qualif_local::<qualifs::NeedsDrop>(base) {
367 return Err(Unpromotable);
370 if let BorrowKind::Mut { .. } = kind {
371 let ty = place.ty(self.body, self.tcx).ty;
373 // In theory, any zero-sized value could be borrowed
374 // mutably without consequences. However, only &mut []
375 // is allowed right now, and only in functions.
376 if self.const_kind == Some(ConstKind::StaticMut) {
377 // Inside a `static mut`, &mut [...] is also allowed.
379 ty::Array(..) | ty::Slice(_) => {}
380 _ => return Err(Unpromotable),
382 } else if let ty::Array(_, len) = ty.kind {
383 // FIXME(eddyb) the `self.is_non_const_fn` condition
384 // seems unnecessary, given that this is merely a ZST.
385 match len.try_eval_usize(self.tcx, self.param_env) {
386 Some(0) if self.const_kind.is_none() => {},
387 _ => return Err(Unpromotable),
390 return Err(Unpromotable);
399 Candidate::Repeat(loc) => {
400 assert!(!self.explicit);
402 let statement = &self.body[loc.block].statements[loc.statement_index];
403 match &statement.kind {
404 StatementKind::Assign(box(_, Rvalue::Repeat(ref operand, _))) => {
405 if !self.tcx.features().const_in_array_repeat_expressions {
406 return Err(Unpromotable);
409 self.validate_operand(operand)
414 Candidate::Argument { bb, index } => {
415 assert!(self.explicit);
417 let terminator = self.body[bb].terminator();
418 match &terminator.kind {
419 TerminatorKind::Call { args, .. } => {
420 self.validate_operand(&args[index])
428 // FIXME(eddyb) maybe cache this?
429 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
430 let per_local = &|l| self.qualif_local::<Q>(l);
432 if let TempState::Defined { location: loc, .. } = self.temps[local] {
433 let num_stmts = self.body[loc.block].statements.len();
435 if loc.statement_index < num_stmts {
436 let statement = &self.body[loc.block].statements[loc.statement_index];
437 match &statement.kind {
438 StatementKind::Assign(box(_, rhs)) => {
439 Q::in_rvalue(&self.item, per_local, rhs)
442 span_bug!(statement.source_info.span, "{:?} is not an assignment",
447 let terminator = self.body[loc.block].terminator();
448 match &terminator.kind {
449 TerminatorKind::Call { func, args, .. } => {
450 let return_ty = self.body.local_decls[local].ty;
451 Q::in_call(&self.item, per_local, func, args, return_ty)
454 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
459 let span = self.body.local_decls[local].source_info.span;
460 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
464 // FIXME(eddyb) maybe cache this?
465 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
466 if let TempState::Defined { location: loc, .. } = self.temps[local] {
467 let num_stmts = self.body[loc.block].statements.len();
469 if loc.statement_index < num_stmts {
470 let statement = &self.body[loc.block].statements[loc.statement_index];
471 match &statement.kind {
472 StatementKind::Assign(box(_, rhs)) => self.validate_rvalue(rhs),
474 span_bug!(statement.source_info.span, "{:?} is not an assignment",
479 let terminator = self.body[loc.block].terminator();
480 match &terminator.kind {
481 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
483 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
492 fn validate_place(&self, place: PlaceRef<'_, 'tcx>) -> Result<(), Unpromotable> {
495 base: PlaceBase::Local(local),
497 } => self.validate_local(*local),
499 base: PlaceBase::Static(_),
501 } => bug!("qualifying already promoted MIR"),
504 projection: [proj_base @ .., elem],
507 ProjectionElem::Deref |
508 ProjectionElem::Downcast(..) => return Err(Unpromotable),
510 ProjectionElem::ConstantIndex {..} |
511 ProjectionElem::Subslice {..} => {}
513 ProjectionElem::Index(local) => {
514 self.validate_local(local)?;
517 ProjectionElem::Field(..) => {
518 if self.const_kind.is_none() {
520 Place::ty_from(place.base, proj_base, self.body, self.tcx).ty;
521 if let Some(def) = base_ty.ty_adt_def() {
522 // No promotion of union field accesses.
524 return Err(Unpromotable);
531 self.validate_place(PlaceRef {
533 projection: proj_base,
539 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
541 Operand::Copy(place) |
542 Operand::Move(place) => self.validate_place(place.as_ref()),
544 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
545 // `validate_rvalue` upon access.
546 Operand::Constant(c) => {
547 if let Some(def_id) = c.check_static_ptr(self.tcx) {
548 // Only allow statics (not consts) to refer to other statics.
549 // FIXME(eddyb) does this matter at all for promotion?
550 let is_static = self.const_kind.map_or(false, |k| k.is_static());
552 return Err(Unpromotable);
555 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
557 return Err(Unpromotable);
566 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
568 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
569 let operand_ty = operand.ty(self.body, self.tcx);
570 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
571 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
572 match (cast_in, cast_out) {
573 (CastTy::Ptr(_), CastTy::Int(_)) |
574 (CastTy::FnPtr, CastTy::Int(_)) => {
575 // in normal functions, mark such casts as not promotable
576 return Err(Unpromotable);
582 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
583 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
584 assert!(op == BinOp::Eq || op == BinOp::Ne ||
585 op == BinOp::Le || op == BinOp::Lt ||
586 op == BinOp::Ge || op == BinOp::Gt ||
587 op == BinOp::Offset);
589 // raw pointer operations are not allowed inside promoteds
590 return Err(Unpromotable);
594 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
600 Rvalue::NullaryOp(..) => Ok(()),
602 Rvalue::Discriminant(place) |
603 Rvalue::Len(place) => self.validate_place(place.as_ref()),
605 Rvalue::Use(operand) |
606 Rvalue::Repeat(operand, _) |
607 Rvalue::UnaryOp(_, operand) |
608 Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
610 Rvalue::BinaryOp(_, lhs, rhs) |
611 Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
612 self.validate_operand(lhs)?;
613 self.validate_operand(rhs)
616 Rvalue::Ref(_, kind, place) => {
617 if let BorrowKind::Mut { .. } = kind {
618 let ty = place.ty(self.body, self.tcx).ty;
620 // In theory, any zero-sized value could be borrowed
621 // mutably without consequences. However, only &mut []
622 // is allowed right now, and only in functions.
623 if self.const_kind == Some(ConstKind::StaticMut) {
624 // Inside a `static mut`, &mut [...] is also allowed.
626 ty::Array(..) | ty::Slice(_) => {}
627 _ => return Err(Unpromotable),
629 } else if let ty::Array(_, len) = ty.kind {
630 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
631 // const context which seems unnecessary given that this is merely a ZST.
632 match len.try_eval_usize(self.tcx, self.param_env) {
633 Some(0) if self.const_kind.is_none() => {},
634 _ => return Err(Unpromotable),
637 return Err(Unpromotable);
641 // Special-case reborrows to be more like a copy of the reference.
642 let mut place = place.as_ref();
643 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
645 Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
646 if let ty::Ref(..) = base_ty.kind {
649 projection: proj_base,
654 self.validate_place(place)?;
656 // HACK(eddyb) this should compute the same thing as
657 // `<HasMutInterior as Qualif>::in_projection` from
658 // `check_consts::qualifs` but without recursion.
659 let mut has_mut_interior = match place.base {
660 PlaceBase::Local(local) => {
661 self.qualif_local::<qualifs::HasMutInterior>(*local)
663 PlaceBase::Static(_) => false,
665 if has_mut_interior {
666 let mut place_projection = place.projection;
667 // FIXME(eddyb) use a forward loop instead of a reverse one.
668 while let [proj_base @ .., elem] = place_projection {
669 // FIXME(eddyb) this is probably excessive, with
670 // the exception of `union` member accesses.
671 let ty = Place::ty_from(place.base, proj_base, self.body, self.tcx)
672 .projection_ty(self.tcx, elem)
674 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
675 has_mut_interior = false;
679 place_projection = proj_base;
682 if has_mut_interior {
683 return Err(Unpromotable);
689 Rvalue::Aggregate(_, ref operands) => {
691 self.validate_operand(o)?;
701 callee: &Operand<'tcx>,
702 args: &[Operand<'tcx>],
703 ) -> Result<(), Unpromotable> {
704 let fn_ty = callee.ty(self.body, self.tcx);
706 if !self.explicit && self.const_kind.is_none() {
707 if let ty::FnDef(def_id, _) = fn_ty.kind {
708 // Never promote runtime `const fn` calls of
709 // functions without `#[rustc_promotable]`.
710 if !self.tcx.is_promotable_const_fn(def_id) {
711 return Err(Unpromotable);
716 let is_const_fn = match fn_ty.kind {
717 ty::FnDef(def_id, _) => {
718 self.tcx.is_const_fn(def_id) ||
719 self.tcx.is_unstable_const_fn(def_id).is_some() ||
720 is_lang_panic_fn(self.tcx, self.def_id)
725 return Err(Unpromotable);
728 self.validate_operand(callee)?;
730 self.validate_operand(arg)?;
737 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
738 pub fn validate_candidates(
742 temps: &IndexVec<Local, TempState>,
743 candidates: &[Candidate],
744 ) -> Vec<Candidate> {
745 let mut validator = Validator {
746 item: Item::new(tcx, def_id, body),
751 candidates.iter().copied().filter(|&candidate| {
752 validator.explicit = candidate.forces_explicit_promotion();
754 // FIXME(eddyb) also emit the errors for shuffle indices
755 // and `#[rustc_args_required_const]` arguments here.
757 let is_promotable = validator.validate_candidate(candidate).is_ok();
759 Candidate::Argument { bb, index } if !is_promotable => {
760 let span = body[bb].terminator().source_info.span;
761 let msg = format!("argument {} is required to be a constant", index + 1);
762 tcx.sess.span_err(span, &msg);
771 struct Promoter<'a, 'tcx> {
773 source: &'a mut Body<'tcx>,
774 promoted: Body<'tcx>,
775 temps: &'a mut IndexVec<Local, TempState>,
777 /// If true, all nested temps are also kept in the
778 /// source MIR, not moved to the promoted MIR.
782 impl<'a, 'tcx> Promoter<'a, 'tcx> {
783 fn new_block(&mut self) -> BasicBlock {
784 let span = self.promoted.span;
785 self.promoted.basic_blocks_mut().push(BasicBlockData {
787 terminator: Some(Terminator {
788 source_info: SourceInfo {
790 scope: OUTERMOST_SOURCE_SCOPE
792 kind: TerminatorKind::Return
798 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
799 let last = self.promoted.basic_blocks().last().unwrap();
800 let data = &mut self.promoted[last];
801 data.statements.push(Statement {
802 source_info: SourceInfo {
804 scope: OUTERMOST_SOURCE_SCOPE
806 kind: StatementKind::Assign(box(Place::from(dest), rvalue))
810 fn is_temp_kind(&self, local: Local) -> bool {
811 self.source.local_kind(local) == LocalKind::Temp
814 /// Copies the initialization of this temp to the
815 /// promoted MIR, recursing through temps.
816 fn promote_temp(&mut self, temp: Local) -> Local {
817 let old_keep_original = self.keep_original;
818 let loc = match self.temps[temp] {
819 TempState::Defined { location, uses } if uses > 0 => {
821 self.keep_original = true;
826 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
830 if !self.keep_original {
831 self.temps[temp] = TempState::PromotedOut;
834 let num_stmts = self.source[loc.block].statements.len();
835 let new_temp = self.promoted.local_decls.push(
836 LocalDecl::new_temp(self.source.local_decls[temp].ty,
837 self.source.local_decls[temp].source_info.span));
839 debug!("promote({:?} @ {:?}/{:?}, {:?})",
840 temp, loc, num_stmts, self.keep_original);
842 // First, take the Rvalue or Call out of the source MIR,
843 // or duplicate it, depending on keep_original.
844 if loc.statement_index < num_stmts {
845 let (mut rvalue, source_info) = {
846 let statement = &mut self.source[loc.block].statements[loc.statement_index];
847 let rhs = match statement.kind {
848 StatementKind::Assign(box(_, ref mut rhs)) => rhs,
850 span_bug!(statement.source_info.span, "{:?} is not an assignment",
855 (if self.keep_original {
858 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
859 mem::replace(rhs, unit)
860 }, statement.source_info)
863 self.visit_rvalue(&mut rvalue, loc);
864 self.assign(new_temp, rvalue, source_info.span);
866 let terminator = if self.keep_original {
867 self.source[loc.block].terminator().clone()
869 let terminator = self.source[loc.block].terminator_mut();
870 let target = match terminator.kind {
871 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
873 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
877 source_info: terminator.source_info,
878 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
884 match terminator.kind {
885 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
886 self.visit_operand(&mut func, loc);
887 for arg in &mut args {
888 self.visit_operand(arg, loc);
891 let last = self.promoted.basic_blocks().last().unwrap();
892 let new_target = self.new_block();
894 *self.promoted[last].terminator_mut() = Terminator {
895 kind: TerminatorKind::Call {
900 (Place::from(new_temp), new_target)
908 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
913 self.keep_original = old_keep_original;
917 fn promote_candidate(
920 candidate: Candidate,
921 next_promoted_id: usize,
922 ) -> Option<Body<'tcx>> {
924 let promoted = &mut self.promoted;
925 let promoted_id = Promoted::new(next_promoted_id);
927 let mut promoted_place = |ty, span| {
928 promoted.span = span;
929 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
931 base: PlaceBase::Static(box Static {
933 StaticKind::Promoted(
935 InternalSubsts::identity_for_item(tcx, def_id),
940 projection: List::empty(),
943 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
945 Candidate::Ref(loc) => {
946 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
947 match statement.kind {
948 StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
949 // Use the underlying local for this (necessarily interior) borrow.
950 let ty = place.base.ty(local_decls).ty;
951 let span = statement.source_info.span;
953 Operand::Move(Place {
956 promoted_place(ty, span).base,
958 projection: List::empty(),
964 Candidate::Repeat(loc) => {
965 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
966 match statement.kind {
967 StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
968 let ty = operand.ty(local_decls, self.tcx);
969 let span = statement.source_info.span;
972 Operand::Copy(promoted_place(ty, span))
978 Candidate::Argument { bb, index } => {
979 let terminator = blocks[bb].terminator_mut();
980 match terminator.kind {
981 TerminatorKind::Call { ref mut args, .. } => {
982 let ty = args[index].ty(local_decls, self.tcx);
983 let span = terminator.source_info.span;
984 let operand = Operand::Copy(promoted_place(ty, span));
985 mem::replace(&mut args[index], operand)
987 // We expected a `TerminatorKind::Call` for which we'd like to promote an
988 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
989 // we are seeing a `Goto`. That means that the `promote_temps` method
990 // already promoted this call away entirely. This case occurs when calling
991 // a function requiring a constant argument and as that constant value
992 // providing a value whose computation contains another call to a function
993 // requiring a constant argument.
994 TerminatorKind::Goto { .. } => return None,
1001 assert_eq!(self.new_block(), START_BLOCK);
1002 self.visit_operand(&mut operand, Location {
1003 block: BasicBlock::new(0),
1004 statement_index: usize::MAX
1007 let span = self.promoted.span;
1008 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
1013 /// Replaces all temporaries with their promoted counterparts.
1014 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1015 fn tcx(&self) -> TyCtxt<'tcx> {
1019 fn visit_local(&mut self,
1023 if self.is_temp_kind(*local) {
1024 *local = self.promote_temp(*local);
1028 fn process_projection_elem(
1030 elem: &PlaceElem<'tcx>,
1031 ) -> Option<PlaceElem<'tcx>> {
1033 PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1034 Some(PlaceElem::Index(self.promote_temp(*local)))
1041 pub fn promote_candidates<'tcx>(
1043 body: &mut Body<'tcx>,
1045 mut temps: IndexVec<Local, TempState>,
1046 candidates: Vec<Candidate>,
1047 ) -> IndexVec<Promoted, Body<'tcx>> {
1048 // Visit candidates in reverse, in case they're nested.
1049 debug!("promote_candidates({:?})", candidates);
1051 let mut promotions = IndexVec::new();
1053 for candidate in candidates.into_iter().rev() {
1055 Candidate::Repeat(Location { block, statement_index }) |
1056 Candidate::Ref(Location { block, statement_index }) => {
1057 match &body[block].statements[statement_index].kind {
1058 StatementKind::Assign(box(place, _)) => {
1059 if let Some(local) = place.as_local() {
1060 if temps[local] == TempState::PromotedOut {
1061 // Already promoted.
1069 Candidate::Argument { .. } => {}
1073 // Declare return place local so that `mir::Body::new` doesn't complain.
1074 let initial_locals = iter::once(
1075 LocalDecl::new_return_place(tcx.types.never, body.span)
1078 let promoter = Promoter {
1079 promoted: Body::new(
1081 // FIXME: maybe try to filter this to avoid blowing up
1083 body.source_scopes.clone(),
1084 body.source_scope_local_data.clone(),
1091 body.generator_kind,
1096 keep_original: false
1099 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1100 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1101 promotions.push(promoted);
1105 // Eliminate assignments to, and drops of promoted temps.
1106 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1107 for block in body.basic_blocks_mut() {
1108 block.statements.retain(|statement| {
1109 match &statement.kind {
1110 StatementKind::Assign(box(place, _)) => {
1111 if let Some(index) = place.as_local() {
1117 StatementKind::StorageLive(index) |
1118 StatementKind::StorageDead(index) => {
1124 let terminator = block.terminator_mut();
1125 match &terminator.kind {
1126 TerminatorKind::Drop { location: place, target, .. } => {
1127 if let Some(index) = place.as_local() {
1128 if promoted(index) {
1129 terminator.kind = TerminatorKind::Goto {
1142 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1143 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1144 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1146 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1150 operand: &Operand<'tcx>,
1152 let mut rpo = traversal::reverse_postorder(body);
1153 let (temps, _) = collect_temps_and_candidates(tcx, body, &mut rpo);
1154 let validator = Validator {
1155 item: Item::new(tcx, mir_def_id, body),
1160 let should_promote = validator.validate_operand(operand).is_ok();
1161 let feature_flag = tcx.features().const_in_array_repeat_expressions;
1162 debug!("should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1163 should_promote={:?} feature_flag={:?}", mir_def_id, should_promote, feature_flag);
1164 should_promote && !feature_flag