]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_place.rs
Remove PlaceBase enum and make Place base field be local: Local
[rust.git] / src / librustc_mir / 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::hair::*;
7 use rustc::middle::region;
8 use rustc::mir::interpret::PanicInfo::BoundsCheck;
9 use rustc::mir::*;
10 use rustc::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 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 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     pub 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     pub fn as_read_only_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
93     where
94         M: Mirror<'tcx, Output = Expr<'tcx>>,
95     {
96         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
97         block.and(place_builder.into_place(self.hir.tcx()))
98     }
99
100     /// This is used when constructing a compound `Place`, so that we can avoid creating
101     /// intermediate `Place` values until we know the full set of projections.
102     /// Mutability note: The caller of this method promises only to read from the resulting
103     /// place. The place itself may or may not be mutable:
104     /// * If this expr is a place expr like a.b, then we will return that place.
105     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
106     fn as_read_only_place_builder<M>(
107         &mut self,
108         block: BasicBlock,
109         expr: M,
110     ) -> BlockAnd<PlaceBuilder<'tcx>>
111     where
112         M: Mirror<'tcx, Output = Expr<'tcx>>,
113     {
114         let expr = self.hir.mirror(expr);
115         self.expr_as_place(block, expr, Mutability::Not, None)
116     }
117
118     fn expr_as_place(
119         &mut self,
120         mut block: BasicBlock,
121         expr: Expr<'tcx>,
122         mutability: Mutability,
123         fake_borrow_temps: Option<&mut Vec<Local>>,
124     ) -> BlockAnd<PlaceBuilder<'tcx>> {
125         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
126
127         let this = self;
128         let expr_span = expr.span;
129         let source_info = this.source_info(expr_span);
130         match expr.kind {
131             ExprKind::Scope { region_scope, lint_level, value } => {
132                 this.in_scope((region_scope, source_info), lint_level, |this| {
133                     let value = this.hir.mirror(value);
134                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
135                 })
136             }
137             ExprKind::Field { lhs, name } => {
138                 let lhs = this.hir.mirror(lhs);
139                 let place_builder =
140                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
141                 block.and(place_builder.field(name, expr.ty))
142             }
143             ExprKind::Deref { arg } => {
144                 let arg = this.hir.mirror(arg);
145                 let place_builder =
146                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
147                 block.and(place_builder.deref())
148             }
149             ExprKind::Index { lhs, index } => this.lower_index_expression(
150                 block,
151                 lhs,
152                 index,
153                 mutability,
154                 fake_borrow_temps,
155                 expr.temp_lifetime,
156                 expr_span,
157                 source_info,
158             ),
159             ExprKind::SelfRef => block.and(PlaceBuilder::from(Local::new(1))),
160             ExprKind::VarRef { id } => {
161                 let place_builder = if this.is_bound_var_in_guard(id) {
162                     let index = this.var_local_id(id, RefWithinGuard);
163                     PlaceBuilder::from(index).deref()
164                 } else {
165                     let index = this.var_local_id(id, OutsideGuard);
166                     PlaceBuilder::from(index)
167                 };
168                 block.and(place_builder)
169             }
170
171             ExprKind::PlaceTypeAscription { source, user_ty } => {
172                 let source = this.hir.mirror(source);
173                 let place_builder = unpack!(
174                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
175                 );
176                 if let Some(user_ty) = user_ty {
177                     let annotation_index =
178                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
179                             span: source_info.span,
180                             user_ty,
181                             inferred_ty: expr.ty,
182                         });
183
184                     let place = place_builder.clone().into_place(this.hir.tcx());
185                     this.cfg.push(
186                         block,
187                         Statement {
188                             source_info,
189                             kind: StatementKind::AscribeUserType(
190                                 box (
191                                     place,
192                                     UserTypeProjection { base: annotation_index, projs: vec![] },
193                                 ),
194                                 Variance::Invariant,
195                             ),
196                         },
197                     );
198                 }
199                 block.and(place_builder)
200             }
201             ExprKind::ValueTypeAscription { source, user_ty } => {
202                 let source = this.hir.mirror(source);
203                 let temp =
204                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
205                 if let Some(user_ty) = user_ty {
206                     let annotation_index =
207                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
208                             span: source_info.span,
209                             user_ty,
210                             inferred_ty: expr.ty,
211                         });
212                     this.cfg.push(
213                         block,
214                         Statement {
215                             source_info,
216                             kind: StatementKind::AscribeUserType(
217                                 box (
218                                     Place::from(temp.clone()),
219                                     UserTypeProjection { base: annotation_index, projs: vec![] },
220                                 ),
221                                 Variance::Invariant,
222                             ),
223                         },
224                     );
225                 }
226                 block.and(PlaceBuilder::from(temp))
227             }
228
229             ExprKind::Array { .. }
230             | ExprKind::Tuple { .. }
231             | ExprKind::Adt { .. }
232             | ExprKind::Closure { .. }
233             | ExprKind::Unary { .. }
234             | ExprKind::Binary { .. }
235             | ExprKind::LogicalOp { .. }
236             | ExprKind::Box { .. }
237             | ExprKind::Cast { .. }
238             | ExprKind::Use { .. }
239             | ExprKind::NeverToAny { .. }
240             | ExprKind::Pointer { .. }
241             | ExprKind::Repeat { .. }
242             | ExprKind::Borrow { .. }
243             | ExprKind::AddressOf { .. }
244             | ExprKind::Match { .. }
245             | ExprKind::Loop { .. }
246             | ExprKind::Block { .. }
247             | ExprKind::Assign { .. }
248             | ExprKind::AssignOp { .. }
249             | ExprKind::Break { .. }
250             | ExprKind::Continue { .. }
251             | ExprKind::Return { .. }
252             | ExprKind::Literal { .. }
253             | ExprKind::StaticRef { .. }
254             | ExprKind::InlineAsm { .. }
255             | ExprKind::Yield { .. }
256             | ExprKind::Call { .. } => {
257                 // these are not places, so we need to make a temporary.
258                 debug_assert!(match Category::of(&expr.kind) {
259                     Some(Category::Place) => false,
260                     _ => true,
261                 });
262                 let temp =
263                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
264                 block.and(PlaceBuilder::from(temp))
265             }
266         }
267     }
268
269     /// Lower an index expression
270     ///
271     /// This has two complications;
272     ///
273     /// * We need to do a bounds check.
274     /// * We need to ensure that the bounds check can't be invalidated using an
275     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
276     ///   that this is the case.
277     fn lower_index_expression(
278         &mut self,
279         mut block: BasicBlock,
280         base: ExprRef<'tcx>,
281         index: ExprRef<'tcx>,
282         mutability: Mutability,
283         fake_borrow_temps: Option<&mut Vec<Local>>,
284         temp_lifetime: Option<region::Scope>,
285         expr_span: Span,
286         source_info: SourceInfo,
287     ) -> BlockAnd<PlaceBuilder<'tcx>> {
288         let lhs = self.hir.mirror(base);
289
290         let base_fake_borrow_temps = &mut Vec::new();
291         let is_outermost_index = fake_borrow_temps.is_none();
292         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
293
294         let base_place =
295             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
296
297         // Making this a *fresh* temporary means we do not have to worry about
298         // the index changing later: Nothing will ever change this temporary.
299         // The "retagging" transformation (for Stacked Borrows) relies on this.
300         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
301
302         block = self.bounds_check(
303             block,
304             base_place.clone().into_place(self.hir.tcx()),
305             idx,
306             expr_span,
307             source_info,
308         );
309
310         if is_outermost_index {
311             self.read_fake_borrows(block, fake_borrow_temps, source_info)
312         } else {
313             self.add_fake_borrows_of_base(
314                 &base_place,
315                 block,
316                 fake_borrow_temps,
317                 expr_span,
318                 source_info,
319             );
320         }
321
322         block.and(base_place.index(idx))
323     }
324
325     fn bounds_check(
326         &mut self,
327         block: BasicBlock,
328         slice: Place<'tcx>,
329         index: Local,
330         expr_span: Span,
331         source_info: SourceInfo,
332     ) -> BasicBlock {
333         let usize_ty = self.hir.usize_ty();
334         let bool_ty = self.hir.bool_ty();
335         // bounds check:
336         let len = self.temp(usize_ty, expr_span);
337         let lt = self.temp(bool_ty, expr_span);
338
339         // len = len(slice)
340         self.cfg.push_assign(block, source_info, &len, Rvalue::Len(slice));
341         // lt = idx < len
342         self.cfg.push_assign(
343             block,
344             source_info,
345             &lt,
346             Rvalue::BinaryOp(
347                 BinOp::Lt,
348                 Operand::Copy(Place::from(index)),
349                 Operand::Copy(len.clone()),
350             ),
351         );
352         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
353         // assert!(lt, "...")
354         self.assert(block, Operand::Move(lt), true, msg, expr_span)
355     }
356
357     fn add_fake_borrows_of_base(
358         &mut self,
359         base_place: &PlaceBuilder<'tcx>,
360         block: BasicBlock,
361         fake_borrow_temps: &mut Vec<Local>,
362         expr_span: Span,
363         source_info: SourceInfo,
364     ) {
365         let tcx = self.hir.tcx();
366         let place_ty =
367             Place::ty_from(&base_place.local, &base_place.projection, &self.local_decls, tcx);
368         if let ty::Slice(_) = place_ty.ty.kind {
369             // We need to create fake borrows to ensure that the bounds
370             // check that we just did stays valid. Since we can't assign to
371             // unsized values, we only need to ensure that none of the
372             // pointers in the base place are modified.
373             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
374                 match elem {
375                     ProjectionElem::Deref => {
376                         let fake_borrow_deref_ty = Place::ty_from(
377                             &base_place.local,
378                             &base_place.projection[..idx],
379                             &self.local_decls,
380                             tcx,
381                         )
382                         .ty;
383                         let fake_borrow_ty =
384                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
385                         let fake_borrow_temp =
386                             self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, expr_span));
387                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
388                         self.cfg.push_assign(
389                             block,
390                             source_info,
391                             &fake_borrow_temp.into(),
392                             Rvalue::Ref(
393                                 tcx.lifetimes.re_erased,
394                                 BorrowKind::Shallow,
395                                 Place { local: base_place.local.clone(), projection },
396                             ),
397                         );
398                         fake_borrow_temps.push(fake_borrow_temp);
399                     }
400                     ProjectionElem::Index(_) => {
401                         let index_ty = Place::ty_from(
402                             &base_place.local,
403                             &base_place.projection[..idx],
404                             &self.local_decls,
405                             tcx,
406                         );
407                         match index_ty.ty.kind {
408                             // The previous index expression has already
409                             // done any index expressions needed here.
410                             ty::Slice(_) => break,
411                             ty::Array(..) => (),
412                             _ => bug!("unexpected index base"),
413                         }
414                     }
415                     ProjectionElem::Field(..)
416                     | ProjectionElem::Downcast(..)
417                     | ProjectionElem::ConstantIndex { .. }
418                     | ProjectionElem::Subslice { .. } => (),
419                 }
420             }
421         }
422     }
423
424     fn read_fake_borrows(
425         &mut self,
426         bb: BasicBlock,
427         fake_borrow_temps: &mut Vec<Local>,
428         source_info: SourceInfo,
429     ) {
430         // All indexes have been evaluated now, read all of the
431         // fake borrows so that they are live across those index
432         // expressions.
433         for temp in fake_borrow_temps {
434             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
435         }
436     }
437 }