]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/elaborate_drops.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[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::hir;
13 use rustc::mir::*;
14 use rustc::middle::const_val::ConstInt;
15 use rustc::middle::lang_items;
16 use rustc::ty::{self, Ty};
17 use rustc::ty::subst::{Kind, Substs};
18 use rustc::ty::util::IntTypeExt;
19 use rustc_data_structures::indexed_vec::Idx;
20 use util::patch::MirPatch;
21
22 use std::iter;
23
24 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
25 pub enum DropFlagState {
26     Present, // i.e. initialized
27     Absent, // i.e. deinitialized or "moved"
28 }
29
30 impl DropFlagState {
31     pub fn value(self) -> bool {
32         match self {
33             DropFlagState::Present => true,
34             DropFlagState::Absent => false
35         }
36     }
37 }
38
39 #[derive(Debug)]
40 pub enum DropStyle {
41     Dead,
42     Static,
43     Conditional,
44     Open,
45 }
46
47 #[derive(Debug)]
48 pub enum DropFlagMode {
49     Shallow,
50     Deep
51 }
52
53 pub trait DropElaborator<'a, 'tcx: 'a> : fmt::Debug {
54     type Path : Copy + fmt::Debug;
55
56     fn patch(&mut self) -> &mut MirPatch<'tcx>;
57     fn mir(&self) -> &'a Mir<'tcx>;
58     fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx>;
59     fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx>;
60
61     fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
62     fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
63     fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
64
65
66     fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
67     fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
68     fn downcast_subpath(&self, path: Self::Path, variant: usize) -> Option<Self::Path>;
69 }
70
71 #[derive(Debug)]
72 struct DropCtxt<'l, 'b: 'l, 'tcx: 'b, D>
73     where D : DropElaborator<'b, 'tcx> + 'l
74 {
75     elaborator: &'l mut D,
76
77     source_info: SourceInfo,
78     is_cleanup: bool,
79
80     lvalue: &'l Lvalue<'tcx>,
81     path: D::Path,
82     succ: BasicBlock,
83     unwind: Option<BasicBlock>,
84 }
85
86 pub fn elaborate_drop<'b, 'tcx, D>(
87     elaborator: &mut D,
88     source_info: SourceInfo,
89     is_cleanup: bool,
90     lvalue: &Lvalue<'tcx>,
91     path: D::Path,
92     succ: BasicBlock,
93     unwind: Option<BasicBlock>,
94     bb: BasicBlock)
95     where D: DropElaborator<'b, 'tcx>
96 {
97     assert_eq!(unwind.is_none(), is_cleanup);
98     DropCtxt {
99         elaborator, source_info, is_cleanup, lvalue, path, succ, unwind
100     }.elaborate_drop(bb)
101 }
102
103 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
104     where D: DropElaborator<'b, 'tcx>
105 {
106     fn lvalue_ty(&self, lvalue: &Lvalue<'tcx>) -> Ty<'tcx> {
107         lvalue.ty(self.elaborator.mir(), self.tcx()).to_ty(self.tcx())
108     }
109
110     fn tcx(&self) -> ty::TyCtxt<'b, 'tcx, 'tcx> {
111         self.elaborator.tcx()
112     }
113
114     /// This elaborates a single drop instruction, located at `bb`, and
115     /// patches over it.
116     ///
117     /// The elaborated drop checks the drop flags to only drop what
118     /// is initialized.
119     ///
120     /// In addition, the relevant drop flags also need to be cleared
121     /// to avoid double-drops. However, in the middle of a complex
122     /// drop, one must avoid clearing some of the flags before they
123     /// are read, as that would cause a memory leak.
124     ///
125     /// In particular, when dropping an ADT, multiple fields may be
126     /// joined together under the `rest` subpath. They are all controlled
127     /// by the primary drop flag, but only the last rest-field dropped
128     /// should clear it (and it must also not clear anything else).
129     ///
130     /// FIXME: I think we should just control the flags externally
131     /// and then we do not need this machinery.
132     pub fn elaborate_drop<'a>(&mut self, bb: BasicBlock) {
133         debug!("elaborate_drop({:?})", self);
134         let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
135         debug!("elaborate_drop({:?}): live - {:?}", self, style);
136         match style {
137             DropStyle::Dead => {
138                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
139                     target: self.succ
140                 });
141             }
142             DropStyle::Static => {
143                 let loc = self.terminator_loc(bb);
144                 self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
145                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
146                     location: self.lvalue.clone(),
147                     target: self.succ,
148                     unwind: self.unwind
149                 });
150             }
151             DropStyle::Conditional => {
152                 let is_cleanup = self.is_cleanup; // FIXME(#6393)
153                 let succ = self.succ;
154                 let drop_bb = self.complete_drop(
155                     is_cleanup, Some(DropFlagMode::Deep), succ);
156                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
157                     target: drop_bb
158                 });
159             }
160             DropStyle::Open => {
161                 let drop_bb = self.open_drop();
162                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
163                     target: drop_bb
164                 });
165             }
166         }
167     }
168
169     /// Return the lvalue and move path for each field of `variant`,
170     /// (the move path is `None` if the field is a rest field).
171     fn move_paths_for_fields(&self,
172                              base_lv: &Lvalue<'tcx>,
173                              variant_path: D::Path,
174                              variant: &'tcx ty::VariantDef,
175                              substs: &'tcx Substs<'tcx>)
176                              -> Vec<(Lvalue<'tcx>, Option<D::Path>)>
177     {
178         variant.fields.iter().enumerate().map(|(i, f)| {
179             let field = Field::new(i);
180             let subpath = self.elaborator.field_subpath(variant_path, field);
181
182             let field_ty =
183                 self.tcx().normalize_associated_type_in_env(
184                     &f.ty(self.tcx(), substs),
185                     self.elaborator.param_env()
186                 );
187             (base_lv.clone().field(field, field_ty), subpath)
188         }).collect()
189     }
190
191     fn drop_subpath(&mut self,
192                     is_cleanup: bool,
193                     lvalue: &Lvalue<'tcx>,
194                     path: Option<D::Path>,
195                     succ: BasicBlock,
196                     unwind: Option<BasicBlock>)
197                     -> BasicBlock
198     {
199         if let Some(path) = path {
200             debug!("drop_subpath: for std field {:?}", lvalue);
201
202             DropCtxt {
203                 elaborator: self.elaborator,
204                 source_info: self.source_info,
205                 path, lvalue, succ, unwind, is_cleanup
206             }.elaborated_drop_block()
207         } else {
208             debug!("drop_subpath: for rest field {:?}", lvalue);
209
210             DropCtxt {
211                 elaborator: self.elaborator,
212                 source_info: self.source_info,
213                 lvalue, succ, unwind, is_cleanup,
214                 // Using `self.path` here to condition the drop on
215                 // our own drop flag.
216                 path: self.path
217             }.complete_drop(is_cleanup, None, succ)
218         }
219     }
220
221     /// Create one-half of the drop ladder for a list of fields, and return
222     /// the list of steps in it in reverse order.
223     ///
224     /// `unwind_ladder` is such a list of steps in reverse order,
225     /// which is called instead of the next step if the drop unwinds
226     /// (the first field is never reached). If it is `None`, all
227     /// unwind targets are left blank.
228     fn drop_halfladder<'a>(&mut self,
229                            unwind_ladder: Option<&[BasicBlock]>,
230                            succ: BasicBlock,
231                            fields: &[(Lvalue<'tcx>, Option<D::Path>)],
232                            is_cleanup: bool)
233                            -> Vec<BasicBlock>
234     {
235         let mut unwind_succ = if is_cleanup {
236             None
237         } else {
238             self.unwind
239         };
240
241         let goto = TerminatorKind::Goto { target: succ };
242         let mut succ = self.new_block(is_cleanup, goto);
243
244         // Always clear the "master" drop flag at the bottom of the
245         // ladder. This is needed because the "master" drop flag
246         // protects the ADT's discriminant, which is invalidated
247         // after the ADT is dropped.
248         let succ_loc = Location { block: succ, statement_index: 0 };
249         self.elaborator.clear_drop_flag(succ_loc, self.path, DropFlagMode::Shallow);
250
251         fields.iter().rev().enumerate().map(|(i, &(ref lv, path))| {
252             succ = self.drop_subpath(is_cleanup, lv, path, succ, unwind_succ);
253             unwind_succ = unwind_ladder.as_ref().map(|p| p[i]);
254             succ
255         }).collect()
256     }
257
258     /// Create a full drop ladder, consisting of 2 connected half-drop-ladders
259     ///
260     /// For example, with 3 fields, the drop ladder is
261     ///
262     /// .d0:
263     ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
264     /// .d1:
265     ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
266     /// .d2:
267     ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
268     /// .c1:
269     ///     ELAB(drop location.1 [target=.c2])
270     /// .c2:
271     ///     ELAB(drop location.2 [target=`self.unwind`])
272     fn drop_ladder<'a>(&mut self,
273                        fields: Vec<(Lvalue<'tcx>, Option<D::Path>)>)
274                        -> (BasicBlock, Option<BasicBlock>)
275     {
276         debug!("drop_ladder({:?}, {:?})", self, fields);
277
278         let mut fields = fields;
279         fields.retain(|&(ref lvalue, _)| {
280             self.lvalue_ty(lvalue).needs_drop(self.tcx(), self.elaborator.param_env())
281         });
282
283         debug!("drop_ladder - fields needing drop: {:?}", fields);
284
285         let unwind_ladder = if self.is_cleanup {
286             None
287         } else {
288             let unwind = self.unwind.unwrap(); // FIXME(#6393)
289             Some(self.drop_halfladder(None, unwind, &fields, true))
290         };
291
292         let succ = self.succ; // FIXME(#6393)
293         let is_cleanup = self.is_cleanup;
294         let normal_ladder =
295             self.drop_halfladder(unwind_ladder.as_ref().map(|x| &**x),
296                                  succ, &fields, is_cleanup);
297
298         (normal_ladder.last().cloned().unwrap_or(succ),
299          unwind_ladder.and_then(|l| l.last().cloned()).or(self.unwind))
300     }
301
302     fn open_drop_for_tuple<'a>(&mut self, tys: &[Ty<'tcx>])
303                                -> BasicBlock
304     {
305         debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
306
307         let fields = tys.iter().enumerate().map(|(i, &ty)| {
308             (self.lvalue.clone().field(Field::new(i), ty),
309              self.elaborator.field_subpath(self.path, Field::new(i)))
310         }).collect();
311
312         self.drop_ladder(fields).0
313     }
314
315     fn open_drop_for_box<'a>(&mut self, ty: Ty<'tcx>) -> BasicBlock
316     {
317         debug!("open_drop_for_box({:?}, {:?})", self, ty);
318
319         let interior = self.lvalue.clone().deref();
320         let interior_path = self.elaborator.deref_subpath(self.path);
321
322         let succ = self.succ; // FIXME(#6393)
323         let is_cleanup = self.is_cleanup;
324         let succ = self.box_free_block(ty, succ, is_cleanup);
325         let unwind_succ = self.unwind.map(|u| {
326             self.box_free_block(ty, u, true)
327         });
328
329         self.drop_subpath(is_cleanup, &interior, interior_path, succ, unwind_succ)
330     }
331
332     fn open_drop_for_adt<'a>(&mut self, adt: &'tcx ty::AdtDef, substs: &'tcx Substs<'tcx>)
333                              -> BasicBlock {
334         debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
335         if adt.variants.len() == 0 {
336             return self.elaborator.patch().new_block(BasicBlockData {
337                 statements: vec![],
338                 terminator: Some(Terminator {
339                     source_info: self.source_info,
340                     kind: TerminatorKind::Unreachable
341                 }),
342                 is_cleanup: self.is_cleanup
343             });
344         }
345
346         let contents_drop = if adt.is_union() {
347             (self.succ, self.unwind)
348         } else {
349             self.open_drop_for_adt_contents(adt, substs)
350         };
351
352         if adt.has_dtor(self.tcx()) {
353             self.destructor_call_block(contents_drop)
354         } else {
355             contents_drop.0
356         }
357     }
358
359     fn open_drop_for_adt_contents<'a>(&mut self, adt: &'tcx ty::AdtDef,
360                                       substs: &'tcx Substs<'tcx>)
361                                       -> (BasicBlock, Option<BasicBlock>) {
362         match adt.variants.len() {
363             1 => {
364                 let fields = self.move_paths_for_fields(
365                     self.lvalue,
366                     self.path,
367                     &adt.variants[0],
368                     substs
369                 );
370                 self.drop_ladder(fields)
371             }
372             _ => {
373                 let is_cleanup = self.is_cleanup;
374                 let succ = self.succ;
375                 let unwind = self.unwind; // FIXME(#6393)
376
377                 let mut values = Vec::with_capacity(adt.variants.len());
378                 let mut normal_blocks = Vec::with_capacity(adt.variants.len());
379                 let mut unwind_blocks = if is_cleanup {
380                     None
381                 } else {
382                     Some(Vec::with_capacity(adt.variants.len()))
383                 };
384                 let mut otherwise = None;
385                 let mut unwind_otherwise = None;
386                 for (variant_index, discr) in adt.discriminants(self.tcx()).enumerate() {
387                     let subpath = self.elaborator.downcast_subpath(
388                         self.path, variant_index);
389                     if let Some(variant_path) = subpath {
390                         let base_lv = self.lvalue.clone().elem(
391                             ProjectionElem::Downcast(adt, variant_index)
392                         );
393                         let fields = self.move_paths_for_fields(
394                             &base_lv,
395                             variant_path,
396                             &adt.variants[variant_index],
397                             substs);
398                         values.push(discr);
399                         if let Some(ref mut unwind_blocks) = unwind_blocks {
400                             // We can't use the half-ladder from the original
401                             // drop ladder, because this breaks the
402                             // "funclet can't have 2 successor funclets"
403                             // requirement from MSVC:
404                             //
405                             //           switch       unwind-switch
406                             //          /      \         /        \
407                             //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
408                             //         |        |      /             |
409                             //    v1.1-unwind  v2.1-unwind           |
410                             //      ^                                |
411                             //       \-------------------------------/
412                             //
413                             // Create a duplicate half-ladder to avoid that. We
414                             // could technically only do this on MSVC, but I
415                             // I want to minimize the divergence between MSVC
416                             // and non-MSVC.
417
418                             let unwind = unwind.unwrap();
419                             let halfladder = self.drop_halfladder(
420                                 None, unwind, &fields, true);
421                             unwind_blocks.push(
422                                 halfladder.last().cloned().unwrap_or(unwind)
423                             );
424                         }
425                         let (normal, _) = self.drop_ladder(fields);
426                         normal_blocks.push(normal);
427                     } else {
428                         // variant not found - drop the entire enum
429                         if let None = otherwise {
430                             otherwise = Some(self.complete_drop(
431                                 is_cleanup,
432                                 Some(DropFlagMode::Shallow),
433                                 succ));
434                             unwind_otherwise = unwind.map(|unwind| self.complete_drop(
435                                 true,
436                                 Some(DropFlagMode::Shallow),
437                                 unwind
438                             ));
439                         }
440                     }
441                 }
442                 if let Some(block) = otherwise {
443                     normal_blocks.push(block);
444                     if let Some(ref mut unwind_blocks) = unwind_blocks {
445                         unwind_blocks.push(unwind_otherwise.unwrap());
446                     }
447                 } else {
448                     values.pop();
449                 }
450
451                 (self.adt_switch_block(is_cleanup, adt, normal_blocks, &values, succ),
452                  unwind_blocks.map(|unwind_blocks| {
453                      self.adt_switch_block(
454                          is_cleanup, adt, unwind_blocks, &values, unwind.unwrap()
455                      )
456                  }))
457             }
458         }
459     }
460
461     fn adt_switch_block(&mut self,
462                         is_cleanup: bool,
463                         adt: &'tcx ty::AdtDef,
464                         blocks: Vec<BasicBlock>,
465                         values: &[ConstInt],
466                         succ: BasicBlock)
467                         -> BasicBlock {
468         // If there are multiple variants, then if something
469         // is present within the enum the discriminant, tracked
470         // by the rest path, must be initialized.
471         //
472         // Additionally, we do not want to switch on the
473         // discriminant after it is free-ed, because that
474         // way lies only trouble.
475         let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
476         let discr = Lvalue::Local(self.new_temp(discr_ty));
477         let discr_rv = Rvalue::Discriminant(self.lvalue.clone());
478         let switch_block = self.elaborator.patch().new_block(BasicBlockData {
479             statements: vec![
480                 Statement {
481                     source_info: self.source_info,
482                     kind: StatementKind::Assign(discr.clone(), discr_rv),
483                 }
484                 ],
485             terminator: Some(Terminator {
486                 source_info: self.source_info,
487                 kind: TerminatorKind::SwitchInt {
488                     discr: Operand::Consume(discr),
489                     switch_ty: discr_ty,
490                     values: From::from(values.to_owned()),
491                     targets: blocks,
492                 }
493             }),
494             is_cleanup: is_cleanup,
495         });
496         self.drop_flag_test_block(is_cleanup, switch_block, succ)
497     }
498
499     fn destructor_call_block<'a>(&mut self, (succ, unwind): (BasicBlock, Option<BasicBlock>))
500                                  -> BasicBlock
501     {
502         debug!("destructor_call_block({:?}, {:?})", self, succ);
503         let tcx = self.tcx();
504         let drop_trait = tcx.lang_items.drop_trait().unwrap();
505         let drop_fn = tcx.associated_items(drop_trait).next().unwrap();
506         let ty = self.lvalue_ty(self.lvalue);
507         let substs = tcx.mk_substs(iter::once(Kind::from(ty)));
508
509         let ref_ty = tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
510             ty: ty,
511             mutbl: hir::Mutability::MutMutable
512         });
513         let ref_lvalue = self.new_temp(ref_ty);
514         let unit_temp = Lvalue::Local(self.new_temp(tcx.mk_nil()));
515
516         self.elaborator.patch().new_block(BasicBlockData {
517             statements: vec![Statement {
518                 source_info: self.source_info,
519                 kind: StatementKind::Assign(
520                     Lvalue::Local(ref_lvalue),
521                     Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, self.lvalue.clone())
522                 )
523             }],
524             terminator: Some(Terminator {
525                 kind: TerminatorKind::Call {
526                     func: Operand::function_handle(tcx, drop_fn.def_id, substs,
527                                                    self.source_info.span),
528                     args: vec![Operand::Consume(Lvalue::Local(ref_lvalue))],
529                     destination: Some((unit_temp, succ)),
530                     cleanup: unwind,
531                 },
532                 source_info: self.source_info
533             }),
534             is_cleanup: self.is_cleanup,
535         })
536     }
537
538     /// The slow-path - create an "open", elaborated drop for a type
539     /// which is moved-out-of only partially, and patch `bb` to a jump
540     /// to it. This must not be called on ADTs with a destructor,
541     /// as these can't be moved-out-of, except for `Box<T>`, which is
542     /// special-cased.
543     ///
544     /// This creates a "drop ladder" that drops the needed fields of the
545     /// ADT, both in the success case or if one of the destructors fail.
546     fn open_drop<'a>(&mut self) -> BasicBlock {
547         let ty = self.lvalue_ty(self.lvalue);
548         let is_cleanup = self.is_cleanup; // FIXME(#6393)
549         let succ = self.succ;
550         match ty.sty {
551             ty::TyClosure(def_id, substs) => {
552                 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
553                 self.open_drop_for_tuple(&tys)
554             }
555             ty::TyTuple(tys, _) => {
556                 self.open_drop_for_tuple(tys)
557             }
558             ty::TyAdt(def, _) if def.is_box() => {
559                 self.open_drop_for_box(ty.boxed_ty())
560             }
561             ty::TyAdt(def, substs) => {
562                 self.open_drop_for_adt(def, substs)
563             }
564             ty::TyDynamic(..) => {
565                 self.complete_drop(is_cleanup, Some(DropFlagMode::Deep), succ)
566             }
567             ty::TyArray(..) | ty::TySlice(..) => {
568                 // FIXME(#34708): handle partially-dropped
569                 // array/slice elements.
570                 self.complete_drop(is_cleanup, Some(DropFlagMode::Deep), succ)
571             }
572             _ => bug!("open drop from non-ADT `{:?}`", ty)
573         }
574     }
575
576     /// Return a basic block that drop an lvalue using the context
577     /// and path in `c`. If `mode` is something, also clear `c`
578     /// according to it.
579     ///
580     /// if FLAG(self.path)
581     ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
582     ///     drop(self.lv)
583     fn complete_drop<'a>(&mut self,
584                          is_cleanup: bool,
585                          drop_mode: Option<DropFlagMode>,
586                          succ: BasicBlock) -> BasicBlock
587     {
588         debug!("complete_drop({:?},{:?})", self, drop_mode);
589
590         let drop_block = self.drop_block(is_cleanup, succ);
591         if let Some(mode) = drop_mode {
592             let block_start = Location { block: drop_block, statement_index: 0 };
593             self.elaborator.clear_drop_flag(block_start, self.path, mode);
594         }
595
596         self.drop_flag_test_block(is_cleanup, drop_block, succ)
597     }
598
599     fn elaborated_drop_block<'a>(&mut self) -> BasicBlock {
600         debug!("elaborated_drop_block({:?})", self);
601         let is_cleanup = self.is_cleanup; // FIXME(#6393)
602         let succ = self.succ;
603         let blk = self.drop_block(is_cleanup, succ);
604         self.elaborate_drop(blk);
605         blk
606     }
607
608     fn box_free_block<'a>(
609         &mut self,
610         ty: Ty<'tcx>,
611         target: BasicBlock,
612         is_cleanup: bool
613     ) -> BasicBlock {
614         let block = self.unelaborated_free_block(ty, target, is_cleanup);
615         self.drop_flag_test_block(is_cleanup, block, target)
616     }
617
618     fn unelaborated_free_block<'a>(
619         &mut self,
620         ty: Ty<'tcx>,
621         target: BasicBlock,
622         is_cleanup: bool
623     ) -> BasicBlock {
624         let tcx = self.tcx();
625         let unit_temp = Lvalue::Local(self.new_temp(tcx.mk_nil()));
626         let free_func = tcx.require_lang_item(lang_items::BoxFreeFnLangItem);
627         let substs = tcx.mk_substs(iter::once(Kind::from(ty)));
628
629         let call = TerminatorKind::Call {
630             func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
631             args: vec![Operand::Consume(self.lvalue.clone())],
632             destination: Some((unit_temp, target)),
633             cleanup: None
634         }; // FIXME(#6393)
635         let free_block = self.new_block(is_cleanup, call);
636
637         let block_start = Location { block: free_block, statement_index: 0 };
638         self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
639         free_block
640     }
641
642     fn drop_block<'a>(&mut self, is_cleanup: bool, succ: BasicBlock) -> BasicBlock {
643         let block = TerminatorKind::Drop {
644             location: self.lvalue.clone(),
645             target: succ,
646             unwind: if is_cleanup { None } else { self.unwind }
647         };
648         self.new_block(is_cleanup, block)
649     }
650
651     fn drop_flag_test_block(&mut self,
652                             is_cleanup: bool,
653                             on_set: BasicBlock,
654                             on_unset: BasicBlock)
655                             -> BasicBlock
656     {
657         let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
658         debug!("drop_flag_test_block({:?},{:?},{:?}) - {:?}",
659                self, is_cleanup, on_set, style);
660
661         match style {
662             DropStyle::Dead => on_unset,
663             DropStyle::Static => on_set,
664             DropStyle::Conditional | DropStyle::Open => {
665                 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
666                 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
667                 self.new_block(is_cleanup, term)
668             }
669         }
670     }
671
672     fn new_block<'a>(&mut self,
673                      is_cleanup: bool,
674                      k: TerminatorKind<'tcx>)
675                      -> BasicBlock
676     {
677         self.elaborator.patch().new_block(BasicBlockData {
678             statements: vec![],
679             terminator: Some(Terminator {
680                 source_info: self.source_info, kind: k
681             }),
682             is_cleanup: is_cleanup
683         })
684     }
685
686     fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
687         self.elaborator.patch().new_temp(ty, self.source_info.span)
688     }
689
690     fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
691         let mir = self.elaborator.mir();
692         self.elaborator.patch().terminator_loc(mir, bb)
693     }
694 }