1 use rustc_index::vec::IndexVec;
2 use rustc_middle::mir::tcx::RvalueInitializationState;
3 use rustc_middle::mir::*;
4 use rustc_middle::ty::{self, TyCtxt};
5 use smallvec::{smallvec, SmallVec};
7 use std::convert::TryInto;
10 use super::abs_domain::Lift;
11 use super::IllegalMoveOriginKind::*;
12 use super::{Init, InitIndex, InitKind, InitLocation, LookupResult, MoveError};
14 LocationMap, MoveData, MoveOut, MoveOutIndex, MovePath, MovePathIndex, MovePathLookup,
17 struct MoveDataBuilder<'a, 'tcx> {
20 param_env: ty::ParamEnv<'tcx>,
22 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>,
25 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
26 fn new(body: &'a Body<'tcx>, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
27 let mut move_paths = IndexVec::new();
28 let mut path_map = IndexVec::new();
29 let mut init_path_map = IndexVec::new();
37 moves: IndexVec::new(),
38 loc_map: LocationMap::new(body),
39 rev_lookup: MovePathLookup {
53 projections: Default::default(),
57 inits: IndexVec::new(),
58 init_loc_map: LocationMap::new(body),
65 move_paths: &mut IndexVec<MovePathIndex, MovePath<'tcx>>,
66 path_map: &mut IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
67 init_path_map: &mut IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
68 parent: Option<MovePathIndex>,
72 move_paths.push(MovePath { next_sibling: None, first_child: None, parent, place });
74 if let Some(parent) = parent {
75 let next_sibling = mem::replace(&mut move_paths[parent].first_child, Some(move_path));
76 move_paths[move_path].next_sibling = next_sibling;
79 let path_map_ent = path_map.push(smallvec![]);
80 assert_eq!(path_map_ent, move_path);
82 let init_path_map_ent = init_path_map.push(smallvec![]);
83 assert_eq!(init_path_map_ent, move_path);
89 impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> {
90 /// This creates a MovePath for a given place, returning an `MovePathError`
91 /// if that place can't be moved from.
93 /// NOTE: places behind references *do not* get a move path, which is
94 /// problematic for borrowck.
96 /// Maybe we should have separate "borrowck" and "moveck" modes.
97 fn move_path_for(&mut self, place: Place<'tcx>) -> Result<MovePathIndex, MoveError<'tcx>> {
98 debug!("lookup({:?})", place);
99 let mut base = self.builder.data.rev_lookup.locals[place.local];
101 // The move path index of the first union that we find. Once this is
102 // some we stop creating child move paths, since moves from unions
103 // move the whole thing.
104 // We continue looking for other move errors though so that moving
105 // from `*(u.f: &_)` isn't allowed.
106 let mut union_path = None;
108 for (i, elem) in place.projection.iter().enumerate() {
109 let proj_base = &place.projection[..i];
110 let body = self.builder.body;
111 let tcx = self.builder.tcx;
112 let place_ty = Place::ty_from(place.local, proj_base, body, tcx).ty;
113 match place_ty.kind {
114 ty::Ref(..) | ty::RawPtr(..) => {
115 let proj = &place.projection[..i + 1];
116 return Err(MoveError::cannot_move_out_of(
119 target_place: Place {
121 projection: tcx.intern_place_elems(proj),
126 ty::Adt(adt, _) if adt.has_dtor(tcx) && !adt.is_box() => {
127 return Err(MoveError::cannot_move_out_of(
129 InteriorOfTypeWithDestructor { container_ty: place_ty },
132 ty::Adt(adt, _) if adt.is_union() => {
133 union_path.get_or_insert(base);
136 return Err(MoveError::cannot_move_out_of(
138 InteriorOfSliceOrArray {
140 is_index: match elem {
141 ProjectionElem::Index(..) => true,
149 if let ProjectionElem::Index(..) = elem {
150 return Err(MoveError::cannot_move_out_of(
152 InteriorOfSliceOrArray { ty: place_ty, is_index: true },
160 if union_path.is_none() {
161 base = self.add_move_path(base, elem, |tcx| Place {
163 projection: tcx.intern_place_elems(&place.projection[..i + 1]),
168 if let Some(base) = union_path {
169 // Move out of union - always move the entire union.
170 Err(MoveError::UnionMove { path: base })
179 elem: PlaceElem<'tcx>,
180 mk_place: impl FnOnce(TyCtxt<'tcx>) -> Place<'tcx>,
182 let MoveDataBuilder {
183 data: MoveData { rev_lookup, move_paths, path_map, init_path_map, .. },
187 *rev_lookup.projections.entry((base, elem.lift())).or_insert_with(move || {
188 MoveDataBuilder::new_move_path(
198 fn create_move_path(&mut self, place: Place<'tcx>) {
199 // This is an non-moving access (such as an overwrite or
200 // drop), so this not being a valid move path is OK.
201 let _ = self.move_path_for(place);
205 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
208 ) -> Result<MoveData<'tcx>, (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
210 debug!("moves for {:?}:", self.body.span);
211 for (j, mo) in self.data.moves.iter_enumerated() {
212 debug!(" {:?} = {:?}", j, mo);
214 debug!("move paths for {:?}:", self.body.span);
215 for (j, path) in self.data.move_paths.iter_enumerated() {
216 debug!(" {:?} = {:?}", j, path);
221 if !self.errors.is_empty() { Err((self.data, self.errors)) } else { Ok(self.data) }
225 pub(super) fn gather_moves<'tcx>(
228 param_env: ty::ParamEnv<'tcx>,
229 ) -> Result<MoveData<'tcx>, (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
230 let mut builder = MoveDataBuilder::new(body, tcx, param_env);
232 builder.gather_args();
234 for (bb, block) in body.basic_blocks().iter_enumerated() {
235 for (i, stmt) in block.statements.iter().enumerate() {
236 let source = Location { block: bb, statement_index: i };
237 builder.gather_statement(source, stmt);
240 let terminator_loc = Location { block: bb, statement_index: block.statements.len() };
241 builder.gather_terminator(terminator_loc, block.terminator());
247 impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> {
248 fn gather_args(&mut self) {
249 for arg in self.body.args_iter() {
250 let path = self.data.rev_lookup.locals[arg];
252 let init = self.data.inits.push(Init {
254 kind: InitKind::Deep,
255 location: InitLocation::Argument(arg),
258 debug!("gather_args: adding init {:?} of {:?} for argument {:?}", init, path, arg);
260 self.data.init_path_map[path].push(init);
264 fn gather_statement(&mut self, loc: Location, stmt: &Statement<'tcx>) {
265 debug!("gather_statement({:?}, {:?})", loc, stmt);
266 (Gatherer { builder: self, loc }).gather_statement(stmt);
269 fn gather_terminator(&mut self, loc: Location, term: &Terminator<'tcx>) {
270 debug!("gather_terminator({:?}, {:?})", loc, term);
271 (Gatherer { builder: self, loc }).gather_terminator(term);
275 struct Gatherer<'b, 'a, 'tcx> {
276 builder: &'b mut MoveDataBuilder<'a, 'tcx>,
280 impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> {
281 fn gather_statement(&mut self, stmt: &Statement<'tcx>) {
283 StatementKind::Assign(box (place, rval)) => {
284 self.create_move_path(*place);
285 if let RvalueInitializationState::Shallow = rval.initialization_state() {
286 // Box starts out uninitialized - need to create a separate
287 // move-path for the interior so it will be separate from
289 self.create_move_path(self.builder.tcx.mk_place_deref(*place));
290 self.gather_init(place.as_ref(), InitKind::Shallow);
292 self.gather_init(place.as_ref(), InitKind::Deep);
294 self.gather_rvalue(rval);
296 StatementKind::FakeRead(_, place) => {
297 self.create_move_path(**place);
299 StatementKind::LlvmInlineAsm(ref asm) => {
300 for (output, kind) in asm.outputs.iter().zip(&asm.asm.outputs) {
301 if !kind.is_indirect {
302 self.gather_init(output.as_ref(), InitKind::Deep);
305 for (_, input) in asm.inputs.iter() {
306 self.gather_operand(input);
309 StatementKind::StorageLive(_) => {}
310 StatementKind::StorageDead(local) => {
311 self.gather_move(Place::from(*local));
313 StatementKind::SetDiscriminant { .. } => {
315 stmt.source_info.span,
316 "SetDiscriminant should not exist during borrowck"
319 StatementKind::Retag { .. }
320 | StatementKind::AscribeUserType(..)
321 | StatementKind::Coverage(..)
322 | StatementKind::Nop => {}
326 fn gather_rvalue(&mut self, rvalue: &Rvalue<'tcx>) {
328 Rvalue::ThreadLocalRef(_) => {} // not-a-move
329 Rvalue::Use(ref operand)
330 | Rvalue::Repeat(ref operand, _)
331 | Rvalue::Cast(_, ref operand, _)
332 | Rvalue::UnaryOp(_, ref operand) => self.gather_operand(operand),
333 Rvalue::BinaryOp(ref _binop, ref lhs, ref rhs)
334 | Rvalue::CheckedBinaryOp(ref _binop, ref lhs, ref rhs) => {
335 self.gather_operand(lhs);
336 self.gather_operand(rhs);
338 Rvalue::Aggregate(ref _kind, ref operands) => {
339 for operand in operands {
340 self.gather_operand(operand);
344 | Rvalue::AddressOf(..)
345 | Rvalue::Discriminant(..)
347 | Rvalue::NullaryOp(NullOp::SizeOf, _)
348 | Rvalue::NullaryOp(NullOp::Box, _) => {
349 // This returns an rvalue with uninitialized contents. We can't
350 // move out of it here because it is an rvalue - assignments always
351 // completely initialize their place.
353 // However, this does not matter - MIR building is careful to
354 // only emit a shallow free for the partially-initialized
357 // In any case, if we want to fix this, we have to register a
358 // special move and change the `statement_effect` functions.
363 fn gather_terminator(&mut self, term: &Terminator<'tcx>) {
365 TerminatorKind::Goto { target: _ }
366 | TerminatorKind::Resume
367 | TerminatorKind::Abort
368 | TerminatorKind::GeneratorDrop
369 | TerminatorKind::FalseEdge { .. }
370 | TerminatorKind::FalseUnwind { .. }
371 | TerminatorKind::Unreachable => {}
373 TerminatorKind::Return => {
374 self.gather_move(Place::return_place());
377 TerminatorKind::Assert { ref cond, .. } => {
378 self.gather_operand(cond);
381 TerminatorKind::SwitchInt { ref discr, .. } => {
382 self.gather_operand(discr);
385 TerminatorKind::Yield { ref value, resume_arg: place, .. } => {
386 self.gather_operand(value);
387 self.create_move_path(place);
388 self.gather_init(place.as_ref(), InitKind::Deep);
391 TerminatorKind::Drop { place, target: _, unwind: _ } => {
392 self.gather_move(place);
394 TerminatorKind::DropAndReplace { place, ref value, .. } => {
395 self.create_move_path(place);
396 self.gather_operand(value);
397 self.gather_init(place.as_ref(), InitKind::Deep);
399 TerminatorKind::Call {
407 self.gather_operand(func);
409 self.gather_operand(arg);
411 if let Some((destination, _bb)) = *destination {
412 self.create_move_path(destination);
413 self.gather_init(destination.as_ref(), InitKind::NonPanicPathOnly);
416 TerminatorKind::InlineAsm {
425 InlineAsmOperand::In { reg: _, ref value }
426 | InlineAsmOperand::Const { ref value } => {
427 self.gather_operand(value);
429 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
430 if let Some(place) = place {
431 self.create_move_path(place);
432 self.gather_init(place.as_ref(), InitKind::Deep);
435 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
436 self.gather_operand(in_value);
437 if let Some(out_place) = out_place {
438 self.create_move_path(out_place);
439 self.gather_init(out_place.as_ref(), InitKind::Deep);
442 InlineAsmOperand::SymFn { value: _ }
443 | InlineAsmOperand::SymStatic { def_id: _ } => {}
450 fn gather_operand(&mut self, operand: &Operand<'tcx>) {
452 Operand::Constant(..) | Operand::Copy(..) => {} // not-a-move
453 Operand::Move(place) => {
455 self.gather_move(place);
460 fn gather_move(&mut self, place: Place<'tcx>) {
461 debug!("gather_move({:?}, {:?})", self.loc, place);
463 if let [ref base @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
466 // Split `Subslice` patterns into the corresponding list of
467 // `ConstIndex` patterns. This is done to ensure that all move paths
468 // are disjoint, which is expected by drop elaboration.
470 Place { local: place.local, projection: self.builder.tcx.intern_place_elems(base) };
471 let base_path = match self.move_path_for(base_place) {
473 Err(MoveError::UnionMove { path }) => {
474 self.record_move(place, path);
477 Err(error @ MoveError::IllegalMove { .. }) => {
478 self.builder.errors.push((base_place, error));
482 let base_ty = base_place.ty(self.builder.body, self.builder.tcx).ty;
483 let len: u32 = match base_ty.kind {
484 ty::Array(_, size) => {
485 let length = size.eval_usize(self.builder.tcx, self.builder.param_env);
488 .expect("slice pattern of array with more than u32::MAX elements")
490 _ => bug!("from_end: false slice pattern of non-array type"),
492 for offset in from..to {
494 ProjectionElem::ConstantIndex { offset, min_length: len, from_end: false };
496 self.add_move_path(base_path, elem, |tcx| tcx.mk_place_elem(base_place, elem));
497 self.record_move(place, path);
500 match self.move_path_for(place) {
501 Ok(path) | Err(MoveError::UnionMove { path }) => self.record_move(place, path),
502 Err(error @ MoveError::IllegalMove { .. }) => {
503 self.builder.errors.push((place, error));
509 fn record_move(&mut self, place: Place<'tcx>, path: MovePathIndex) {
510 let move_out = self.builder.data.moves.push(MoveOut { path, source: self.loc });
512 "gather_move({:?}, {:?}): adding move {:?} of {:?}",
513 self.loc, place, move_out, path
515 self.builder.data.path_map[path].push(move_out);
516 self.builder.data.loc_map[self.loc].push(move_out);
519 fn gather_init(&mut self, place: PlaceRef<'tcx>, kind: InitKind) {
520 debug!("gather_init({:?}, {:?})", self.loc, place);
522 let mut place = place;
524 // Check if we are assigning into a field of a union, if so, lookup the place
525 // of the union so it is marked as initialized again.
526 if let [proj_base @ .., ProjectionElem::Field(_, _)] = place.projection {
527 if let ty::Adt(def, _) =
528 Place::ty_from(place.local, proj_base, self.builder.body, self.builder.tcx).ty.kind
531 place = PlaceRef { local: place.local, projection: proj_base }
536 if let LookupResult::Exact(path) = self.builder.data.rev_lookup.find(place) {
537 let init = self.builder.data.inits.push(Init {
538 location: InitLocation::Statement(self.loc),
544 "gather_init({:?}, {:?}): adding init {:?} of {:?}",
545 self.loc, place, init, path
548 self.builder.data.init_path_map[path].push(init);
549 self.builder.data.init_loc_map[self.loc].push(init);