]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Merge commit '645ef505da378b6f810b1567806d1bcc2856395f' into clippyup
[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::SelfRef => block.and(PlaceBuilder::from(Local::new(1))),
164             ExprKind::VarRef { id } => {
165                 let place_builder = if this.is_bound_var_in_guard(id) {
166                     let index = this.var_local_id(id, RefWithinGuard);
167                     PlaceBuilder::from(index).deref()
168                 } else {
169                     let index = this.var_local_id(id, OutsideGuard);
170                     PlaceBuilder::from(index)
171                 };
172                 block.and(place_builder)
173             }
174
175             ExprKind::PlaceTypeAscription { source, user_ty } => {
176                 let source = this.hir.mirror(source);
177                 let place_builder = unpack!(
178                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
179                 );
180                 if let Some(user_ty) = user_ty {
181                     let annotation_index =
182                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
183                             span: source_info.span,
184                             user_ty,
185                             inferred_ty: expr.ty,
186                         });
187
188                     let place = place_builder.clone().into_place(this.hir.tcx());
189                     this.cfg.push(
190                         block,
191                         Statement {
192                             source_info,
193                             kind: StatementKind::AscribeUserType(
194                                 box (
195                                     place,
196                                     UserTypeProjection { base: annotation_index, projs: vec![] },
197                                 ),
198                                 Variance::Invariant,
199                             ),
200                         },
201                     );
202                 }
203                 block.and(place_builder)
204             }
205             ExprKind::ValueTypeAscription { source, user_ty } => {
206                 let source = this.hir.mirror(source);
207                 let temp =
208                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
209                 if let Some(user_ty) = user_ty {
210                     let annotation_index =
211                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
212                             span: source_info.span,
213                             user_ty,
214                             inferred_ty: expr.ty,
215                         });
216                     this.cfg.push(
217                         block,
218                         Statement {
219                             source_info,
220                             kind: StatementKind::AscribeUserType(
221                                 box (
222                                     Place::from(temp),
223                                     UserTypeProjection { base: annotation_index, projs: vec![] },
224                                 ),
225                                 Variance::Invariant,
226                             ),
227                         },
228                     );
229                 }
230                 block.and(PlaceBuilder::from(temp))
231             }
232
233             ExprKind::Array { .. }
234             | ExprKind::Tuple { .. }
235             | ExprKind::Adt { .. }
236             | ExprKind::Closure { .. }
237             | ExprKind::Unary { .. }
238             | ExprKind::Binary { .. }
239             | ExprKind::LogicalOp { .. }
240             | ExprKind::Box { .. }
241             | ExprKind::Cast { .. }
242             | ExprKind::Use { .. }
243             | ExprKind::NeverToAny { .. }
244             | ExprKind::Pointer { .. }
245             | ExprKind::Repeat { .. }
246             | ExprKind::Borrow { .. }
247             | ExprKind::AddressOf { .. }
248             | ExprKind::Match { .. }
249             | ExprKind::Loop { .. }
250             | ExprKind::Block { .. }
251             | ExprKind::Assign { .. }
252             | ExprKind::AssignOp { .. }
253             | ExprKind::Break { .. }
254             | ExprKind::Continue { .. }
255             | ExprKind::Return { .. }
256             | ExprKind::Literal { .. }
257             | ExprKind::ConstBlock { .. }
258             | ExprKind::StaticRef { .. }
259             | ExprKind::InlineAsm { .. }
260             | ExprKind::LlvmInlineAsm { .. }
261             | ExprKind::Yield { .. }
262             | ExprKind::ThreadLocalRef(_)
263             | ExprKind::Call { .. } => {
264                 // these are not places, so we need to make a temporary.
265                 debug_assert!(match Category::of(&expr.kind) {
266                     Some(Category::Place) => false,
267                     _ => true,
268                 });
269                 let temp =
270                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
271                 block.and(PlaceBuilder::from(temp))
272             }
273         }
274     }
275
276     /// Lower an index expression
277     ///
278     /// This has two complications;
279     ///
280     /// * We need to do a bounds check.
281     /// * We need to ensure that the bounds check can't be invalidated using an
282     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
283     ///   that this is the case.
284     fn lower_index_expression(
285         &mut self,
286         mut block: BasicBlock,
287         base: ExprRef<'tcx>,
288         index: ExprRef<'tcx>,
289         mutability: Mutability,
290         fake_borrow_temps: Option<&mut Vec<Local>>,
291         temp_lifetime: Option<region::Scope>,
292         expr_span: Span,
293         source_info: SourceInfo,
294     ) -> BlockAnd<PlaceBuilder<'tcx>> {
295         let lhs = self.hir.mirror(base);
296
297         let base_fake_borrow_temps = &mut Vec::new();
298         let is_outermost_index = fake_borrow_temps.is_none();
299         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
300
301         let base_place =
302             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
303
304         // Making this a *fresh* temporary means we do not have to worry about
305         // the index changing later: Nothing will ever change this temporary.
306         // The "retagging" transformation (for Stacked Borrows) relies on this.
307         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
308
309         block = self.bounds_check(
310             block,
311             base_place.clone().into_place(self.hir.tcx()),
312             idx,
313             expr_span,
314             source_info,
315         );
316
317         if is_outermost_index {
318             self.read_fake_borrows(block, fake_borrow_temps, source_info)
319         } else {
320             self.add_fake_borrows_of_base(
321                 &base_place,
322                 block,
323                 fake_borrow_temps,
324                 expr_span,
325                 source_info,
326             );
327         }
328
329         block.and(base_place.index(idx))
330     }
331
332     fn bounds_check(
333         &mut self,
334         block: BasicBlock,
335         slice: Place<'tcx>,
336         index: Local,
337         expr_span: Span,
338         source_info: SourceInfo,
339     ) -> BasicBlock {
340         let usize_ty = self.hir.usize_ty();
341         let bool_ty = self.hir.bool_ty();
342         // bounds check:
343         let len = self.temp(usize_ty, expr_span);
344         let lt = self.temp(bool_ty, expr_span);
345
346         // len = len(slice)
347         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
348         // lt = idx < len
349         self.cfg.push_assign(
350             block,
351             source_info,
352             lt,
353             Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
354         );
355         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
356         // assert!(lt, "...")
357         self.assert(block, Operand::Move(lt), true, msg, expr_span)
358     }
359
360     fn add_fake_borrows_of_base(
361         &mut self,
362         base_place: &PlaceBuilder<'tcx>,
363         block: BasicBlock,
364         fake_borrow_temps: &mut Vec<Local>,
365         expr_span: Span,
366         source_info: SourceInfo,
367     ) {
368         let tcx = self.hir.tcx();
369         let place_ty =
370             Place::ty_from(base_place.local, &base_place.projection, &self.local_decls, tcx);
371         if let ty::Slice(_) = place_ty.ty.kind() {
372             // We need to create fake borrows to ensure that the bounds
373             // check that we just did stays valid. Since we can't assign to
374             // unsized values, we only need to ensure that none of the
375             // pointers in the base place are modified.
376             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
377                 match elem {
378                     ProjectionElem::Deref => {
379                         let fake_borrow_deref_ty = Place::ty_from(
380                             base_place.local,
381                             &base_place.projection[..idx],
382                             &self.local_decls,
383                             tcx,
384                         )
385                         .ty;
386                         let fake_borrow_ty =
387                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
388                         let fake_borrow_temp =
389                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
390                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
391                         self.cfg.push_assign(
392                             block,
393                             source_info,
394                             fake_borrow_temp.into(),
395                             Rvalue::Ref(
396                                 tcx.lifetimes.re_erased,
397                                 BorrowKind::Shallow,
398                                 Place { local: base_place.local, projection },
399                             ),
400                         );
401                         fake_borrow_temps.push(fake_borrow_temp);
402                     }
403                     ProjectionElem::Index(_) => {
404                         let index_ty = Place::ty_from(
405                             base_place.local,
406                             &base_place.projection[..idx],
407                             &self.local_decls,
408                             tcx,
409                         );
410                         match index_ty.ty.kind() {
411                             // The previous index expression has already
412                             // done any index expressions needed here.
413                             ty::Slice(_) => break,
414                             ty::Array(..) => (),
415                             _ => bug!("unexpected index base"),
416                         }
417                     }
418                     ProjectionElem::Field(..)
419                     | ProjectionElem::Downcast(..)
420                     | ProjectionElem::ConstantIndex { .. }
421                     | ProjectionElem::Subslice { .. } => (),
422                 }
423             }
424         }
425     }
426
427     fn read_fake_borrows(
428         &mut self,
429         bb: BasicBlock,
430         fake_borrow_temps: &mut Vec<Local>,
431         source_info: SourceInfo,
432     ) {
433         // All indexes have been evaluated now, read all of the
434         // fake borrows so that they are live across those index
435         // expressions.
436         for temp in fake_borrow_temps {
437             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
438         }
439     }
440 }