]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/transform/promote_consts.rs
Auto merge of #106925 - imWildCat:imWildCat/remove-hardcoded-ios-macbi-target-version...
[rust.git] / compiler / rustc_const_eval / 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_hir as hir;
16 use rustc_middle::mir;
17 use rustc_middle::mir::traversal::ReversePostorderIter;
18 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::subst::InternalSubsts;
21 use rustc_middle::ty::{self, List, TyCtxt, TypeVisitable};
22 use rustc_span::Span;
23
24 use rustc_index::vec::{Idx, IndexVec};
25
26 use std::cell::Cell;
27 use std::{cmp, iter, mem};
28
29 use crate::transform::check_consts::{qualifs, ConstCx};
30
31 /// A `MirPass` for promotion.
32 ///
33 /// Promotion is the extraction of promotable temps into separate MIR bodies so they can have
34 /// `'static` lifetime.
35 ///
36 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
37 /// newly created `Constant`.
38 #[derive(Default)]
39 pub struct PromoteTemps<'tcx> {
40     pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
41 }
42
43 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
44     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
45         // There's not really any point in promoting errorful MIR.
46         //
47         // This does not include MIR that failed const-checking, which we still try to promote.
48         if let Err(_) = body.return_ty().error_reported() {
49             debug!("PromoteTemps: MIR had errors");
50             return;
51         }
52         if body.source.promoted.is_some() {
53             return;
54         }
55
56         let mut rpo = traversal::reverse_postorder(body);
57         let ccx = ConstCx::new(tcx, body);
58         let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
59
60         let promotable_candidates = validate_candidates(&ccx, &mut temps, &all_candidates);
61
62         let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
63         self.promoted_fragments.set(promoted);
64     }
65 }
66
67 /// State of a temporary during collection and promotion.
68 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
69 pub enum TempState {
70     /// No references to this temp.
71     Undefined,
72     /// One direct assignment and any number of direct uses.
73     /// A borrow of this temp is promotable if the assigned
74     /// value is qualified as constant.
75     Defined { location: Location, uses: usize, valid: Result<(), ()> },
76     /// Any other combination of assignments/uses.
77     Unpromotable,
78     /// This temp was part of an rvalue which got extracted
79     /// during promotion and needs cleanup.
80     PromotedOut,
81 }
82
83 impl TempState {
84     pub fn is_promotable(&self) -> bool {
85         debug!("is_promotable: self={:?}", self);
86         matches!(self, TempState::Defined { .. })
87     }
88 }
89
90 /// A "root candidate" for promotion, which will become the
91 /// returned value in a promoted MIR, unless it's a subset
92 /// of a larger candidate.
93 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
94 pub struct Candidate {
95     location: Location,
96 }
97
98 struct Collector<'a, 'tcx> {
99     ccx: &'a ConstCx<'a, 'tcx>,
100     temps: IndexVec<Local, TempState>,
101     candidates: Vec<Candidate>,
102 }
103
104 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
105     fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
106         debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
107         // We're only interested in temporaries and the return place
108         match self.ccx.body.local_kind(index) {
109             LocalKind::Temp | LocalKind::ReturnPointer => {}
110             LocalKind::Arg | LocalKind::Var => return,
111         }
112
113         // Ignore drops, if the temp gets promoted,
114         // then it's constant and thus drop is noop.
115         // Non-uses are also irrelevant.
116         if context.is_drop() || !context.is_use() {
117             debug!(
118                 "visit_local: context.is_drop={:?} context.is_use={:?}",
119                 context.is_drop(),
120                 context.is_use(),
121             );
122             return;
123         }
124
125         let temp = &mut self.temps[index];
126         debug!("visit_local: temp={:?}", temp);
127         if *temp == TempState::Undefined {
128             match context {
129                 PlaceContext::MutatingUse(MutatingUseContext::Store)
130                 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
131                     *temp = TempState::Defined { location, uses: 0, valid: Err(()) };
132                     return;
133                 }
134                 _ => { /* mark as unpromotable below */ }
135             }
136         } else if let TempState::Defined { uses, .. } = temp {
137             // We always allow borrows, even mutable ones, as we need
138             // to promote mutable borrows of some ZSTs e.g., `&mut []`.
139             let allowed_use = match context {
140                 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
141                 | PlaceContext::NonMutatingUse(_) => true,
142                 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
143             };
144             debug!("visit_local: allowed_use={:?}", allowed_use);
145             if allowed_use {
146                 *uses += 1;
147                 return;
148             }
149             /* mark as unpromotable below */
150         }
151         *temp = TempState::Unpromotable;
152     }
153
154     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
155         self.super_rvalue(rvalue, location);
156
157         match *rvalue {
158             Rvalue::Ref(..) => {
159                 self.candidates.push(Candidate { location });
160             }
161             _ => {}
162         }
163     }
164 }
165
166 pub fn collect_temps_and_candidates<'tcx>(
167     ccx: &ConstCx<'_, 'tcx>,
168     rpo: &mut ReversePostorderIter<'_, 'tcx>,
169 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
170     let mut collector = Collector {
171         temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
172         candidates: vec![],
173         ccx,
174     };
175     for (bb, data) in rpo {
176         collector.visit_basic_block_data(bb, data);
177     }
178     (collector.temps, collector.candidates)
179 }
180
181 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
182 ///
183 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
184 struct Validator<'a, 'tcx> {
185     ccx: &'a ConstCx<'a, 'tcx>,
186     temps: &'a mut IndexVec<Local, TempState>,
187 }
188
189 impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
190     type Target = ConstCx<'a, 'tcx>;
191
192     fn deref(&self) -> &Self::Target {
193         &self.ccx
194     }
195 }
196
197 struct Unpromotable;
198
199 impl<'tcx> Validator<'_, 'tcx> {
200     fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
201         let loc = candidate.location;
202         let statement = &self.body[loc.block].statements[loc.statement_index];
203         match &statement.kind {
204             StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
205                 // We can only promote interior borrows of promotable temps (non-temps
206                 // don't get promoted anyway).
207                 self.validate_local(place.local)?;
208
209                 // The reference operation itself must be promotable.
210                 // (Needs to come after `validate_local` to avoid ICEs.)
211                 self.validate_ref(*kind, place)?;
212
213                 // We do not check all the projections (they do not get promoted anyway),
214                 // but we do stay away from promoting anything involving a dereference.
215                 if place.projection.contains(&ProjectionElem::Deref) {
216                     return Err(Unpromotable);
217                 }
218
219                 Ok(())
220             }
221             _ => bug!(),
222         }
223     }
224
225     // FIXME(eddyb) maybe cache this?
226     fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
227         if let TempState::Defined { location: loc, .. } = self.temps[local] {
228             let num_stmts = self.body[loc.block].statements.len();
229
230             if loc.statement_index < num_stmts {
231                 let statement = &self.body[loc.block].statements[loc.statement_index];
232                 match &statement.kind {
233                     StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
234                         &self.ccx,
235                         &mut |l| self.qualif_local::<Q>(l),
236                         rhs,
237                     ),
238                     _ => {
239                         span_bug!(
240                             statement.source_info.span,
241                             "{:?} is not an assignment",
242                             statement
243                         );
244                     }
245                 }
246             } else {
247                 let terminator = self.body[loc.block].terminator();
248                 match &terminator.kind {
249                     TerminatorKind::Call { .. } => {
250                         let return_ty = self.body.local_decls[local].ty;
251                         Q::in_any_value_of_ty(&self.ccx, return_ty)
252                     }
253                     kind => {
254                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
255                     }
256                 }
257             }
258         } else {
259             false
260         }
261     }
262
263     fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
264         if let TempState::Defined { location: loc, uses, valid } = self.temps[local] {
265             // We cannot promote things that need dropping, since the promoted value
266             // would not get dropped.
267             if self.qualif_local::<qualifs::NeedsDrop>(local) {
268                 return Err(Unpromotable);
269             }
270             valid.or_else(|_| {
271                 let ok = {
272                     let block = &self.body[loc.block];
273                     let num_stmts = block.statements.len();
274
275                     if loc.statement_index < num_stmts {
276                         let statement = &block.statements[loc.statement_index];
277                         match &statement.kind {
278                             StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
279                             _ => {
280                                 span_bug!(
281                                     statement.source_info.span,
282                                     "{:?} is not an assignment",
283                                     statement
284                                 );
285                             }
286                         }
287                     } else {
288                         let terminator = block.terminator();
289                         match &terminator.kind {
290                             TerminatorKind::Call { func, args, .. } => {
291                                 self.validate_call(func, args)
292                             }
293                             TerminatorKind::Yield { .. } => Err(Unpromotable),
294                             kind => {
295                                 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
296                             }
297                         }
298                     }
299                 };
300                 self.temps[local] = match ok {
301                     Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
302                     Err(_) => TempState::Unpromotable,
303                 };
304                 ok
305             })
306         } else {
307             Err(Unpromotable)
308         }
309     }
310
311     fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
312         match place.last_projection() {
313             None => self.validate_local(place.local),
314             Some((place_base, elem)) => {
315                 // Validate topmost projection, then recurse.
316                 match elem {
317                     ProjectionElem::Deref => {
318                         let mut promotable = false;
319                         // When a static is used by-value, that gets desugared to `*STATIC_ADDR`,
320                         // and we need to be able to promote this. So check if this deref matches
321                         // that specific pattern.
322
323                         // We need to make sure this is a `Deref` of a local with no further projections.
324                         // Discussion can be found at
325                         // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
326                         if let Some(local) = place_base.as_local() {
327                             if let TempState::Defined { location, .. } = self.temps[local] {
328                                 let def_stmt = self.body[location.block]
329                                     .statements
330                                     .get(location.statement_index);
331                                 if let Some(Statement {
332                                     kind:
333                                         StatementKind::Assign(box (
334                                             _,
335                                             Rvalue::Use(Operand::Constant(c)),
336                                         )),
337                                     ..
338                                 }) = def_stmt
339                                 {
340                                     if let Some(did) = c.check_static_ptr(self.tcx) {
341                                         // Evaluating a promoted may not read statics except if it got
342                                         // promoted from a static (this is a CTFE check). So we
343                                         // can only promote static accesses inside statics.
344                                         if let Some(hir::ConstContext::Static(..)) = self.const_kind
345                                         {
346                                             if !self.tcx.is_thread_local_static(did) {
347                                                 promotable = true;
348                                             }
349                                         }
350                                     }
351                                 }
352                             }
353                         }
354                         if !promotable {
355                             return Err(Unpromotable);
356                         }
357                     }
358                     ProjectionElem::OpaqueCast(..) | ProjectionElem::Downcast(..) => {
359                         return Err(Unpromotable);
360                     }
361
362                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
363
364                     ProjectionElem::Index(local) => {
365                         let mut promotable = false;
366                         // Only accept if we can predict the index and are indexing an array.
367                         let val =
368                             if let TempState::Defined { location: loc, .. } = self.temps[local] {
369                                 let block = &self.body[loc.block];
370                                 if loc.statement_index < block.statements.len() {
371                                     let statement = &block.statements[loc.statement_index];
372                                     match &statement.kind {
373                                         StatementKind::Assign(box (
374                                             _,
375                                             Rvalue::Use(Operand::Constant(c)),
376                                         )) => c.literal.try_eval_usize(self.tcx, self.param_env),
377                                         _ => None,
378                                     }
379                                 } else {
380                                     None
381                                 }
382                             } else {
383                                 None
384                             };
385                         if let Some(idx) = val {
386                             // Determine the type of the thing we are indexing.
387                             let ty = place_base.ty(self.body, self.tcx).ty;
388                             match ty.kind() {
389                                 ty::Array(_, len) => {
390                                     // It's an array; determine its length.
391                                     if let Some(len) = len.try_eval_usize(self.tcx, self.param_env)
392                                     {
393                                         // If the index is in-bounds, go ahead.
394                                         if idx < len {
395                                             promotable = true;
396                                         }
397                                     }
398                                 }
399                                 _ => {}
400                             }
401                         }
402                         if !promotable {
403                             return Err(Unpromotable);
404                         }
405
406                         self.validate_local(local)?;
407                     }
408
409                     ProjectionElem::Field(..) => {
410                         let base_ty = place_base.ty(self.body, self.tcx).ty;
411                         if base_ty.is_union() {
412                             // No promotion of union field accesses.
413                             return Err(Unpromotable);
414                         }
415                     }
416                 }
417
418                 self.validate_place(place_base)
419             }
420         }
421     }
422
423     fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
424         match operand {
425             Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
426
427             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
428             // `validate_rvalue` upon access.
429             Operand::Constant(c) => {
430                 if let Some(def_id) = c.check_static_ptr(self.tcx) {
431                     // Only allow statics (not consts) to refer to other statics.
432                     // FIXME(eddyb) does this matter at all for promotion?
433                     // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
434                     // and in `const` this cannot occur anyway. The only concern is that we might
435                     // promote even `let x = &STATIC` which would be useless, but this applies to
436                     // promotion inside statics as well.
437                     let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
438                     if !is_static {
439                         return Err(Unpromotable);
440                     }
441
442                     let is_thread_local = self.tcx.is_thread_local_static(def_id);
443                     if is_thread_local {
444                         return Err(Unpromotable);
445                     }
446                 }
447
448                 Ok(())
449             }
450         }
451     }
452
453     fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
454         match kind {
455             // Reject these borrow types just to be safe.
456             // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase.
457             BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
458
459             BorrowKind::Shared => {
460                 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
461                 if has_mut_interior {
462                     return Err(Unpromotable);
463                 }
464             }
465
466             BorrowKind::Mut { .. } => {
467                 let ty = place.ty(self.body, self.tcx).ty;
468
469                 // In theory, any zero-sized value could be borrowed
470                 // mutably without consequences. However, only &mut []
471                 // is allowed right now.
472                 if let ty::Array(_, len) = ty.kind() {
473                     match len.try_eval_usize(self.tcx, self.param_env) {
474                         Some(0) => {}
475                         _ => return Err(Unpromotable),
476                     }
477                 } else {
478                     return Err(Unpromotable);
479                 }
480             }
481         }
482
483         Ok(())
484     }
485
486     fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
487         match rvalue {
488             Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => {
489                 self.validate_operand(operand)?;
490             }
491             Rvalue::CopyForDeref(place) => {
492                 let op = &Operand::Copy(*place);
493                 self.validate_operand(op)?
494             }
495
496             Rvalue::Discriminant(place) | Rvalue::Len(place) => {
497                 self.validate_place(place.as_ref())?
498             }
499
500             Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
501
502             // ptr-to-int casts are not possible in consts and thus not promotable
503             Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => return Err(Unpromotable),
504
505             // all other casts including int-to-ptr casts are fine, they just use the integer value
506             // at pointer type.
507             Rvalue::Cast(_, operand, _) => {
508                 self.validate_operand(operand)?;
509             }
510
511             Rvalue::NullaryOp(op, _) => match op {
512                 NullOp::SizeOf => {}
513                 NullOp::AlignOf => {}
514             },
515
516             Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),
517
518             Rvalue::UnaryOp(op, operand) => {
519                 match op {
520                     // These operations can never fail.
521                     UnOp::Neg | UnOp::Not => {}
522                 }
523
524                 self.validate_operand(operand)?;
525             }
526
527             Rvalue::BinaryOp(op, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(op, box (lhs, rhs)) => {
528                 let op = *op;
529                 let lhs_ty = lhs.ty(self.body, self.tcx);
530
531                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs_ty.kind() {
532                     // Raw and fn pointer operations are not allowed inside consts and thus not promotable.
533                     assert!(matches!(
534                         op,
535                         BinOp::Eq
536                             | BinOp::Ne
537                             | BinOp::Le
538                             | BinOp::Lt
539                             | BinOp::Ge
540                             | BinOp::Gt
541                             | BinOp::Offset
542                     ));
543                     return Err(Unpromotable);
544                 }
545
546                 match op {
547                     BinOp::Div | BinOp::Rem => {
548                         if lhs_ty.is_integral() {
549                             // Integer division: the RHS must be a non-zero const.
550                             let const_val = match rhs {
551                                 Operand::Constant(c) => {
552                                     c.literal.try_eval_bits(self.tcx, self.param_env, lhs_ty)
553                                 }
554                                 _ => None,
555                             };
556                             match const_val {
557                                 Some(x) if x != 0 => {}        // okay
558                                 _ => return Err(Unpromotable), // value not known or 0 -- not okay
559                             }
560                         }
561                     }
562                     // The remaining operations can never fail.
563                     BinOp::Eq
564                     | BinOp::Ne
565                     | BinOp::Le
566                     | BinOp::Lt
567                     | BinOp::Ge
568                     | BinOp::Gt
569                     | BinOp::Offset
570                     | BinOp::Add
571                     | BinOp::Sub
572                     | BinOp::Mul
573                     | BinOp::BitXor
574                     | BinOp::BitAnd
575                     | BinOp::BitOr
576                     | BinOp::Shl
577                     | BinOp::Shr => {}
578                 }
579
580                 self.validate_operand(lhs)?;
581                 self.validate_operand(rhs)?;
582             }
583
584             Rvalue::AddressOf(_, place) => {
585                 // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
586                 // no problem, only using it is.
587                 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
588                 {
589                     let base_ty = place_base.ty(self.body, self.tcx).ty;
590                     if let ty::Ref(..) = base_ty.kind() {
591                         return self.validate_place(place_base);
592                     }
593                 }
594                 return Err(Unpromotable);
595             }
596
597             Rvalue::Ref(_, kind, place) => {
598                 // Special-case reborrows to be more like a copy of the reference.
599                 let mut place_simplified = place.as_ref();
600                 if let Some((place_base, ProjectionElem::Deref)) =
601                     place_simplified.last_projection()
602                 {
603                     let base_ty = place_base.ty(self.body, self.tcx).ty;
604                     if let ty::Ref(..) = base_ty.kind() {
605                         place_simplified = place_base;
606                     }
607                 }
608
609                 self.validate_place(place_simplified)?;
610
611                 // Check that the reference is fine (using the original place!).
612                 // (Needs to come after `validate_place` to avoid ICEs.)
613                 self.validate_ref(*kind, place)?;
614             }
615
616             Rvalue::Aggregate(_, operands) => {
617                 for o in operands {
618                     self.validate_operand(o)?;
619                 }
620             }
621         }
622
623         Ok(())
624     }
625
626     fn validate_call(
627         &mut self,
628         callee: &Operand<'tcx>,
629         args: &[Operand<'tcx>],
630     ) -> Result<(), Unpromotable> {
631         let fn_ty = callee.ty(self.body, self.tcx);
632
633         // Inside const/static items, we promote all (eligible) function calls.
634         // Everywhere else, we require `#[rustc_promotable]` on the callee.
635         let promote_all_const_fn = matches!(
636             self.const_kind,
637             Some(hir::ConstContext::Static(_) | hir::ConstContext::Const)
638         );
639         if !promote_all_const_fn {
640             if let ty::FnDef(def_id, _) = *fn_ty.kind() {
641                 // Never promote runtime `const fn` calls of
642                 // functions without `#[rustc_promotable]`.
643                 if !self.tcx.is_promotable_const_fn(def_id) {
644                     return Err(Unpromotable);
645                 }
646             }
647         }
648
649         let is_const_fn = match *fn_ty.kind() {
650             ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id),
651             _ => false,
652         };
653         if !is_const_fn {
654             return Err(Unpromotable);
655         }
656
657         self.validate_operand(callee)?;
658         for arg in args {
659             self.validate_operand(arg)?;
660         }
661
662         Ok(())
663     }
664 }
665
666 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
667 pub fn validate_candidates(
668     ccx: &ConstCx<'_, '_>,
669     temps: &mut IndexVec<Local, TempState>,
670     candidates: &[Candidate],
671 ) -> Vec<Candidate> {
672     let mut validator = Validator { ccx, temps };
673
674     candidates
675         .iter()
676         .copied()
677         .filter(|&candidate| validator.validate_candidate(candidate).is_ok())
678         .collect()
679 }
680
681 struct Promoter<'a, 'tcx> {
682     tcx: TyCtxt<'tcx>,
683     source: &'a mut Body<'tcx>,
684     promoted: Body<'tcx>,
685     temps: &'a mut IndexVec<Local, TempState>,
686     extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
687
688     /// If true, all nested temps are also kept in the
689     /// source MIR, not moved to the promoted MIR.
690     keep_original: bool,
691 }
692
693 impl<'a, 'tcx> Promoter<'a, 'tcx> {
694     fn new_block(&mut self) -> BasicBlock {
695         let span = self.promoted.span;
696         self.promoted.basic_blocks_mut().push(BasicBlockData {
697             statements: vec![],
698             terminator: Some(Terminator {
699                 source_info: SourceInfo::outermost(span),
700                 kind: TerminatorKind::Return,
701             }),
702             is_cleanup: false,
703         })
704     }
705
706     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
707         let last = self.promoted.basic_blocks.last().unwrap();
708         let data = &mut self.promoted[last];
709         data.statements.push(Statement {
710             source_info: SourceInfo::outermost(span),
711             kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
712         });
713     }
714
715     fn is_temp_kind(&self, local: Local) -> bool {
716         self.source.local_kind(local) == LocalKind::Temp
717     }
718
719     /// Copies the initialization of this temp to the
720     /// promoted MIR, recursing through temps.
721     fn promote_temp(&mut self, temp: Local) -> Local {
722         let old_keep_original = self.keep_original;
723         let loc = match self.temps[temp] {
724             TempState::Defined { location, uses, .. } if uses > 0 => {
725                 if uses > 1 {
726                     self.keep_original = true;
727                 }
728                 location
729             }
730             state => {
731                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
732             }
733         };
734         if !self.keep_original {
735             self.temps[temp] = TempState::PromotedOut;
736         }
737
738         let num_stmts = self.source[loc.block].statements.len();
739         let new_temp = self.promoted.local_decls.push(LocalDecl::new(
740             self.source.local_decls[temp].ty,
741             self.source.local_decls[temp].source_info.span,
742         ));
743
744         debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
745
746         // First, take the Rvalue or Call out of the source MIR,
747         // or duplicate it, depending on keep_original.
748         if loc.statement_index < num_stmts {
749             let (mut rvalue, source_info) = {
750                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
751                 let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else {
752                     span_bug!(
753                         statement.source_info.span,
754                         "{:?} is not an assignment",
755                         statement
756                     );
757                 };
758
759                 (
760                     if self.keep_original {
761                         rhs.clone()
762                     } else {
763                         let unit = Rvalue::Use(Operand::Constant(Box::new(Constant {
764                             span: statement.source_info.span,
765                             user_ty: None,
766                             literal: ConstantKind::zero_sized(self.tcx.types.unit),
767                         })));
768                         mem::replace(rhs, unit)
769                     },
770                     statement.source_info,
771                 )
772             };
773
774             self.visit_rvalue(&mut rvalue, loc);
775             self.assign(new_temp, rvalue, source_info.span);
776         } else {
777             let terminator = if self.keep_original {
778                 self.source[loc.block].terminator().clone()
779             } else {
780                 let terminator = self.source[loc.block].terminator_mut();
781                 let target = match &terminator.kind {
782                     TerminatorKind::Call { target: Some(target), .. } => *target,
783                     kind => {
784                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
785                     }
786                 };
787                 Terminator {
788                     source_info: terminator.source_info,
789                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
790                 }
791             };
792
793             match terminator.kind {
794                 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
795                     self.visit_operand(&mut func, loc);
796                     for arg in &mut args {
797                         self.visit_operand(arg, loc);
798                     }
799
800                     let last = self.promoted.basic_blocks.last().unwrap();
801                     let new_target = self.new_block();
802
803                     *self.promoted[last].terminator_mut() = Terminator {
804                         kind: TerminatorKind::Call {
805                             func,
806                             args,
807                             cleanup: None,
808                             destination: Place::from(new_temp),
809                             target: Some(new_target),
810                             from_hir_call,
811                             fn_span,
812                         },
813                         source_info: SourceInfo::outermost(terminator.source_info.span),
814                         ..terminator
815                     };
816                 }
817                 kind => {
818                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
819                 }
820             };
821         };
822
823         self.keep_original = old_keep_original;
824         new_temp
825     }
826
827     fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Body<'tcx> {
828         let def = self.source.source.with_opt_param();
829         let mut rvalue = {
830             let promoted = &mut self.promoted;
831             let promoted_id = Promoted::new(next_promoted_id);
832             let tcx = self.tcx;
833             let mut promoted_operand = |ty, span| {
834                 promoted.span = span;
835                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
836                 let substs = tcx.erase_regions(InternalSubsts::identity_for_item(tcx, def.did));
837                 let uneval = mir::UnevaluatedConst { def, substs, promoted: Some(promoted_id) };
838
839                 Operand::Constant(Box::new(Constant {
840                     span,
841                     user_ty: None,
842                     literal: ConstantKind::Unevaluated(uneval, ty),
843                 }))
844             };
845
846             let blocks = self.source.basic_blocks.as_mut();
847             let local_decls = &mut self.source.local_decls;
848             let loc = candidate.location;
849             let statement = &mut blocks[loc.block].statements[loc.statement_index];
850             let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = &mut statement.kind else {
851                 bug!()
852             };
853
854             // Use the underlying local for this (necessarily interior) borrow.
855             let ty = local_decls[place.local].ty;
856             let span = statement.source_info.span;
857
858             let ref_ty = tcx.mk_ref(
859                 tcx.lifetimes.re_erased,
860                 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
861             );
862
863             *region = tcx.lifetimes.re_erased;
864
865             let mut projection = vec![PlaceElem::Deref];
866             projection.extend(place.projection);
867             place.projection = tcx.intern_place_elems(&projection);
868
869             // Create a temp to hold the promoted reference.
870             // This is because `*r` requires `r` to be a local,
871             // otherwise we would use the `promoted` directly.
872             let mut promoted_ref = LocalDecl::new(ref_ty, span);
873             promoted_ref.source_info = statement.source_info;
874             let promoted_ref = local_decls.push(promoted_ref);
875             assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
876
877             let promoted_ref_statement = Statement {
878                 source_info: statement.source_info,
879                 kind: StatementKind::Assign(Box::new((
880                     Place::from(promoted_ref),
881                     Rvalue::Use(promoted_operand(ref_ty, span)),
882                 ))),
883             };
884             self.extra_statements.push((loc, promoted_ref_statement));
885
886             Rvalue::Ref(
887                 tcx.lifetimes.re_erased,
888                 *borrow_kind,
889                 Place {
890                     local: mem::replace(&mut place.local, promoted_ref),
891                     projection: List::empty(),
892                 },
893             )
894         };
895
896         assert_eq!(self.new_block(), START_BLOCK);
897         self.visit_rvalue(
898             &mut rvalue,
899             Location { block: BasicBlock::new(0), statement_index: usize::MAX },
900         );
901
902         let span = self.promoted.span;
903         self.assign(RETURN_PLACE, rvalue, span);
904         self.promoted
905     }
906 }
907
908 /// Replaces all temporaries with their promoted counterparts.
909 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
910     fn tcx(&self) -> TyCtxt<'tcx> {
911         self.tcx
912     }
913
914     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
915         if self.is_temp_kind(*local) {
916             *local = self.promote_temp(*local);
917         }
918     }
919 }
920
921 pub fn promote_candidates<'tcx>(
922     body: &mut Body<'tcx>,
923     tcx: TyCtxt<'tcx>,
924     mut temps: IndexVec<Local, TempState>,
925     candidates: Vec<Candidate>,
926 ) -> IndexVec<Promoted, Body<'tcx>> {
927     // Visit candidates in reverse, in case they're nested.
928     debug!("promote_candidates({:?})", candidates);
929
930     let mut promotions = IndexVec::new();
931
932     let mut extra_statements = vec![];
933     for candidate in candidates.into_iter().rev() {
934         let Location { block, statement_index } = candidate.location;
935         if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind
936         {
937             if let Some(local) = place.as_local() {
938                 if temps[local] == TempState::PromotedOut {
939                     // Already promoted.
940                     continue;
941                 }
942             }
943         }
944
945         // Declare return place local so that `mir::Body::new` doesn't complain.
946         let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
947
948         let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
949         scope.parent_scope = None;
950
951         let mut promoted = Body::new(
952             body.source, // `promoted` gets filled in below
953             IndexVec::new(),
954             IndexVec::from_elem_n(scope, 1),
955             initial_locals,
956             IndexVec::new(),
957             0,
958             vec![],
959             body.span,
960             body.generator_kind(),
961             body.tainted_by_errors,
962         );
963         promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
964
965         let promoter = Promoter {
966             promoted,
967             tcx,
968             source: body,
969             temps: &mut temps,
970             extra_statements: &mut extra_statements,
971             keep_original: false,
972         };
973
974         let mut promoted = promoter.promote_candidate(candidate, promotions.len());
975         promoted.source.promoted = Some(promotions.next_index());
976         promotions.push(promoted);
977     }
978
979     // Insert each of `extra_statements` before its indicated location, which
980     // has to be done in reverse location order, to not invalidate the rest.
981     extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
982     for (loc, statement) in extra_statements {
983         body[loc.block].statements.insert(loc.statement_index, statement);
984     }
985
986     // Eliminate assignments to, and drops of promoted temps.
987     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
988     for block in body.basic_blocks_mut() {
989         block.statements.retain(|statement| match &statement.kind {
990             StatementKind::Assign(box (place, _)) => {
991                 if let Some(index) = place.as_local() {
992                     !promoted(index)
993                 } else {
994                     true
995                 }
996             }
997             StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
998                 !promoted(*index)
999             }
1000             _ => true,
1001         });
1002         let terminator = block.terminator_mut();
1003         if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1004             if let Some(index) = place.as_local() {
1005                 if promoted(index) {
1006                     terminator.kind = TerminatorKind::Goto { target: *target };
1007                 }
1008             }
1009         }
1010     }
1011
1012     promotions
1013 }
1014
1015 /// This function returns `true` if the function being called in the array
1016 /// repeat expression is a `const` function.
1017 pub fn is_const_fn_in_array_repeat_expression<'tcx>(
1018     ccx: &ConstCx<'_, 'tcx>,
1019     place: &Place<'tcx>,
1020     body: &Body<'tcx>,
1021 ) -> bool {
1022     match place.as_local() {
1023         // rule out cases such as: `let my_var = some_fn(); [my_var; N]`
1024         Some(local) if body.local_decls[local].is_user_variable() => return false,
1025         None => return false,
1026         _ => {}
1027     }
1028
1029     for block in body.basic_blocks.iter() {
1030         if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) =
1031             &block.terminator
1032         {
1033             if let Operand::Constant(box Constant { literal, .. }) = func {
1034                 if let ty::FnDef(def_id, _) = *literal.ty().kind() {
1035                     if destination == place {
1036                         if ccx.tcx.is_const_fn(def_id) {
1037                             return true;
1038                         }
1039                     }
1040                 }
1041             }
1042         }
1043     }
1044
1045     false
1046 }