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::mir::traversal::ReversePostorder;
16 use rustc::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
18 use rustc::ty::cast::CastTy;
19 use rustc::ty::subst::InternalSubsts;
20 use rustc::ty::{self, List, TyCtxt, TypeFoldable};
21 use rustc_hir::def_id::DefId;
22 use rustc_span::symbol::sym;
23 use rustc_span::{Span, DUMMY_SP};
24 use syntax::ast::LitKind;
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_target::spec::abi::Abi;
30 use std::{iter, mem, usize};
32 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
33 use crate::transform::{MirPass, MirSource};
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, BodyAndCache<'tcx>>>,
47 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
48 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut BodyAndCache<'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 =
67 validate_candidates(tcx, read_only!(body), def_id, &temps, &all_candidates);
69 let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
70 self.promoted_fragments.set(promoted);
74 /// State of a temporary during collection and promotion.
75 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 /// No references to this temp.
79 /// One direct assignment and any number of direct uses.
80 /// A borrow of this temp is promotable if the assigned
81 /// value is qualified as constant.
82 Defined { location: Location, uses: usize },
83 /// Any other combination of assignments/uses.
85 /// This temp was part of an rvalue which got extracted
86 /// during promotion and needs cleanup.
91 pub fn is_promotable(&self) -> bool {
92 debug!("is_promotable: self={:?}", self);
93 if let TempState::Defined { .. } = *self { true } else { false }
97 /// A "root candidate" for promotion, which will become the
98 /// returned value in a promoted MIR, unless it's a subset
99 /// of a larger candidate.
100 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
102 /// Borrow of a constant temporary.
105 /// Promotion of the `x` in `[x; 32]`.
108 /// Currently applied to function calls where the callee has the unstable
109 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
110 /// intrinsic. The intrinsic requires the arguments are indeed constant and
111 /// the attribute currently provides the semantic requirement that arguments
112 /// must be constant.
113 Argument { bb: BasicBlock, index: usize },
117 /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
118 fn forces_explicit_promotion(&self) -> bool {
120 Candidate::Ref(_) | Candidate::Repeat(_) => false,
121 Candidate::Argument { .. } => true,
126 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
127 let attrs = tcx.get_attrs(def_id);
128 let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
129 let mut ret = vec![];
130 for meta in attr.meta_item_list()? {
131 match meta.literal()?.kind {
132 LitKind::Int(a, _) => {
133 ret.push(a as usize);
141 struct Collector<'a, 'tcx> {
143 body: &'a Body<'tcx>,
144 temps: IndexVec<Local, TempState>,
145 candidates: Vec<Candidate>,
149 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
150 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
151 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
152 // We're only interested in temporaries and the return place
153 match self.body.local_kind(index) {
154 LocalKind::Temp | LocalKind::ReturnPointer => {}
155 LocalKind::Arg | LocalKind::Var => return,
158 // Ignore drops, if the temp gets promoted,
159 // then it's constant and thus drop is noop.
160 // Non-uses are also irrelevant.
161 if context.is_drop() || !context.is_use() {
163 "visit_local: context.is_drop={:?} context.is_use={:?}",
170 let temp = &mut self.temps[index];
171 debug!("visit_local: temp={:?}", temp);
172 if *temp == TempState::Undefined {
174 PlaceContext::MutatingUse(MutatingUseContext::Store)
175 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
176 *temp = TempState::Defined { location, uses: 0 };
179 _ => { /* mark as unpromotable below */ }
181 } else if let TempState::Defined { ref mut uses, .. } = *temp {
182 // We always allow borrows, even mutable ones, as we need
183 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
184 let allowed_use = match context {
185 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
186 | PlaceContext::NonMutatingUse(_) => true,
187 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
189 debug!("visit_local: allowed_use={:?}", allowed_use);
194 /* mark as unpromotable below */
196 *temp = TempState::Unpromotable;
199 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
200 self.super_rvalue(rvalue, location);
204 self.candidates.push(Candidate::Ref(location));
206 Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
207 // FIXME(#49147) only promote the element when it isn't `Copy`
208 // (so that code that can copy it at runtime is unaffected).
209 self.candidates.push(Candidate::Repeat(location));
215 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
216 self.super_terminator_kind(kind, location);
218 if let TerminatorKind::Call { ref func, .. } = *kind {
219 if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
220 let fn_sig = self.tcx.fn_sig(def_id);
221 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
222 let name = self.tcx.item_name(def_id);
223 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
224 if name.as_str().starts_with("simd_shuffle") {
225 self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
227 return; // Don't double count `simd_shuffle` candidates
231 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
232 for index in constant_args {
233 self.candidates.push(Candidate::Argument { bb: location.block, index });
240 fn visit_source_info(&mut self, source_info: &SourceInfo) {
241 self.span = source_info.span;
245 pub fn collect_temps_and_candidates(
248 rpo: &mut ReversePostorder<'_, 'tcx>,
249 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
250 let mut collector = Collector {
253 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
257 for (bb, data) in rpo {
258 collector.visit_basic_block_data(bb, data);
260 (collector.temps, collector.candidates)
263 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
265 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
266 struct Validator<'a, 'tcx> {
267 item: Item<'a, 'tcx>,
268 temps: &'a IndexVec<Local, TempState>,
270 /// Explicit promotion happens e.g. for constant arguments declared via
271 /// `rustc_args_required_const`.
272 /// Implicit promotion has almost the same rules, except that disallows `const fn`
273 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
274 /// a legitimate run-time operation into a failing compile-time operation
275 /// e.g. due to addresses being compared inside the function.
279 impl std::ops::Deref for Validator<'a, 'tcx> {
280 type Target = Item<'a, 'tcx>;
282 fn deref(&self) -> &Self::Target {
289 impl<'tcx> Validator<'_, 'tcx> {
290 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
292 Candidate::Ref(loc) => {
293 assert!(!self.explicit);
295 let statement = &self.body[loc.block].statements[loc.statement_index];
296 match &statement.kind {
297 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
299 BorrowKind::Shared | BorrowKind::Mut { .. } => {}
301 // FIXME(eddyb) these aren't promoted here but *could*
302 // be promoted as part of a larger value because
303 // `validate_rvalue` doesn't check them, need to
304 // figure out what is the intended behavior.
305 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
308 // We can only promote interior borrows of promotable temps (non-temps
309 // don't get promoted anyway).
310 let base = match place.base {
311 PlaceBase::Local(local) => local,
312 _ => return Err(Unpromotable),
314 self.validate_local(base)?;
316 if place.projection.contains(&ProjectionElem::Deref) {
317 return Err(Unpromotable);
320 let mut has_mut_interior =
321 self.qualif_local::<qualifs::HasMutInterior>(base);
322 // HACK(eddyb) this should compute the same thing as
323 // `<HasMutInterior as Qualif>::in_projection` from
324 // `check_consts::qualifs` but without recursion.
325 if has_mut_interior {
326 // This allows borrowing fields which don't have
327 // `HasMutInterior`, from a type that does, e.g.:
328 // `let _: &'static _ = &(Cell::new(1), 2).1;`
329 let mut place_projection = &place.projection[..];
330 // FIXME(eddyb) use a forward loop instead of a reverse one.
331 while let [proj_base @ .., elem] = place_projection {
332 // FIXME(eddyb) this is probably excessive, with
333 // the exception of `union` member accesses.
335 Place::ty_from(&place.base, proj_base, *self.body, self.tcx)
336 .projection_ty(self.tcx, elem)
338 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
339 has_mut_interior = false;
343 place_projection = proj_base;
347 // FIXME(eddyb) this duplicates part of `validate_rvalue`.
348 if has_mut_interior {
349 return Err(Unpromotable);
351 if self.qualif_local::<qualifs::NeedsDrop>(base) {
352 return Err(Unpromotable);
355 if let BorrowKind::Mut { .. } = kind {
356 let ty = place.ty(*self.body, self.tcx).ty;
358 // In theory, any zero-sized value could be borrowed
359 // mutably without consequences. However, only &mut []
360 // is allowed right now, and only in functions.
361 if self.const_kind == Some(ConstKind::StaticMut) {
362 // Inside a `static mut`, &mut [...] is also allowed.
364 ty::Array(..) | ty::Slice(_) => {}
365 _ => return Err(Unpromotable),
367 } else if let ty::Array(_, len) = ty.kind {
368 // FIXME(eddyb) the `self.is_non_const_fn` condition
369 // seems unnecessary, given that this is merely a ZST.
370 match len.try_eval_usize(self.tcx, self.param_env) {
371 Some(0) if self.const_kind.is_none() => {}
372 _ => return Err(Unpromotable),
375 return Err(Unpromotable);
384 Candidate::Repeat(loc) => {
385 assert!(!self.explicit);
387 let statement = &self.body[loc.block].statements[loc.statement_index];
388 match &statement.kind {
389 StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
390 if !self.tcx.features().const_in_array_repeat_expressions {
391 return Err(Unpromotable);
394 self.validate_operand(operand)
399 Candidate::Argument { bb, index } => {
400 assert!(self.explicit);
402 let terminator = self.body[bb].terminator();
403 match &terminator.kind {
404 TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
411 // FIXME(eddyb) maybe cache this?
412 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
413 let per_local = &|l| self.qualif_local::<Q>(l);
415 if let TempState::Defined { location: loc, .. } = self.temps[local] {
416 let num_stmts = self.body[loc.block].statements.len();
418 if loc.statement_index < num_stmts {
419 let statement = &self.body[loc.block].statements[loc.statement_index];
420 match &statement.kind {
421 StatementKind::Assign(box (_, rhs)) => Q::in_rvalue(&self.item, per_local, rhs),
424 statement.source_info.span,
425 "{:?} is not an assignment",
431 let terminator = self.body[loc.block].terminator();
432 match &terminator.kind {
433 TerminatorKind::Call { func, args, .. } => {
434 let return_ty = self.body.local_decls[local].ty;
435 Q::in_call(&self.item, per_local, func, args, return_ty)
438 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
443 let span = self.body.local_decls[local].source_info.span;
444 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
448 // FIXME(eddyb) maybe cache this?
449 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
450 if let TempState::Defined { location: loc, .. } = self.temps[local] {
451 let num_stmts = self.body[loc.block].statements.len();
453 if loc.statement_index < num_stmts {
454 let statement = &self.body[loc.block].statements[loc.statement_index];
455 match &statement.kind {
456 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
459 statement.source_info.span,
460 "{:?} is not an assignment",
466 let terminator = self.body[loc.block].terminator();
467 match &terminator.kind {
468 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
470 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
479 fn validate_place(&self, place: PlaceRef<'_, 'tcx>) -> Result<(), Unpromotable> {
481 PlaceRef { base: PlaceBase::Local(local), projection: [] } => {
482 self.validate_local(*local)
484 PlaceRef { base: PlaceBase::Static(_), projection: [] } => {
485 bug!("qualifying already promoted MIR")
487 PlaceRef { base: _, projection: [proj_base @ .., elem] } => {
489 ProjectionElem::Deref | ProjectionElem::Downcast(..) => {
490 return Err(Unpromotable);
493 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
495 ProjectionElem::Index(local) => {
496 self.validate_local(local)?;
499 ProjectionElem::Field(..) => {
500 if self.const_kind.is_none() {
502 Place::ty_from(place.base, proj_base, *self.body, self.tcx).ty;
503 if let Some(def) = base_ty.ty_adt_def() {
504 // No promotion of union field accesses.
506 return Err(Unpromotable);
513 self.validate_place(PlaceRef { base: place.base, projection: proj_base })
518 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
520 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
522 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
523 // `validate_rvalue` upon access.
524 Operand::Constant(c) => {
525 if let Some(def_id) = c.check_static_ptr(self.tcx) {
526 // Only allow statics (not consts) to refer to other statics.
527 // FIXME(eddyb) does this matter at all for promotion?
528 let is_static = self.const_kind.map_or(false, |k| k.is_static());
530 return Err(Unpromotable);
533 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
535 return Err(Unpromotable);
544 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
546 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
547 let operand_ty = operand.ty(*self.body, self.tcx);
548 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
549 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
550 match (cast_in, cast_out) {
551 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
552 // in normal functions, mark such casts as not promotable
553 return Err(Unpromotable);
559 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
560 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
568 || op == BinOp::Offset
571 // raw pointer operations are not allowed inside promoteds
572 return Err(Unpromotable);
576 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
582 Rvalue::NullaryOp(..) => Ok(()),
584 Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
587 | Rvalue::Repeat(operand, _)
588 | Rvalue::UnaryOp(_, operand)
589 | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
591 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
592 self.validate_operand(lhs)?;
593 self.validate_operand(rhs)
596 Rvalue::AddressOf(_, place) => {
597 // Raw reborrows can come from reference to pointer coercions,
599 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
600 let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
601 if let ty::Ref(..) = base_ty.kind {
603 .validate_place(PlaceRef { base: &place.base, projection: proj_base });
609 Rvalue::Ref(_, kind, place) => {
610 if let BorrowKind::Mut { .. } = kind {
611 let ty = place.ty(*self.body, self.tcx).ty;
613 // In theory, any zero-sized value could be borrowed
614 // mutably without consequences. However, only &mut []
615 // is allowed right now, and only in functions.
616 if self.const_kind == Some(ConstKind::StaticMut) {
617 // Inside a `static mut`, &mut [...] is also allowed.
619 ty::Array(..) | ty::Slice(_) => {}
620 _ => return Err(Unpromotable),
622 } else if let ty::Array(_, len) = ty.kind {
623 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
624 // const context which seems unnecessary given that this is merely a ZST.
625 match len.try_eval_usize(self.tcx, self.param_env) {
626 Some(0) if self.const_kind.is_none() => {}
627 _ => return Err(Unpromotable),
630 return Err(Unpromotable);
634 // Special-case reborrows to be more like a copy of the reference.
635 let mut place = place.as_ref();
636 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
637 let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
638 if let ty::Ref(..) = base_ty.kind {
639 place = PlaceRef { base: &place.base, projection: proj_base };
643 self.validate_place(place)?;
645 // HACK(eddyb) this should compute the same thing as
646 // `<HasMutInterior as Qualif>::in_projection` from
647 // `check_consts::qualifs` but without recursion.
648 let mut has_mut_interior = match place.base {
649 PlaceBase::Local(local) => self.qualif_local::<qualifs::HasMutInterior>(*local),
650 PlaceBase::Static(_) => false,
652 if has_mut_interior {
653 let mut place_projection = place.projection;
654 // FIXME(eddyb) use a forward loop instead of a reverse one.
655 while let [proj_base @ .., elem] = place_projection {
656 // FIXME(eddyb) this is probably excessive, with
657 // the exception of `union` member accesses.
658 let ty = Place::ty_from(place.base, proj_base, *self.body, self.tcx)
659 .projection_ty(self.tcx, elem)
661 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
662 has_mut_interior = false;
666 place_projection = proj_base;
669 if has_mut_interior {
670 return Err(Unpromotable);
676 Rvalue::Aggregate(_, ref operands) => {
678 self.validate_operand(o)?;
688 callee: &Operand<'tcx>,
689 args: &[Operand<'tcx>],
690 ) -> Result<(), Unpromotable> {
691 let fn_ty = callee.ty(*self.body, self.tcx);
693 if !self.explicit && self.const_kind.is_none() {
694 if let ty::FnDef(def_id, _) = fn_ty.kind {
695 // Never promote runtime `const fn` calls of
696 // functions without `#[rustc_promotable]`.
697 if !self.tcx.is_promotable_const_fn(def_id) {
698 return Err(Unpromotable);
703 let is_const_fn = match fn_ty.kind {
704 ty::FnDef(def_id, _) => {
705 self.tcx.is_const_fn(def_id)
706 || self.tcx.is_unstable_const_fn(def_id).is_some()
707 || is_lang_panic_fn(self.tcx, self.def_id)
712 return Err(Unpromotable);
715 self.validate_operand(callee)?;
717 self.validate_operand(arg)?;
724 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
725 pub fn validate_candidates(
727 body: ReadOnlyBodyAndCache<'_, 'tcx>,
729 temps: &IndexVec<Local, TempState>,
730 candidates: &[Candidate],
731 ) -> Vec<Candidate> {
732 let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
737 .filter(|&candidate| {
738 validator.explicit = candidate.forces_explicit_promotion();
740 // FIXME(eddyb) also emit the errors for shuffle indices
741 // and `#[rustc_args_required_const]` arguments here.
743 let is_promotable = validator.validate_candidate(candidate).is_ok();
745 Candidate::Argument { bb, index } if !is_promotable => {
746 let span = body[bb].terminator().source_info.span;
747 let msg = format!("argument {} is required to be a constant", index + 1);
748 tcx.sess.span_err(span, &msg);
758 struct Promoter<'a, 'tcx> {
760 source: &'a mut BodyAndCache<'tcx>,
761 promoted: BodyAndCache<'tcx>,
762 temps: &'a mut IndexVec<Local, TempState>,
764 /// If true, all nested temps are also kept in the
765 /// source MIR, not moved to the promoted MIR.
769 impl<'a, 'tcx> Promoter<'a, 'tcx> {
770 fn new_block(&mut self) -> BasicBlock {
771 let span = self.promoted.span;
772 self.promoted.basic_blocks_mut().push(BasicBlockData {
774 terminator: Some(Terminator {
775 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
776 kind: TerminatorKind::Return,
782 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
783 let last = self.promoted.basic_blocks().last().unwrap();
784 let data = &mut self.promoted[last];
785 data.statements.push(Statement {
786 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
787 kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
791 fn is_temp_kind(&self, local: Local) -> bool {
792 self.source.local_kind(local) == LocalKind::Temp
795 /// Copies the initialization of this temp to the
796 /// promoted MIR, recursing through temps.
797 fn promote_temp(&mut self, temp: Local) -> Local {
798 let old_keep_original = self.keep_original;
799 let loc = match self.temps[temp] {
800 TempState::Defined { location, uses } if uses > 0 => {
802 self.keep_original = true;
807 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
810 if !self.keep_original {
811 self.temps[temp] = TempState::PromotedOut;
814 let num_stmts = self.source[loc.block].statements.len();
815 let new_temp = self.promoted.local_decls.push(LocalDecl::new_temp(
816 self.source.local_decls[temp].ty,
817 self.source.local_decls[temp].source_info.span,
820 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
822 // First, take the Rvalue or Call out of the source MIR,
823 // or duplicate it, depending on keep_original.
824 if loc.statement_index < num_stmts {
825 let (mut rvalue, source_info) = {
826 let statement = &mut self.source[loc.block].statements[loc.statement_index];
827 let rhs = match statement.kind {
828 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
831 statement.source_info.span,
832 "{:?} is not an assignment",
839 if self.keep_original {
842 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
843 mem::replace(rhs, unit)
845 statement.source_info,
849 self.visit_rvalue(&mut rvalue, loc);
850 self.assign(new_temp, rvalue, source_info.span);
852 let terminator = if self.keep_original {
853 self.source[loc.block].terminator().clone()
855 let terminator = self.source[loc.block].terminator_mut();
856 let target = match terminator.kind {
857 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
859 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
863 source_info: terminator.source_info,
864 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
868 match terminator.kind {
869 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
870 self.visit_operand(&mut func, loc);
871 for arg in &mut args {
872 self.visit_operand(arg, loc);
875 let last = self.promoted.basic_blocks().last().unwrap();
876 let new_target = self.new_block();
878 *self.promoted[last].terminator_mut() = Terminator {
879 kind: TerminatorKind::Call {
883 destination: Some((Place::from(new_temp), new_target)),
890 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
895 self.keep_original = old_keep_original;
899 fn promote_candidate(
902 candidate: Candidate,
903 next_promoted_id: usize,
904 ) -> Option<BodyAndCache<'tcx>> {
906 let promoted = &mut self.promoted;
907 let promoted_id = Promoted::new(next_promoted_id);
909 let mut promoted_place = |ty, span| {
910 promoted.span = span;
911 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
913 base: PlaceBase::Static(box Static {
914 kind: StaticKind::Promoted(
916 InternalSubsts::identity_for_item(tcx, def_id),
921 projection: List::empty(),
924 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
926 Candidate::Ref(loc) => {
927 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
928 match statement.kind {
929 StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref mut place))) => {
930 // Use the underlying local for this (necessarily interior) borrow.
931 let ty = place.base.ty(local_decls).ty;
932 let span = statement.source_info.span;
934 Operand::Move(Place {
935 base: mem::replace(&mut place.base, promoted_place(ty, span).base),
936 projection: List::empty(),
942 Candidate::Repeat(loc) => {
943 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
944 match statement.kind {
945 StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
946 let ty = operand.ty(local_decls, self.tcx);
947 let span = statement.source_info.span;
948 mem::replace(operand, Operand::Copy(promoted_place(ty, span)))
953 Candidate::Argument { bb, index } => {
954 let terminator = blocks[bb].terminator_mut();
955 match terminator.kind {
956 TerminatorKind::Call { ref mut args, .. } => {
957 let ty = args[index].ty(local_decls, self.tcx);
958 let span = terminator.source_info.span;
959 let operand = Operand::Copy(promoted_place(ty, span));
960 mem::replace(&mut args[index], operand)
962 // We expected a `TerminatorKind::Call` for which we'd like to promote an
963 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
964 // we are seeing a `Goto`. That means that the `promote_temps` method
965 // already promoted this call away entirely. This case occurs when calling
966 // a function requiring a constant argument and as that constant value
967 // providing a value whose computation contains another call to a function
968 // requiring a constant argument.
969 TerminatorKind::Goto { .. } => return None,
976 assert_eq!(self.new_block(), START_BLOCK);
979 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
982 let span = self.promoted.span;
983 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
988 /// Replaces all temporaries with their promoted counterparts.
989 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
990 fn tcx(&self) -> TyCtxt<'tcx> {
994 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
995 if self.is_temp_kind(*local) {
996 *local = self.promote_temp(*local);
1000 fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
1002 PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1003 Some(PlaceElem::Index(self.promote_temp(*local)))
1010 pub fn promote_candidates<'tcx>(
1012 body: &mut BodyAndCache<'tcx>,
1014 mut temps: IndexVec<Local, TempState>,
1015 candidates: Vec<Candidate>,
1016 ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1017 // Visit candidates in reverse, in case they're nested.
1018 debug!("promote_candidates({:?})", candidates);
1020 let mut promotions = IndexVec::new();
1022 for candidate in candidates.into_iter().rev() {
1024 Candidate::Repeat(Location { block, statement_index })
1025 | Candidate::Ref(Location { block, statement_index }) => {
1026 match &body[block].statements[statement_index].kind {
1027 StatementKind::Assign(box (place, _)) => {
1028 if let Some(local) = place.as_local() {
1029 if temps[local] == TempState::PromotedOut {
1030 // Already promoted.
1038 Candidate::Argument { .. } => {}
1041 // Declare return place local so that `mir::Body::new` doesn't complain.
1042 let initial_locals =
1043 iter::once(LocalDecl::new_return_place(tcx.types.never, body.span)).collect();
1045 let promoter = Promoter {
1046 promoted: BodyAndCache::new(Body::new(
1048 // FIXME: maybe try to filter this to avoid blowing up
1050 body.source_scopes.clone(),
1057 body.generator_kind,
1062 keep_original: false,
1065 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1066 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1067 promotions.push(promoted);
1071 // Eliminate assignments to, and drops of promoted temps.
1072 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1073 for block in body.basic_blocks_mut() {
1074 block.statements.retain(|statement| match &statement.kind {
1075 StatementKind::Assign(box (place, _)) => {
1076 if let Some(index) = place.as_local() {
1082 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1087 let terminator = block.terminator_mut();
1088 match &terminator.kind {
1089 TerminatorKind::Drop { location: place, target, .. } => {
1090 if let Some(index) = place.as_local() {
1091 if promoted(index) {
1092 terminator.kind = TerminatorKind::Goto { target: *target };
1103 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1104 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1105 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1107 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1110 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1111 operand: &Operand<'tcx>,
1113 let mut rpo = traversal::reverse_postorder(&body);
1114 let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
1116 Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
1118 let should_promote = validator.validate_operand(operand).is_ok();
1119 let feature_flag = tcx.features().const_in_array_repeat_expressions;
1121 "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1122 should_promote={:?} feature_flag={:?}",
1123 mir_def_id, should_promote, feature_flag
1125 should_promote && !feature_flag