]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/elaborate_drops.rs
move the drop expansion code to rustc_mir
[rust.git] / src / librustc_mir / util / elaborate_drops.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::fmt;
12 use rustc::mir::*;
13 use rustc::middle::lang_items;
14 use rustc::ty::{self, Ty};
15 use rustc::ty::subst::{Kind, Subst, Substs};
16 use rustc::ty::util::IntTypeExt;
17 use rustc_data_structures::indexed_vec::Idx;
18 use util::patch::MirPatch;
19
20 use std::iter;
21
22 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
23 pub enum DropFlagState {
24     Present, // i.e. initialized
25     Absent, // i.e. deinitialized or "moved"
26 }
27
28 impl DropFlagState {
29     pub fn value(self) -> bool {
30         match self {
31             DropFlagState::Present => true,
32             DropFlagState::Absent => false
33         }
34     }
35 }
36
37 #[derive(Debug)]
38 pub enum DropStyle {
39     Dead,
40     Static,
41     Conditional,
42     Open,
43 }
44
45 #[derive(Debug)]
46 pub enum DropFlagMode {
47     Shallow,
48     Deep
49 }
50
51 pub trait DropElaborator<'a, 'tcx: 'a> : fmt::Debug {
52     type Path : Copy + fmt::Debug;
53
54     fn patch(&mut self) -> &mut MirPatch<'tcx>;
55     fn mir(&self) -> &'a Mir<'tcx>;
56     fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx>;
57     fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx>;
58
59     fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
60     fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
61     fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
62
63
64     fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
65     fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
66     fn downcast_subpath(&self, path: Self::Path, variant: usize) -> Option<Self::Path>;
67 }
68
69 #[derive(Debug)]
70 struct DropCtxt<'l, 'b: 'l, 'tcx: 'b, D>
71     where D : DropElaborator<'b, 'tcx> + 'l
72 {
73     elaborator: &'l mut D,
74
75     source_info: SourceInfo,
76     is_cleanup: bool,
77
78     lvalue: &'l Lvalue<'tcx>,
79     path: D::Path,
80     succ: BasicBlock,
81     unwind: Option<BasicBlock>,
82 }
83
84 pub fn elaborate_drop<'b, 'tcx, D>(
85     elaborator: &mut D,
86     source_info: SourceInfo,
87     is_cleanup: bool,
88     lvalue: &Lvalue<'tcx>,
89     path: D::Path,
90     succ: BasicBlock,
91     unwind: Option<BasicBlock>,
92     bb: BasicBlock)
93     where D: DropElaborator<'b, 'tcx>
94 {
95     DropCtxt {
96         elaborator, source_info, is_cleanup, lvalue, path, succ, unwind
97     }.elaborate_drop(bb)
98 }
99
100 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
101     where D: DropElaborator<'b, 'tcx>
102 {
103     fn lvalue_ty(&self, lvalue: &Lvalue<'tcx>) -> Ty<'tcx> {
104         lvalue.ty(self.elaborator.mir(), self.tcx()).to_ty(self.tcx())
105     }
106
107     fn tcx(&self) -> ty::TyCtxt<'b, 'tcx, 'tcx> {
108         self.elaborator.tcx()
109     }
110
111     /// This elaborates a single drop instruction, located at `bb`, and
112     /// patches over it.
113     ///
114     /// The elaborated drop checks the drop flags to only drop what
115     /// is initialized.
116     ///
117     /// In addition, the relevant drop flags also need to be cleared
118     /// to avoid double-drops. However, in the middle of a complex
119     /// drop, one must avoid clearing some of the flags before they
120     /// are read, as that would cause a memory leak.
121     ///
122     /// In particular, when dropping an ADT, multiple fields may be
123     /// joined together under the `rest` subpath. They are all controlled
124     /// by the primary drop flag, but only the last rest-field dropped
125     /// should clear it (and it must also not clear anything else).
126     ///
127     /// FIXME: I think we should just control the flags externally
128     /// and then we do not need this machinery.
129     pub fn elaborate_drop<'a>(&mut self, bb: BasicBlock) {
130         debug!("elaborate_drop({:?})", self);
131         let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
132         debug!("elaborate_drop({:?}): live - {:?}", self, style);
133         match style {
134             DropStyle::Dead => {
135                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
136                     target: self.succ
137                 });
138             }
139             DropStyle::Static => {
140                 let loc = self.terminator_loc(bb);
141                 self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
142                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
143                     location: self.lvalue.clone(),
144                     target: self.succ,
145                     unwind: self.unwind
146                 });
147             }
148             DropStyle::Conditional => {
149                 let drop_bb = self.complete_drop(Some(DropFlagMode::Deep));
150                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
151                     target: drop_bb
152                 });
153             }
154             DropStyle::Open => {
155                 let drop_bb = self.open_drop();
156                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
157                     target: drop_bb
158                 });
159             }
160         }
161     }
162
163     /// Return the lvalue and move path for each field of `variant`,
164     /// (the move path is `None` if the field is a rest field).
165     fn move_paths_for_fields(&self,
166                              base_lv: &Lvalue<'tcx>,
167                              variant_path: D::Path,
168                              variant: &'tcx ty::VariantDef,
169                              substs: &'tcx Substs<'tcx>)
170                              -> Vec<(Lvalue<'tcx>, Option<D::Path>)>
171     {
172         variant.fields.iter().enumerate().map(|(i, f)| {
173             let field = Field::new(i);
174             let subpath = self.elaborator.field_subpath(variant_path, field);
175
176             let field_ty =
177                 self.tcx().normalize_associated_type_in_env(
178                     &f.ty(self.tcx(), substs),
179                     self.elaborator.param_env()
180                 );
181             (base_lv.clone().field(field, field_ty), subpath)
182         }).collect()
183     }
184
185     fn drop_subpath(&mut self,
186                     is_cleanup: bool,
187                     lvalue: &Lvalue<'tcx>,
188                     path: Option<D::Path>,
189                     succ: BasicBlock,
190                     unwind: Option<BasicBlock>)
191                     -> BasicBlock
192     {
193         if let Some(path) = path {
194             debug!("drop_subpath: for std field {:?}", lvalue);
195
196             DropCtxt {
197                 elaborator: self.elaborator,
198                 source_info: self.source_info,
199                 path, lvalue, succ, unwind, is_cleanup
200             }.elaborated_drop_block()
201         } else {
202             debug!("drop_subpath: for rest field {:?}", lvalue);
203
204             DropCtxt {
205                 elaborator: self.elaborator,
206                 source_info: self.source_info,
207                 lvalue, succ, unwind, is_cleanup,
208                 // Using `self.path` here to condition the drop on
209                 // our own drop flag.
210                 path: self.path
211             }.complete_drop(None)
212         }
213     }
214
215     /// Create one-half of the drop ladder for a list of fields, and return
216     /// the list of steps in it in reverse order.
217     ///
218     /// `unwind_ladder` is such a list of steps in reverse order,
219     /// which is called instead of the next step if the drop unwinds
220     /// (the first field is never reached). If it is `None`, all
221     /// unwind targets are left blank.
222     fn drop_halfladder<'a>(&mut self,
223                            unwind_ladder: Option<Vec<BasicBlock>>,
224                            succ: BasicBlock,
225                            fields: &[(Lvalue<'tcx>, Option<D::Path>)],
226                            is_cleanup: bool)
227                            -> Vec<BasicBlock>
228     {
229         let mut unwind_succ = if is_cleanup {
230             None
231         } else {
232             self.unwind
233         };
234
235         let goto = TerminatorKind::Goto { target: succ };
236         let mut succ = self.new_block(is_cleanup, goto);
237
238         // Always clear the "master" drop flag at the bottom of the
239         // ladder. This is needed because the "master" drop flag
240         // protects the ADT's discriminant, which is invalidated
241         // after the ADT is dropped.
242         let succ_loc = Location { block: succ, statement_index: 0 };
243         self.elaborator.clear_drop_flag(succ_loc, self.path, DropFlagMode::Shallow);
244
245         fields.iter().rev().enumerate().map(|(i, &(ref lv, path))| {
246             succ = self.drop_subpath(is_cleanup, lv, path, succ, unwind_succ);
247             unwind_succ = unwind_ladder.as_ref().map(|p| p[i]);
248             succ
249         }).collect()
250     }
251
252     /// Create a full drop ladder, consisting of 2 connected half-drop-ladders
253     ///
254     /// For example, with 3 fields, the drop ladder is
255     ///
256     /// .d0:
257     ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
258     /// .d1:
259     ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
260     /// .d2:
261     ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
262     /// .c1:
263     ///     ELAB(drop location.1 [target=.c2])
264     /// .c2:
265     ///     ELAB(drop location.2 [target=`self.unwind])
266     fn drop_ladder<'a>(&mut self,
267                        fields: Vec<(Lvalue<'tcx>, Option<D::Path>)>)
268                        -> BasicBlock
269     {
270         debug!("drop_ladder({:?}, {:?})", self, fields);
271
272         let mut fields = fields;
273         fields.retain(|&(ref lvalue, _)| {
274             self.tcx().type_needs_drop_given_env(
275                 self.lvalue_ty(lvalue), self.elaborator.param_env())
276         });
277
278         debug!("drop_ladder - fields needing drop: {:?}", fields);
279
280         let unwind_ladder = if self.is_cleanup {
281             None
282         } else {
283             let unwind = self.unwind.unwrap(); // FIXME(#6393)
284             Some(self.drop_halfladder(None, unwind, &fields, true))
285         };
286
287         let succ = self.succ; // FIXME(#6393)
288         let is_cleanup = self.is_cleanup;
289         self.drop_halfladder(unwind_ladder, succ, &fields, is_cleanup)
290             .last().cloned().unwrap_or(succ)
291     }
292
293     fn open_drop_for_tuple<'a>(&mut self, tys: &[Ty<'tcx>])
294                                -> BasicBlock
295     {
296         debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
297
298         let fields = tys.iter().enumerate().map(|(i, &ty)| {
299             (self.lvalue.clone().field(Field::new(i), ty),
300              self.elaborator.field_subpath(self.path, Field::new(i)))
301         }).collect();
302
303         self.drop_ladder(fields)
304     }
305
306     fn open_drop_for_box<'a>(&mut self, ty: Ty<'tcx>) -> BasicBlock
307     {
308         debug!("open_drop_for_box({:?}, {:?})", self, ty);
309
310         let interior = self.lvalue.clone().deref();
311         let interior_path = self.elaborator.deref_subpath(self.path);
312
313         let succ = self.succ; // FIXME(#6393)
314         let is_cleanup = self.is_cleanup;
315         let succ = self.box_free_block(ty, succ, is_cleanup);
316         let unwind_succ = self.unwind.map(|u| {
317             self.box_free_block(ty, u, true)
318         });
319
320         self.drop_subpath(is_cleanup, &interior, interior_path, succ, unwind_succ)
321     }
322
323     fn open_drop_for_adt<'a>(&mut self, adt: &'tcx ty::AdtDef, substs: &'tcx Substs<'tcx>)
324                              -> BasicBlock {
325         debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
326
327         match adt.variants.len() {
328             1 => {
329                 let fields = self.move_paths_for_fields(
330                     self.lvalue,
331                     self.path,
332                     &adt.variants[0],
333                     substs
334                 );
335                 self.drop_ladder(fields)
336             }
337             _ => {
338                 let mut values = Vec::with_capacity(adt.variants.len());
339                 let mut blocks = Vec::with_capacity(adt.variants.len());
340                 let mut otherwise = None;
341                 for (variant_index, discr) in adt.discriminants(self.tcx()).enumerate() {
342                     let subpath = self.elaborator.downcast_subpath(
343                         self.path, variant_index);
344                     if let Some(variant_path) = subpath {
345                         let base_lv = self.lvalue.clone().elem(
346                             ProjectionElem::Downcast(adt, variant_index)
347                         );
348                         let fields = self.move_paths_for_fields(
349                             &base_lv,
350                             variant_path,
351                             &adt.variants[variant_index],
352                             substs);
353                         values.push(discr);
354                         blocks.push(self.drop_ladder(fields));
355                     } else {
356                         // variant not found - drop the entire enum
357                         if let None = otherwise {
358                             otherwise =
359                                 Some(self.complete_drop(Some(DropFlagMode::Shallow)));
360                         }
361                     }
362                 }
363                 if let Some(block) = otherwise {
364                     blocks.push(block);
365                 } else {
366                     values.pop();
367                 }
368                 // If there are multiple variants, then if something
369                 // is present within the enum the discriminant, tracked
370                 // by the rest path, must be initialized.
371                 //
372                 // Additionally, we do not want to switch on the
373                 // discriminant after it is free-ed, because that
374                 // way lies only trouble.
375                 let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
376                 let discr = Lvalue::Local(self.new_temp(discr_ty));
377                 let discr_rv = Rvalue::Discriminant(self.lvalue.clone());
378                 let switch_block = self.elaborator.patch().new_block(BasicBlockData {
379                     statements: vec![
380                         Statement {
381                             source_info: self.source_info,
382                             kind: StatementKind::Assign(discr.clone(), discr_rv),
383                         }
384                     ],
385                     terminator: Some(Terminator {
386                         source_info: self.source_info,
387                         kind: TerminatorKind::SwitchInt {
388                             discr: Operand::Consume(discr),
389                             switch_ty: discr_ty,
390                             values: From::from(values),
391                             targets: blocks,
392                         }
393                     }),
394                     is_cleanup: self.is_cleanup,
395                 });
396                 self.drop_flag_test_block(switch_block)
397             }
398         }
399     }
400
401     /// The slow-path - create an "open", elaborated drop for a type
402     /// which is moved-out-of only partially, and patch `bb` to a jump
403     /// to it. This must not be called on ADTs with a destructor,
404     /// as these can't be moved-out-of, except for `Box<T>`, which is
405     /// special-cased.
406     ///
407     /// This creates a "drop ladder" that drops the needed fields of the
408     /// ADT, both in the success case or if one of the destructors fail.
409     fn open_drop<'a>(&mut self) -> BasicBlock {
410         let ty = self.lvalue_ty(self.lvalue);
411         match ty.sty {
412             ty::TyClosure(def_id, substs) => {
413                 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
414                 self.open_drop_for_tuple(&tys)
415             }
416             ty::TyTuple(tys, _) => {
417                 self.open_drop_for_tuple(tys)
418             }
419             ty::TyAdt(def, _) if def.is_box() => {
420                 self.open_drop_for_box(ty.boxed_ty())
421             }
422             ty::TyAdt(def, substs) => {
423                 self.open_drop_for_adt(def, substs)
424             }
425             _ => bug!("open drop from non-ADT `{:?}`", ty)
426         }
427     }
428
429     /// Return a basic block that drop an lvalue using the context
430     /// and path in `c`. If `mode` is something, also clear `c`
431     /// according to it.
432     ///
433     /// if FLAG(self.path)
434     ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
435     ///     drop(self.lv)
436     fn complete_drop<'a>(&mut self, drop_mode: Option<DropFlagMode>) -> BasicBlock
437     {
438         debug!("complete_drop({:?},{:?})", self, drop_mode);
439
440         let drop_block = self.drop_block();
441         if let Some(mode) = drop_mode {
442             let block_start = Location { block: drop_block, statement_index: 0 };
443             self.elaborator.clear_drop_flag(block_start, self.path, mode);
444         }
445
446         self.drop_flag_test_block(drop_block)
447     }
448
449     fn elaborated_drop_block<'a>(&mut self) -> BasicBlock {
450         debug!("elaborated_drop_block({:?})", self);
451         let blk = self.drop_block();
452         self.elaborate_drop(blk);
453         blk
454     }
455
456     fn box_free_block<'a>(
457         &mut self,
458         ty: Ty<'tcx>,
459         target: BasicBlock,
460         is_cleanup: bool
461     ) -> BasicBlock {
462         let block = self.unelaborated_free_block(ty, target, is_cleanup);
463         self.drop_flag_test_block_with_succ(is_cleanup, block, target)
464     }
465
466     fn unelaborated_free_block<'a>(
467         &mut self,
468         ty: Ty<'tcx>,
469         target: BasicBlock,
470         is_cleanup: bool
471     ) -> BasicBlock {
472         let tcx = self.tcx();
473         let unit_temp = Lvalue::Local(self.new_temp(tcx.mk_nil()));
474         let free_func = tcx.require_lang_item(lang_items::BoxFreeFnLangItem);
475         let substs = tcx.mk_substs(iter::once(Kind::from(ty)));
476         let fty = tcx.item_type(free_func).subst(tcx, substs);
477
478         let free_block = self.elaborator.patch().new_block(BasicBlockData {
479             statements: vec![],
480             terminator: Some(Terminator {
481                 source_info: self.source_info, kind: TerminatorKind::Call {
482                     func: Operand::Constant(Constant {
483                         span: self.source_info.span,
484                         ty: fty,
485                         literal: Literal::Item {
486                             def_id: free_func,
487                             substs: substs
488                         }
489                     }),
490                     args: vec![Operand::Consume(self.lvalue.clone())],
491                     destination: Some((unit_temp, target)),
492                     cleanup: None
493                 }
494             }),
495             is_cleanup: is_cleanup
496         });
497         let block_start = Location { block: free_block, statement_index: 0 };
498         self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
499         free_block
500     }
501
502     fn drop_block<'a>(&mut self) -> BasicBlock {
503         let block = TerminatorKind::Drop {
504             location: self.lvalue.clone(),
505             target: self.succ,
506             unwind: self.unwind
507         };
508         let is_cleanup = self.is_cleanup; // FIXME(#6393)
509         self.new_block(is_cleanup, block)
510     }
511
512     fn drop_flag_test_block<'a>(&mut self, on_set: BasicBlock) -> BasicBlock {
513         let is_cleanup = self.is_cleanup;
514         let succ = self.succ; // FIXME(#6393)
515         self.drop_flag_test_block_with_succ(is_cleanup, on_set, succ)
516     }
517
518     fn drop_flag_test_block_with_succ<'a>(&mut self,
519                                           is_cleanup: bool,
520                                           on_set: BasicBlock,
521                                           on_unset: BasicBlock)
522                                           -> BasicBlock
523     {
524         let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
525         debug!("drop_flag_test_block({:?},{:?},{:?}) - {:?}",
526                self, is_cleanup, on_set, style);
527
528         match style {
529             DropStyle::Dead => on_unset,
530             DropStyle::Static => on_set,
531             DropStyle::Conditional | DropStyle::Open => {
532                 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
533                 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
534                 self.new_block(is_cleanup, term)
535             }
536         }
537     }
538
539     fn new_block<'a>(&mut self,
540                      is_cleanup: bool,
541                      k: TerminatorKind<'tcx>)
542                      -> BasicBlock
543     {
544         self.elaborator.patch().new_block(BasicBlockData {
545             statements: vec![],
546             terminator: Some(Terminator {
547                 source_info: self.source_info, kind: k
548             }),
549             is_cleanup: is_cleanup
550         })
551     }
552
553     fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
554         self.elaborator.patch().new_temp(ty)
555     }
556
557     fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
558         let mir = self.elaborator.mir();
559         self.elaborator.patch().terminator_loc(mir, bb)
560     }
561 }