]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Check the sizes of Operand, Rvalue, AggregateKind and Place
[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_hir::def_id::DefId;
8 use rustc_hir::HirId;
9 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::AssertKind::BoundsCheck;
12 use rustc_middle::mir::*;
13 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
14 use rustc_span::Span;
15 use rustc_target::abi::VariantIdx;
16
17 use rustc_index::vec::Idx;
18
19 /// The "outermost" place that holds this value.
20 #[derive(Copy, Clone)]
21 crate enum PlaceBase {
22     /// Denotes the start of a `Place`.
23     Local(Local),
24
25     /// When building place for an expression within a closure, the place might start off a
26     /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
27     /// index (within the desugared closure) of the captured path until most of the projections
28     /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
29     /// captured path starts, the closure the capture belongs to and the trait the closure
30     /// implements.
31     ///
32     /// Once we have figured out the capture index, we can convert the place builder to start from
33     /// `PlaceBase::Local`.
34     ///
35     /// Consider the following example
36     /// ```rust
37     /// let t = (10, (10, (10, 10)));
38     ///
39     /// let c = || {
40     ///     println!("{}", t.0.0.0);
41     /// };
42     /// ```
43     /// Here the THIR expression for `t.0.0.0` will be something like
44     ///
45     /// ```
46     /// * Field(0)
47     ///     * Field(0)
48     ///         * Field(0)
49     ///             * UpvarRef(t)
50     /// ```
51     ///
52     /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
53     /// figure out that it is captured until all the `Field` projections are applied.
54     Upvar {
55         /// HirId of the upvar
56         var_hir_id: HirId,
57         /// DefId of the closure
58         closure_def_id: DefId,
59         /// The trait closure implements, `Fn`, `FnMut`, `FnOnce`
60         closure_kind: ty::ClosureKind,
61     },
62 }
63
64 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
65 /// place by pushing more and more projections onto the end, and then convert the final set into a
66 /// place using the `into_place` method.
67 ///
68 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
69 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
70 #[derive(Clone)]
71 crate struct PlaceBuilder<'tcx> {
72     base: PlaceBase,
73     projection: Vec<PlaceElem<'tcx>>,
74 }
75
76 /// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
77 /// The projections are truncated to represent a path that might be captured by a
78 /// closure/generator. This implies the vector returned from this function doesn't contain
79 /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
80 /// part of a path that is captued by a closure. We stop applying projections once we see the first
81 /// projection that isn't captured by a closure.
82 fn convert_to_hir_projections_and_truncate_for_capture<'tcx>(
83     mir_projections: &[PlaceElem<'tcx>],
84 ) -> Vec<HirProjectionKind> {
85     let mut hir_projections = Vec::new();
86
87     for mir_projection in mir_projections {
88         let hir_projection = match mir_projection {
89             ProjectionElem::Deref => HirProjectionKind::Deref,
90             ProjectionElem::Field(field, _) => {
91                 // We will never encouter this for multivariant enums,
92                 // read the comment for `Downcast`.
93                 HirProjectionKind::Field(field.index() as u32, VariantIdx::new(0))
94             }
95             ProjectionElem::Downcast(..) => {
96                 // This projections exist only for enums that have
97                 // multiple variants. Since such enums that are captured
98                 // completely, we can stop here.
99                 break;
100             }
101             ProjectionElem::Index(..)
102             | ProjectionElem::ConstantIndex { .. }
103             | ProjectionElem::Subslice { .. } => {
104                 // We don't capture array-access projections.
105                 // We can stop here as arrays are captured completely.
106                 break;
107             }
108         };
109
110         hir_projections.push(hir_projection);
111     }
112
113     hir_projections
114 }
115
116 /// Return true if the `proj_possible_ancestor` represents an ancestor path
117 /// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
118 /// assuming they both start off of the same root variable.
119 ///
120 /// **Note:** It's the caller's responsibility to ensure that both lists of projections
121 ///           start off of the same root variable.
122 ///
123 /// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
124 ///        `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
125 ///        Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
126 ///     2. Since we only look at the projections here function will return `bar.x` as an a valid
127 ///        ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
128 ///        list are being applied to the same root variable.
129 fn is_ancestor_or_same_capture(
130     proj_possible_ancestor: &Vec<HirProjectionKind>,
131     proj_capture: &[HirProjectionKind],
132 ) -> bool {
133     // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
134     // Therefore we can't just check if all projections are same in the zipped iterator below.
135     if proj_possible_ancestor.len() > proj_capture.len() {
136         return false;
137     }
138
139     proj_possible_ancestor.iter().zip(proj_capture).all(|(a, b)| a == b)
140 }
141
142 /// Computes the index of a capture within the desugared closure provided the closure's
143 /// `closure_min_captures` and the capture's index of the capture in the
144 /// `ty::MinCaptureList` of the root variable `var_hir_id`.
145 fn compute_capture_idx<'tcx>(
146     closure_min_captures: &ty::RootVariableMinCaptureList<'tcx>,
147     var_hir_id: HirId,
148     root_var_idx: usize,
149 ) -> usize {
150     let mut res = 0;
151     for (var_id, capture_list) in closure_min_captures {
152         if *var_id == var_hir_id {
153             res += root_var_idx;
154             break;
155         } else {
156             res += capture_list.len();
157         }
158     }
159
160     res
161 }
162
163 /// Given a closure, returns the index of a capture within the desugared closure struct and the
164 /// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
165 /// and `projection`.
166 ///
167 /// Note there will be at most one ancestor for any given Place.
168 ///
169 /// Returns None, when the ancestor is not found.
170 fn find_capture_matching_projections<'a, 'tcx>(
171     typeck_results: &'a ty::TypeckResults<'tcx>,
172     var_hir_id: HirId,
173     closure_def_id: DefId,
174     projections: &[PlaceElem<'tcx>],
175 ) -> Option<(usize, &'a ty::CapturedPlace<'tcx>)> {
176     let closure_min_captures = typeck_results.closure_min_captures.get(&closure_def_id)?;
177     let root_variable_min_captures = closure_min_captures.get(&var_hir_id)?;
178
179     let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
180
181     // If an ancestor is found, `idx` is the index within the list of captured places
182     // for root variable `var_hir_id` and `capture` is the `ty::CapturedPlace` itself.
183     let (idx, capture) = root_variable_min_captures.iter().enumerate().find(|(_, capture)| {
184         let possible_ancestor_proj_kinds =
185             capture.place.projections.iter().map(|proj| proj.kind).collect();
186         is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
187     })?;
188
189     // Convert index to be from the presepective of the entire closure_min_captures map
190     // instead of just the root variable capture list
191     Some((compute_capture_idx(closure_min_captures, var_hir_id, idx), capture))
192 }
193
194 /// Takes a PlaceBuilder and resolves the upvar (if any) within it, so that the
195 /// `PlaceBuilder` now starts from `PlaceBase::Local`.
196 ///
197 /// Returns a Result with the error being the HirId of the Upvar that was not found.
198 fn to_upvars_resolved_place_builder<'a, 'tcx>(
199     from_builder: PlaceBuilder<'tcx>,
200     tcx: TyCtxt<'tcx>,
201     typeck_results: &'a ty::TypeckResults<'tcx>,
202 ) -> Result<PlaceBuilder<'tcx>, HirId> {
203     match from_builder.base {
204         PlaceBase::Local(_) => Ok(from_builder),
205         PlaceBase::Upvar { var_hir_id, closure_def_id, closure_kind } => {
206             // Captures are represented using fields inside a structure.
207             // This represents accessing self in the closure structure
208             let mut upvar_resolved_place_builder = PlaceBuilder::from(Local::new(1));
209             match closure_kind {
210                 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
211                     upvar_resolved_place_builder = upvar_resolved_place_builder.deref();
212                 }
213                 ty::ClosureKind::FnOnce => {}
214             }
215
216             let (capture_index, capture) = if let Some(capture_details) =
217                 find_capture_matching_projections(
218                     typeck_results,
219                     var_hir_id,
220                     closure_def_id,
221                     &from_builder.projection,
222                 ) {
223                 capture_details
224             } else {
225                 if !tcx.features().capture_disjoint_fields {
226                     bug!(
227                         "No associated capture found for {:?}[{:#?}] even though \
228                             capture_disjoint_fields isn't enabled",
229                         var_hir_id,
230                         from_builder.projection
231                     )
232                 } else {
233                     // FIXME(project-rfc-2229#24): Handle this case properly
234                     debug!(
235                         "No associated capture found for {:?}[{:#?}]",
236                         var_hir_id, from_builder.projection,
237                     );
238                 }
239                 return Err(var_hir_id);
240             };
241
242             let closure_ty = typeck_results
243                 .node_type(tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local()));
244
245             let substs = match closure_ty.kind() {
246                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
247                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
248                 _ => bug!("Lowering capture for non-closure type {:?}", closure_ty),
249             };
250
251             // Access the capture by accessing the field within the Closure struct.
252             //
253             // We must have inferred the capture types since we are building MIR, therefore
254             // it's safe to call `tuple_element_ty` and we can unwrap here because
255             // we know that the capture exists and is the `capture_index`-th capture.
256             let var_ty = substs.tupled_upvars_ty().tuple_element_ty(capture_index).unwrap();
257
258             upvar_resolved_place_builder =
259                 upvar_resolved_place_builder.field(Field::new(capture_index), var_ty);
260
261             // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
262             // we need to deref it
263             upvar_resolved_place_builder = match capture.info.capture_kind {
264                 ty::UpvarCapture::ByRef(_) => upvar_resolved_place_builder.deref(),
265                 ty::UpvarCapture::ByValue(_) => upvar_resolved_place_builder,
266             };
267
268             let next_projection = capture.place.projections.len();
269             let mut curr_projections = from_builder.projection;
270
271             // We used some of the projections to build the capture itself,
272             // now we apply the remaining to the upvar resolved place.
273             upvar_resolved_place_builder
274                 .projection
275                 .extend(curr_projections.drain(next_projection..));
276
277             Ok(upvar_resolved_place_builder)
278         }
279     }
280 }
281
282 impl<'tcx> PlaceBuilder<'tcx> {
283     crate fn into_place<'a>(
284         self,
285         tcx: TyCtxt<'tcx>,
286         typeck_results: &'a ty::TypeckResults<'tcx>,
287     ) -> Place<'tcx> {
288         if let PlaceBase::Local(local) = self.base {
289             Place { local, projection: tcx.intern_place_elems(&self.projection) }
290         } else {
291             self.expect_upvars_resolved(tcx, typeck_results).into_place(tcx, typeck_results)
292         }
293     }
294
295     fn expect_upvars_resolved<'a>(
296         self,
297         tcx: TyCtxt<'tcx>,
298         typeck_results: &'a ty::TypeckResults<'tcx>,
299     ) -> PlaceBuilder<'tcx> {
300         to_upvars_resolved_place_builder(self, tcx, typeck_results).unwrap()
301     }
302
303     crate fn base(&self) -> PlaceBase {
304         self.base
305     }
306
307     crate fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
308         self.project(PlaceElem::Field(f, ty))
309     }
310
311     fn deref(self) -> Self {
312         self.project(PlaceElem::Deref)
313     }
314
315     fn index(self, index: Local) -> Self {
316         self.project(PlaceElem::Index(index))
317     }
318
319     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
320         self.projection.push(elem);
321         self
322     }
323 }
324
325 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
326     fn from(local: Local) -> Self {
327         Self { base: PlaceBase::Local(local), projection: Vec::new() }
328     }
329 }
330
331 impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
332     fn from(base: PlaceBase) -> Self {
333         Self { base, projection: Vec::new() }
334     }
335 }
336
337 impl<'a, 'tcx> Builder<'a, 'tcx> {
338     /// Compile `expr`, yielding a place that we can move from etc.
339     ///
340     /// WARNING: Any user code might:
341     /// * Invalidate any slice bounds checks performed.
342     /// * Change the address that this `Place` refers to.
343     /// * Modify the memory that this place refers to.
344     /// * Invalidate the memory that this place refers to, this will be caught
345     ///   by borrow checking.
346     ///
347     /// Extra care is needed if any user code is allowed to run between calling
348     /// this method and using it, as is the case for `match` and index
349     /// expressions.
350     crate fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
351     where
352         M: Mirror<'tcx, Output = Expr<'tcx>>,
353     {
354         let place_builder = unpack!(block = self.as_place_builder(block, expr));
355         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
356     }
357
358     /// This is used when constructing a compound `Place`, so that we can avoid creating
359     /// intermediate `Place` values until we know the full set of projections.
360     crate fn as_place_builder<M>(
361         &mut self,
362         block: BasicBlock,
363         expr: M,
364     ) -> BlockAnd<PlaceBuilder<'tcx>>
365     where
366         M: Mirror<'tcx, Output = Expr<'tcx>>,
367     {
368         let expr = self.hir.mirror(expr);
369         self.expr_as_place(block, expr, Mutability::Mut, None)
370     }
371
372     /// Compile `expr`, yielding a place that we can move from etc.
373     /// Mutability note: The caller of this method promises only to read from the resulting
374     /// place. The place itself may or may not be mutable:
375     /// * If this expr is a place expr like a.b, then we will return that place.
376     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
377     crate fn as_read_only_place<M>(
378         &mut self,
379         mut block: BasicBlock,
380         expr: M,
381     ) -> BlockAnd<Place<'tcx>>
382     where
383         M: Mirror<'tcx, Output = Expr<'tcx>>,
384     {
385         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
386         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
387     }
388
389     /// This is used when constructing a compound `Place`, so that we can avoid creating
390     /// intermediate `Place` values until we know the full set of projections.
391     /// Mutability note: The caller of this method promises only to read from the resulting
392     /// place. The place itself may or may not be mutable:
393     /// * If this expr is a place expr like a.b, then we will return that place.
394     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
395     fn as_read_only_place_builder<M>(
396         &mut self,
397         block: BasicBlock,
398         expr: M,
399     ) -> BlockAnd<PlaceBuilder<'tcx>>
400     where
401         M: Mirror<'tcx, Output = Expr<'tcx>>,
402     {
403         let expr = self.hir.mirror(expr);
404         self.expr_as_place(block, expr, Mutability::Not, None)
405     }
406
407     fn expr_as_place(
408         &mut self,
409         mut block: BasicBlock,
410         expr: Expr<'tcx>,
411         mutability: Mutability,
412         fake_borrow_temps: Option<&mut Vec<Local>>,
413     ) -> BlockAnd<PlaceBuilder<'tcx>> {
414         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
415
416         let this = self;
417         let expr_span = expr.span;
418         let source_info = this.source_info(expr_span);
419         match expr.kind {
420             ExprKind::Scope { region_scope, lint_level, value } => {
421                 this.in_scope((region_scope, source_info), lint_level, |this| {
422                     let value = this.hir.mirror(value);
423                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
424                 })
425             }
426             ExprKind::Field { lhs, name } => {
427                 let lhs = this.hir.mirror(lhs);
428                 let place_builder =
429                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
430                 block.and(place_builder.field(name, expr.ty))
431             }
432             ExprKind::Deref { arg } => {
433                 let arg = this.hir.mirror(arg);
434                 let place_builder =
435                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
436                 block.and(place_builder.deref())
437             }
438             ExprKind::Index { lhs, index } => this.lower_index_expression(
439                 block,
440                 lhs,
441                 index,
442                 mutability,
443                 fake_borrow_temps,
444                 expr.temp_lifetime,
445                 expr_span,
446                 source_info,
447             ),
448             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
449                 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id.expect_local());
450                 this.lower_captured_upvar(block, upvar_id)
451             }
452
453             ExprKind::VarRef { id } => {
454                 let place_builder = if this.is_bound_var_in_guard(id) {
455                     let index = this.var_local_id(id, RefWithinGuard);
456                     PlaceBuilder::from(index).deref()
457                 } else {
458                     let index = this.var_local_id(id, OutsideGuard);
459                     PlaceBuilder::from(index)
460                 };
461                 block.and(place_builder)
462             }
463
464             ExprKind::PlaceTypeAscription { source, user_ty } => {
465                 let source = this.hir.mirror(source);
466                 let place_builder = unpack!(
467                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
468                 );
469                 if let Some(user_ty) = user_ty {
470                     let annotation_index =
471                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
472                             span: source_info.span,
473                             user_ty,
474                             inferred_ty: expr.ty,
475                         });
476
477                     let place =
478                         place_builder.clone().into_place(this.hir.tcx(), this.hir.typeck_results());
479                     this.cfg.push(
480                         block,
481                         Statement {
482                             source_info,
483                             kind: StatementKind::AscribeUserType(
484                                 box (
485                                     place,
486                                     UserTypeProjection { base: annotation_index, projs: vec![] },
487                                 ),
488                                 Variance::Invariant,
489                             ),
490                         },
491                     );
492                 }
493                 block.and(place_builder)
494             }
495             ExprKind::ValueTypeAscription { source, user_ty } => {
496                 let source = this.hir.mirror(source);
497                 let temp =
498                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
499                 if let Some(user_ty) = user_ty {
500                     let annotation_index =
501                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
502                             span: source_info.span,
503                             user_ty,
504                             inferred_ty: expr.ty,
505                         });
506                     this.cfg.push(
507                         block,
508                         Statement {
509                             source_info,
510                             kind: StatementKind::AscribeUserType(
511                                 box (
512                                     Place::from(temp),
513                                     UserTypeProjection { base: annotation_index, projs: vec![] },
514                                 ),
515                                 Variance::Invariant,
516                             ),
517                         },
518                     );
519                 }
520                 block.and(PlaceBuilder::from(temp))
521             }
522
523             ExprKind::Array { .. }
524             | ExprKind::Tuple { .. }
525             | ExprKind::Adt { .. }
526             | ExprKind::Closure { .. }
527             | ExprKind::Unary { .. }
528             | ExprKind::Binary { .. }
529             | ExprKind::LogicalOp { .. }
530             | ExprKind::Box { .. }
531             | ExprKind::Cast { .. }
532             | ExprKind::Use { .. }
533             | ExprKind::NeverToAny { .. }
534             | ExprKind::Pointer { .. }
535             | ExprKind::Repeat { .. }
536             | ExprKind::Borrow { .. }
537             | ExprKind::AddressOf { .. }
538             | ExprKind::Match { .. }
539             | ExprKind::If { .. }
540             | ExprKind::Loop { .. }
541             | ExprKind::Block { .. }
542             | ExprKind::Assign { .. }
543             | ExprKind::AssignOp { .. }
544             | ExprKind::Break { .. }
545             | ExprKind::Continue { .. }
546             | ExprKind::Return { .. }
547             | ExprKind::Literal { .. }
548             | ExprKind::ConstBlock { .. }
549             | ExprKind::StaticRef { .. }
550             | ExprKind::InlineAsm { .. }
551             | ExprKind::LlvmInlineAsm { .. }
552             | ExprKind::Yield { .. }
553             | ExprKind::ThreadLocalRef(_)
554             | ExprKind::Call { .. } => {
555                 // these are not places, so we need to make a temporary.
556                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
557                 let temp =
558                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
559                 block.and(PlaceBuilder::from(temp))
560             }
561         }
562     }
563
564     /// Lower a captured upvar. Note we might not know the actual capture index,
565     /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
566     /// once all projections that allow us to indentify a capture have been applied.
567     fn lower_captured_upvar(
568         &mut self,
569         block: BasicBlock,
570         upvar_id: ty::UpvarId,
571     ) -> BlockAnd<PlaceBuilder<'tcx>> {
572         let closure_ty = self
573             .hir
574             .typeck_results()
575             .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
576
577         let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
578             self.hir.infcx().closure_kind(closure_substs).unwrap()
579         } else {
580             // Generators are considered FnOnce.
581             ty::ClosureKind::FnOnce
582         };
583
584         block.and(PlaceBuilder::from(PlaceBase::Upvar {
585             var_hir_id: upvar_id.var_path.hir_id,
586             closure_def_id: upvar_id.closure_expr_id.to_def_id(),
587             closure_kind,
588         }))
589     }
590
591     /// Lower an index expression
592     ///
593     /// This has two complications;
594     ///
595     /// * We need to do a bounds check.
596     /// * We need to ensure that the bounds check can't be invalidated using an
597     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
598     ///   that this is the case.
599     fn lower_index_expression(
600         &mut self,
601         mut block: BasicBlock,
602         base: ExprRef<'tcx>,
603         index: ExprRef<'tcx>,
604         mutability: Mutability,
605         fake_borrow_temps: Option<&mut Vec<Local>>,
606         temp_lifetime: Option<region::Scope>,
607         expr_span: Span,
608         source_info: SourceInfo,
609     ) -> BlockAnd<PlaceBuilder<'tcx>> {
610         let lhs = self.hir.mirror(base);
611
612         let base_fake_borrow_temps = &mut Vec::new();
613         let is_outermost_index = fake_borrow_temps.is_none();
614         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
615
616         let mut base_place =
617             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
618
619         // Making this a *fresh* temporary means we do not have to worry about
620         // the index changing later: Nothing will ever change this temporary.
621         // The "retagging" transformation (for Stacked Borrows) relies on this.
622         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
623
624         block = self.bounds_check(
625             block,
626             base_place.clone().into_place(self.hir.tcx(), self.hir.typeck_results()),
627             idx,
628             expr_span,
629             source_info,
630         );
631
632         if is_outermost_index {
633             self.read_fake_borrows(block, fake_borrow_temps, source_info)
634         } else {
635             base_place =
636                 base_place.expect_upvars_resolved(self.hir.tcx(), self.hir.typeck_results());
637             self.add_fake_borrows_of_base(
638                 &base_place,
639                 block,
640                 fake_borrow_temps,
641                 expr_span,
642                 source_info,
643             );
644         }
645
646         block.and(base_place.index(idx))
647     }
648
649     fn bounds_check(
650         &mut self,
651         block: BasicBlock,
652         slice: Place<'tcx>,
653         index: Local,
654         expr_span: Span,
655         source_info: SourceInfo,
656     ) -> BasicBlock {
657         let usize_ty = self.hir.usize_ty();
658         let bool_ty = self.hir.bool_ty();
659         // bounds check:
660         let len = self.temp(usize_ty, expr_span);
661         let lt = self.temp(bool_ty, expr_span);
662
663         // len = len(slice)
664         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
665         // lt = idx < len
666         self.cfg.push_assign(
667             block,
668             source_info,
669             lt,
670             Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
671         );
672         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
673         // assert!(lt, "...")
674         self.assert(block, Operand::Move(lt), true, msg, expr_span)
675     }
676
677     fn add_fake_borrows_of_base(
678         &mut self,
679         base_place: &PlaceBuilder<'tcx>,
680         block: BasicBlock,
681         fake_borrow_temps: &mut Vec<Local>,
682         expr_span: Span,
683         source_info: SourceInfo,
684     ) {
685         let tcx = self.hir.tcx();
686         let local = match base_place.base {
687             PlaceBase::Local(local) => local,
688             PlaceBase::Upvar { .. } => bug!("Expected PlacseBase::Local found Upvar"),
689         };
690
691         let place_ty = Place::ty_from(local, &base_place.projection, &self.local_decls, tcx);
692         if let ty::Slice(_) = place_ty.ty.kind() {
693             // We need to create fake borrows to ensure that the bounds
694             // check that we just did stays valid. Since we can't assign to
695             // unsized values, we only need to ensure that none of the
696             // pointers in the base place are modified.
697             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
698                 match elem {
699                     ProjectionElem::Deref => {
700                         let fake_borrow_deref_ty = Place::ty_from(
701                             local,
702                             &base_place.projection[..idx],
703                             &self.local_decls,
704                             tcx,
705                         )
706                         .ty;
707                         let fake_borrow_ty =
708                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
709                         let fake_borrow_temp =
710                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
711                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
712                         self.cfg.push_assign(
713                             block,
714                             source_info,
715                             fake_borrow_temp.into(),
716                             Rvalue::Ref(
717                                 tcx.lifetimes.re_erased,
718                                 BorrowKind::Shallow,
719                                 Place { local, projection },
720                             ),
721                         );
722                         fake_borrow_temps.push(fake_borrow_temp);
723                     }
724                     ProjectionElem::Index(_) => {
725                         let index_ty = Place::ty_from(
726                             local,
727                             &base_place.projection[..idx],
728                             &self.local_decls,
729                             tcx,
730                         );
731                         match index_ty.ty.kind() {
732                             // The previous index expression has already
733                             // done any index expressions needed here.
734                             ty::Slice(_) => break,
735                             ty::Array(..) => (),
736                             _ => bug!("unexpected index base"),
737                         }
738                     }
739                     ProjectionElem::Field(..)
740                     | ProjectionElem::Downcast(..)
741                     | ProjectionElem::ConstantIndex { .. }
742                     | ProjectionElem::Subslice { .. } => (),
743                 }
744             }
745         }
746     }
747
748     fn read_fake_borrows(
749         &mut self,
750         bb: BasicBlock,
751         fake_borrow_temps: &mut Vec<Local>,
752         source_info: SourceInfo,
753     ) {
754         // All indexes have been evaluated now, read all of the
755         // fake borrows so that they are live across those index
756         // expressions.
757         for temp in fake_borrow_temps {
758             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
759         }
760     }
761 }