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