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.
16 use rustc::mir::visit::{PlaceContext, MutatingUseContext, MutVisitor, Visitor};
17 use rustc::mir::traversal::ReversePostorder;
18 use rustc::ty::TyCtxt;
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
23 use std::{iter, mem, usize};
25 /// State of a temporary during collection and promotion.
26 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
28 /// No references to this temp.
30 /// One direct assignment and any number of direct uses.
31 /// A borrow of this temp is promotable if the assigned
32 /// value is qualified as constant.
37 /// Any other combination of assignments/uses.
39 /// This temp was part of an rvalue which got extracted
40 /// during promotion and needs cleanup.
45 pub fn is_promotable(&self) -> bool {
46 debug!("is_promotable: self={:?}", self);
47 if let TempState::Defined { .. } = *self {
55 /// A "root candidate" for promotion, which will become the
56 /// returned value in a promoted MIR, unless it's a subset
57 /// of a larger candidate.
60 /// Borrow of a constant temporary.
63 /// Promotion of the `x` in `[x; 32]`.
66 /// Currently applied to function calls where the callee has the unstable
67 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
68 /// intrinsic. The intrinsic requires the arguments are indeed constant and
69 /// the attribute currently provides the semantic requirement that arguments
71 Argument { bb: BasicBlock, index: usize },
74 struct TempCollector<'tcx> {
75 temps: IndexVec<Local, TempState>,
77 body: &'tcx Body<'tcx>,
80 impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
81 fn visit_local(&mut self,
83 context: PlaceContext,
85 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
86 // We're only interested in temporaries and the return place
87 match self.body.local_kind(index) {
89 | LocalKind::ReturnPointer
96 // Ignore drops, if the temp gets promoted,
97 // then it's constant and thus drop is noop.
98 // Non-uses are also irrelevent.
99 if context.is_drop() || !context.is_use() {
101 "visit_local: context.is_drop={:?} context.is_use={:?}",
102 context.is_drop(), context.is_use(),
107 let temp = &mut self.temps[index];
108 debug!("visit_local: temp={:?}", temp);
109 if *temp == TempState::Undefined {
111 PlaceContext::MutatingUse(MutatingUseContext::Store) |
112 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
113 *temp = TempState::Defined {
119 _ => { /* mark as unpromotable below */ }
121 } else if let TempState::Defined { ref mut uses, .. } = *temp {
122 // We always allow borrows, even mutable ones, as we need
123 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
124 let allowed_use = context.is_borrow() || context.is_nonmutating_use();
125 debug!("visit_local: allowed_use={:?}", allowed_use);
130 /* mark as unpromotable below */
132 *temp = TempState::Unpromotable;
135 fn visit_source_info(&mut self, source_info: &SourceInfo) {
136 self.span = source_info.span;
140 pub fn collect_temps(body: &Body<'_>,
141 rpo: &mut ReversePostorder<'_, '_>) -> IndexVec<Local, TempState> {
142 let mut collector = TempCollector {
143 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
147 for (bb, data) in rpo {
148 collector.visit_basic_block_data(bb, data);
153 struct Promoter<'a, 'tcx> {
155 source: &'a mut Body<'tcx>,
156 promoted: Body<'tcx>,
157 temps: &'a mut IndexVec<Local, TempState>,
159 /// If true, all nested temps are also kept in the
160 /// source MIR, not moved to the promoted MIR.
164 impl<'a, 'tcx> Promoter<'a, 'tcx> {
165 fn new_block(&mut self) -> BasicBlock {
166 let span = self.promoted.span;
167 self.promoted.basic_blocks_mut().push(BasicBlockData {
169 terminator: Some(Terminator {
170 source_info: SourceInfo {
172 scope: OUTERMOST_SOURCE_SCOPE
174 kind: TerminatorKind::Return
180 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
181 let last = self.promoted.basic_blocks().last().unwrap();
182 let data = &mut self.promoted[last];
183 data.statements.push(Statement {
184 source_info: SourceInfo {
186 scope: OUTERMOST_SOURCE_SCOPE
188 kind: StatementKind::Assign(Place::from(dest), box rvalue)
192 /// Copies the initialization of this temp to the
193 /// promoted MIR, recursing through temps.
194 fn promote_temp(&mut self, temp: Local) -> Local {
195 let old_keep_original = self.keep_original;
196 let loc = match self.temps[temp] {
197 TempState::Defined { location, uses } if uses > 0 => {
199 self.keep_original = true;
204 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
208 if !self.keep_original {
209 self.temps[temp] = TempState::PromotedOut;
212 let no_stmts = self.source[loc.block].statements.len();
213 let new_temp = self.promoted.local_decls.push(
214 LocalDecl::new_temp(self.source.local_decls[temp].ty,
215 self.source.local_decls[temp].source_info.span));
217 debug!("promote({:?} @ {:?}/{:?}, {:?})",
218 temp, loc, no_stmts, self.keep_original);
220 // First, take the Rvalue or Call out of the source MIR,
221 // or duplicate it, depending on keep_original.
222 if loc.statement_index < no_stmts {
223 let (rvalue, source_info) = {
224 let statement = &mut self.source[loc.block].statements[loc.statement_index];
225 let rhs = match statement.kind {
226 StatementKind::Assign(_, ref mut rhs) => rhs,
228 span_bug!(statement.source_info.span, "{:?} is not an assignment",
233 (if self.keep_original {
236 let unit = box Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
237 mem::replace(rhs, unit)
238 }, statement.source_info)
241 let mut rvalue = *rvalue;
242 self.visit_rvalue(&mut rvalue, loc);
243 self.assign(new_temp, rvalue, source_info.span);
245 let terminator = if self.keep_original {
246 self.source[loc.block].terminator().clone()
248 let terminator = self.source[loc.block].terminator_mut();
249 let target = match terminator.kind {
250 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
252 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
256 source_info: terminator.source_info,
257 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
263 match terminator.kind {
264 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
265 self.visit_operand(&mut func, loc);
266 for arg in &mut args {
267 self.visit_operand(arg, loc);
270 let last = self.promoted.basic_blocks().last().unwrap();
271 let new_target = self.new_block();
273 *self.promoted[last].terminator_mut() = Terminator {
274 kind: TerminatorKind::Call {
279 (Place::from(new_temp), new_target)
287 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
292 self.keep_original = old_keep_original;
296 fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Option<Body<'tcx>> {
298 let promoted = &mut self.promoted;
299 let promoted_id = Promoted::new(next_promoted_id);
300 let mut promoted_place = |ty, span| {
301 promoted.span = span;
302 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
304 base: PlaceBase::Static(box Static {
305 kind: StaticKind::Promoted(promoted_id),
311 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
313 Candidate::Ref(loc) => {
314 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
315 match statement.kind {
316 StatementKind::Assign(_, box Rvalue::Ref(_, _, ref mut place)) => {
317 // Use the underlying local for this (necessarily interior) borrow.
318 let ty = place.base.ty(local_decls).ty;
319 let span = statement.source_info.span;
321 Operand::Move(Place {
322 base: mem::replace(&mut place.base, promoted_place(ty, span).base),
329 Candidate::Repeat(loc) => {
330 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
331 match statement.kind {
332 StatementKind::Assign(_, box Rvalue::Repeat(ref mut operand, _)) => {
333 let ty = operand.ty(local_decls, self.tcx);
334 let span = statement.source_info.span;
335 mem::replace(operand, Operand::Copy(promoted_place(ty, span)))
340 Candidate::Argument { bb, index } => {
341 let terminator = blocks[bb].terminator_mut();
342 match terminator.kind {
343 TerminatorKind::Call { ref mut args, .. } => {
344 let ty = args[index].ty(local_decls, self.tcx);
345 let span = terminator.source_info.span;
346 let operand = Operand::Copy(promoted_place(ty, span));
347 mem::replace(&mut args[index], operand)
349 // We expected a `TerminatorKind::Call` for which we'd like to promote an
350 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
351 // we are seeing a `Goto`. That means that the `promote_temps` method
352 // already promoted this call away entirely. This case occurs when calling
353 // a function requiring a constant argument and as that constant value
354 // providing a value whose computation contains another call to a function
355 // requiring a constant argument.
356 TerminatorKind::Goto { .. } => return None,
363 assert_eq!(self.new_block(), START_BLOCK);
364 self.visit_operand(&mut operand, Location {
365 block: BasicBlock::new(0),
366 statement_index: usize::MAX
369 let span = self.promoted.span;
370 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
375 /// Replaces all temporaries with their promoted counterparts.
376 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
377 fn visit_local(&mut self,
381 if self.source.local_kind(*local) == LocalKind::Temp {
382 *local = self.promote_temp(*local);
387 pub fn promote_candidates<'tcx>(
388 body: &mut Body<'tcx>,
390 mut temps: IndexVec<Local, TempState>,
391 candidates: Vec<Candidate>,
392 ) -> IndexVec<Promoted, Body<'tcx>> {
393 // Visit candidates in reverse, in case they're nested.
394 debug!("promote_candidates({:?})", candidates);
396 let mut promotions = IndexVec::new();
398 for candidate in candidates.into_iter().rev() {
400 Candidate::Repeat(Location { block, statement_index }) |
401 Candidate::Ref(Location { block, statement_index }) => {
402 match body[block].statements[statement_index].kind {
403 StatementKind::Assign(Place {
404 base: PlaceBase::Local(local),
407 if temps[local] == TempState::PromotedOut {
415 Candidate::Argument { .. } => {}
419 // Declare return place local so that `mir::Body::new` doesn't complain.
420 let initial_locals = iter::once(
421 LocalDecl::new_return_place(tcx.types.never, body.span)
424 let promoter = Promoter {
427 // FIXME: maybe try to filter this to avoid blowing up
429 body.source_scopes.clone(),
430 body.source_scope_local_data.clone(),
445 if let Some(promoted) = promoter.promote_candidate(candidate, promotions.len()) {
446 promotions.push(promoted);
450 // Eliminate assignments to, and drops of promoted temps.
451 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
452 for block in body.basic_blocks_mut() {
453 block.statements.retain(|statement| {
454 match statement.kind {
455 StatementKind::Assign(Place {
456 base: PlaceBase::Local(index),
459 StatementKind::StorageLive(index) |
460 StatementKind::StorageDead(index) => {
466 let terminator = block.terminator_mut();
467 match terminator.kind {
468 TerminatorKind::Drop { location: Place {
469 base: PlaceBase::Local(index),
473 terminator.kind = TerminatorKind::Goto {