]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Create promoted MIR fragments in `const` and `static`s
[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::{self, List, TyCtxt, TypeFoldable};
20 use rustc::ty::subst::InternalSubsts;
21 use rustc::ty::cast::CastTy;
22 use syntax::ast::LitKind;
23 use syntax::symbol::sym;
24 use syntax_pos::{Span, DUMMY_SP};
25
26 use rustc_index::vec::{IndexVec, Idx};
27 use rustc_target::spec::abi::Abi;
28
29 use std::cell::Cell;
30 use std::{iter, mem, usize};
31
32 use crate::transform::{MirPass, MirSource};
33 use crate::transform::check_consts::{qualifs, Item, ConstKind, is_lang_panic_fn};
34
35 /// A `MirPass` for promotion.
36 ///
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.
39 ///
40 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
41 /// newly created `StaticKind::Promoted`.
42 #[derive(Default)]
43 pub struct PromoteTemps<'tcx> {
44     pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
45 }
46
47 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
48     fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
49         // There's not really any point in promoting errorful MIR.
50         //
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");
54             return;
55         }
56
57         if src.promoted.is_some() {
58             return;
59         }
60
61         let def_id = src.def_id();
62
63         let mut rpo = traversal::reverse_postorder(body);
64         let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
65
66         let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates);
67
68         let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
69         self.promoted_fragments.set(promoted);
70     }
71 }
72
73 /// State of a temporary during collection and promotion.
74 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
75 pub enum TempState {
76     /// No references to this temp.
77     Undefined,
78     /// One direct assignment and any number of direct uses.
79     /// A borrow of this temp is promotable if the assigned
80     /// value is qualified as constant.
81     Defined {
82         location: Location,
83         uses: usize
84     },
85     /// Any other combination of assignments/uses.
86     Unpromotable,
87     /// This temp was part of an rvalue which got extracted
88     /// during promotion and needs cleanup.
89     PromotedOut
90 }
91
92 impl TempState {
93     pub fn is_promotable(&self) -> bool {
94         debug!("is_promotable: self={:?}", self);
95         if let TempState::Defined { .. } = *self {
96             true
97         } else {
98             false
99         }
100     }
101 }
102
103 /// A "root candidate" for promotion, which will become the
104 /// returned value in a promoted MIR, unless it's a subset
105 /// of a larger candidate.
106 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
107 pub enum Candidate {
108     /// Borrow of a constant temporary.
109     Ref(Location),
110
111     /// Promotion of the `x` in `[x; 32]`.
112     Repeat(Location),
113
114     /// Currently applied to function calls where the callee has the unstable
115     /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
116     /// intrinsic. The intrinsic requires the arguments are indeed constant and
117     /// the attribute currently provides the semantic requirement that arguments
118     /// must be constant.
119     Argument { bb: BasicBlock, index: usize },
120 }
121
122 impl Candidate {
123     /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
124     fn forces_explicit_promotion(&self) -> bool {
125         match self {
126             Candidate::Ref(_) |
127             Candidate::Repeat(_) => false,
128             Candidate::Argument { .. } => true,
129         }
130     }
131 }
132
133 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
134     let attrs = tcx.get_attrs(def_id);
135     let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
136     let mut ret = vec![];
137     for meta in attr.meta_item_list()? {
138         match meta.literal()?.kind {
139             LitKind::Int(a, _) => { ret.push(a as usize); }
140             _ => return None,
141         }
142     }
143     Some(ret)
144 }
145
146 struct Collector<'a, 'tcx> {
147     tcx: TyCtxt<'tcx>,
148     body: &'a Body<'tcx>,
149     temps: IndexVec<Local, TempState>,
150     candidates: Vec<Candidate>,
151     span: Span,
152 }
153
154 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
155     fn visit_local(&mut self,
156                    &index: &Local,
157                    context: PlaceContext,
158                    location: Location) {
159         debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
160         // We're only interested in temporaries and the return place
161         match self.body.local_kind(index) {
162             | LocalKind::Temp
163             | LocalKind::ReturnPointer
164             => {},
165             | LocalKind::Arg
166             | LocalKind::Var
167             => return,
168         }
169
170         // Ignore drops, if the temp gets promoted,
171         // then it's constant and thus drop is noop.
172         // Non-uses are also irrelevent.
173         if context.is_drop() || !context.is_use() {
174             debug!(
175                 "visit_local: context.is_drop={:?} context.is_use={:?}",
176                 context.is_drop(), context.is_use(),
177             );
178             return;
179         }
180
181         let temp = &mut self.temps[index];
182         debug!("visit_local: temp={:?}", temp);
183         if *temp == TempState::Undefined {
184             match context {
185                 PlaceContext::MutatingUse(MutatingUseContext::Store) |
186                 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
187                     *temp = TempState::Defined {
188                         location,
189                         uses: 0
190                     };
191                     return;
192                 }
193                 _ => { /* mark as unpromotable below */ }
194             }
195         } else if let TempState::Defined { ref mut uses, .. } = *temp {
196             // We always allow borrows, even mutable ones, as we need
197             // to promote mutable borrows of some ZSTs e.g., `&mut []`.
198             let allowed_use = context.is_borrow() || context.is_nonmutating_use();
199             debug!("visit_local: allowed_use={:?}", allowed_use);
200             if allowed_use {
201                 *uses += 1;
202                 return;
203             }
204             /* mark as unpromotable below */
205         }
206         *temp = TempState::Unpromotable;
207     }
208
209     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
210         self.super_rvalue(rvalue, location);
211
212         match *rvalue {
213             Rvalue::Ref(..) => {
214                 self.candidates.push(Candidate::Ref(location));
215             }
216             Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
217                 // FIXME(#49147) only promote the element when it isn't `Copy`
218                 // (so that code that can copy it at runtime is unaffected).
219                 self.candidates.push(Candidate::Repeat(location));
220             }
221             _ => {}
222         }
223     }
224
225     fn visit_terminator_kind(&mut self,
226                              kind: &TerminatorKind<'tcx>,
227                              location: Location) {
228         self.super_terminator_kind(kind, location);
229
230         if let TerminatorKind::Call { ref func, .. } = *kind {
231             if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
232                 let fn_sig = self.tcx.fn_sig(def_id);
233                 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
234                     let name = self.tcx.item_name(def_id);
235                     // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
236                     if name.as_str().starts_with("simd_shuffle") {
237                         self.candidates.push(Candidate::Argument {
238                             bb: location.block,
239                             index: 2,
240                         });
241
242                         return; // Don't double count `simd_shuffle` candidates
243                     }
244                 }
245
246                 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
247                     for index in constant_args {
248                         self.candidates.push(Candidate::Argument { bb: location.block, index });
249                     }
250                 }
251             }
252         }
253     }
254
255     fn visit_source_info(&mut self, source_info: &SourceInfo) {
256         self.span = source_info.span;
257     }
258 }
259
260 pub fn collect_temps_and_candidates(
261     tcx: TyCtxt<'tcx>,
262     body: &Body<'tcx>,
263     rpo: &mut ReversePostorder<'_, 'tcx>,
264 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
265     let mut collector = Collector {
266         tcx,
267         body,
268         temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
269         candidates: vec![],
270         span: body.span,
271     };
272     for (bb, data) in rpo {
273         collector.visit_basic_block_data(bb, data);
274     }
275     (collector.temps, collector.candidates)
276 }
277
278 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
279 ///
280 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
281 struct Validator<'a, 'tcx> {
282     item: Item<'a, 'tcx>,
283     temps: &'a IndexVec<Local, TempState>,
284
285     /// Explicit promotion happens e.g. for constant arguments declared via
286     /// `rustc_args_required_const`.
287     /// Implicit promotion has almost the same rules, except that disallows `const fn`
288     /// except for those marked `#[rustc_promotable]`. This is to avoid changing
289     /// a legitimate run-time operation into a failing compile-time operation
290     /// e.g. due to addresses being compared inside the function.
291     explicit: bool,
292 }
293
294 impl std::ops::Deref for Validator<'a, 'tcx> {
295     type Target = Item<'a, 'tcx>;
296
297     fn deref(&self) -> &Self::Target {
298         &self.item
299     }
300 }
301
302 struct Unpromotable;
303
304 impl<'tcx> Validator<'_, 'tcx> {
305     fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
306         match candidate {
307             Candidate::Ref(loc) => {
308                 assert!(!self.explicit);
309
310                 let statement = &self.body[loc.block].statements[loc.statement_index];
311                 match &statement.kind {
312                     StatementKind::Assign(box(_, Rvalue::Ref(_, kind, place))) => {
313                         match kind {
314                             BorrowKind::Shared | BorrowKind::Mut { .. } => {}
315
316                             // FIXME(eddyb) these aren't promoted here but *could*
317                             // be promoted as part of a larger value because
318                             // `validate_rvalue`  doesn't check them, need to
319                             // figure out what is the intended behavior.
320                             BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
321                         }
322
323                         // We can only promote interior borrows of promotable temps (non-temps
324                         // don't get promoted anyway).
325                         let base = match place.base {
326                             PlaceBase::Local(local) => local,
327                             _ => return Err(Unpromotable),
328                         };
329                         self.validate_local(base)?;
330
331                         if place.projection.contains(&ProjectionElem::Deref) {
332                             return Err(Unpromotable);
333                         }
334
335                         let mut has_mut_interior =
336                             self.qualif_local::<qualifs::HasMutInterior>(base);
337                         // HACK(eddyb) this should compute the same thing as
338                         // `<HasMutInterior as Qualif>::in_projection` from
339                         // `check_consts::qualifs` but without recursion.
340                         if has_mut_interior {
341                             // This allows borrowing fields which don't have
342                             // `HasMutInterior`, from a type that does, e.g.:
343                             // `let _: &'static _ = &(Cell::new(1), 2).1;`
344                             let mut place_projection = &place.projection[..];
345                             // FIXME(eddyb) use a forward loop instead of a reverse one.
346                             while let [proj_base @ .., elem] = place_projection {
347                                 // FIXME(eddyb) this is probably excessive, with
348                                 // the exception of `union` member accesses.
349                                 let ty =
350                                     Place::ty_from(&place.base, proj_base, self.body, self.tcx)
351                                         .projection_ty(self.tcx, elem)
352                                         .ty;
353                                 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
354                                     has_mut_interior = false;
355                                     break;
356                                 }
357
358                                 place_projection = proj_base;
359                             }
360                         }
361
362                         // FIXME(eddyb) this duplicates part of `validate_rvalue`.
363                         if has_mut_interior {
364                             return Err(Unpromotable);
365                         }
366                         if self.qualif_local::<qualifs::NeedsDrop>(base) {
367                             return Err(Unpromotable);
368                         }
369
370                         if let BorrowKind::Mut { .. } = kind {
371                             let ty = place.ty(self.body, self.tcx).ty;
372
373                             // In theory, any zero-sized value could be borrowed
374                             // mutably without consequences. However, only &mut []
375                             // is allowed right now, and only in functions.
376                             if self.const_kind == Some(ConstKind::StaticMut) {
377                                 // Inside a `static mut`, &mut [...] is also allowed.
378                                 match ty.kind {
379                                     ty::Array(..) | ty::Slice(_) => {}
380                                     _ => return Err(Unpromotable),
381                                 }
382                             } else if let ty::Array(_, len) = ty.kind {
383                                 // FIXME(eddyb) the `self.is_non_const_fn` condition
384                                 // seems unnecessary, given that this is merely a ZST.
385                                 match len.try_eval_usize(self.tcx, self.param_env) {
386                                     Some(0) if self.const_kind.is_none() => {},
387                                     _ => return Err(Unpromotable),
388                                 }
389                             } else {
390                                 return Err(Unpromotable);
391                             }
392                         }
393
394                         Ok(())
395                     }
396                     _ => bug!()
397                 }
398             }
399             Candidate::Repeat(loc) => {
400                 assert!(!self.explicit);
401
402                 let statement = &self.body[loc.block].statements[loc.statement_index];
403                 match &statement.kind {
404                     StatementKind::Assign(box(_, Rvalue::Repeat(ref operand, _))) => {
405                         if !self.tcx.features().const_in_array_repeat_expressions {
406                             return Err(Unpromotable);
407                         }
408
409                         self.validate_operand(operand)
410                     }
411                     _ => bug!()
412                 }
413             },
414             Candidate::Argument { bb, index } => {
415                 assert!(self.explicit);
416
417                 let terminator = self.body[bb].terminator();
418                 match &terminator.kind {
419                     TerminatorKind::Call { args, .. } => {
420                         self.validate_operand(&args[index])
421                     }
422                     _ => bug!()
423                 }
424             }
425         }
426     }
427
428     // FIXME(eddyb) maybe cache this?
429     fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
430         let per_local = &|l| self.qualif_local::<Q>(l);
431
432         if let TempState::Defined { location: loc, .. } = self.temps[local] {
433             let num_stmts = self.body[loc.block].statements.len();
434
435             if loc.statement_index < num_stmts {
436                 let statement = &self.body[loc.block].statements[loc.statement_index];
437                 match &statement.kind {
438                     StatementKind::Assign(box(_, rhs)) => {
439                         Q::in_rvalue(&self.item, per_local, rhs)
440                     }
441                     _ => {
442                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
443                                 statement);
444                     }
445                 }
446             } else {
447                 let terminator = self.body[loc.block].terminator();
448                 match &terminator.kind {
449                     TerminatorKind::Call { func, args, .. } => {
450                         let return_ty = self.body.local_decls[local].ty;
451                         Q::in_call(&self.item, per_local, func, args, return_ty)
452                     }
453                     kind => {
454                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
455                     }
456                 }
457             }
458         } else {
459             let span = self.body.local_decls[local].source_info.span;
460             span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
461         }
462     }
463
464     // FIXME(eddyb) maybe cache this?
465     fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
466         if let TempState::Defined { location: loc, .. } = self.temps[local] {
467             let num_stmts = self.body[loc.block].statements.len();
468
469             if loc.statement_index < num_stmts {
470                 let statement = &self.body[loc.block].statements[loc.statement_index];
471                 match &statement.kind {
472                     StatementKind::Assign(box(_, rhs)) => self.validate_rvalue(rhs),
473                     _ => {
474                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
475                                 statement);
476                     }
477                 }
478             } else {
479                 let terminator = self.body[loc.block].terminator();
480                 match &terminator.kind {
481                     TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
482                     kind => {
483                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
484                     }
485                 }
486             }
487         } else {
488             Err(Unpromotable)
489         }
490     }
491
492     fn validate_place(&self, place: PlaceRef<'_, 'tcx>) -> Result<(), Unpromotable> {
493         match place {
494             PlaceRef {
495                 base: PlaceBase::Local(local),
496                 projection: [],
497             } => self.validate_local(*local),
498             PlaceRef {
499                 base: PlaceBase::Static(box Static {
500                     kind: StaticKind::Promoted { .. },
501                     ..
502                 }),
503                 projection: [],
504             } => bug!("qualifying already promoted MIR"),
505             PlaceRef {
506                 base: PlaceBase::Static(box Static {
507                     kind: StaticKind::Static,
508                     def_id,
509                     ..
510                 }),
511                 projection: [],
512             } => {
513                 // Only allow statics (not consts) to refer to other statics.
514                 // FIXME(eddyb) does this matter at all for promotion?
515                 let is_static = self.const_kind.map_or(false, |k| k.is_static());
516                 if !is_static {
517                     return Err(Unpromotable);
518                 }
519
520                 let is_thread_local = self.tcx.has_attr(*def_id, sym::thread_local);
521                 if is_thread_local {
522                     return Err(Unpromotable);
523                 }
524
525                 Ok(())
526             }
527             PlaceRef {
528                 base: _,
529                 projection: [proj_base @ .., elem],
530             } => {
531                 match *elem {
532                     ProjectionElem::Deref |
533                     ProjectionElem::Downcast(..) => return Err(Unpromotable),
534
535                     ProjectionElem::ConstantIndex {..} |
536                     ProjectionElem::Subslice {..} => {}
537
538                     ProjectionElem::Index(local) => {
539                         self.validate_local(local)?;
540                     }
541
542                     ProjectionElem::Field(..) => {
543                         if self.const_kind.is_none() {
544                             let base_ty =
545                                 Place::ty_from(place.base, proj_base, self.body, self.tcx).ty;
546                             if let Some(def) = base_ty.ty_adt_def() {
547                                 // No promotion of union field accesses.
548                                 if def.is_union() {
549                                     return Err(Unpromotable);
550                                 }
551                             }
552                         }
553                     }
554                 }
555
556                 self.validate_place(PlaceRef {
557                     base: place.base,
558                     projection: proj_base,
559                 })
560             }
561         }
562     }
563
564     fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
565         match operand {
566             Operand::Copy(place) |
567             Operand::Move(place) => self.validate_place(place.as_ref()),
568
569             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
570             // `validate_rvalue` upon access.
571             Operand::Constant(_) => Ok(()),
572         }
573     }
574
575     fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
576         match *rvalue {
577             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
578                 let operand_ty = operand.ty(self.body, self.tcx);
579                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
580                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
581                 match (cast_in, cast_out) {
582                     (CastTy::Ptr(_), CastTy::Int(_)) |
583                     (CastTy::FnPtr, CastTy::Int(_)) => {
584                         // in normal functions, mark such casts as not promotable
585                         return Err(Unpromotable);
586                     }
587                     _ => {}
588                 }
589             }
590
591             Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
592                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
593                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
594                             op == BinOp::Le || op == BinOp::Lt ||
595                             op == BinOp::Ge || op == BinOp::Gt ||
596                             op == BinOp::Offset);
597
598                     // raw pointer operations are not allowed inside promoteds
599                     return Err(Unpromotable);
600                 }
601             }
602
603             Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
604
605             _ => {}
606         }
607
608         match rvalue {
609             Rvalue::NullaryOp(..) => Ok(()),
610
611             Rvalue::Discriminant(place) |
612             Rvalue::Len(place) => self.validate_place(place.as_ref()),
613
614             Rvalue::Use(operand) |
615             Rvalue::Repeat(operand, _) |
616             Rvalue::UnaryOp(_, operand) |
617             Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
618
619             Rvalue::BinaryOp(_, lhs, rhs) |
620             Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
621                 self.validate_operand(lhs)?;
622                 self.validate_operand(rhs)
623             }
624
625             Rvalue::Ref(_, kind, place) => {
626                 if let BorrowKind::Mut { .. } = kind {
627                     let ty = place.ty(self.body, self.tcx).ty;
628
629                     // In theory, any zero-sized value could be borrowed
630                     // mutably without consequences. However, only &mut []
631                     // is allowed right now, and only in functions.
632                     if self.const_kind == Some(ConstKind::StaticMut) {
633                         // Inside a `static mut`, &mut [...] is also allowed.
634                         match ty.kind {
635                             ty::Array(..) | ty::Slice(_) => {}
636                             _ => return Err(Unpromotable),
637                         }
638                     } else if let ty::Array(_, len) = ty.kind {
639                         // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
640                         // const context which seems unnecessary given that this is merely a ZST.
641                         match len.try_eval_usize(self.tcx, self.param_env) {
642                             Some(0) if self.const_kind.is_none() => {},
643                             _ => return Err(Unpromotable),
644                         }
645                     } else {
646                         return Err(Unpromotable);
647                     }
648                 }
649
650                 // Special-case reborrows to be more like a copy of the reference.
651                 let mut place = place.as_ref();
652                 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
653                     let base_ty =
654                         Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
655                     if let ty::Ref(..) = base_ty.kind {
656                         place = PlaceRef {
657                             base: &place.base,
658                             projection: proj_base,
659                         };
660                     }
661                 }
662
663                 self.validate_place(place)?;
664
665                 // HACK(eddyb) this should compute the same thing as
666                 // `<HasMutInterior as Qualif>::in_projection` from
667                 // `check_consts::qualifs` but without recursion.
668                 let mut has_mut_interior = match place.base {
669                     PlaceBase::Local(local) => {
670                         self.qualif_local::<qualifs::HasMutInterior>(*local)
671                     }
672                     PlaceBase::Static(_) => false,
673                 };
674                 if has_mut_interior {
675                     let mut place_projection = place.projection;
676                     // FIXME(eddyb) use a forward loop instead of a reverse one.
677                     while let [proj_base @ .., elem] = place_projection {
678                         // FIXME(eddyb) this is probably excessive, with
679                         // the exception of `union` member accesses.
680                         let ty = Place::ty_from(place.base, proj_base, self.body, self.tcx)
681                             .projection_ty(self.tcx, elem)
682                             .ty;
683                         if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
684                             has_mut_interior = false;
685                             break;
686                         }
687
688                         place_projection = proj_base;
689                     }
690                 }
691                 if has_mut_interior {
692                     return Err(Unpromotable);
693                 }
694
695                 Ok(())
696             }
697
698             Rvalue::Aggregate(_, ref operands) => {
699                 for o in operands {
700                     self.validate_operand(o)?;
701                 }
702
703                 Ok(())
704             }
705         }
706     }
707
708     fn validate_call(
709         &self,
710         callee: &Operand<'tcx>,
711         args: &[Operand<'tcx>],
712     ) -> Result<(), Unpromotable> {
713         let fn_ty = callee.ty(self.body, self.tcx);
714
715         if !self.explicit && self.const_kind.is_none() {
716             if let ty::FnDef(def_id, _) = fn_ty.kind {
717                 // Never promote runtime `const fn` calls of
718                 // functions without `#[rustc_promotable]`.
719                 if !self.tcx.is_promotable_const_fn(def_id) {
720                     return Err(Unpromotable);
721                 }
722             }
723         }
724
725         let is_const_fn = match fn_ty.kind {
726             ty::FnDef(def_id, _) => {
727                 self.tcx.is_const_fn(def_id) ||
728                 self.tcx.is_unstable_const_fn(def_id).is_some() ||
729                 is_lang_panic_fn(self.tcx, self.def_id)
730             }
731             _ => false,
732         };
733         if !is_const_fn {
734             return Err(Unpromotable);
735         }
736
737         self.validate_operand(callee)?;
738         for arg in args {
739             self.validate_operand(arg)?;
740         }
741
742         Ok(())
743     }
744 }
745
746 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
747 pub fn validate_candidates(
748     tcx: TyCtxt<'tcx>,
749     body: &Body<'tcx>,
750     def_id: DefId,
751     temps: &IndexVec<Local, TempState>,
752     candidates: &[Candidate],
753 ) -> Vec<Candidate> {
754     let mut validator = Validator {
755         item: Item::new(tcx, def_id, body),
756         temps,
757         explicit: false,
758     };
759
760     candidates.iter().copied().filter(|&candidate| {
761         validator.explicit = candidate.forces_explicit_promotion();
762
763         // FIXME(eddyb) also emit the errors for shuffle indices
764         // and `#[rustc_args_required_const]` arguments here.
765
766         let is_promotable = validator.validate_candidate(candidate).is_ok();
767         match candidate {
768             Candidate::Argument { bb, index } if !is_promotable => {
769                 let span = body[bb].terminator().source_info.span;
770                 let msg = format!("argument {} is required to be a constant", index + 1);
771                 tcx.sess.span_err(span, &msg);
772             }
773             _ => ()
774         }
775
776         is_promotable
777     }).collect()
778 }
779
780 struct Promoter<'a, 'tcx> {
781     tcx: TyCtxt<'tcx>,
782     source: &'a mut Body<'tcx>,
783     promoted: Body<'tcx>,
784     temps: &'a mut IndexVec<Local, TempState>,
785
786     /// If true, all nested temps are also kept in the
787     /// source MIR, not moved to the promoted MIR.
788     keep_original: bool,
789 }
790
791 impl<'a, 'tcx> Promoter<'a, 'tcx> {
792     fn new_block(&mut self) -> BasicBlock {
793         let span = self.promoted.span;
794         self.promoted.basic_blocks_mut().push(BasicBlockData {
795             statements: vec![],
796             terminator: Some(Terminator {
797                 source_info: SourceInfo {
798                     span,
799                     scope: OUTERMOST_SOURCE_SCOPE
800                 },
801                 kind: TerminatorKind::Return
802             }),
803             is_cleanup: false
804         })
805     }
806
807     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
808         let last = self.promoted.basic_blocks().last().unwrap();
809         let data = &mut self.promoted[last];
810         data.statements.push(Statement {
811             source_info: SourceInfo {
812                 span,
813                 scope: OUTERMOST_SOURCE_SCOPE
814             },
815             kind: StatementKind::Assign(box(Place::from(dest), rvalue))
816         });
817     }
818
819     fn is_temp_kind(&self, local: Local) -> bool {
820         self.source.local_kind(local) == LocalKind::Temp
821     }
822
823     /// Copies the initialization of this temp to the
824     /// promoted MIR, recursing through temps.
825     fn promote_temp(&mut self, temp: Local) -> Local {
826         let old_keep_original = self.keep_original;
827         let loc = match self.temps[temp] {
828             TempState::Defined { location, uses } if uses > 0 => {
829                 if uses > 1 {
830                     self.keep_original = true;
831                 }
832                 location
833             }
834             state =>  {
835                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
836                           temp, state);
837             }
838         };
839         if !self.keep_original {
840             self.temps[temp] = TempState::PromotedOut;
841         }
842
843         let num_stmts = self.source[loc.block].statements.len();
844         let new_temp = self.promoted.local_decls.push(
845             LocalDecl::new_temp(self.source.local_decls[temp].ty,
846                                 self.source.local_decls[temp].source_info.span));
847
848         debug!("promote({:?} @ {:?}/{:?}, {:?})",
849                temp, loc, num_stmts, self.keep_original);
850
851         // First, take the Rvalue or Call out of the source MIR,
852         // or duplicate it, depending on keep_original.
853         if loc.statement_index < num_stmts {
854             let (mut rvalue, source_info) = {
855                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
856                 let rhs = match statement.kind {
857                     StatementKind::Assign(box(_, ref mut rhs)) => rhs,
858                     _ => {
859                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
860                                   statement);
861                     }
862                 };
863
864                 (if self.keep_original {
865                     rhs.clone()
866                 } else {
867                     let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
868                     mem::replace(rhs, unit)
869                 }, statement.source_info)
870             };
871
872             self.visit_rvalue(&mut rvalue, loc);
873             self.assign(new_temp, rvalue, source_info.span);
874         } else {
875             let terminator = if self.keep_original {
876                 self.source[loc.block].terminator().clone()
877             } else {
878                 let terminator = self.source[loc.block].terminator_mut();
879                 let target = match terminator.kind {
880                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
881                     ref kind => {
882                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
883                     }
884                 };
885                 Terminator {
886                     source_info: terminator.source_info,
887                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
888                         target,
889                     })
890                 }
891             };
892
893             match terminator.kind {
894                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
895                     self.visit_operand(&mut func, loc);
896                     for arg in &mut args {
897                         self.visit_operand(arg, loc);
898                     }
899
900                     let last = self.promoted.basic_blocks().last().unwrap();
901                     let new_target = self.new_block();
902
903                     *self.promoted[last].terminator_mut() = Terminator {
904                         kind: TerminatorKind::Call {
905                             func,
906                             args,
907                             cleanup: None,
908                             destination: Some(
909                                 (Place::from(new_temp), new_target)
910                             ),
911                             from_hir_call,
912                         },
913                         ..terminator
914                     };
915                 }
916                 ref kind => {
917                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
918                 }
919             };
920         };
921
922         self.keep_original = old_keep_original;
923         new_temp
924     }
925
926     fn promote_candidate(
927         mut self,
928         def_id: DefId,
929         candidate: Candidate,
930         next_promoted_id: usize,
931     ) -> Option<Body<'tcx>> {
932         let mut operand = {
933             let promoted = &mut self.promoted;
934             let promoted_id = Promoted::new(next_promoted_id);
935             let tcx = self.tcx;
936             let mut promoted_place = |ty, span| {
937                 promoted.span = span;
938                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
939                 Place {
940                     base: PlaceBase::Static(box Static {
941                         kind:
942                             StaticKind::Promoted(
943                                 promoted_id,
944                                 InternalSubsts::identity_for_item(tcx, def_id),
945                             ),
946                         ty,
947                         def_id,
948                     }),
949                     projection: List::empty(),
950                 }
951             };
952             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
953             match candidate {
954                 Candidate::Ref(loc) => {
955                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
956                     match statement.kind {
957                         StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
958                             // Use the underlying local for this (necessarily interior) borrow.
959                             let ty = place.base.ty(local_decls).ty;
960                             let span = statement.source_info.span;
961
962                             Operand::Move(Place {
963                                 base: mem::replace(
964                                     &mut place.base,
965                                     promoted_place(ty, span).base,
966                                 ),
967                                 projection: List::empty(),
968                             })
969                         }
970                         _ => bug!()
971                     }
972                 }
973                 Candidate::Repeat(loc) => {
974                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
975                     match statement.kind {
976                         StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
977                             let ty = operand.ty(local_decls, self.tcx);
978                             let span = statement.source_info.span;
979                             mem::replace(
980                                 operand,
981                                 Operand::Copy(promoted_place(ty, span))
982                             )
983                         }
984                         _ => bug!()
985                     }
986                 },
987                 Candidate::Argument { bb, index } => {
988                     let terminator = blocks[bb].terminator_mut();
989                     match terminator.kind {
990                         TerminatorKind::Call { ref mut args, .. } => {
991                             let ty = args[index].ty(local_decls, self.tcx);
992                             let span = terminator.source_info.span;
993                             let operand = Operand::Copy(promoted_place(ty, span));
994                             mem::replace(&mut args[index], operand)
995                         }
996                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
997                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
998                         // we are seeing a `Goto`. That means that the `promote_temps` method
999                         // already promoted this call away entirely. This case occurs when calling
1000                         // a function requiring a constant argument and as that constant value
1001                         // providing a value whose computation contains another call to a function
1002                         // requiring a constant argument.
1003                         TerminatorKind::Goto { .. } => return None,
1004                         _ => bug!()
1005                     }
1006                 }
1007             }
1008         };
1009
1010         assert_eq!(self.new_block(), START_BLOCK);
1011         self.visit_operand(&mut operand, Location {
1012             block: BasicBlock::new(0),
1013             statement_index: usize::MAX
1014         });
1015
1016         let span = self.promoted.span;
1017         self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
1018         Some(self.promoted)
1019     }
1020 }
1021
1022 /// Replaces all temporaries with their promoted counterparts.
1023 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1024     fn tcx(&self) -> TyCtxt<'tcx> {
1025         self.tcx
1026     }
1027
1028     fn visit_local(&mut self,
1029                    local: &mut Local,
1030                    _: PlaceContext,
1031                    _: Location) {
1032         if self.is_temp_kind(*local) {
1033             *local = self.promote_temp(*local);
1034         }
1035     }
1036
1037     fn process_projection_elem(
1038         &mut self,
1039         elem: &PlaceElem<'tcx>,
1040     ) -> Option<PlaceElem<'tcx>> {
1041         match elem {
1042             PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1043                 Some(PlaceElem::Index(self.promote_temp(*local)))
1044             }
1045             _ => None,
1046         }
1047     }
1048 }
1049
1050 pub fn promote_candidates<'tcx>(
1051     def_id: DefId,
1052     body: &mut Body<'tcx>,
1053     tcx: TyCtxt<'tcx>,
1054     mut temps: IndexVec<Local, TempState>,
1055     candidates: Vec<Candidate>,
1056 ) -> IndexVec<Promoted, Body<'tcx>> {
1057     // Visit candidates in reverse, in case they're nested.
1058     debug!("promote_candidates({:?})", candidates);
1059
1060     let mut promotions = IndexVec::new();
1061
1062     for candidate in candidates.into_iter().rev() {
1063         match candidate {
1064             Candidate::Repeat(Location { block, statement_index }) |
1065             Candidate::Ref(Location { block, statement_index }) => {
1066                 match &body[block].statements[statement_index].kind {
1067                     StatementKind::Assign(box(place, _)) => {
1068                         if let Some(local) = place.as_local() {
1069                             if temps[local] == TempState::PromotedOut {
1070                                 // Already promoted.
1071                                 continue;
1072                             }
1073                         }
1074                     }
1075                     _ => {}
1076                 }
1077             }
1078             Candidate::Argument { .. } => {}
1079         }
1080
1081
1082         // Declare return place local so that `mir::Body::new` doesn't complain.
1083         let initial_locals = iter::once(
1084             LocalDecl::new_return_place(tcx.types.never, body.span)
1085         ).collect();
1086
1087         let promoter = Promoter {
1088             promoted: Body::new(
1089                 IndexVec::new(),
1090                 // FIXME: maybe try to filter this to avoid blowing up
1091                 // memory usage?
1092                 body.source_scopes.clone(),
1093                 body.source_scope_local_data.clone(),
1094                 None,
1095                 initial_locals,
1096                 IndexVec::new(),
1097                 0,
1098                 vec![],
1099                 body.span,
1100                 vec![],
1101             ),
1102             tcx,
1103             source: body,
1104             temps: &mut temps,
1105             keep_original: false
1106         };
1107
1108         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1109         if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1110             promotions.push(promoted);
1111         }
1112     }
1113
1114     // Eliminate assignments to, and drops of promoted temps.
1115     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1116     for block in body.basic_blocks_mut() {
1117         block.statements.retain(|statement| {
1118             match &statement.kind {
1119                 StatementKind::Assign(box(place, _)) => {
1120                     if let Some(index) = place.as_local() {
1121                         !promoted(index)
1122                     } else {
1123                         true
1124                     }
1125                 }
1126                 StatementKind::StorageLive(index) |
1127                 StatementKind::StorageDead(index) => {
1128                     !promoted(*index)
1129                 }
1130                 _ => true
1131             }
1132         });
1133         let terminator = block.terminator_mut();
1134         match &terminator.kind {
1135             TerminatorKind::Drop { location: place, target, .. } => {
1136                 if let Some(index) = place.as_local() {
1137                     if promoted(index) {
1138                         terminator.kind = TerminatorKind::Goto {
1139                             target: *target,
1140                         };
1141                     }
1142                 }
1143             }
1144             _ => {}
1145         }
1146     }
1147
1148     promotions
1149 }
1150
1151 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1152 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1153 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1154 /// enabled.
1155 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1156     tcx: TyCtxt<'tcx>,
1157     mir_def_id: DefId,
1158     body: &Body<'tcx>,
1159     operand: &Operand<'tcx>,
1160 ) -> bool {
1161     let mut rpo = traversal::reverse_postorder(body);
1162     let (temps, _) = collect_temps_and_candidates(tcx, body, &mut rpo);
1163     let validator = Validator {
1164         item: Item::new(tcx, mir_def_id, body),
1165         temps: &temps,
1166         explicit: false,
1167     };
1168
1169     let should_promote = validator.validate_operand(operand).is_ok();
1170     let feature_flag = tcx.features().const_in_array_repeat_expressions;
1171     debug!("should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1172             should_promote={:?} feature_flag={:?}", mir_def_id, should_promote, feature_flag);
1173     should_promote && !feature_flag
1174 }