]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/promote_consts.rs
Rollup merge of #76867 - poliorcetics:intra-doc-core-iter, r=jyn514
[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         matches!(self, TempState::Defined { .. } )
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     /// Determines if this code could be executed at runtime and thus is subject to codegen.
301     /// That means even unused constants need to be evaluated.
302     ///
303     /// `const_kind` should not be used in this file other than through this method!
304     fn maybe_runtime(&self) -> bool {
305         match self.const_kind {
306             None | Some(hir::ConstContext::ConstFn) => true,
307             Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) => false,
308         }
309     }
310
311     fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
312         match candidate {
313             Candidate::Ref(loc) => {
314                 assert!(!self.explicit);
315
316                 let statement = &self.body[loc.block].statements[loc.statement_index];
317                 match &statement.kind {
318                     StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
319                         match kind {
320                             BorrowKind::Shared | BorrowKind::Mut { .. } => {}
321
322                             // FIXME(eddyb) these aren't promoted here but *could*
323                             // be promoted as part of a larger value because
324                             // `validate_rvalue`  doesn't check them, need to
325                             // figure out what is the intended behavior.
326                             BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
327                         }
328
329                         // We can only promote interior borrows of promotable temps (non-temps
330                         // don't get promoted anyway).
331                         self.validate_local(place.local)?;
332
333                         if place.projection.contains(&ProjectionElem::Deref) {
334                             return Err(Unpromotable);
335                         }
336
337                         let mut has_mut_interior =
338                             self.qualif_local::<qualifs::HasMutInterior>(place.local);
339                         // HACK(eddyb) this should compute the same thing as
340                         // `<HasMutInterior as Qualif>::in_projection` from
341                         // `check_consts::qualifs` but without recursion.
342                         if has_mut_interior {
343                             // This allows borrowing fields which don't have
344                             // `HasMutInterior`, from a type that does, e.g.:
345                             // `let _: &'static _ = &(Cell::new(1), 2).1;`
346                             let mut place_projection = &place.projection[..];
347                             // FIXME(eddyb) use a forward loop instead of a reverse one.
348                             while let &[ref proj_base @ .., elem] = place_projection {
349                                 // FIXME(eddyb) this is probably excessive, with
350                                 // the exception of `union` member accesses.
351                                 let ty =
352                                     Place::ty_from(place.local, proj_base, self.body, self.tcx)
353                                         .projection_ty(self.tcx, elem)
354                                         .ty;
355                                 if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
356                                     has_mut_interior = false;
357                                     break;
358                                 }
359
360                                 place_projection = proj_base;
361                             }
362                         }
363
364                         // FIXME(eddyb) this duplicates part of `validate_rvalue`.
365                         if has_mut_interior {
366                             return Err(Unpromotable);
367                         }
368                         if self.qualif_local::<qualifs::NeedsDrop>(place.local) {
369                             return Err(Unpromotable);
370                         }
371
372                         if let BorrowKind::Mut { .. } = kind {
373                             let ty = place.ty(self.body, self.tcx).ty;
374
375                             // In theory, any zero-sized value could be borrowed
376                             // mutably without consequences. However, only &mut []
377                             // is allowed right now.
378                             if let ty::Array(_, len) = ty.kind() {
379                                 match len.try_eval_usize(self.tcx, self.param_env) {
380                                     Some(0) => {}
381                                     _ => return Err(Unpromotable),
382                                 }
383                             } else {
384                                 return Err(Unpromotable);
385                             }
386                         }
387
388                         Ok(())
389                     }
390                     _ => bug!(),
391                 }
392             }
393             Candidate::Repeat(loc) => {
394                 assert!(!self.explicit);
395
396                 let statement = &self.body[loc.block].statements[loc.statement_index];
397                 match &statement.kind {
398                     StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
399                         if !self.tcx.features().const_in_array_repeat_expressions {
400                             return Err(Unpromotable);
401                         }
402
403                         self.validate_operand(operand)
404                     }
405                     _ => bug!(),
406                 }
407             }
408             Candidate::Argument { bb, index } => {
409                 assert!(self.explicit);
410
411                 let terminator = self.body[bb].terminator();
412                 match &terminator.kind {
413                     TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
414                     _ => bug!(),
415                 }
416             }
417             Candidate::InlineAsm { bb, index } => {
418                 assert!(self.explicit);
419
420                 let terminator = self.body[bb].terminator();
421                 match &terminator.kind {
422                     TerminatorKind::InlineAsm { operands, .. } => match &operands[index] {
423                         InlineAsmOperand::Const { value } => self.validate_operand(value),
424                         _ => bug!(),
425                     },
426                     _ => bug!(),
427                 }
428             }
429         }
430     }
431
432     // FIXME(eddyb) maybe cache this?
433     fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
434         if let TempState::Defined { location: loc, .. } = self.temps[local] {
435             let num_stmts = self.body[loc.block].statements.len();
436
437             if loc.statement_index < num_stmts {
438                 let statement = &self.body[loc.block].statements[loc.statement_index];
439                 match &statement.kind {
440                     StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
441                         &self.ccx,
442                         &mut |l| self.qualif_local::<Q>(l),
443                         rhs,
444                     ),
445                     _ => {
446                         span_bug!(
447                             statement.source_info.span,
448                             "{:?} is not an assignment",
449                             statement
450                         );
451                     }
452                 }
453             } else {
454                 let terminator = self.body[loc.block].terminator();
455                 match &terminator.kind {
456                     TerminatorKind::Call { .. } => {
457                         let return_ty = self.body.local_decls[local].ty;
458                         Q::in_any_value_of_ty(&self.ccx, return_ty)
459                     }
460                     kind => {
461                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
462                     }
463                 }
464             }
465         } else {
466             let span = self.body.local_decls[local].source_info.span;
467             span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
468         }
469     }
470
471     // FIXME(eddyb) maybe cache this?
472     fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
473         if let TempState::Defined { location: loc, .. } = self.temps[local] {
474             let num_stmts = self.body[loc.block].statements.len();
475
476             if loc.statement_index < num_stmts {
477                 let statement = &self.body[loc.block].statements[loc.statement_index];
478                 match &statement.kind {
479                     StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
480                     _ => {
481                         span_bug!(
482                             statement.source_info.span,
483                             "{:?} is not an assignment",
484                             statement
485                         );
486                     }
487                 }
488             } else {
489                 let terminator = self.body[loc.block].terminator();
490                 match &terminator.kind {
491                     TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
492                     TerminatorKind::Yield { .. } => Err(Unpromotable),
493                     kind => {
494                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
495                     }
496                 }
497             }
498         } else {
499             Err(Unpromotable)
500         }
501     }
502
503     fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
504         match place {
505             PlaceRef { local, projection: [] } => self.validate_local(local),
506             PlaceRef { local, projection: [proj_base @ .., elem] } => {
507                 // Validate topmost projection, then recurse.
508                 match *elem {
509                     ProjectionElem::Deref => {
510                         let mut promotable = false;
511                         // This is a special treatment for cases like *&STATIC where STATIC is a
512                         // global static variable.
513                         // This pattern is generated only when global static variables are directly
514                         // accessed and is qualified for promotion safely.
515                         if let TempState::Defined { location, .. } = self.temps[local] {
516                             let def_stmt =
517                                 self.body[location.block].statements.get(location.statement_index);
518                             if let Some(Statement {
519                                 kind:
520                                     StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(c)))),
521                                 ..
522                             }) = def_stmt
523                             {
524                                 if let Some(did) = c.check_static_ptr(self.tcx) {
525                                     // Evaluating a promoted may not read statics except if it got
526                                     // promoted from a static (this is a CTFE check). So we
527                                     // can only promote static accesses inside statics.
528                                     if let Some(hir::ConstContext::Static(..)) = self.const_kind {
529                                         // The `is_empty` predicate is introduced to exclude the case
530                                         // where the projection operations are [ .field, * ].
531                                         // The reason is because promotion will be illegal if field
532                                         // accesses precede the dereferencing.
533                                         // Discussion can be found at
534                                         // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
535                                         // There may be opportunity for generalization, but this needs to be
536                                         // accounted for.
537                                         if proj_base.is_empty()
538                                             && !self.tcx.is_thread_local_static(did)
539                                         {
540                                             promotable = true;
541                                         }
542                                     }
543                                 }
544                             }
545                         }
546                         if !promotable {
547                             return Err(Unpromotable);
548                         }
549                     }
550                     ProjectionElem::Downcast(..) => {
551                         return Err(Unpromotable);
552                     }
553
554                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
555
556                     ProjectionElem::Index(local) => {
557                         self.validate_local(local)?;
558                     }
559
560                     ProjectionElem::Field(..) => {
561                         if self.maybe_runtime() {
562                             let base_ty =
563                                 Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
564                             if let Some(def) = base_ty.ty_adt_def() {
565                                 // No promotion of union field accesses.
566                                 if def.is_union() {
567                                     return Err(Unpromotable);
568                                 }
569                             }
570                         }
571                     }
572                 }
573
574                 self.validate_place(PlaceRef { local: place.local, projection: proj_base })
575             }
576         }
577     }
578
579     fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
580         match operand {
581             Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
582
583             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
584             // `validate_rvalue` upon access.
585             Operand::Constant(c) => {
586                 if let Some(def_id) = c.check_static_ptr(self.tcx) {
587                     // Only allow statics (not consts) to refer to other statics.
588                     // FIXME(eddyb) does this matter at all for promotion?
589                     // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
590                     // and in `const` this cannot occur anyway. The only concern is that we might
591                     // promote even `let x = &STATIC` which would be useless, but this applies to
592                     // promotion inside statics as well.
593                     let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
594                     if !is_static {
595                         return Err(Unpromotable);
596                     }
597
598                     let is_thread_local = self.tcx.is_thread_local_static(def_id);
599                     if is_thread_local {
600                         return Err(Unpromotable);
601                     }
602                 }
603
604                 Ok(())
605             }
606         }
607     }
608
609     fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
610         match *rvalue {
611             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
612                 let operand_ty = operand.ty(self.body, self.tcx);
613                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
614                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
615                 match (cast_in, cast_out) {
616                     (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
617                         // ptr-to-int casts are not possible in consts and thus not promotable
618                         return Err(Unpromotable);
619                     }
620                     _ => {}
621                 }
622             }
623
624             Rvalue::BinaryOp(op, ref lhs, _) => {
625                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind() {
626                     assert!(
627                         op == BinOp::Eq
628                             || op == BinOp::Ne
629                             || op == BinOp::Le
630                             || op == BinOp::Lt
631                             || op == BinOp::Ge
632                             || op == BinOp::Gt
633                             || op == BinOp::Offset
634                     );
635
636                     // raw pointer operations are not allowed inside consts and thus not promotable
637                     return Err(Unpromotable);
638                 }
639             }
640
641             Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
642
643             // FIXME(RalfJung): the rest is *implicitly considered promotable*... that seems dangerous.
644             _ => {}
645         }
646
647         match rvalue {
648             Rvalue::ThreadLocalRef(_) => Err(Unpromotable),
649
650             Rvalue::NullaryOp(..) => Ok(()),
651
652             Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
653
654             Rvalue::Use(operand)
655             | Rvalue::Repeat(operand, _)
656             | Rvalue::UnaryOp(_, operand)
657             | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
658
659             Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
660                 self.validate_operand(lhs)?;
661                 self.validate_operand(rhs)
662             }
663
664             Rvalue::AddressOf(_, place) => {
665                 // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
666                 // no problem, only using it is.
667                 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
668                     let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
669                     if let ty::Ref(..) = base_ty.kind() {
670                         return self.validate_place(PlaceRef {
671                             local: place.local,
672                             projection: proj_base,
673                         });
674                     }
675                 }
676                 Err(Unpromotable)
677             }
678
679             Rvalue::Ref(_, kind, place) => {
680                 if let BorrowKind::Mut { .. } = kind {
681                     let ty = place.ty(self.body, self.tcx).ty;
682
683                     // In theory, any zero-sized value could be borrowed
684                     // mutably without consequences. However, only &mut []
685                     // is allowed right now.
686                     if let ty::Array(_, len) = ty.kind() {
687                         match len.try_eval_usize(self.tcx, self.param_env) {
688                             Some(0) => {}
689                             _ => return Err(Unpromotable),
690                         }
691                     } else {
692                         return Err(Unpromotable);
693                     }
694                 }
695
696                 // Special-case reborrows to be more like a copy of the reference.
697                 let mut place = place.as_ref();
698                 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
699                     let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
700                     if let ty::Ref(..) = base_ty.kind() {
701                         place = PlaceRef { local: place.local, projection: proj_base };
702                     }
703                 }
704
705                 self.validate_place(place)?;
706
707                 // HACK(eddyb) this should compute the same thing as
708                 // `<HasMutInterior as Qualif>::in_projection` from
709                 // `check_consts::qualifs` but without recursion.
710                 let mut has_mut_interior =
711                     self.qualif_local::<qualifs::HasMutInterior>(place.local);
712                 if has_mut_interior {
713                     let mut place_projection = place.projection;
714                     // FIXME(eddyb) use a forward loop instead of a reverse one.
715                     while let &[ref proj_base @ .., elem] = place_projection {
716                         // FIXME(eddyb) this is probably excessive, with
717                         // the exception of `union` member accesses.
718                         let ty = Place::ty_from(place.local, proj_base, self.body, self.tcx)
719                             .projection_ty(self.tcx, elem)
720                             .ty;
721                         if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
722                             has_mut_interior = false;
723                             break;
724                         }
725
726                         place_projection = proj_base;
727                     }
728                 }
729                 if has_mut_interior {
730                     return Err(Unpromotable);
731                 }
732
733                 Ok(())
734             }
735
736             Rvalue::Aggregate(_, ref operands) => {
737                 for o in operands {
738                     self.validate_operand(o)?;
739                 }
740
741                 Ok(())
742             }
743         }
744     }
745
746     fn validate_call(
747         &self,
748         callee: &Operand<'tcx>,
749         args: &[Operand<'tcx>],
750     ) -> Result<(), Unpromotable> {
751         let fn_ty = callee.ty(self.body, self.tcx);
752
753         if !self.explicit && self.maybe_runtime() {
754             if let ty::FnDef(def_id, _) = *fn_ty.kind() {
755                 // Never promote runtime `const fn` calls of
756                 // functions without `#[rustc_promotable]`.
757                 if !self.tcx.is_promotable_const_fn(def_id) {
758                     return Err(Unpromotable);
759                 }
760             }
761         }
762
763         let is_const_fn = match *fn_ty.kind() {
764             ty::FnDef(def_id, _) => {
765                 is_const_fn(self.tcx, def_id)
766                     || is_unstable_const_fn(self.tcx, def_id).is_some()
767                     || is_lang_panic_fn(self.tcx, self.def_id.to_def_id())
768             }
769             _ => false,
770         };
771         if !is_const_fn {
772             return Err(Unpromotable);
773         }
774
775         self.validate_operand(callee)?;
776         for arg in args {
777             self.validate_operand(arg)?;
778         }
779
780         Ok(())
781     }
782 }
783
784 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
785 pub fn validate_candidates(
786     ccx: &ConstCx<'_, '_>,
787     temps: &IndexVec<Local, TempState>,
788     candidates: &[Candidate],
789 ) -> Vec<Candidate> {
790     let mut validator = Validator { ccx, temps, explicit: false };
791
792     candidates
793         .iter()
794         .copied()
795         .filter(|&candidate| {
796             validator.explicit = candidate.forces_explicit_promotion();
797
798             // FIXME(eddyb) also emit the errors for shuffle indices
799             // and `#[rustc_args_required_const]` arguments here.
800
801             let is_promotable = validator.validate_candidate(candidate).is_ok();
802
803             // If we use explicit validation, we carry the risk of turning a legitimate run-time
804             // operation into a failing compile-time operation. Make sure that does not happen
805             // by asserting that there is no possible run-time behavior here in case promotion
806             // fails.
807             if validator.explicit && !is_promotable {
808                 ccx.tcx.sess.delay_span_bug(
809                     ccx.body.span,
810                     "Explicit promotion requested, but failed to promote",
811                 );
812             }
813
814             match candidate {
815                 Candidate::Argument { bb, index } | Candidate::InlineAsm { bb, index }
816                     if !is_promotable =>
817                 {
818                     let span = ccx.body[bb].terminator().source_info.span;
819                     let msg = format!("argument {} is required to be a constant", index + 1);
820                     ccx.tcx.sess.span_err(span, &msg);
821                 }
822                 _ => (),
823             }
824
825             is_promotable
826         })
827         .collect()
828 }
829
830 struct Promoter<'a, 'tcx> {
831     tcx: TyCtxt<'tcx>,
832     source: &'a mut Body<'tcx>,
833     promoted: Body<'tcx>,
834     temps: &'a mut IndexVec<Local, TempState>,
835     extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
836
837     /// If true, all nested temps are also kept in the
838     /// source MIR, not moved to the promoted MIR.
839     keep_original: bool,
840 }
841
842 impl<'a, 'tcx> Promoter<'a, 'tcx> {
843     fn new_block(&mut self) -> BasicBlock {
844         let span = self.promoted.span;
845         self.promoted.basic_blocks_mut().push(BasicBlockData {
846             statements: vec![],
847             terminator: Some(Terminator {
848                 source_info: SourceInfo::outermost(span),
849                 kind: TerminatorKind::Return,
850             }),
851             is_cleanup: false,
852         })
853     }
854
855     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
856         let last = self.promoted.basic_blocks().last().unwrap();
857         let data = &mut self.promoted[last];
858         data.statements.push(Statement {
859             source_info: SourceInfo::outermost(span),
860             kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
861         });
862     }
863
864     fn is_temp_kind(&self, local: Local) -> bool {
865         self.source.local_kind(local) == LocalKind::Temp
866     }
867
868     /// Copies the initialization of this temp to the
869     /// promoted MIR, recursing through temps.
870     fn promote_temp(&mut self, temp: Local) -> Local {
871         let old_keep_original = self.keep_original;
872         let loc = match self.temps[temp] {
873             TempState::Defined { location, uses } if uses > 0 => {
874                 if uses > 1 {
875                     self.keep_original = true;
876                 }
877                 location
878             }
879             state => {
880                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
881             }
882         };
883         if !self.keep_original {
884             self.temps[temp] = TempState::PromotedOut;
885         }
886
887         let num_stmts = self.source[loc.block].statements.len();
888         let new_temp = self.promoted.local_decls.push(LocalDecl::new(
889             self.source.local_decls[temp].ty,
890             self.source.local_decls[temp].source_info.span,
891         ));
892
893         debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
894
895         // First, take the Rvalue or Call out of the source MIR,
896         // or duplicate it, depending on keep_original.
897         if loc.statement_index < num_stmts {
898             let (mut rvalue, source_info) = {
899                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
900                 let rhs = match statement.kind {
901                     StatementKind::Assign(box (_, ref mut rhs)) => rhs,
902                     _ => {
903                         span_bug!(
904                             statement.source_info.span,
905                             "{:?} is not an assignment",
906                             statement
907                         );
908                     }
909                 };
910
911                 (
912                     if self.keep_original {
913                         rhs.clone()
914                     } else {
915                         let unit = Rvalue::Use(Operand::Constant(box Constant {
916                             span: statement.source_info.span,
917                             user_ty: None,
918                             literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit),
919                         }));
920                         mem::replace(rhs, unit)
921                     },
922                     statement.source_info,
923                 )
924             };
925
926             self.visit_rvalue(&mut rvalue, loc);
927             self.assign(new_temp, rvalue, source_info.span);
928         } else {
929             let terminator = if self.keep_original {
930                 self.source[loc.block].terminator().clone()
931             } else {
932                 let terminator = self.source[loc.block].terminator_mut();
933                 let target = match terminator.kind {
934                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
935                     ref kind => {
936                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
937                     }
938                 };
939                 Terminator {
940                     source_info: terminator.source_info,
941                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
942                 }
943             };
944
945             match terminator.kind {
946                 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
947                     self.visit_operand(&mut func, loc);
948                     for arg in &mut args {
949                         self.visit_operand(arg, loc);
950                     }
951
952                     let last = self.promoted.basic_blocks().last().unwrap();
953                     let new_target = self.new_block();
954
955                     *self.promoted[last].terminator_mut() = Terminator {
956                         kind: TerminatorKind::Call {
957                             func,
958                             args,
959                             cleanup: None,
960                             destination: Some((Place::from(new_temp), new_target)),
961                             from_hir_call,
962                             fn_span,
963                         },
964                         ..terminator
965                     };
966                 }
967                 ref kind => {
968                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
969                 }
970             };
971         };
972
973         self.keep_original = old_keep_original;
974         new_temp
975     }
976
977     fn promote_candidate(
978         mut self,
979         def: ty::WithOptConstParam<DefId>,
980         candidate: Candidate,
981         next_promoted_id: usize,
982     ) -> Option<Body<'tcx>> {
983         let mut rvalue = {
984             let promoted = &mut self.promoted;
985             let promoted_id = Promoted::new(next_promoted_id);
986             let tcx = self.tcx;
987             let mut promoted_operand = |ty, span| {
988                 promoted.span = span;
989                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
990
991                 Operand::Constant(Box::new(Constant {
992                     span,
993                     user_ty: None,
994                     literal: tcx.mk_const(ty::Const {
995                         ty,
996                         val: ty::ConstKind::Unevaluated(
997                             def,
998                             InternalSubsts::for_item(tcx, def.did, |param, _| {
999                                 if let ty::GenericParamDefKind::Lifetime = param.kind {
1000                                     tcx.lifetimes.re_erased.into()
1001                                 } else {
1002                                     tcx.mk_param_from_def(param)
1003                                 }
1004                             }),
1005                             Some(promoted_id),
1006                         ),
1007                     }),
1008                 }))
1009             };
1010             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
1011             match candidate {
1012                 Candidate::Ref(loc) => {
1013                     let statement = &mut blocks[loc.block].statements[loc.statement_index];
1014                     match statement.kind {
1015                         StatementKind::Assign(box (
1016                             _,
1017                             Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
1018                         )) => {
1019                             // Use the underlying local for this (necessarily interior) borrow.
1020                             let ty = local_decls.local_decls()[place.local].ty;
1021                             let span = statement.source_info.span;
1022
1023                             let ref_ty = tcx.mk_ref(
1024                                 tcx.lifetimes.re_erased,
1025                                 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
1026                             );
1027
1028                             *region = tcx.lifetimes.re_erased;
1029
1030                             let mut projection = vec![PlaceElem::Deref];
1031                             projection.extend(place.projection);
1032                             place.projection = tcx.intern_place_elems(&projection);
1033
1034                             // Create a temp to hold the promoted reference.
1035                             // This is because `*r` requires `r` to be a local,
1036                             // otherwise we would use the `promoted` directly.
1037                             let mut promoted_ref = LocalDecl::new(ref_ty, span);
1038                             promoted_ref.source_info = statement.source_info;
1039                             let promoted_ref = local_decls.push(promoted_ref);
1040                             assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
1041
1042                             let promoted_ref_statement = Statement {
1043                                 source_info: statement.source_info,
1044                                 kind: StatementKind::Assign(Box::new((
1045                                     Place::from(promoted_ref),
1046                                     Rvalue::Use(promoted_operand(ref_ty, span)),
1047                                 ))),
1048                             };
1049                             self.extra_statements.push((loc, promoted_ref_statement));
1050
1051                             Rvalue::Ref(
1052                                 tcx.lifetimes.re_erased,
1053                                 borrow_kind,
1054                                 Place {
1055                                     local: mem::replace(&mut place.local, promoted_ref),
1056                                     projection: List::empty(),
1057                                 },
1058                             )
1059                         }
1060                         _ => bug!(),
1061                     }
1062                 }
1063                 Candidate::Repeat(loc) => {
1064                     let statement = &mut blocks[loc.block].statements[loc.statement_index];
1065                     match statement.kind {
1066                         StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
1067                             let ty = operand.ty(local_decls, self.tcx);
1068                             let span = statement.source_info.span;
1069
1070                             Rvalue::Use(mem::replace(operand, promoted_operand(ty, span)))
1071                         }
1072                         _ => bug!(),
1073                     }
1074                 }
1075                 Candidate::Argument { bb, index } => {
1076                     let terminator = blocks[bb].terminator_mut();
1077                     match terminator.kind {
1078                         TerminatorKind::Call { ref mut args, .. } => {
1079                             let ty = args[index].ty(local_decls, self.tcx);
1080                             let span = terminator.source_info.span;
1081
1082                             Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
1083                         }
1084                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
1085                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1086                         // we are seeing a `Goto`. That means that the `promote_temps` method
1087                         // already promoted this call away entirely. This case occurs when calling
1088                         // a function requiring a constant argument and as that constant value
1089                         // providing a value whose computation contains another call to a function
1090                         // requiring a constant argument.
1091                         TerminatorKind::Goto { .. } => return None,
1092                         _ => bug!(),
1093                     }
1094                 }
1095                 Candidate::InlineAsm { bb, index } => {
1096                     let terminator = blocks[bb].terminator_mut();
1097                     match terminator.kind {
1098                         TerminatorKind::InlineAsm { ref mut operands, .. } => {
1099                             match &mut operands[index] {
1100                                 InlineAsmOperand::Const { ref mut value } => {
1101                                     let ty = value.ty(local_decls, self.tcx);
1102                                     let span = terminator.source_info.span;
1103
1104                                     Rvalue::Use(mem::replace(value, promoted_operand(ty, span)))
1105                                 }
1106                                 _ => bug!(),
1107                             }
1108                         }
1109
1110                         _ => bug!(),
1111                     }
1112                 }
1113             }
1114         };
1115
1116         assert_eq!(self.new_block(), START_BLOCK);
1117         self.visit_rvalue(
1118             &mut rvalue,
1119             Location { block: BasicBlock::new(0), statement_index: usize::MAX },
1120         );
1121
1122         let span = self.promoted.span;
1123         self.assign(RETURN_PLACE, rvalue, span);
1124         Some(self.promoted)
1125     }
1126 }
1127
1128 /// Replaces all temporaries with their promoted counterparts.
1129 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1130     fn tcx(&self) -> TyCtxt<'tcx> {
1131         self.tcx
1132     }
1133
1134     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
1135         if self.is_temp_kind(*local) {
1136             *local = self.promote_temp(*local);
1137         }
1138     }
1139 }
1140
1141 pub fn promote_candidates<'tcx>(
1142     def: ty::WithOptConstParam<DefId>,
1143     body: &mut Body<'tcx>,
1144     tcx: TyCtxt<'tcx>,
1145     mut temps: IndexVec<Local, TempState>,
1146     candidates: Vec<Candidate>,
1147 ) -> IndexVec<Promoted, Body<'tcx>> {
1148     // Visit candidates in reverse, in case they're nested.
1149     debug!("promote_candidates({:?})", candidates);
1150
1151     let mut promotions = IndexVec::new();
1152
1153     let mut extra_statements = vec![];
1154     for candidate in candidates.into_iter().rev() {
1155         match candidate {
1156             Candidate::Repeat(Location { block, statement_index })
1157             | Candidate::Ref(Location { block, statement_index }) => {
1158                 if let StatementKind::Assign(box (place, _)) =
1159                     &body[block].statements[statement_index].kind
1160                 {
1161                     if let Some(local) = place.as_local() {
1162                         if temps[local] == TempState::PromotedOut {
1163                             // Already promoted.
1164                             continue;
1165                         }
1166                     }
1167                 }
1168             }
1169             Candidate::Argument { .. } | Candidate::InlineAsm { .. } => {}
1170         }
1171
1172         // Declare return place local so that `mir::Body::new` doesn't complain.
1173         let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1174
1175         let mut promoted = Body::new(
1176             IndexVec::new(),
1177             // FIXME: maybe try to filter this to avoid blowing up
1178             // memory usage?
1179             body.source_scopes.clone(),
1180             initial_locals,
1181             IndexVec::new(),
1182             0,
1183             vec![],
1184             body.span,
1185             body.generator_kind,
1186         );
1187         promoted.ignore_interior_mut_in_const_validation = true;
1188
1189         let promoter = Promoter {
1190             promoted,
1191             tcx,
1192             source: body,
1193             temps: &mut temps,
1194             extra_statements: &mut extra_statements,
1195             keep_original: false,
1196         };
1197
1198         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1199         if let Some(promoted) = promoter.promote_candidate(def, candidate, promotions.len()) {
1200             promotions.push(promoted);
1201         }
1202     }
1203
1204     // Insert each of `extra_statements` before its indicated location, which
1205     // has to be done in reverse location order, to not invalidate the rest.
1206     extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1207     for (loc, statement) in extra_statements {
1208         body[loc.block].statements.insert(loc.statement_index, statement);
1209     }
1210
1211     // Eliminate assignments to, and drops of promoted temps.
1212     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1213     for block in body.basic_blocks_mut() {
1214         block.statements.retain(|statement| match &statement.kind {
1215             StatementKind::Assign(box (place, _)) => {
1216                 if let Some(index) = place.as_local() {
1217                     !promoted(index)
1218                 } else {
1219                     true
1220                 }
1221             }
1222             StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1223                 !promoted(*index)
1224             }
1225             _ => true,
1226         });
1227         let terminator = block.terminator_mut();
1228         if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1229             if let Some(index) = place.as_local() {
1230                 if promoted(index) {
1231                     terminator.kind = TerminatorKind::Goto { target: *target };
1232                 }
1233             }
1234         }
1235     }
1236
1237     promotions
1238 }
1239
1240 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1241 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1242 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1243 /// enabled.
1244 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1245     ccx: &ConstCx<'_, 'tcx>,
1246     operand: &Operand<'tcx>,
1247 ) -> bool {
1248     let mut rpo = traversal::reverse_postorder(&ccx.body);
1249     let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo);
1250     let validator = Validator { ccx, temps: &temps, explicit: false };
1251
1252     let should_promote = validator.validate_operand(operand).is_ok();
1253     let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions;
1254     debug!(
1255         "should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \
1256             should_promote={:?} feature_flag={:?}",
1257         validator.ccx.def_id, should_promote, feature_flag
1258     );
1259     should_promote && !feature_flag
1260 }