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 irrelevent.
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(box Static {
500 kind: StaticKind::Promoted { .. },
504 } => bug!("qualifying already promoted MIR"),
506 base: PlaceBase::Static(box Static {
507 kind: StaticKind::Static,
513 // Only allow statics (not consts) to refer to other statics.
514 // FIXME(eddyb) does this matter at all for promotion?
515 let is_static = self.const_kind.map_or(false, |k| k.is_static());
517 return Err(Unpromotable);
520 let is_thread_local = self.tcx.has_attr(*def_id, sym::thread_local);
522 return Err(Unpromotable);
529 projection: [proj_base @ .., elem],
532 ProjectionElem::Deref |
533 ProjectionElem::Downcast(..) => return Err(Unpromotable),
535 ProjectionElem::ConstantIndex {..} |
536 ProjectionElem::Subslice {..} => {}
538 ProjectionElem::Index(local) => {
539 self.validate_local(local)?;
542 ProjectionElem::Field(..) => {
543 if self.const_kind.is_none() {
545 Place::ty_from(place.base, proj_base, self.body, self.tcx).ty;
546 if let Some(def) = base_ty.ty_adt_def() {
547 // No promotion of union field accesses.
549 return Err(Unpromotable);
556 self.validate_place(PlaceRef {
558 projection: proj_base,
564 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
566 Operand::Copy(place) |
567 Operand::Move(place) => self.validate_place(place.as_ref()),
569 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
570 // `validate_rvalue` upon access.
571 Operand::Constant(_) => Ok(()),
575 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
577 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
578 let operand_ty = operand.ty(self.body, self.tcx);
579 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
580 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
581 match (cast_in, cast_out) {
582 (CastTy::Ptr(_), CastTy::Int(_)) |
583 (CastTy::FnPtr, CastTy::Int(_)) => {
584 // in normal functions, mark such casts as not promotable
585 return Err(Unpromotable);
591 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
592 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
593 assert!(op == BinOp::Eq || op == BinOp::Ne ||
594 op == BinOp::Le || op == BinOp::Lt ||
595 op == BinOp::Ge || op == BinOp::Gt ||
596 op == BinOp::Offset);
598 // raw pointer operations are not allowed inside promoteds
599 return Err(Unpromotable);
603 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
609 Rvalue::NullaryOp(..) => Ok(()),
611 Rvalue::Discriminant(place) |
612 Rvalue::Len(place) => self.validate_place(place.as_ref()),
614 Rvalue::Use(operand) |
615 Rvalue::Repeat(operand, _) |
616 Rvalue::UnaryOp(_, operand) |
617 Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
619 Rvalue::BinaryOp(_, lhs, rhs) |
620 Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
621 self.validate_operand(lhs)?;
622 self.validate_operand(rhs)
625 Rvalue::Ref(_, kind, place) => {
626 if let BorrowKind::Mut { .. } = kind {
627 let ty = place.ty(self.body, self.tcx).ty;
629 // In theory, any zero-sized value could be borrowed
630 // mutably without consequences. However, only &mut []
631 // is allowed right now, and only in functions.
632 if self.const_kind == Some(ConstKind::StaticMut) {
633 // Inside a `static mut`, &mut [...] is also allowed.
635 ty::Array(..) | ty::Slice(_) => {}
636 _ => return Err(Unpromotable),
638 } else if let ty::Array(_, len) = ty.kind {
639 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
640 // const context which seems unnecessary given that this is merely a ZST.
641 match len.try_eval_usize(self.tcx, self.param_env) {
642 Some(0) if self.const_kind.is_none() => {},
643 _ => return Err(Unpromotable),
646 return Err(Unpromotable);
650 // Special-case reborrows to be more like a copy of the reference.
651 let mut place = place.as_ref();
652 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
654 Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
655 if let ty::Ref(..) = base_ty.kind {
658 projection: proj_base,
663 self.validate_place(place)?;
665 // HACK(eddyb) this should compute the same thing as
666 // `<HasMutInterior as Qualif>::in_projection` from
667 // `check_consts::qualifs` but without recursion.
668 let mut has_mut_interior = match place.base {
669 PlaceBase::Local(local) => {
670 self.qualif_local::<qualifs::HasMutInterior>(*local)
672 PlaceBase::Static(_) => false,
674 if has_mut_interior {
675 let mut place_projection = place.projection;
676 // FIXME(eddyb) use a forward loop instead of a reverse one.
677 while let [proj_base @ .., elem] = place_projection {
678 // FIXME(eddyb) this is probably excessive, with
679 // the exception of `union` member accesses.
680 let ty = Place::ty_from(place.base, proj_base, self.body, self.tcx)
681 .projection_ty(self.tcx, elem)
683 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
684 has_mut_interior = false;
688 place_projection = proj_base;
691 if has_mut_interior {
692 return Err(Unpromotable);
698 Rvalue::Aggregate(_, ref operands) => {
700 self.validate_operand(o)?;
710 callee: &Operand<'tcx>,
711 args: &[Operand<'tcx>],
712 ) -> Result<(), Unpromotable> {
713 let fn_ty = callee.ty(self.body, self.tcx);
715 if !self.explicit && self.const_kind.is_none() {
716 if let ty::FnDef(def_id, _) = fn_ty.kind {
717 // Never promote runtime `const fn` calls of
718 // functions without `#[rustc_promotable]`.
719 if !self.tcx.is_promotable_const_fn(def_id) {
720 return Err(Unpromotable);
725 let is_const_fn = match fn_ty.kind {
726 ty::FnDef(def_id, _) => {
727 self.tcx.is_const_fn(def_id) ||
728 self.tcx.is_unstable_const_fn(def_id).is_some() ||
729 is_lang_panic_fn(self.tcx, self.def_id)
734 return Err(Unpromotable);
737 self.validate_operand(callee)?;
739 self.validate_operand(arg)?;
746 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
747 pub fn validate_candidates(
751 temps: &IndexVec<Local, TempState>,
752 candidates: &[Candidate],
753 ) -> Vec<Candidate> {
754 let mut validator = Validator {
755 item: Item::new(tcx, def_id, body),
760 candidates.iter().copied().filter(|&candidate| {
761 validator.explicit = candidate.forces_explicit_promotion();
763 // FIXME(eddyb) also emit the errors for shuffle indices
764 // and `#[rustc_args_required_const]` arguments here.
766 let is_promotable = validator.validate_candidate(candidate).is_ok();
768 Candidate::Argument { bb, index } if !is_promotable => {
769 let span = body[bb].terminator().source_info.span;
770 let msg = format!("argument {} is required to be a constant", index + 1);
771 tcx.sess.span_err(span, &msg);
780 struct Promoter<'a, 'tcx> {
782 source: &'a mut Body<'tcx>,
783 promoted: Body<'tcx>,
784 temps: &'a mut IndexVec<Local, TempState>,
786 /// If true, all nested temps are also kept in the
787 /// source MIR, not moved to the promoted MIR.
791 impl<'a, 'tcx> Promoter<'a, 'tcx> {
792 fn new_block(&mut self) -> BasicBlock {
793 let span = self.promoted.span;
794 self.promoted.basic_blocks_mut().push(BasicBlockData {
796 terminator: Some(Terminator {
797 source_info: SourceInfo {
799 scope: OUTERMOST_SOURCE_SCOPE
801 kind: TerminatorKind::Return
807 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
808 let last = self.promoted.basic_blocks().last().unwrap();
809 let data = &mut self.promoted[last];
810 data.statements.push(Statement {
811 source_info: SourceInfo {
813 scope: OUTERMOST_SOURCE_SCOPE
815 kind: StatementKind::Assign(box(Place::from(dest), rvalue))
819 fn is_temp_kind(&self, local: Local) -> bool {
820 self.source.local_kind(local) == LocalKind::Temp
823 /// Copies the initialization of this temp to the
824 /// promoted MIR, recursing through temps.
825 fn promote_temp(&mut self, temp: Local) -> Local {
826 let old_keep_original = self.keep_original;
827 let loc = match self.temps[temp] {
828 TempState::Defined { location, uses } if uses > 0 => {
830 self.keep_original = true;
835 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
839 if !self.keep_original {
840 self.temps[temp] = TempState::PromotedOut;
843 let num_stmts = self.source[loc.block].statements.len();
844 let new_temp = self.promoted.local_decls.push(
845 LocalDecl::new_temp(self.source.local_decls[temp].ty,
846 self.source.local_decls[temp].source_info.span));
848 debug!("promote({:?} @ {:?}/{:?}, {:?})",
849 temp, loc, num_stmts, self.keep_original);
851 // First, take the Rvalue or Call out of the source MIR,
852 // or duplicate it, depending on keep_original.
853 if loc.statement_index < num_stmts {
854 let (mut rvalue, source_info) = {
855 let statement = &mut self.source[loc.block].statements[loc.statement_index];
856 let rhs = match statement.kind {
857 StatementKind::Assign(box(_, ref mut rhs)) => rhs,
859 span_bug!(statement.source_info.span, "{:?} is not an assignment",
864 (if self.keep_original {
867 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
868 mem::replace(rhs, unit)
869 }, statement.source_info)
872 self.visit_rvalue(&mut rvalue, loc);
873 self.assign(new_temp, rvalue, source_info.span);
875 let terminator = if self.keep_original {
876 self.source[loc.block].terminator().clone()
878 let terminator = self.source[loc.block].terminator_mut();
879 let target = match terminator.kind {
880 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
882 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
886 source_info: terminator.source_info,
887 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
893 match terminator.kind {
894 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
895 self.visit_operand(&mut func, loc);
896 for arg in &mut args {
897 self.visit_operand(arg, loc);
900 let last = self.promoted.basic_blocks().last().unwrap();
901 let new_target = self.new_block();
903 *self.promoted[last].terminator_mut() = Terminator {
904 kind: TerminatorKind::Call {
909 (Place::from(new_temp), new_target)
917 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
922 self.keep_original = old_keep_original;
926 fn promote_candidate(
929 candidate: Candidate,
930 next_promoted_id: usize,
931 ) -> Option<Body<'tcx>> {
933 let promoted = &mut self.promoted;
934 let promoted_id = Promoted::new(next_promoted_id);
936 let mut promoted_place = |ty, span| {
937 promoted.span = span;
938 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
940 base: PlaceBase::Static(box Static {
942 StaticKind::Promoted(
944 InternalSubsts::identity_for_item(tcx, def_id),
949 projection: List::empty(),
952 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
954 Candidate::Ref(loc) => {
955 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
956 match statement.kind {
957 StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
958 // Use the underlying local for this (necessarily interior) borrow.
959 let ty = place.base.ty(local_decls).ty;
960 let span = statement.source_info.span;
962 Operand::Move(Place {
965 promoted_place(ty, span).base,
967 projection: List::empty(),
973 Candidate::Repeat(loc) => {
974 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
975 match statement.kind {
976 StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
977 let ty = operand.ty(local_decls, self.tcx);
978 let span = statement.source_info.span;
981 Operand::Copy(promoted_place(ty, span))
987 Candidate::Argument { bb, index } => {
988 let terminator = blocks[bb].terminator_mut();
989 match terminator.kind {
990 TerminatorKind::Call { ref mut args, .. } => {
991 let ty = args[index].ty(local_decls, self.tcx);
992 let span = terminator.source_info.span;
993 let operand = Operand::Copy(promoted_place(ty, span));
994 mem::replace(&mut args[index], operand)
996 // We expected a `TerminatorKind::Call` for which we'd like to promote an
997 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
998 // we are seeing a `Goto`. That means that the `promote_temps` method
999 // already promoted this call away entirely. This case occurs when calling
1000 // a function requiring a constant argument and as that constant value
1001 // providing a value whose computation contains another call to a function
1002 // requiring a constant argument.
1003 TerminatorKind::Goto { .. } => return None,
1010 assert_eq!(self.new_block(), START_BLOCK);
1011 self.visit_operand(&mut operand, Location {
1012 block: BasicBlock::new(0),
1013 statement_index: usize::MAX
1016 let span = self.promoted.span;
1017 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
1022 /// Replaces all temporaries with their promoted counterparts.
1023 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1024 fn tcx(&self) -> TyCtxt<'tcx> {
1028 fn visit_local(&mut self,
1032 if self.is_temp_kind(*local) {
1033 *local = self.promote_temp(*local);
1037 fn process_projection_elem(
1039 elem: &PlaceElem<'tcx>,
1040 ) -> Option<PlaceElem<'tcx>> {
1042 PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1043 Some(PlaceElem::Index(self.promote_temp(*local)))
1050 pub fn promote_candidates<'tcx>(
1052 body: &mut Body<'tcx>,
1054 mut temps: IndexVec<Local, TempState>,
1055 candidates: Vec<Candidate>,
1056 ) -> IndexVec<Promoted, Body<'tcx>> {
1057 // Visit candidates in reverse, in case they're nested.
1058 debug!("promote_candidates({:?})", candidates);
1060 let mut promotions = IndexVec::new();
1062 for candidate in candidates.into_iter().rev() {
1064 Candidate::Repeat(Location { block, statement_index }) |
1065 Candidate::Ref(Location { block, statement_index }) => {
1066 match &body[block].statements[statement_index].kind {
1067 StatementKind::Assign(box(place, _)) => {
1068 if let Some(local) = place.as_local() {
1069 if temps[local] == TempState::PromotedOut {
1070 // Already promoted.
1078 Candidate::Argument { .. } => {}
1082 // Declare return place local so that `mir::Body::new` doesn't complain.
1083 let initial_locals = iter::once(
1084 LocalDecl::new_return_place(tcx.types.never, body.span)
1087 let promoter = Promoter {
1088 promoted: Body::new(
1090 // FIXME: maybe try to filter this to avoid blowing up
1092 body.source_scopes.clone(),
1093 body.source_scope_local_data.clone(),
1105 keep_original: false
1108 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1109 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1110 promotions.push(promoted);
1114 // Eliminate assignments to, and drops of promoted temps.
1115 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1116 for block in body.basic_blocks_mut() {
1117 block.statements.retain(|statement| {
1118 match &statement.kind {
1119 StatementKind::Assign(box(place, _)) => {
1120 if let Some(index) = place.as_local() {
1126 StatementKind::StorageLive(index) |
1127 StatementKind::StorageDead(index) => {
1133 let terminator = block.terminator_mut();
1134 match &terminator.kind {
1135 TerminatorKind::Drop { location: place, target, .. } => {
1136 if let Some(index) = place.as_local() {
1137 if promoted(index) {
1138 terminator.kind = TerminatorKind::Goto {
1151 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1152 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1153 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1155 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1159 operand: &Operand<'tcx>,
1161 let mut rpo = traversal::reverse_postorder(body);
1162 let (temps, _) = collect_temps_and_candidates(tcx, body, &mut rpo);
1163 let validator = Validator {
1164 item: Item::new(tcx, mir_def_id, body),
1169 let should_promote = validator.validate_operand(operand).is_ok();
1170 let feature_flag = tcx.features().const_in_array_repeat_expressions;
1171 debug!("should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1172 should_promote={:?} feature_flag={:?}", mir_def_id, should_promote, feature_flag);
1173 should_promote && !feature_flag