]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Auto merge of #64949 - nnethercote:avoid-SmallVec-collect, r=zackmdavis
[rust.git] / src / librustc_mir / transform / promote_consts.rs
1 //! A pass that promotes borrows of constant rvalues.
2 //!
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.
10 //!
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.
14
15 use rustc::hir::def_id::DefId;
16 use rustc::mir::*;
17 use rustc::mir::visit::{PlaceContext, MutatingUseContext, MutVisitor, Visitor};
18 use rustc::mir::traversal::ReversePostorder;
19 use rustc::ty::subst::InternalSubsts;
20 use rustc::ty::TyCtxt;
21 use syntax_pos::Span;
22
23 use rustc_index::vec::{IndexVec, Idx};
24
25 use std::{iter, mem, usize};
26
27 /// State of a temporary during collection and promotion.
28 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
29 pub enum TempState {
30     /// No references to this temp.
31     Undefined,
32     /// One direct assignment and any number of direct uses.
33     /// A borrow of this temp is promotable if the assigned
34     /// value is qualified as constant.
35     Defined {
36         location: Location,
37         uses: usize
38     },
39     /// Any other combination of assignments/uses.
40     Unpromotable,
41     /// This temp was part of an rvalue which got extracted
42     /// during promotion and needs cleanup.
43     PromotedOut
44 }
45
46 impl TempState {
47     pub fn is_promotable(&self) -> bool {
48         debug!("is_promotable: self={:?}", self);
49         if let TempState::Defined { .. } = *self {
50             true
51         } else {
52             false
53         }
54     }
55 }
56
57 /// A "root candidate" for promotion, which will become the
58 /// returned value in a promoted MIR, unless it's a subset
59 /// of a larger candidate.
60 #[derive(Debug)]
61 pub enum Candidate {
62     /// Borrow of a constant temporary.
63     Ref(Location),
64
65     /// Promotion of the `x` in `[x; 32]`.
66     Repeat(Location),
67
68     /// Currently applied to function calls where the callee has the unstable
69     /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
70     /// intrinsic. The intrinsic requires the arguments are indeed constant and
71     /// the attribute currently provides the semantic requirement that arguments
72     /// must be constant.
73     Argument { bb: BasicBlock, index: usize },
74 }
75
76 struct TempCollector<'tcx> {
77     temps: IndexVec<Local, TempState>,
78     span: Span,
79     body: &'tcx Body<'tcx>,
80 }
81
82 impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
83     fn visit_local(&mut self,
84                    &index: &Local,
85                    context: PlaceContext,
86                    location: Location) {
87         debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
88         // We're only interested in temporaries and the return place
89         match self.body.local_kind(index) {
90             | LocalKind::Temp
91             | LocalKind::ReturnPointer
92             => {},
93             | LocalKind::Arg
94             | LocalKind::Var
95             => return,
96         }
97
98         // Ignore drops, if the temp gets promoted,
99         // then it's constant and thus drop is noop.
100         // Non-uses are also irrelevent.
101         if context.is_drop() || !context.is_use() {
102             debug!(
103                 "visit_local: context.is_drop={:?} context.is_use={:?}",
104                 context.is_drop(), context.is_use(),
105             );
106             return;
107         }
108
109         let temp = &mut self.temps[index];
110         debug!("visit_local: temp={:?}", temp);
111         if *temp == TempState::Undefined {
112             match context {
113                 PlaceContext::MutatingUse(MutatingUseContext::Store) |
114                 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
115                     *temp = TempState::Defined {
116                         location,
117                         uses: 0
118                     };
119                     return;
120                 }
121                 _ => { /* mark as unpromotable below */ }
122             }
123         } else if let TempState::Defined { ref mut uses, .. } = *temp {
124             // We always allow borrows, even mutable ones, as we need
125             // to promote mutable borrows of some ZSTs e.g., `&mut []`.
126             let allowed_use = context.is_borrow() || context.is_nonmutating_use();
127             debug!("visit_local: allowed_use={:?}", allowed_use);
128             if allowed_use {
129                 *uses += 1;
130                 return;
131             }
132             /* mark as unpromotable below */
133         }
134         *temp = TempState::Unpromotable;
135     }
136
137     fn visit_source_info(&mut self, source_info: &SourceInfo) {
138         self.span = source_info.span;
139     }
140 }
141
142 pub fn collect_temps(body: &Body<'_>,
143                      rpo: &mut ReversePostorder<'_, '_>) -> IndexVec<Local, TempState> {
144     let mut collector = TempCollector {
145         temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
146         span: body.span,
147         body,
148     };
149     for (bb, data) in rpo {
150         collector.visit_basic_block_data(bb, data);
151     }
152     collector.temps
153 }
154
155 struct Promoter<'a, 'tcx> {
156     tcx: TyCtxt<'tcx>,
157     source: &'a mut Body<'tcx>,
158     promoted: Body<'tcx>,
159     temps: &'a mut IndexVec<Local, TempState>,
160
161     /// If true, all nested temps are also kept in the
162     /// source MIR, not moved to the promoted MIR.
163     keep_original: bool,
164 }
165
166 impl<'a, 'tcx> Promoter<'a, 'tcx> {
167     fn new_block(&mut self) -> BasicBlock {
168         let span = self.promoted.span;
169         self.promoted.basic_blocks_mut().push(BasicBlockData {
170             statements: vec![],
171             terminator: Some(Terminator {
172                 source_info: SourceInfo {
173                     span,
174                     scope: OUTERMOST_SOURCE_SCOPE
175                 },
176                 kind: TerminatorKind::Return
177             }),
178             is_cleanup: false
179         })
180     }
181
182     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
183         let last = self.promoted.basic_blocks().last().unwrap();
184         let data = &mut self.promoted[last];
185         data.statements.push(Statement {
186             source_info: SourceInfo {
187                 span,
188                 scope: OUTERMOST_SOURCE_SCOPE
189             },
190             kind: StatementKind::Assign(box(Place::from(dest), rvalue))
191         });
192     }
193
194     /// Copies the initialization of this temp to the
195     /// promoted MIR, recursing through temps.
196     fn promote_temp(&mut self, temp: Local) -> Local {
197         let old_keep_original = self.keep_original;
198         let loc = match self.temps[temp] {
199             TempState::Defined { location, uses } if uses > 0 => {
200                 if uses > 1 {
201                     self.keep_original = true;
202                 }
203                 location
204             }
205             state =>  {
206                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
207                           temp, state);
208             }
209         };
210         if !self.keep_original {
211             self.temps[temp] = TempState::PromotedOut;
212         }
213
214         let no_stmts = self.source[loc.block].statements.len();
215         let new_temp = self.promoted.local_decls.push(
216             LocalDecl::new_temp(self.source.local_decls[temp].ty,
217                                 self.source.local_decls[temp].source_info.span));
218
219         debug!("promote({:?} @ {:?}/{:?}, {:?})",
220                temp, loc, no_stmts, self.keep_original);
221
222         // First, take the Rvalue or Call out of the source MIR,
223         // or duplicate it, depending on keep_original.
224         if loc.statement_index < no_stmts {
225             let (mut rvalue, source_info) = {
226                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
227                 let rhs = match statement.kind {
228                     StatementKind::Assign(box(_, ref mut rhs)) => rhs,
229                     _ => {
230                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
231                                   statement);
232                     }
233                 };
234
235                 (if self.keep_original {
236                     rhs.clone()
237                 } else {
238                     let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
239                     mem::replace(rhs, unit)
240                 }, statement.source_info)
241             };
242
243             self.visit_rvalue(&mut rvalue, loc);
244             self.assign(new_temp, rvalue, source_info.span);
245         } else {
246             let terminator = if self.keep_original {
247                 self.source[loc.block].terminator().clone()
248             } else {
249                 let terminator = self.source[loc.block].terminator_mut();
250                 let target = match terminator.kind {
251                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
252                     ref kind => {
253                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
254                     }
255                 };
256                 Terminator {
257                     source_info: terminator.source_info,
258                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
259                         target,
260                     })
261                 }
262             };
263
264             match terminator.kind {
265                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
266                     self.visit_operand(&mut func, loc);
267                     for arg in &mut args {
268                         self.visit_operand(arg, loc);
269                     }
270
271                     let last = self.promoted.basic_blocks().last().unwrap();
272                     let new_target = self.new_block();
273
274                     *self.promoted[last].terminator_mut() = Terminator {
275                         kind: TerminatorKind::Call {
276                             func,
277                             args,
278                             cleanup: None,
279                             destination: Some(
280                                 (Place::from(new_temp), new_target)
281                             ),
282                             from_hir_call,
283                         },
284                         ..terminator
285                     };
286                 }
287                 ref kind => {
288                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
289                 }
290             };
291         };
292
293         self.keep_original = old_keep_original;
294         new_temp
295     }
296
297     fn promote_candidate(
298         mut self,
299         def_id: DefId,
300         candidate: Candidate,
301         next_promoted_id: usize,
302     ) -> Option<Body<'tcx>> {
303         let mut operand = {
304             let promoted = &mut self.promoted;
305             let promoted_id = Promoted::new(next_promoted_id);
306             let tcx = self.tcx;
307             let mut promoted_place = |ty, span| {
308                 promoted.span = span;
309                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
310                 Place {
311                     base: PlaceBase::Static(box Static {
312                         kind:
313                             StaticKind::Promoted(
314                                 promoted_id,
315                                 InternalSubsts::identity_for_item(tcx, def_id),
316                             ),
317                         ty,
318                         def_id,
319                     }),
320                     projection: box [],
321                 }
322             };
323             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
324             match candidate {
325                 Candidate::Ref(loc) => {
326                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
327                     match statement.kind {
328                         StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
329                             // Use the underlying local for this (necessarily interior) borrow.
330                             let ty = place.base.ty(local_decls).ty;
331                             let span = statement.source_info.span;
332
333                             Operand::Move(Place {
334                                 base: mem::replace(
335                                     &mut place.base,
336                                     promoted_place(ty, span).base,
337                                 ),
338                                 projection: box [],
339                             })
340                         }
341                         _ => bug!()
342                     }
343                 }
344                 Candidate::Repeat(loc) => {
345                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
346                     match statement.kind {
347                         StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
348                             let ty = operand.ty(local_decls, self.tcx);
349                             let span = statement.source_info.span;
350                             mem::replace(
351                                 operand,
352                                 Operand::Copy(promoted_place(ty, span))
353                             )
354                         }
355                         _ => bug!()
356                     }
357                 },
358                 Candidate::Argument { bb, index } => {
359                     let terminator = blocks[bb].terminator_mut();
360                     match terminator.kind {
361                         TerminatorKind::Call { ref mut args, .. } => {
362                             let ty = args[index].ty(local_decls, self.tcx);
363                             let span = terminator.source_info.span;
364                             let operand = Operand::Copy(promoted_place(ty, span));
365                             mem::replace(&mut args[index], operand)
366                         }
367                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
368                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
369                         // we are seeing a `Goto`. That means that the `promote_temps` method
370                         // already promoted this call away entirely. This case occurs when calling
371                         // a function requiring a constant argument and as that constant value
372                         // providing a value whose computation contains another call to a function
373                         // requiring a constant argument.
374                         TerminatorKind::Goto { .. } => return None,
375                         _ => bug!()
376                     }
377                 }
378             }
379         };
380
381         assert_eq!(self.new_block(), START_BLOCK);
382         self.visit_operand(&mut operand, Location {
383             block: BasicBlock::new(0),
384             statement_index: usize::MAX
385         });
386
387         let span = self.promoted.span;
388         self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
389         Some(self.promoted)
390     }
391 }
392
393 /// Replaces all temporaries with their promoted counterparts.
394 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
395     fn visit_local(&mut self,
396                    local: &mut Local,
397                    _: PlaceContext,
398                    _: Location) {
399         if self.source.local_kind(*local) == LocalKind::Temp {
400             *local = self.promote_temp(*local);
401         }
402     }
403 }
404
405 pub fn promote_candidates<'tcx>(
406     def_id: DefId,
407     body: &mut Body<'tcx>,
408     tcx: TyCtxt<'tcx>,
409     mut temps: IndexVec<Local, TempState>,
410     candidates: Vec<Candidate>,
411 ) -> IndexVec<Promoted, Body<'tcx>> {
412     // Visit candidates in reverse, in case they're nested.
413     debug!("promote_candidates({:?})", candidates);
414
415     let mut promotions = IndexVec::new();
416
417     for candidate in candidates.into_iter().rev() {
418         match candidate {
419             Candidate::Repeat(Location { block, statement_index }) |
420             Candidate::Ref(Location { block, statement_index }) => {
421                 match body[block].statements[statement_index].kind {
422                     StatementKind::Assign(box(Place {
423                         base: PlaceBase::Local(local),
424                         projection: box [],
425                     }, _)) => {
426                         if temps[local] == TempState::PromotedOut {
427                             // Already promoted.
428                             continue;
429                         }
430                     }
431                     _ => {}
432                 }
433             }
434             Candidate::Argument { .. } => {}
435         }
436
437
438         // Declare return place local so that `mir::Body::new` doesn't complain.
439         let initial_locals = iter::once(
440             LocalDecl::new_return_place(tcx.types.never, body.span)
441         ).collect();
442
443         let promoter = Promoter {
444             promoted: Body::new(
445                 IndexVec::new(),
446                 // FIXME: maybe try to filter this to avoid blowing up
447                 // memory usage?
448                 body.source_scopes.clone(),
449                 body.source_scope_local_data.clone(),
450                 None,
451                 initial_locals,
452                 IndexVec::new(),
453                 0,
454                 vec![],
455                 body.span,
456                 vec![],
457             ),
458             tcx,
459             source: body,
460             temps: &mut temps,
461             keep_original: false
462         };
463
464         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
465         if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
466             promotions.push(promoted);
467         }
468     }
469
470     // Eliminate assignments to, and drops of promoted temps.
471     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
472     for block in body.basic_blocks_mut() {
473         block.statements.retain(|statement| {
474             match statement.kind {
475                 StatementKind::Assign(box(Place {
476                     base: PlaceBase::Local(index),
477                     projection: box [],
478                 }, _)) |
479                 StatementKind::StorageLive(index) |
480                 StatementKind::StorageDead(index) => {
481                     !promoted(index)
482                 }
483                 _ => true
484             }
485         });
486         let terminator = block.terminator_mut();
487         match terminator.kind {
488             TerminatorKind::Drop { location: Place {
489                 base: PlaceBase::Local(index),
490                 projection: box [],
491             }, target, .. } => {
492                 if promoted(index) {
493                     terminator.kind = TerminatorKind::Goto {
494                         target,
495                     };
496                 }
497             }
498             _ => {}
499         }
500     }
501
502     promotions
503 }