]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Remove ord lang item
[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 irrelevant.
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(_),
500                 projection: [],
501             } => bug!("qualifying already promoted MIR"),
502             PlaceRef {
503                 base: _,
504                 projection: [proj_base @ .., elem],
505             } => {
506                 match *elem {
507                     ProjectionElem::Deref |
508                     ProjectionElem::Downcast(..) => return Err(Unpromotable),
509
510                     ProjectionElem::ConstantIndex {..} |
511                     ProjectionElem::Subslice {..} => {}
512
513                     ProjectionElem::Index(local) => {
514                         self.validate_local(local)?;
515                     }
516
517                     ProjectionElem::Field(..) => {
518                         if self.const_kind.is_none() {
519                             let base_ty =
520                                 Place::ty_from(place.base, proj_base, self.body, self.tcx).ty;
521                             if let Some(def) = base_ty.ty_adt_def() {
522                                 // No promotion of union field accesses.
523                                 if def.is_union() {
524                                     return Err(Unpromotable);
525                                 }
526                             }
527                         }
528                     }
529                 }
530
531                 self.validate_place(PlaceRef {
532                     base: place.base,
533                     projection: proj_base,
534                 })
535             }
536         }
537     }
538
539     fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
540         match operand {
541             Operand::Copy(place) |
542             Operand::Move(place) => self.validate_place(place.as_ref()),
543
544             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
545             // `validate_rvalue` upon access.
546             Operand::Constant(c) => {
547                 if let Some(def_id) = c.check_static_ptr(self.tcx) {
548                     // Only allow statics (not consts) to refer to other statics.
549                     // FIXME(eddyb) does this matter at all for promotion?
550                     let is_static = self.const_kind.map_or(false, |k| k.is_static());
551                     if !is_static {
552                         return Err(Unpromotable);
553                     }
554
555                     let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
556                     if is_thread_local {
557                         return Err(Unpromotable);
558                     }
559                 }
560
561                 Ok(())
562             },
563         }
564     }
565
566     fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
567         match *rvalue {
568             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
569                 let operand_ty = operand.ty(self.body, self.tcx);
570                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
571                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
572                 match (cast_in, cast_out) {
573                     (CastTy::Ptr(_), CastTy::Int(_)) |
574                     (CastTy::FnPtr, CastTy::Int(_)) => {
575                         // in normal functions, mark such casts as not promotable
576                         return Err(Unpromotable);
577                     }
578                     _ => {}
579                 }
580             }
581
582             Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
583                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
584                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
585                             op == BinOp::Le || op == BinOp::Lt ||
586                             op == BinOp::Ge || op == BinOp::Gt ||
587                             op == BinOp::Offset);
588
589                     // raw pointer operations are not allowed inside promoteds
590                     return Err(Unpromotable);
591                 }
592             }
593
594             Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
595
596             _ => {}
597         }
598
599         match rvalue {
600             Rvalue::NullaryOp(..) => Ok(()),
601
602             Rvalue::Discriminant(place) |
603             Rvalue::Len(place) => self.validate_place(place.as_ref()),
604
605             Rvalue::Use(operand) |
606             Rvalue::Repeat(operand, _) |
607             Rvalue::UnaryOp(_, operand) |
608             Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
609
610             Rvalue::BinaryOp(_, lhs, rhs) |
611             Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
612                 self.validate_operand(lhs)?;
613                 self.validate_operand(rhs)
614             }
615
616             Rvalue::Ref(_, kind, place) => {
617                 if let BorrowKind::Mut { .. } = kind {
618                     let ty = place.ty(self.body, self.tcx).ty;
619
620                     // In theory, any zero-sized value could be borrowed
621                     // mutably without consequences. However, only &mut []
622                     // is allowed right now, and only in functions.
623                     if self.const_kind == Some(ConstKind::StaticMut) {
624                         // Inside a `static mut`, &mut [...] is also allowed.
625                         match ty.kind {
626                             ty::Array(..) | ty::Slice(_) => {}
627                             _ => return Err(Unpromotable),
628                         }
629                     } else if let ty::Array(_, len) = ty.kind {
630                         // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
631                         // const context which seems unnecessary given that this is merely a ZST.
632                         match len.try_eval_usize(self.tcx, self.param_env) {
633                             Some(0) if self.const_kind.is_none() => {},
634                             _ => return Err(Unpromotable),
635                         }
636                     } else {
637                         return Err(Unpromotable);
638                     }
639                 }
640
641                 // Special-case reborrows to be more like a copy of the reference.
642                 let mut place = place.as_ref();
643                 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
644                     let base_ty =
645                         Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
646                     if let ty::Ref(..) = base_ty.kind {
647                         place = PlaceRef {
648                             base: &place.base,
649                             projection: proj_base,
650                         };
651                     }
652                 }
653
654                 self.validate_place(place)?;
655
656                 // HACK(eddyb) this should compute the same thing as
657                 // `<HasMutInterior as Qualif>::in_projection` from
658                 // `check_consts::qualifs` but without recursion.
659                 let mut has_mut_interior = match place.base {
660                     PlaceBase::Local(local) => {
661                         self.qualif_local::<qualifs::HasMutInterior>(*local)
662                     }
663                     PlaceBase::Static(_) => false,
664                 };
665                 if has_mut_interior {
666                     let mut place_projection = place.projection;
667                     // FIXME(eddyb) use a forward loop instead of a reverse one.
668                     while let [proj_base @ .., elem] = place_projection {
669                         // FIXME(eddyb) this is probably excessive, with
670                         // the exception of `union` member accesses.
671                         let ty = Place::ty_from(place.base, proj_base, self.body, self.tcx)
672                             .projection_ty(self.tcx, elem)
673                             .ty;
674                         if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
675                             has_mut_interior = false;
676                             break;
677                         }
678
679                         place_projection = proj_base;
680                     }
681                 }
682                 if has_mut_interior {
683                     return Err(Unpromotable);
684                 }
685
686                 Ok(())
687             }
688
689             Rvalue::Aggregate(_, ref operands) => {
690                 for o in operands {
691                     self.validate_operand(o)?;
692                 }
693
694                 Ok(())
695             }
696         }
697     }
698
699     fn validate_call(
700         &self,
701         callee: &Operand<'tcx>,
702         args: &[Operand<'tcx>],
703     ) -> Result<(), Unpromotable> {
704         let fn_ty = callee.ty(self.body, self.tcx);
705
706         if !self.explicit && self.const_kind.is_none() {
707             if let ty::FnDef(def_id, _) = fn_ty.kind {
708                 // Never promote runtime `const fn` calls of
709                 // functions without `#[rustc_promotable]`.
710                 if !self.tcx.is_promotable_const_fn(def_id) {
711                     return Err(Unpromotable);
712                 }
713             }
714         }
715
716         let is_const_fn = match fn_ty.kind {
717             ty::FnDef(def_id, _) => {
718                 self.tcx.is_const_fn(def_id) ||
719                 self.tcx.is_unstable_const_fn(def_id).is_some() ||
720                 is_lang_panic_fn(self.tcx, self.def_id)
721             }
722             _ => false,
723         };
724         if !is_const_fn {
725             return Err(Unpromotable);
726         }
727
728         self.validate_operand(callee)?;
729         for arg in args {
730             self.validate_operand(arg)?;
731         }
732
733         Ok(())
734     }
735 }
736
737 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
738 pub fn validate_candidates(
739     tcx: TyCtxt<'tcx>,
740     body: &Body<'tcx>,
741     def_id: DefId,
742     temps: &IndexVec<Local, TempState>,
743     candidates: &[Candidate],
744 ) -> Vec<Candidate> {
745     let mut validator = Validator {
746         item: Item::new(tcx, def_id, body),
747         temps,
748         explicit: false,
749     };
750
751     candidates.iter().copied().filter(|&candidate| {
752         validator.explicit = candidate.forces_explicit_promotion();
753
754         // FIXME(eddyb) also emit the errors for shuffle indices
755         // and `#[rustc_args_required_const]` arguments here.
756
757         let is_promotable = validator.validate_candidate(candidate).is_ok();
758         match candidate {
759             Candidate::Argument { bb, index } if !is_promotable => {
760                 let span = body[bb].terminator().source_info.span;
761                 let msg = format!("argument {} is required to be a constant", index + 1);
762                 tcx.sess.span_err(span, &msg);
763             }
764             _ => ()
765         }
766
767         is_promotable
768     }).collect()
769 }
770
771 struct Promoter<'a, 'tcx> {
772     tcx: TyCtxt<'tcx>,
773     source: &'a mut Body<'tcx>,
774     promoted: Body<'tcx>,
775     temps: &'a mut IndexVec<Local, TempState>,
776
777     /// If true, all nested temps are also kept in the
778     /// source MIR, not moved to the promoted MIR.
779     keep_original: bool,
780 }
781
782 impl<'a, 'tcx> Promoter<'a, 'tcx> {
783     fn new_block(&mut self) -> BasicBlock {
784         let span = self.promoted.span;
785         self.promoted.basic_blocks_mut().push(BasicBlockData {
786             statements: vec![],
787             terminator: Some(Terminator {
788                 source_info: SourceInfo {
789                     span,
790                     scope: OUTERMOST_SOURCE_SCOPE
791                 },
792                 kind: TerminatorKind::Return
793             }),
794             is_cleanup: false
795         })
796     }
797
798     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
799         let last = self.promoted.basic_blocks().last().unwrap();
800         let data = &mut self.promoted[last];
801         data.statements.push(Statement {
802             source_info: SourceInfo {
803                 span,
804                 scope: OUTERMOST_SOURCE_SCOPE
805             },
806             kind: StatementKind::Assign(box(Place::from(dest), rvalue))
807         });
808     }
809
810     fn is_temp_kind(&self, local: Local) -> bool {
811         self.source.local_kind(local) == LocalKind::Temp
812     }
813
814     /// Copies the initialization of this temp to the
815     /// promoted MIR, recursing through temps.
816     fn promote_temp(&mut self, temp: Local) -> Local {
817         let old_keep_original = self.keep_original;
818         let loc = match self.temps[temp] {
819             TempState::Defined { location, uses } if uses > 0 => {
820                 if uses > 1 {
821                     self.keep_original = true;
822                 }
823                 location
824             }
825             state =>  {
826                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
827                           temp, state);
828             }
829         };
830         if !self.keep_original {
831             self.temps[temp] = TempState::PromotedOut;
832         }
833
834         let num_stmts = self.source[loc.block].statements.len();
835         let new_temp = self.promoted.local_decls.push(
836             LocalDecl::new_temp(self.source.local_decls[temp].ty,
837                                 self.source.local_decls[temp].source_info.span));
838
839         debug!("promote({:?} @ {:?}/{:?}, {:?})",
840                temp, loc, num_stmts, self.keep_original);
841
842         // First, take the Rvalue or Call out of the source MIR,
843         // or duplicate it, depending on keep_original.
844         if loc.statement_index < num_stmts {
845             let (mut rvalue, source_info) = {
846                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
847                 let rhs = match statement.kind {
848                     StatementKind::Assign(box(_, ref mut rhs)) => rhs,
849                     _ => {
850                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
851                                   statement);
852                     }
853                 };
854
855                 (if self.keep_original {
856                     rhs.clone()
857                 } else {
858                     let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
859                     mem::replace(rhs, unit)
860                 }, statement.source_info)
861             };
862
863             self.visit_rvalue(&mut rvalue, loc);
864             self.assign(new_temp, rvalue, source_info.span);
865         } else {
866             let terminator = if self.keep_original {
867                 self.source[loc.block].terminator().clone()
868             } else {
869                 let terminator = self.source[loc.block].terminator_mut();
870                 let target = match terminator.kind {
871                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
872                     ref kind => {
873                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
874                     }
875                 };
876                 Terminator {
877                     source_info: terminator.source_info,
878                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
879                         target,
880                     })
881                 }
882             };
883
884             match terminator.kind {
885                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
886                     self.visit_operand(&mut func, loc);
887                     for arg in &mut args {
888                         self.visit_operand(arg, loc);
889                     }
890
891                     let last = self.promoted.basic_blocks().last().unwrap();
892                     let new_target = self.new_block();
893
894                     *self.promoted[last].terminator_mut() = Terminator {
895                         kind: TerminatorKind::Call {
896                             func,
897                             args,
898                             cleanup: None,
899                             destination: Some(
900                                 (Place::from(new_temp), new_target)
901                             ),
902                             from_hir_call,
903                         },
904                         ..terminator
905                     };
906                 }
907                 ref kind => {
908                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
909                 }
910             };
911         };
912
913         self.keep_original = old_keep_original;
914         new_temp
915     }
916
917     fn promote_candidate(
918         mut self,
919         def_id: DefId,
920         candidate: Candidate,
921         next_promoted_id: usize,
922     ) -> Option<Body<'tcx>> {
923         let mut operand = {
924             let promoted = &mut self.promoted;
925             let promoted_id = Promoted::new(next_promoted_id);
926             let tcx = self.tcx;
927             let mut promoted_place = |ty, span| {
928                 promoted.span = span;
929                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
930                 Place {
931                     base: PlaceBase::Static(box Static {
932                         kind:
933                             StaticKind::Promoted(
934                                 promoted_id,
935                                 InternalSubsts::identity_for_item(tcx, def_id),
936                             ),
937                         ty,
938                         def_id,
939                     }),
940                     projection: List::empty(),
941                 }
942             };
943             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
944             match candidate {
945                 Candidate::Ref(loc) => {
946                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
947                     match statement.kind {
948                         StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
949                             // Use the underlying local for this (necessarily interior) borrow.
950                             let ty = place.base.ty(local_decls).ty;
951                             let span = statement.source_info.span;
952
953                             Operand::Move(Place {
954                                 base: mem::replace(
955                                     &mut place.base,
956                                     promoted_place(ty, span).base,
957                                 ),
958                                 projection: List::empty(),
959                             })
960                         }
961                         _ => bug!()
962                     }
963                 }
964                 Candidate::Repeat(loc) => {
965                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
966                     match statement.kind {
967                         StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
968                             let ty = operand.ty(local_decls, self.tcx);
969                             let span = statement.source_info.span;
970                             mem::replace(
971                                 operand,
972                                 Operand::Copy(promoted_place(ty, span))
973                             )
974                         }
975                         _ => bug!()
976                     }
977                 },
978                 Candidate::Argument { bb, index } => {
979                     let terminator = blocks[bb].terminator_mut();
980                     match terminator.kind {
981                         TerminatorKind::Call { ref mut args, .. } => {
982                             let ty = args[index].ty(local_decls, self.tcx);
983                             let span = terminator.source_info.span;
984                             let operand = Operand::Copy(promoted_place(ty, span));
985                             mem::replace(&mut args[index], operand)
986                         }
987                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
988                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
989                         // we are seeing a `Goto`. That means that the `promote_temps` method
990                         // already promoted this call away entirely. This case occurs when calling
991                         // a function requiring a constant argument and as that constant value
992                         // providing a value whose computation contains another call to a function
993                         // requiring a constant argument.
994                         TerminatorKind::Goto { .. } => return None,
995                         _ => bug!()
996                     }
997                 }
998             }
999         };
1000
1001         assert_eq!(self.new_block(), START_BLOCK);
1002         self.visit_operand(&mut operand, Location {
1003             block: BasicBlock::new(0),
1004             statement_index: usize::MAX
1005         });
1006
1007         let span = self.promoted.span;
1008         self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
1009         Some(self.promoted)
1010     }
1011 }
1012
1013 /// Replaces all temporaries with their promoted counterparts.
1014 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1015     fn tcx(&self) -> TyCtxt<'tcx> {
1016         self.tcx
1017     }
1018
1019     fn visit_local(&mut self,
1020                    local: &mut Local,
1021                    _: PlaceContext,
1022                    _: Location) {
1023         if self.is_temp_kind(*local) {
1024             *local = self.promote_temp(*local);
1025         }
1026     }
1027
1028     fn process_projection_elem(
1029         &mut self,
1030         elem: &PlaceElem<'tcx>,
1031     ) -> Option<PlaceElem<'tcx>> {
1032         match elem {
1033             PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1034                 Some(PlaceElem::Index(self.promote_temp(*local)))
1035             }
1036             _ => None,
1037         }
1038     }
1039 }
1040
1041 pub fn promote_candidates<'tcx>(
1042     def_id: DefId,
1043     body: &mut Body<'tcx>,
1044     tcx: TyCtxt<'tcx>,
1045     mut temps: IndexVec<Local, TempState>,
1046     candidates: Vec<Candidate>,
1047 ) -> IndexVec<Promoted, Body<'tcx>> {
1048     // Visit candidates in reverse, in case they're nested.
1049     debug!("promote_candidates({:?})", candidates);
1050
1051     let mut promotions = IndexVec::new();
1052
1053     for candidate in candidates.into_iter().rev() {
1054         match candidate {
1055             Candidate::Repeat(Location { block, statement_index }) |
1056             Candidate::Ref(Location { block, statement_index }) => {
1057                 match &body[block].statements[statement_index].kind {
1058                     StatementKind::Assign(box(place, _)) => {
1059                         if let Some(local) = place.as_local() {
1060                             if temps[local] == TempState::PromotedOut {
1061                                 // Already promoted.
1062                                 continue;
1063                             }
1064                         }
1065                     }
1066                     _ => {}
1067                 }
1068             }
1069             Candidate::Argument { .. } => {}
1070         }
1071
1072
1073         // Declare return place local so that `mir::Body::new` doesn't complain.
1074         let initial_locals = iter::once(
1075             LocalDecl::new_return_place(tcx.types.never, body.span)
1076         ).collect();
1077
1078         let promoter = Promoter {
1079             promoted: Body::new(
1080                 IndexVec::new(),
1081                 // FIXME: maybe try to filter this to avoid blowing up
1082                 // memory usage?
1083                 body.source_scopes.clone(),
1084                 body.source_scope_local_data.clone(),
1085                 initial_locals,
1086                 IndexVec::new(),
1087                 0,
1088                 vec![],
1089                 body.span,
1090                 vec![],
1091                 body.generator_kind,
1092             ),
1093             tcx,
1094             source: body,
1095             temps: &mut temps,
1096             keep_original: false
1097         };
1098
1099         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1100         if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1101             promotions.push(promoted);
1102         }
1103     }
1104
1105     // Eliminate assignments to, and drops of promoted temps.
1106     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1107     for block in body.basic_blocks_mut() {
1108         block.statements.retain(|statement| {
1109             match &statement.kind {
1110                 StatementKind::Assign(box(place, _)) => {
1111                     if let Some(index) = place.as_local() {
1112                         !promoted(index)
1113                     } else {
1114                         true
1115                     }
1116                 }
1117                 StatementKind::StorageLive(index) |
1118                 StatementKind::StorageDead(index) => {
1119                     !promoted(*index)
1120                 }
1121                 _ => true
1122             }
1123         });
1124         let terminator = block.terminator_mut();
1125         match &terminator.kind {
1126             TerminatorKind::Drop { location: place, target, .. } => {
1127                 if let Some(index) = place.as_local() {
1128                     if promoted(index) {
1129                         terminator.kind = TerminatorKind::Goto {
1130                             target: *target,
1131                         };
1132                     }
1133                 }
1134             }
1135             _ => {}
1136         }
1137     }
1138
1139     promotions
1140 }
1141
1142 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1143 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1144 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1145 /// enabled.
1146 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1147     tcx: TyCtxt<'tcx>,
1148     mir_def_id: DefId,
1149     body: &Body<'tcx>,
1150     operand: &Operand<'tcx>,
1151 ) -> bool {
1152     let mut rpo = traversal::reverse_postorder(body);
1153     let (temps, _) = collect_temps_and_candidates(tcx, body, &mut rpo);
1154     let validator = Validator {
1155         item: Item::new(tcx, mir_def_id, body),
1156         temps: &temps,
1157         explicit: false,
1158     };
1159
1160     let should_promote = validator.validate_operand(operand).is_ok();
1161     let feature_flag = tcx.features().const_in_array_repeat_expressions;
1162     debug!("should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1163             should_promote={:?} feature_flag={:?}", mir_def_id, should_promote, feature_flag);
1164     should_promote && !feature_flag
1165 }