]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Move capture lowering from THIR to MIR
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_place.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::expr::category::Category;
4 use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
5 use crate::build::{BlockAnd, BlockAndExtension, Builder};
6 use crate::thir::*;
7 use rustc_middle::middle::region;
8 use rustc_middle::mir::AssertKind::BoundsCheck;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
11 use rustc_span::Span;
12
13 use rustc_index::vec::Idx;
14
15 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
16 /// place by pushing more and more projections onto the end, and then convert the final set into a
17 /// place using the `into_place` method.
18 ///
19 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
20 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
21 #[derive(Clone)]
22 struct PlaceBuilder<'tcx> {
23     local: Local,
24     projection: Vec<PlaceElem<'tcx>>,
25 }
26
27 impl<'tcx> PlaceBuilder<'tcx> {
28     fn into_place(self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
29         Place { local: self.local, projection: tcx.intern_place_elems(&self.projection) }
30     }
31
32     fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
33         self.project(PlaceElem::Field(f, ty))
34     }
35
36     fn deref(self) -> Self {
37         self.project(PlaceElem::Deref)
38     }
39
40     fn index(self, index: Local) -> Self {
41         self.project(PlaceElem::Index(index))
42     }
43
44     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
45         self.projection.push(elem);
46         self
47     }
48 }
49
50 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
51     fn from(local: Local) -> Self {
52         Self { local, projection: Vec::new() }
53     }
54 }
55
56 impl<'a, 'tcx> Builder<'a, 'tcx> {
57     /// Compile `expr`, yielding a place that we can move from etc.
58     ///
59     /// WARNING: Any user code might:
60     /// * Invalidate any slice bounds checks performed.
61     /// * Change the address that this `Place` refers to.
62     /// * Modify the memory that this place refers to.
63     /// * Invalidate the memory that this place refers to, this will be caught
64     ///   by borrow checking.
65     ///
66     /// Extra care is needed if any user code is allowed to run between calling
67     /// this method and using it, as is the case for `match` and index
68     /// expressions.
69     crate fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
70     where
71         M: Mirror<'tcx, Output = Expr<'tcx>>,
72     {
73         let place_builder = unpack!(block = self.as_place_builder(block, expr));
74         block.and(place_builder.into_place(self.hir.tcx()))
75     }
76
77     /// This is used when constructing a compound `Place`, so that we can avoid creating
78     /// intermediate `Place` values until we know the full set of projections.
79     fn as_place_builder<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<PlaceBuilder<'tcx>>
80     where
81         M: Mirror<'tcx, Output = Expr<'tcx>>,
82     {
83         let expr = self.hir.mirror(expr);
84         self.expr_as_place(block, expr, Mutability::Mut, None)
85     }
86
87     /// Compile `expr`, yielding a place that we can move from etc.
88     /// Mutability note: The caller of this method promises only to read from the resulting
89     /// place. The place itself may or may not be mutable:
90     /// * If this expr is a place expr like a.b, then we will return that place.
91     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
92     crate fn as_read_only_place<M>(
93         &mut self,
94         mut block: BasicBlock,
95         expr: M,
96     ) -> BlockAnd<Place<'tcx>>
97     where
98         M: Mirror<'tcx, Output = Expr<'tcx>>,
99     {
100         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
101         block.and(place_builder.into_place(self.hir.tcx()))
102     }
103
104     /// This is used when constructing a compound `Place`, so that we can avoid creating
105     /// intermediate `Place` values until we know the full set of projections.
106     /// Mutability note: The caller of this method promises only to read from the resulting
107     /// place. The place itself may or may not be mutable:
108     /// * If this expr is a place expr like a.b, then we will return that place.
109     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
110     fn as_read_only_place_builder<M>(
111         &mut self,
112         block: BasicBlock,
113         expr: M,
114     ) -> BlockAnd<PlaceBuilder<'tcx>>
115     where
116         M: Mirror<'tcx, Output = Expr<'tcx>>,
117     {
118         let expr = self.hir.mirror(expr);
119         self.expr_as_place(block, expr, Mutability::Not, None)
120     }
121
122     fn expr_as_place(
123         &mut self,
124         mut block: BasicBlock,
125         expr: Expr<'tcx>,
126         mutability: Mutability,
127         fake_borrow_temps: Option<&mut Vec<Local>>,
128     ) -> BlockAnd<PlaceBuilder<'tcx>> {
129         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
130
131         let this = self;
132         let expr_span = expr.span;
133         let source_info = this.source_info(expr_span);
134         match expr.kind {
135             ExprKind::Scope { region_scope, lint_level, value } => {
136                 this.in_scope((region_scope, source_info), lint_level, |this| {
137                     let value = this.hir.mirror(value);
138                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
139                 })
140             }
141             ExprKind::Field { lhs, name } => {
142                 let lhs = this.hir.mirror(lhs);
143                 let place_builder =
144                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
145                 block.and(place_builder.field(name, expr.ty))
146             }
147             ExprKind::Deref { arg } => {
148                 let arg = this.hir.mirror(arg);
149                 let place_builder =
150                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
151                 block.and(place_builder.deref())
152             }
153             ExprKind::Index { lhs, index } => this.lower_index_expression(
154                 block,
155                 lhs,
156                 index,
157                 mutability,
158                 fake_borrow_temps,
159                 expr.temp_lifetime,
160                 expr_span,
161                 source_info,
162             ),
163             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
164                 let capture = this
165                     .hir
166                     .typeck_results
167                     .closure_captures
168                     .get(&closure_def_id)
169                     .and_then(|captures| captures.get_full(&var_hir_id));
170
171                 if capture.is_none() {
172                     if !this.hir.tcx().features().capture_disjoint_fields {
173                         bug!(
174                             "No associated capture found for {:?} even though \
175                             capture_disjoint_fields isn't enabled",
176                             expr.kind
177                         )
178                     }
179                     // FIXME(project-rfc-2229#24): Handle this case properly
180                 }
181
182                 // Unwrap until the FIXME has been resolved
183                 let (capture_index, _, upvar_id) = capture.unwrap();
184                 this.lower_closure_capture(block, capture_index, *upvar_id)
185             }
186
187             ExprKind::SelfRef => block.and(PlaceBuilder::from(Local::new(1))),
188             ExprKind::VarRef { id } => {
189                 let place_builder = if this.is_bound_var_in_guard(id) {
190                     let index = this.var_local_id(id, RefWithinGuard);
191                     PlaceBuilder::from(index).deref()
192                 } else {
193                     let index = this.var_local_id(id, OutsideGuard);
194                     PlaceBuilder::from(index)
195                 };
196                 block.and(place_builder)
197             }
198
199             ExprKind::PlaceTypeAscription { source, user_ty } => {
200                 let source = this.hir.mirror(source);
201                 let place_builder = unpack!(
202                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
203                 );
204                 if let Some(user_ty) = user_ty {
205                     let annotation_index =
206                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
207                             span: source_info.span,
208                             user_ty,
209                             inferred_ty: expr.ty,
210                         });
211
212                     let place = place_builder.clone().into_place(this.hir.tcx());
213                     this.cfg.push(
214                         block,
215                         Statement {
216                             source_info,
217                             kind: StatementKind::AscribeUserType(
218                                 box (
219                                     place,
220                                     UserTypeProjection { base: annotation_index, projs: vec![] },
221                                 ),
222                                 Variance::Invariant,
223                             ),
224                         },
225                     );
226                 }
227                 block.and(place_builder)
228             }
229             ExprKind::ValueTypeAscription { source, user_ty } => {
230                 let source = this.hir.mirror(source);
231                 let temp =
232                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
233                 if let Some(user_ty) = user_ty {
234                     let annotation_index =
235                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
236                             span: source_info.span,
237                             user_ty,
238                             inferred_ty: expr.ty,
239                         });
240                     this.cfg.push(
241                         block,
242                         Statement {
243                             source_info,
244                             kind: StatementKind::AscribeUserType(
245                                 box (
246                                     Place::from(temp),
247                                     UserTypeProjection { base: annotation_index, projs: vec![] },
248                                 ),
249                                 Variance::Invariant,
250                             ),
251                         },
252                     );
253                 }
254                 block.and(PlaceBuilder::from(temp))
255             }
256
257             ExprKind::Array { .. }
258             | ExprKind::Tuple { .. }
259             | ExprKind::Adt { .. }
260             | ExprKind::Closure { .. }
261             | ExprKind::Unary { .. }
262             | ExprKind::Binary { .. }
263             | ExprKind::LogicalOp { .. }
264             | ExprKind::Box { .. }
265             | ExprKind::Cast { .. }
266             | ExprKind::Use { .. }
267             | ExprKind::NeverToAny { .. }
268             | ExprKind::Pointer { .. }
269             | ExprKind::Repeat { .. }
270             | ExprKind::Borrow { .. }
271             | ExprKind::AddressOf { .. }
272             | ExprKind::Match { .. }
273             | ExprKind::Loop { .. }
274             | ExprKind::Block { .. }
275             | ExprKind::Assign { .. }
276             | ExprKind::AssignOp { .. }
277             | ExprKind::Break { .. }
278             | ExprKind::Continue { .. }
279             | ExprKind::Return { .. }
280             | ExprKind::Literal { .. }
281             | ExprKind::ConstBlock { .. }
282             | ExprKind::StaticRef { .. }
283             | ExprKind::InlineAsm { .. }
284             | ExprKind::LlvmInlineAsm { .. }
285             | ExprKind::Yield { .. }
286             | ExprKind::ThreadLocalRef(_)
287             | ExprKind::Call { .. } => {
288                 // these are not places, so we need to make a temporary.
289                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
290                 let temp =
291                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
292                 block.and(PlaceBuilder::from(temp))
293             }
294         }
295     }
296
297     /// Lower a closure/generator capture by representing it as a field
298     /// access within the desugared closure/generator.
299     ///
300     /// `capture_index` is the index of the capture within the desugared
301     /// closure/generator.
302     fn lower_closure_capture(
303         &mut self,
304         block: BasicBlock,
305         capture_index: usize,
306         upvar_id: ty::UpvarId,
307     )  -> BlockAnd<PlaceBuilder<'tcx>> {
308         let closure_ty = self
309             .hir
310             .typeck_results()
311             .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
312
313         // Captures are represented using fields inside a structure.
314         // This represents accessing self in the closure structure
315         let mut place_builder = PlaceBuilder::from(Local::new(1));
316
317         // In case of Fn/FnMut closures we must deref to access the fields
318         // Generators are considered FnOnce, so we ignore this step for them.
319         if let ty::Closure(_, closure_substs) = closure_ty.kind() {
320             match self.hir.infcx().closure_kind(closure_substs).unwrap() {
321                 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
322                     place_builder = place_builder.deref();
323                 }
324                 ty::ClosureKind::FnOnce => {}
325             }
326         }
327
328         let substs = match closure_ty.kind() {
329             ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
330             ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
331             _ => bug!("Lowering capture for non-closure type {:?}", closure_ty)
332         };
333
334         // Access the capture by accessing the field within the Closure struct.
335         //
336         // We must have inferred the capture types since we are building MIR, therefore
337         // it's safe to call `upvar_tys` and we can unwrap here because
338         // we know that the capture exists and is the `capture_index`-th capture.
339         let var_ty = substs.upvar_tys().nth(capture_index).unwrap();
340         place_builder = place_builder.field(Field::new(capture_index), var_ty);
341
342         // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
343         // we need to deref it
344         match self.hir.typeck_results.upvar_capture(upvar_id) {
345             ty::UpvarCapture::ByRef(_) => {
346                 block.and(place_builder.deref())
347             }
348             ty::UpvarCapture::ByValue(_) => block.and(place_builder),
349         }
350     }
351
352     /// Lower an index expression
353     ///
354     /// This has two complications;
355     ///
356     /// * We need to do a bounds check.
357     /// * We need to ensure that the bounds check can't be invalidated using an
358     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
359     ///   that this is the case.
360     fn lower_index_expression(
361         &mut self,
362         mut block: BasicBlock,
363         base: ExprRef<'tcx>,
364         index: ExprRef<'tcx>,
365         mutability: Mutability,
366         fake_borrow_temps: Option<&mut Vec<Local>>,
367         temp_lifetime: Option<region::Scope>,
368         expr_span: Span,
369         source_info: SourceInfo,
370     ) -> BlockAnd<PlaceBuilder<'tcx>> {
371         let lhs = self.hir.mirror(base);
372
373         let base_fake_borrow_temps = &mut Vec::new();
374         let is_outermost_index = fake_borrow_temps.is_none();
375         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
376
377         let base_place =
378             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
379
380         // Making this a *fresh* temporary means we do not have to worry about
381         // the index changing later: Nothing will ever change this temporary.
382         // The "retagging" transformation (for Stacked Borrows) relies on this.
383         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
384
385         block = self.bounds_check(
386             block,
387             base_place.clone().into_place(self.hir.tcx()),
388             idx,
389             expr_span,
390             source_info,
391         );
392
393         if is_outermost_index {
394             self.read_fake_borrows(block, fake_borrow_temps, source_info)
395         } else {
396             self.add_fake_borrows_of_base(
397                 &base_place,
398                 block,
399                 fake_borrow_temps,
400                 expr_span,
401                 source_info,
402             );
403         }
404
405         block.and(base_place.index(idx))
406     }
407
408     fn bounds_check(
409         &mut self,
410         block: BasicBlock,
411         slice: Place<'tcx>,
412         index: Local,
413         expr_span: Span,
414         source_info: SourceInfo,
415     ) -> BasicBlock {
416         let usize_ty = self.hir.usize_ty();
417         let bool_ty = self.hir.bool_ty();
418         // bounds check:
419         let len = self.temp(usize_ty, expr_span);
420         let lt = self.temp(bool_ty, expr_span);
421
422         // len = len(slice)
423         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
424         // lt = idx < len
425         self.cfg.push_assign(
426             block,
427             source_info,
428             lt,
429             Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
430         );
431         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
432         // assert!(lt, "...")
433         self.assert(block, Operand::Move(lt), true, msg, expr_span)
434     }
435
436     fn add_fake_borrows_of_base(
437         &mut self,
438         base_place: &PlaceBuilder<'tcx>,
439         block: BasicBlock,
440         fake_borrow_temps: &mut Vec<Local>,
441         expr_span: Span,
442         source_info: SourceInfo,
443     ) {
444         let tcx = self.hir.tcx();
445         let place_ty =
446             Place::ty_from(base_place.local, &base_place.projection, &self.local_decls, tcx);
447         if let ty::Slice(_) = place_ty.ty.kind() {
448             // We need to create fake borrows to ensure that the bounds
449             // check that we just did stays valid. Since we can't assign to
450             // unsized values, we only need to ensure that none of the
451             // pointers in the base place are modified.
452             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
453                 match elem {
454                     ProjectionElem::Deref => {
455                         let fake_borrow_deref_ty = Place::ty_from(
456                             base_place.local,
457                             &base_place.projection[..idx],
458                             &self.local_decls,
459                             tcx,
460                         )
461                         .ty;
462                         let fake_borrow_ty =
463                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
464                         let fake_borrow_temp =
465                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
466                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
467                         self.cfg.push_assign(
468                             block,
469                             source_info,
470                             fake_borrow_temp.into(),
471                             Rvalue::Ref(
472                                 tcx.lifetimes.re_erased,
473                                 BorrowKind::Shallow,
474                                 Place { local: base_place.local, projection },
475                             ),
476                         );
477                         fake_borrow_temps.push(fake_borrow_temp);
478                     }
479                     ProjectionElem::Index(_) => {
480                         let index_ty = Place::ty_from(
481                             base_place.local,
482                             &base_place.projection[..idx],
483                             &self.local_decls,
484                             tcx,
485                         );
486                         match index_ty.ty.kind() {
487                             // The previous index expression has already
488                             // done any index expressions needed here.
489                             ty::Slice(_) => break,
490                             ty::Array(..) => (),
491                             _ => bug!("unexpected index base"),
492                         }
493                     }
494                     ProjectionElem::Field(..)
495                     | ProjectionElem::Downcast(..)
496                     | ProjectionElem::ConstantIndex { .. }
497                     | ProjectionElem::Subslice { .. } => (),
498                 }
499             }
500         }
501     }
502
503     fn read_fake_borrows(
504         &mut self,
505         bb: BasicBlock,
506         fake_borrow_temps: &mut Vec<Local>,
507         source_info: SourceInfo,
508     ) {
509         // All indexes have been evaluated now, read all of the
510         // fake borrows so that they are live across those index
511         // expressions.
512         for temp in fake_borrow_temps {
513             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
514         }
515     }
516 }