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_ast::ast::LitKind;
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::mir::traversal::ReversePostorder;
19 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
20 use rustc_middle::mir::*;
21 use rustc_middle::ty::cast::CastTy;
22 use rustc_middle::ty::subst::InternalSubsts;
23 use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable};
24 use rustc_span::symbol::sym;
25 use rustc_span::{Span, DUMMY_SP};
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_target::spec::abi::Abi;
31 use std::{cmp, iter, mem};
33 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
34 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx};
35 use crate::transform::{MirPass, MirSource};
37 /// A `MirPass` for promotion.
39 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
40 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
42 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
43 /// newly created `Constant`.
45 pub struct PromoteTemps<'tcx> {
46 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
49 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
50 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
51 // There's not really any point in promoting errorful MIR.
53 // This does not include MIR that failed const-checking, which we still try to promote.
54 if body.return_ty().references_error() {
55 tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
59 if src.promoted.is_some() {
63 let def = src.with_opt_param().expect_local();
65 let mut rpo = traversal::reverse_postorder(body);
66 let ccx = ConstCx::new(tcx, def.did, body);
67 let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
69 let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
71 let promoted = promote_candidates(def.to_global(), body, tcx, temps, promotable_candidates);
72 self.promoted_fragments.set(promoted);
76 /// State of a temporary during collection and promotion.
77 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
79 /// No references to this temp.
81 /// One direct assignment and any number of direct uses.
82 /// A borrow of this temp is promotable if the assigned
83 /// value is qualified as constant.
84 Defined { location: Location, uses: usize },
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 { true } else { false }
99 /// A "root candidate" for promotion, which will become the
100 /// returned value in a promoted MIR, unless it's a subset
101 /// of a larger candidate.
102 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
104 /// Borrow of a constant temporary.
107 /// Promotion of the `x` in `[x; 32]`.
110 /// Currently applied to function calls where the callee has the unstable
111 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
112 /// intrinsic. The intrinsic requires the arguments are indeed constant and
113 /// the attribute currently provides the semantic requirement that arguments
114 /// must be constant.
115 Argument { bb: BasicBlock, index: usize },
117 /// `const` operand in asm!.
118 InlineAsm { bb: BasicBlock, index: usize },
122 /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
123 fn forces_explicit_promotion(&self) -> bool {
125 Candidate::Ref(_) | Candidate::Repeat(_) => false,
126 Candidate::Argument { .. } | Candidate::InlineAsm { .. } => true,
131 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
132 let attrs = tcx.get_attrs(def_id);
133 let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
134 let mut ret = vec![];
135 for meta in attr.meta_item_list()? {
136 match meta.literal()?.kind {
137 LitKind::Int(a, _) => {
138 ret.push(a as usize);
146 struct Collector<'a, 'tcx> {
147 ccx: &'a ConstCx<'a, 'tcx>,
148 temps: IndexVec<Local, TempState>,
149 candidates: Vec<Candidate>,
152 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
153 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
154 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
155 // We're only interested in temporaries and the return place
156 match self.ccx.body.local_kind(index) {
157 LocalKind::Temp | LocalKind::ReturnPointer => {}
158 LocalKind::Arg | LocalKind::Var => return,
161 // Ignore drops, if the temp gets promoted,
162 // then it's constant and thus drop is noop.
163 // Non-uses are also irrelevant.
164 if context.is_drop() || !context.is_use() {
166 "visit_local: context.is_drop={:?} context.is_use={:?}",
173 let temp = &mut self.temps[index];
174 debug!("visit_local: temp={:?}", temp);
175 if *temp == TempState::Undefined {
177 PlaceContext::MutatingUse(MutatingUseContext::Store)
178 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
179 *temp = TempState::Defined { location, uses: 0 };
182 _ => { /* mark as unpromotable below */ }
184 } else if let TempState::Defined { ref mut uses, .. } = *temp {
185 // We always allow borrows, even mutable ones, as we need
186 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
187 let allowed_use = match context {
188 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
189 | PlaceContext::NonMutatingUse(_) => true,
190 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
192 debug!("visit_local: allowed_use={:?}", allowed_use);
197 /* mark as unpromotable below */
199 *temp = TempState::Unpromotable;
202 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
203 self.super_rvalue(rvalue, location);
207 self.candidates.push(Candidate::Ref(location));
209 Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => {
210 // FIXME(#49147) only promote the element when it isn't `Copy`
211 // (so that code that can copy it at runtime is unaffected).
212 self.candidates.push(Candidate::Repeat(location));
218 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
219 self.super_terminator(terminator, location);
221 match terminator.kind {
222 TerminatorKind::Call { ref func, .. } => {
223 if let ty::FnDef(def_id, _) = func.ty(self.ccx.body, self.ccx.tcx).kind {
224 let fn_sig = self.ccx.tcx.fn_sig(def_id);
225 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
226 let name = self.ccx.tcx.item_name(def_id);
227 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
228 if name.as_str().starts_with("simd_shuffle") {
230 .push(Candidate::Argument { bb: location.block, index: 2 });
232 return; // Don't double count `simd_shuffle` candidates
236 if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) {
237 for index in constant_args {
238 self.candidates.push(Candidate::Argument { bb: location.block, index });
243 TerminatorKind::InlineAsm { ref operands, .. } => {
244 for (index, op) in operands.iter().enumerate() {
246 InlineAsmOperand::Const { .. } => {
247 self.candidates.push(Candidate::InlineAsm { bb: location.block, index })
258 pub fn collect_temps_and_candidates(
259 ccx: &ConstCx<'mir, 'tcx>,
260 rpo: &mut ReversePostorder<'_, 'tcx>,
261 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
262 let mut collector = Collector {
263 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
267 for (bb, data) in rpo {
268 collector.visit_basic_block_data(bb, data);
270 (collector.temps, collector.candidates)
273 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
275 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
276 struct Validator<'a, 'tcx> {
277 ccx: &'a ConstCx<'a, 'tcx>,
278 temps: &'a IndexVec<Local, TempState>,
280 /// Explicit promotion happens e.g. for constant arguments declared via
281 /// `rustc_args_required_const`.
282 /// Implicit promotion has almost the same rules, except that disallows `const fn`
283 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
284 /// a legitimate run-time operation into a failing compile-time operation
285 /// e.g. due to addresses being compared inside the function.
289 impl std::ops::Deref for Validator<'a, 'tcx> {
290 type Target = ConstCx<'a, 'tcx>;
292 fn deref(&self) -> &Self::Target {
299 impl<'tcx> Validator<'_, 'tcx> {
300 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
302 Candidate::Ref(loc) => {
303 assert!(!self.explicit);
305 let statement = &self.body[loc.block].statements[loc.statement_index];
306 match &statement.kind {
307 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
309 BorrowKind::Shared | BorrowKind::Mut { .. } => {}
311 // FIXME(eddyb) these aren't promoted here but *could*
312 // be promoted as part of a larger value because
313 // `validate_rvalue` doesn't check them, need to
314 // figure out what is the intended behavior.
315 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
318 // We can only promote interior borrows of promotable temps (non-temps
319 // don't get promoted anyway).
320 self.validate_local(place.local)?;
322 if place.projection.contains(&ProjectionElem::Deref) {
323 return Err(Unpromotable);
326 let mut has_mut_interior =
327 self.qualif_local::<qualifs::HasMutInterior>(place.local);
328 // HACK(eddyb) this should compute the same thing as
329 // `<HasMutInterior as Qualif>::in_projection` from
330 // `check_consts::qualifs` but without recursion.
331 if has_mut_interior {
332 // This allows borrowing fields which don't have
333 // `HasMutInterior`, from a type that does, e.g.:
334 // `let _: &'static _ = &(Cell::new(1), 2).1;`
335 let mut place_projection = &place.projection[..];
336 // FIXME(eddyb) use a forward loop instead of a reverse one.
337 while let &[ref proj_base @ .., elem] = place_projection {
338 // FIXME(eddyb) this is probably excessive, with
339 // the exception of `union` member accesses.
341 Place::ty_from(place.local, proj_base, self.body, self.tcx)
342 .projection_ty(self.tcx, elem)
344 if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
345 has_mut_interior = false;
349 place_projection = proj_base;
353 // FIXME(eddyb) this duplicates part of `validate_rvalue`.
354 if has_mut_interior {
355 return Err(Unpromotable);
357 if self.qualif_local::<qualifs::NeedsDrop>(place.local) {
358 return Err(Unpromotable);
361 if let BorrowKind::Mut { .. } = kind {
362 let ty = place.ty(self.body, self.tcx).ty;
364 // In theory, any zero-sized value could be borrowed
365 // mutably without consequences. However, only &mut []
366 // is allowed right now, and only in functions.
368 == Some(hir::ConstContext::Static(hir::Mutability::Mut))
370 // Inside a `static mut`, &mut [...] is also allowed.
372 ty::Array(..) | ty::Slice(_) => {}
373 _ => return Err(Unpromotable),
375 } else if let ty::Array(_, len) = ty.kind {
376 // FIXME(eddyb) the `self.is_non_const_fn` condition
377 // seems unnecessary, given that this is merely a ZST.
378 match len.try_eval_usize(self.tcx, self.param_env) {
379 Some(0) if self.const_kind.is_none() => {}
380 _ => return Err(Unpromotable),
383 return Err(Unpromotable);
392 Candidate::Repeat(loc) => {
393 assert!(!self.explicit);
395 let statement = &self.body[loc.block].statements[loc.statement_index];
396 match &statement.kind {
397 StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
398 if !self.tcx.features().const_in_array_repeat_expressions {
399 return Err(Unpromotable);
402 self.validate_operand(operand)
407 Candidate::Argument { bb, index } => {
408 assert!(self.explicit);
410 let terminator = self.body[bb].terminator();
411 match &terminator.kind {
412 TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
416 Candidate::InlineAsm { bb, index } => {
417 assert!(self.explicit);
419 let terminator = self.body[bb].terminator();
420 match &terminator.kind {
421 TerminatorKind::InlineAsm { operands, .. } => match &operands[index] {
422 InlineAsmOperand::Const { value } => self.validate_operand(value),
431 // FIXME(eddyb) maybe cache this?
432 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
433 if let TempState::Defined { location: loc, .. } = self.temps[local] {
434 let num_stmts = self.body[loc.block].statements.len();
436 if loc.statement_index < num_stmts {
437 let statement = &self.body[loc.block].statements[loc.statement_index];
438 match &statement.kind {
439 StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
441 &mut |l| self.qualif_local::<Q>(l),
446 statement.source_info.span,
447 "{:?} is not an assignment",
453 let terminator = self.body[loc.block].terminator();
454 match &terminator.kind {
455 TerminatorKind::Call { .. } => {
456 let return_ty = self.body.local_decls[local].ty;
457 Q::in_any_value_of_ty(&self.ccx, return_ty)
460 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
465 let span = self.body.local_decls[local].source_info.span;
466 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
470 // FIXME(eddyb) maybe cache this?
471 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
472 if let TempState::Defined { location: loc, .. } = self.temps[local] {
473 let num_stmts = self.body[loc.block].statements.len();
475 if loc.statement_index < num_stmts {
476 let statement = &self.body[loc.block].statements[loc.statement_index];
477 match &statement.kind {
478 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
481 statement.source_info.span,
482 "{:?} is not an assignment",
488 let terminator = self.body[loc.block].terminator();
489 match &terminator.kind {
490 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
491 TerminatorKind::Yield { .. } => Err(Unpromotable),
493 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
502 fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
504 PlaceRef { local, projection: [] } => self.validate_local(local),
505 PlaceRef { local, projection: [proj_base @ .., elem] } => {
507 ProjectionElem::Deref => {
508 let mut not_promotable = true;
509 // This is a special treatment for cases like *&STATIC where STATIC is a
510 // global static variable.
511 // This pattern is generated only when global static variables are directly
512 // accessed and is qualified for promotion safely.
513 if let TempState::Defined { location, .. } = self.temps[local] {
515 self.body[location.block].statements.get(location.statement_index);
516 if let Some(Statement {
518 StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(c)))),
522 if let Some(did) = c.check_static_ptr(self.tcx) {
523 if let Some(hir::ConstContext::Static(..)) = self.const_kind {
524 // The `is_empty` predicate is introduced to exclude the case
525 // where the projection operations are [ .field, * ].
526 // The reason is because promotion will be illegal if field
527 // accesses precede the dereferencing.
528 // Discussion can be found at
529 // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
530 // There may be opportunity for generalization, but this needs to be
532 if proj_base.is_empty()
533 && !self.tcx.is_thread_local_static(did)
535 not_promotable = false;
542 return Err(Unpromotable);
545 ProjectionElem::Downcast(..) => {
546 return Err(Unpromotable);
549 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
551 ProjectionElem::Index(local) => {
552 self.validate_local(local)?;
555 ProjectionElem::Field(..) => {
556 if self.const_kind.is_none() {
558 Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
559 if let Some(def) = base_ty.ty_adt_def() {
560 // No promotion of union field accesses.
562 return Err(Unpromotable);
569 self.validate_place(PlaceRef { local: place.local, projection: proj_base })
574 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
576 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
578 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
579 // `validate_rvalue` upon access.
580 Operand::Constant(c) => {
581 if let Some(def_id) = c.check_static_ptr(self.tcx) {
582 // Only allow statics (not consts) to refer to other statics.
583 // FIXME(eddyb) does this matter at all for promotion?
584 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
586 return Err(Unpromotable);
589 let is_thread_local = self.tcx.is_thread_local_static(def_id);
591 return Err(Unpromotable);
600 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
602 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
603 let operand_ty = operand.ty(self.body, self.tcx);
604 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
605 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
606 match (cast_in, cast_out) {
607 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
608 // in normal functions, mark such casts as not promotable
609 return Err(Unpromotable);
615 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
616 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
624 || op == BinOp::Offset
627 // raw pointer operations are not allowed inside promoteds
628 return Err(Unpromotable);
632 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
638 Rvalue::ThreadLocalRef(_) => Err(Unpromotable),
640 Rvalue::NullaryOp(..) => Ok(()),
642 Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
645 | Rvalue::Repeat(operand, _)
646 | Rvalue::UnaryOp(_, operand)
647 | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
649 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
650 self.validate_operand(lhs)?;
651 self.validate_operand(rhs)
654 Rvalue::AddressOf(_, place) => {
655 // Raw reborrows can come from reference to pointer coercions,
657 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
658 let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
659 if let ty::Ref(..) = base_ty.kind {
660 return self.validate_place(PlaceRef {
662 projection: proj_base,
669 Rvalue::Ref(_, kind, place) => {
670 if let BorrowKind::Mut { .. } = kind {
671 let ty = place.ty(self.body, self.tcx).ty;
673 // In theory, any zero-sized value could be borrowed
674 // mutably without consequences. However, only &mut []
675 // is allowed right now, and only in functions.
676 if self.const_kind == Some(hir::ConstContext::Static(hir::Mutability::Mut)) {
677 // Inside a `static mut`, &mut [...] is also allowed.
679 ty::Array(..) | ty::Slice(_) => {}
680 _ => return Err(Unpromotable),
682 } else if let ty::Array(_, len) = ty.kind {
683 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
684 // const context which seems unnecessary given that this is merely a ZST.
685 match len.try_eval_usize(self.tcx, self.param_env) {
686 Some(0) if self.const_kind.is_none() => {}
687 _ => return Err(Unpromotable),
690 return Err(Unpromotable);
694 // Special-case reborrows to be more like a copy of the reference.
695 let mut place = place.as_ref();
696 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
697 let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
698 if let ty::Ref(..) = base_ty.kind {
699 place = PlaceRef { local: place.local, projection: proj_base };
703 self.validate_place(place)?;
705 // HACK(eddyb) this should compute the same thing as
706 // `<HasMutInterior as Qualif>::in_projection` from
707 // `check_consts::qualifs` but without recursion.
708 let mut has_mut_interior =
709 self.qualif_local::<qualifs::HasMutInterior>(place.local);
710 if has_mut_interior {
711 let mut place_projection = place.projection;
712 // FIXME(eddyb) use a forward loop instead of a reverse one.
713 while let &[ref proj_base @ .., elem] = place_projection {
714 // FIXME(eddyb) this is probably excessive, with
715 // the exception of `union` member accesses.
716 let ty = Place::ty_from(place.local, proj_base, self.body, self.tcx)
717 .projection_ty(self.tcx, elem)
719 if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
720 has_mut_interior = false;
724 place_projection = proj_base;
727 if has_mut_interior {
728 return Err(Unpromotable);
734 Rvalue::Aggregate(_, ref operands) => {
736 self.validate_operand(o)?;
746 callee: &Operand<'tcx>,
747 args: &[Operand<'tcx>],
748 ) -> Result<(), Unpromotable> {
749 let fn_ty = callee.ty(self.body, self.tcx);
751 if !self.explicit && self.const_kind.is_none() {
752 if let ty::FnDef(def_id, _) = fn_ty.kind {
753 // Never promote runtime `const fn` calls of
754 // functions without `#[rustc_promotable]`.
755 if !self.tcx.is_promotable_const_fn(def_id) {
756 return Err(Unpromotable);
761 let is_const_fn = match fn_ty.kind {
762 ty::FnDef(def_id, _) => {
763 is_const_fn(self.tcx, def_id)
764 || is_unstable_const_fn(self.tcx, def_id).is_some()
765 || is_lang_panic_fn(self.tcx, self.def_id.to_def_id())
770 return Err(Unpromotable);
773 self.validate_operand(callee)?;
775 self.validate_operand(arg)?;
782 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
783 pub fn validate_candidates(
784 ccx: &ConstCx<'_, '_>,
785 temps: &IndexVec<Local, TempState>,
786 candidates: &[Candidate],
787 ) -> Vec<Candidate> {
788 let mut validator = Validator { ccx, temps, explicit: false };
793 .filter(|&candidate| {
794 validator.explicit = candidate.forces_explicit_promotion();
796 // FIXME(eddyb) also emit the errors for shuffle indices
797 // and `#[rustc_args_required_const]` arguments here.
799 let is_promotable = validator.validate_candidate(candidate).is_ok();
801 // If we use explicit validation, we carry the risk of turning a legitimate run-time
802 // operation into a failing compile-time operation. Make sure that does not happen
803 // by asserting that there is no possible run-time behavior here in case promotion
805 if validator.explicit && !is_promotable {
806 ccx.tcx.sess.delay_span_bug(
808 "Explicit promotion requested, but failed to promote",
813 Candidate::Argument { bb, index } | Candidate::InlineAsm { bb, index }
816 let span = ccx.body[bb].terminator().source_info.span;
817 let msg = format!("argument {} is required to be a constant", index + 1);
818 ccx.tcx.sess.span_err(span, &msg);
828 struct Promoter<'a, 'tcx> {
830 source: &'a mut Body<'tcx>,
831 promoted: Body<'tcx>,
832 temps: &'a mut IndexVec<Local, TempState>,
833 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
835 /// If true, all nested temps are also kept in the
836 /// source MIR, not moved to the promoted MIR.
840 impl<'a, 'tcx> Promoter<'a, 'tcx> {
841 fn new_block(&mut self) -> BasicBlock {
842 let span = self.promoted.span;
843 self.promoted.basic_blocks_mut().push(BasicBlockData {
845 terminator: Some(Terminator {
846 source_info: SourceInfo::outermost(span),
847 kind: TerminatorKind::Return,
853 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
854 let last = self.promoted.basic_blocks().last().unwrap();
855 let data = &mut self.promoted[last];
856 data.statements.push(Statement {
857 source_info: SourceInfo::outermost(span),
858 kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
862 fn is_temp_kind(&self, local: Local) -> bool {
863 self.source.local_kind(local) == LocalKind::Temp
866 /// Copies the initialization of this temp to the
867 /// promoted MIR, recursing through temps.
868 fn promote_temp(&mut self, temp: Local) -> Local {
869 let old_keep_original = self.keep_original;
870 let loc = match self.temps[temp] {
871 TempState::Defined { location, uses } if uses > 0 => {
873 self.keep_original = true;
878 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
881 if !self.keep_original {
882 self.temps[temp] = TempState::PromotedOut;
885 let num_stmts = self.source[loc.block].statements.len();
886 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
887 self.source.local_decls[temp].ty,
888 self.source.local_decls[temp].source_info.span,
891 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
893 // First, take the Rvalue or Call out of the source MIR,
894 // or duplicate it, depending on keep_original.
895 if loc.statement_index < num_stmts {
896 let (mut rvalue, source_info) = {
897 let statement = &mut self.source[loc.block].statements[loc.statement_index];
898 let rhs = match statement.kind {
899 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
902 statement.source_info.span,
903 "{:?} is not an assignment",
910 if self.keep_original {
913 let unit = Rvalue::Use(Operand::Constant(box Constant {
914 span: statement.source_info.span,
916 literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit),
918 mem::replace(rhs, unit)
920 statement.source_info,
924 self.visit_rvalue(&mut rvalue, loc);
925 self.assign(new_temp, rvalue, source_info.span);
927 let terminator = if self.keep_original {
928 self.source[loc.block].terminator().clone()
930 let terminator = self.source[loc.block].terminator_mut();
931 let target = match terminator.kind {
932 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
934 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
938 source_info: terminator.source_info,
939 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
943 match terminator.kind {
944 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
945 self.visit_operand(&mut func, loc);
946 for arg in &mut args {
947 self.visit_operand(arg, loc);
950 let last = self.promoted.basic_blocks().last().unwrap();
951 let new_target = self.new_block();
953 *self.promoted[last].terminator_mut() = Terminator {
954 kind: TerminatorKind::Call {
958 destination: Some((Place::from(new_temp), new_target)),
966 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
971 self.keep_original = old_keep_original;
975 fn promote_candidate(
977 def: ty::WithOptConstParam<DefId>,
978 candidate: Candidate,
979 next_promoted_id: usize,
980 ) -> Option<Body<'tcx>> {
982 let promoted = &mut self.promoted;
983 let promoted_id = Promoted::new(next_promoted_id);
985 let mut promoted_operand = |ty, span| {
986 promoted.span = span;
987 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
989 Operand::Constant(Box::new(Constant {
992 literal: tcx.mk_const(ty::Const {
994 val: ty::ConstKind::Unevaluated(
996 InternalSubsts::for_item(tcx, def.did, |param, _| {
997 if let ty::GenericParamDefKind::Lifetime = param.kind {
998 tcx.lifetimes.re_erased.into()
1000 tcx.mk_param_from_def(param)
1008 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
1010 Candidate::Ref(loc) => {
1011 let statement = &mut blocks[loc.block].statements[loc.statement_index];
1012 match statement.kind {
1013 StatementKind::Assign(box (
1015 Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
1017 // Use the underlying local for this (necessarily interior) borrow.
1018 let ty = local_decls.local_decls()[place.local].ty;
1019 let span = statement.source_info.span;
1021 let ref_ty = tcx.mk_ref(
1022 tcx.lifetimes.re_erased,
1023 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
1026 *region = tcx.lifetimes.re_erased;
1028 let mut projection = vec![PlaceElem::Deref];
1029 projection.extend(place.projection);
1030 place.projection = tcx.intern_place_elems(&projection);
1032 // Create a temp to hold the promoted reference.
1033 // This is because `*r` requires `r` to be a local,
1034 // otherwise we would use the `promoted` directly.
1035 let mut promoted_ref = LocalDecl::new(ref_ty, span);
1036 promoted_ref.source_info = statement.source_info;
1037 let promoted_ref = local_decls.push(promoted_ref);
1038 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
1040 let promoted_ref_statement = Statement {
1041 source_info: statement.source_info,
1042 kind: StatementKind::Assign(Box::new((
1043 Place::from(promoted_ref),
1044 Rvalue::Use(promoted_operand(ref_ty, span)),
1047 self.extra_statements.push((loc, promoted_ref_statement));
1050 tcx.lifetimes.re_erased,
1053 local: mem::replace(&mut place.local, promoted_ref),
1054 projection: List::empty(),
1061 Candidate::Repeat(loc) => {
1062 let statement = &mut blocks[loc.block].statements[loc.statement_index];
1063 match statement.kind {
1064 StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
1065 let ty = operand.ty(local_decls, self.tcx);
1066 let span = statement.source_info.span;
1068 Rvalue::Use(mem::replace(operand, promoted_operand(ty, span)))
1073 Candidate::Argument { bb, index } => {
1074 let terminator = blocks[bb].terminator_mut();
1075 match terminator.kind {
1076 TerminatorKind::Call { ref mut args, .. } => {
1077 let ty = args[index].ty(local_decls, self.tcx);
1078 let span = terminator.source_info.span;
1080 Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
1082 // We expected a `TerminatorKind::Call` for which we'd like to promote an
1083 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1084 // we are seeing a `Goto`. That means that the `promote_temps` method
1085 // already promoted this call away entirely. This case occurs when calling
1086 // a function requiring a constant argument and as that constant value
1087 // providing a value whose computation contains another call to a function
1088 // requiring a constant argument.
1089 TerminatorKind::Goto { .. } => return None,
1093 Candidate::InlineAsm { bb, index } => {
1094 let terminator = blocks[bb].terminator_mut();
1095 match terminator.kind {
1096 TerminatorKind::InlineAsm { ref mut operands, .. } => {
1097 match &mut operands[index] {
1098 InlineAsmOperand::Const { ref mut value } => {
1099 let ty = value.ty(local_decls, self.tcx);
1100 let span = terminator.source_info.span;
1102 Rvalue::Use(mem::replace(value, promoted_operand(ty, span)))
1114 assert_eq!(self.new_block(), START_BLOCK);
1117 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
1120 let span = self.promoted.span;
1121 self.assign(RETURN_PLACE, rvalue, span);
1126 /// Replaces all temporaries with their promoted counterparts.
1127 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1128 fn tcx(&self) -> TyCtxt<'tcx> {
1132 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
1133 if self.is_temp_kind(*local) {
1134 *local = self.promote_temp(*local);
1139 pub fn promote_candidates<'tcx>(
1140 def: ty::WithOptConstParam<DefId>,
1141 body: &mut Body<'tcx>,
1143 mut temps: IndexVec<Local, TempState>,
1144 candidates: Vec<Candidate>,
1145 ) -> IndexVec<Promoted, Body<'tcx>> {
1146 // Visit candidates in reverse, in case they're nested.
1147 debug!("promote_candidates({:?})", candidates);
1149 let mut promotions = IndexVec::new();
1151 let mut extra_statements = vec![];
1152 for candidate in candidates.into_iter().rev() {
1154 Candidate::Repeat(Location { block, statement_index })
1155 | Candidate::Ref(Location { block, statement_index }) => {
1156 if let StatementKind::Assign(box (place, _)) =
1157 &body[block].statements[statement_index].kind
1159 if let Some(local) = place.as_local() {
1160 if temps[local] == TempState::PromotedOut {
1161 // Already promoted.
1167 Candidate::Argument { .. } | Candidate::InlineAsm { .. } => {}
1170 // Declare return place local so that `mir::Body::new` doesn't complain.
1171 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1173 let mut promoted = Body::new(
1175 // FIXME: maybe try to filter this to avoid blowing up
1177 body.source_scopes.clone(),
1183 body.generator_kind,
1185 promoted.ignore_interior_mut_in_const_validation = true;
1187 let promoter = Promoter {
1192 extra_statements: &mut extra_statements,
1193 keep_original: false,
1196 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1197 if let Some(promoted) = promoter.promote_candidate(def, candidate, promotions.len()) {
1198 promotions.push(promoted);
1202 // Insert each of `extra_statements` before its indicated location, which
1203 // has to be done in reverse location order, to not invalidate the rest.
1204 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1205 for (loc, statement) in extra_statements {
1206 body[loc.block].statements.insert(loc.statement_index, statement);
1209 // Eliminate assignments to, and drops of promoted temps.
1210 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1211 for block in body.basic_blocks_mut() {
1212 block.statements.retain(|statement| match &statement.kind {
1213 StatementKind::Assign(box (place, _)) => {
1214 if let Some(index) = place.as_local() {
1220 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1225 let terminator = block.terminator_mut();
1226 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1227 if let Some(index) = place.as_local() {
1228 if promoted(index) {
1229 terminator.kind = TerminatorKind::Goto { target: *target };
1238 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1239 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1240 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1242 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1243 ccx: &ConstCx<'_, 'tcx>,
1244 operand: &Operand<'tcx>,
1246 let mut rpo = traversal::reverse_postorder(&ccx.body);
1247 let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo);
1248 let validator = Validator { ccx, temps: &temps, explicit: false };
1250 let should_promote = validator.validate_operand(operand).is_ok();
1251 let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions;
1253 "should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \
1254 should_promote={:?} feature_flag={:?}",
1255 validator.ccx.def_id, should_promote, feature_flag
1257 should_promote && !feature_flag