]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/elaborate_drops.rs
f3e03e7f81daa89c9f5c09bfeb8135c85e92403c
[rust.git] / src / librustc_mir / util / elaborate_drops.rs
1 use std::fmt;
2 use rustc::hir;
3 use rustc::mir::*;
4 use rustc::middle::lang_items;
5 use rustc::traits::Reveal;
6 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc::ty::layout::VariantIdx;
8 use rustc::ty::subst::SubstsRef;
9 use rustc::ty::util::IntTypeExt;
10 use rustc_data_structures::indexed_vec::Idx;
11 use crate::util::patch::MirPatch;
12
13 use std::convert::TryInto;
14
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 pub enum DropFlagState {
17     Present, // i.e., initialized
18     Absent, // i.e., deinitialized or "moved"
19 }
20
21 impl DropFlagState {
22     pub fn value(self) -> bool {
23         match self {
24             DropFlagState::Present => true,
25             DropFlagState::Absent => false
26         }
27     }
28 }
29
30 #[derive(Debug)]
31 pub enum DropStyle {
32     Dead,
33     Static,
34     Conditional,
35     Open,
36 }
37
38 #[derive(Debug)]
39 pub enum DropFlagMode {
40     Shallow,
41     Deep
42 }
43
44 #[derive(Copy, Clone, Debug)]
45 pub enum Unwind {
46     To(BasicBlock),
47     InCleanup
48 }
49
50 impl Unwind {
51     fn is_cleanup(self) -> bool {
52         match self {
53             Unwind::To(..) => false,
54             Unwind::InCleanup => true
55         }
56     }
57
58     fn into_option(self) -> Option<BasicBlock> {
59         match self {
60             Unwind::To(bb) => Some(bb),
61             Unwind::InCleanup => None,
62         }
63     }
64
65     fn map<F>(self, f: F) -> Self where F: FnOnce(BasicBlock) -> BasicBlock {
66         match self {
67             Unwind::To(bb) => Unwind::To(f(bb)),
68             Unwind::InCleanup => Unwind::InCleanup
69         }
70     }
71 }
72
73 pub trait DropElaborator<'a, 'tcx>: fmt::Debug {
74     type Path : Copy + fmt::Debug;
75
76     fn patch(&mut self) -> &mut MirPatch<'tcx>;
77     fn body(&self) -> &'a Body<'tcx>;
78     fn tcx(&self) -> TyCtxt<'tcx>;
79     fn param_env(&self) -> ty::ParamEnv<'tcx>;
80
81     fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
82     fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
83     fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
84
85
86     fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
87     fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
88     fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
89     fn array_subpath(&self, path: Self::Path, index: u32, size: u32) -> Option<Self::Path>;
90 }
91
92 #[derive(Debug)]
93 struct DropCtxt<'l, 'b, 'tcx, D>
94 where
95     D: DropElaborator<'b, 'tcx>,
96 {
97     elaborator: &'l mut D,
98
99     source_info: SourceInfo,
100
101     place: &'l Place<'tcx>,
102     path: D::Path,
103     succ: BasicBlock,
104     unwind: Unwind,
105 }
106
107 pub fn elaborate_drop<'b, 'tcx, D>(
108     elaborator: &mut D,
109     source_info: SourceInfo,
110     place: &Place<'tcx>,
111     path: D::Path,
112     succ: BasicBlock,
113     unwind: Unwind,
114     bb: BasicBlock,
115 ) where
116     D: DropElaborator<'b, 'tcx>,
117     'tcx: 'b,
118 {
119     DropCtxt {
120         elaborator, source_info, place, path, succ, unwind
121     }.elaborate_drop(bb)
122 }
123
124 impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
125 where
126     D: DropElaborator<'b, 'tcx>,
127     'tcx: 'b,
128 {
129     fn place_ty(&self, place: &Place<'tcx>) -> Ty<'tcx> {
130         place.ty(self.elaborator.body(), self.tcx()).ty
131     }
132
133     fn tcx(&self) -> TyCtxt<'tcx> {
134         self.elaborator.tcx()
135     }
136
137     /// This elaborates a single drop instruction, located at `bb`, and
138     /// patches over it.
139     ///
140     /// The elaborated drop checks the drop flags to only drop what
141     /// is initialized.
142     ///
143     /// In addition, the relevant drop flags also need to be cleared
144     /// to avoid double-drops. However, in the middle of a complex
145     /// drop, one must avoid clearing some of the flags before they
146     /// are read, as that would cause a memory leak.
147     ///
148     /// In particular, when dropping an ADT, multiple fields may be
149     /// joined together under the `rest` subpath. They are all controlled
150     /// by the primary drop flag, but only the last rest-field dropped
151     /// should clear it (and it must also not clear anything else).
152     //
153     // FIXME: I think we should just control the flags externally,
154     // and then we do not need this machinery.
155     pub fn elaborate_drop(&mut self, bb: BasicBlock) {
156         debug!("elaborate_drop({:?})", self);
157         let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
158         debug!("elaborate_drop({:?}): live - {:?}", self, style);
159         match style {
160             DropStyle::Dead => {
161                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
162                     target: self.succ
163                 });
164             }
165             DropStyle::Static => {
166                 let loc = self.terminator_loc(bb);
167                 self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
168                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
169                     location: self.place.clone(),
170                     target: self.succ,
171                     unwind: self.unwind.into_option(),
172                 });
173             }
174             DropStyle::Conditional => {
175                 let unwind = self.unwind; // FIXME(#43234)
176                 let succ = self.succ;
177                 let drop_bb = self.complete_drop(Some(DropFlagMode::Deep), succ, unwind);
178                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
179                     target: drop_bb
180                 });
181             }
182             DropStyle::Open => {
183                 let drop_bb = self.open_drop();
184                 self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
185                     target: drop_bb
186                 });
187             }
188         }
189     }
190
191     /// Returns the place and move path for each field of `variant`,
192     /// (the move path is `None` if the field is a rest field).
193     fn move_paths_for_fields(&self,
194                              base_place: &Place<'tcx>,
195                              variant_path: D::Path,
196                              variant: &'tcx ty::VariantDef,
197                              substs: SubstsRef<'tcx>)
198                              -> Vec<(Place<'tcx>, Option<D::Path>)>
199     {
200         variant.fields.iter().enumerate().map(|(i, f)| {
201             let field = Field::new(i);
202             let subpath = self.elaborator.field_subpath(variant_path, field);
203
204             assert_eq!(self.elaborator.param_env().reveal, Reveal::All);
205             let field_ty = self.tcx().normalize_erasing_regions(
206                 self.elaborator.param_env(),
207                 f.ty(self.tcx(), substs),
208             );
209             (base_place.clone().field(field, field_ty), subpath)
210         }).collect()
211     }
212
213     fn drop_subpath(&mut self,
214                     place: &Place<'tcx>,
215                     path: Option<D::Path>,
216                     succ: BasicBlock,
217                     unwind: Unwind)
218                     -> BasicBlock
219     {
220         if let Some(path) = path {
221             debug!("drop_subpath: for std field {:?}", place);
222
223             DropCtxt {
224                 elaborator: self.elaborator,
225                 source_info: self.source_info,
226                 path, place, succ, unwind,
227             }.elaborated_drop_block()
228         } else {
229             debug!("drop_subpath: for rest field {:?}", place);
230
231             DropCtxt {
232                 elaborator: self.elaborator,
233                 source_info: self.source_info,
234                 place, succ, unwind,
235                 // Using `self.path` here to condition the drop on
236                 // our own drop flag.
237                 path: self.path
238             }.complete_drop(None, succ, unwind)
239         }
240     }
241
242     /// Creates one-half of the drop ladder for a list of fields, and return
243     /// the list of steps in it in reverse order, with the first step
244     /// dropping 0 fields and so on.
245     ///
246     /// `unwind_ladder` is such a list of steps in reverse order,
247     /// which is called if the matching step of the drop glue panics.
248     fn drop_halfladder(&mut self,
249                        unwind_ladder: &[Unwind],
250                        mut succ: BasicBlock,
251                        fields: &[(Place<'tcx>, Option<D::Path>)])
252                        -> Vec<BasicBlock>
253     {
254         Some(succ).into_iter().chain(
255             fields.iter().rev().zip(unwind_ladder)
256                 .map(|(&(ref place, path), &unwind_succ)| {
257                     succ = self.drop_subpath(place, path, succ, unwind_succ);
258                     succ
259                 })
260         ).collect()
261     }
262
263     fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind) {
264         // Clear the "master" drop flag at the end. This is needed
265         // because the "master" drop protects the ADT's discriminant,
266         // which is invalidated after the ADT is dropped.
267         let (succ, unwind) = (self.succ, self.unwind); // FIXME(#43234)
268         (
269             self.drop_flag_reset_block(DropFlagMode::Shallow, succ, unwind),
270             unwind.map(|unwind| {
271                 self.drop_flag_reset_block(DropFlagMode::Shallow, unwind, Unwind::InCleanup)
272             })
273         )
274     }
275
276     /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
277     ///
278     /// For example, with 3 fields, the drop ladder is
279     ///
280     /// .d0:
281     ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
282     /// .d1:
283     ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
284     /// .d2:
285     ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
286     /// .c1:
287     ///     ELAB(drop location.1 [target=.c2])
288     /// .c2:
289     ///     ELAB(drop location.2 [target=`self.unwind`])
290     ///
291     /// NOTE: this does not clear the master drop flag, so you need
292     /// to point succ/unwind on a `drop_ladder_bottom`.
293     fn drop_ladder(
294         &mut self,
295         fields: Vec<(Place<'tcx>, Option<D::Path>)>,
296         succ: BasicBlock,
297         unwind: Unwind,
298     ) -> (BasicBlock, Unwind) {
299         debug!("drop_ladder({:?}, {:?})", self, fields);
300
301         let mut fields = fields;
302         fields.retain(|&(ref place, _)| {
303             self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
304         });
305
306         debug!("drop_ladder - fields needing drop: {:?}", fields);
307
308         let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
309         let unwind_ladder: Vec<_> = if let Unwind::To(target) = unwind {
310             let halfladder = self.drop_halfladder(&unwind_ladder, target, &fields);
311             halfladder.into_iter().map(Unwind::To).collect()
312         } else {
313             unwind_ladder
314         };
315
316         let normal_ladder =
317             self.drop_halfladder(&unwind_ladder, succ, &fields);
318
319         (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
320     }
321
322     fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
323         debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
324
325         let fields = tys.iter().enumerate().map(|(i, &ty)| {
326             (self.place.clone().field(Field::new(i), ty),
327              self.elaborator.field_subpath(self.path, Field::new(i)))
328         }).collect();
329
330         let (succ, unwind) = self.drop_ladder_bottom();
331         self.drop_ladder(fields, succ, unwind).0
332     }
333
334     fn open_drop_for_box(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
335         debug!("open_drop_for_box({:?}, {:?}, {:?})", self, adt, substs);
336
337         let interior = self.place.clone().deref();
338         let interior_path = self.elaborator.deref_subpath(self.path);
339
340         let succ = self.succ; // FIXME(#43234)
341         let unwind = self.unwind;
342         let succ = self.box_free_block(adt, substs, succ, unwind);
343         let unwind_succ = self.unwind.map(|unwind| {
344             self.box_free_block(adt, substs, unwind, Unwind::InCleanup)
345         });
346
347         self.drop_subpath(&interior, interior_path, succ, unwind_succ)
348     }
349
350     fn open_drop_for_adt(&mut self, adt: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>) -> BasicBlock {
351         debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
352         if adt.variants.len() == 0 {
353             return self.elaborator.patch().new_block(BasicBlockData {
354                 statements: vec![],
355                 terminator: Some(Terminator {
356                     source_info: self.source_info,
357                     kind: TerminatorKind::Unreachable
358                 }),
359                 is_cleanup: self.unwind.is_cleanup()
360             });
361         }
362
363         let skip_contents =
364             adt.is_union() || Some(adt.did) == self.tcx().lang_items().manually_drop();
365         let contents_drop = if skip_contents {
366             (self.succ, self.unwind)
367         } else {
368             self.open_drop_for_adt_contents(adt, substs)
369         };
370
371         if adt.has_dtor(self.tcx()) {
372             self.destructor_call_block(contents_drop)
373         } else {
374             contents_drop.0
375         }
376     }
377
378     fn open_drop_for_adt_contents(&mut self, adt: &'tcx ty::AdtDef,
379                                   substs: SubstsRef<'tcx>)
380                                   -> (BasicBlock, Unwind) {
381         let (succ, unwind) = self.drop_ladder_bottom();
382         if !adt.is_enum() {
383             let fields = self.move_paths_for_fields(
384                 self.place,
385                 self.path,
386                 &adt.variants[VariantIdx::new(0)],
387                 substs
388             );
389             self.drop_ladder(fields, succ, unwind)
390         } else {
391             self.open_drop_for_multivariant(adt, substs, succ, unwind)
392         }
393     }
394
395     fn open_drop_for_multivariant(&mut self, adt: &'tcx ty::AdtDef,
396                                   substs: SubstsRef<'tcx>,
397                                   succ: BasicBlock,
398                                   unwind: Unwind)
399                                   -> (BasicBlock, Unwind) {
400         let mut values = Vec::with_capacity(adt.variants.len());
401         let mut normal_blocks = Vec::with_capacity(adt.variants.len());
402         let mut unwind_blocks = if unwind.is_cleanup() {
403             None
404         } else {
405             Some(Vec::with_capacity(adt.variants.len()))
406         };
407
408         let mut have_otherwise = false;
409
410         for (variant_index, discr) in adt.discriminants(self.tcx()) {
411             let subpath = self.elaborator.downcast_subpath(
412                 self.path, variant_index);
413             if let Some(variant_path) = subpath {
414                 let base_place = self.place.clone().elem(
415                     ProjectionElem::Downcast(Some(adt.variants[variant_index].ident.name),
416                                              variant_index));
417                 let fields = self.move_paths_for_fields(
418                     &base_place,
419                     variant_path,
420                     &adt.variants[variant_index],
421                     substs);
422                 values.push(discr.val);
423                 if let Unwind::To(unwind) = unwind {
424                     // We can't use the half-ladder from the original
425                     // drop ladder, because this breaks the
426                     // "funclet can't have 2 successor funclets"
427                     // requirement from MSVC:
428                     //
429                     //           switch       unwind-switch
430                     //          /      \         /        \
431                     //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
432                     //         |        |      /             |
433                     //    v1.1-unwind  v2.1-unwind           |
434                     //      ^                                |
435                     //       \-------------------------------/
436                     //
437                     // Create a duplicate half-ladder to avoid that. We
438                     // could technically only do this on MSVC, but I
439                     // I want to minimize the divergence between MSVC
440                     // and non-MSVC.
441
442                     let unwind_blocks = unwind_blocks.as_mut().unwrap();
443                     let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
444                     let halfladder =
445                         self.drop_halfladder(&unwind_ladder, unwind, &fields);
446                     unwind_blocks.push(halfladder.last().cloned().unwrap());
447                 }
448                 let (normal, _) = self.drop_ladder(fields, succ, unwind);
449                 normal_blocks.push(normal);
450             } else {
451                 have_otherwise = true;
452             }
453         }
454
455         if have_otherwise {
456             normal_blocks.push(self.drop_block(succ, unwind));
457             if let Unwind::To(unwind) = unwind {
458                 unwind_blocks.as_mut().unwrap().push(
459                     self.drop_block(unwind, Unwind::InCleanup)
460                         );
461             }
462         } else {
463             values.pop();
464         }
465
466         (self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
467          unwind.map(|unwind| {
468              self.adt_switch_block(
469                  adt, unwind_blocks.unwrap(), &values, unwind, Unwind::InCleanup
470              )
471          }))
472     }
473
474     fn adt_switch_block(&mut self,
475                         adt: &'tcx ty::AdtDef,
476                         blocks: Vec<BasicBlock>,
477                         values: &[u128],
478                         succ: BasicBlock,
479                         unwind: Unwind)
480                         -> BasicBlock {
481         // If there are multiple variants, then if something
482         // is present within the enum the discriminant, tracked
483         // by the rest path, must be initialized.
484         //
485         // Additionally, we do not want to switch on the
486         // discriminant after it is free-ed, because that
487         // way lies only trouble.
488         let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
489         let discr = Place::from(self.new_temp(discr_ty));
490         let discr_rv = Rvalue::Discriminant(self.place.clone());
491         let switch_block = BasicBlockData {
492             statements: vec![self.assign(&discr, discr_rv)],
493             terminator: Some(Terminator {
494                 source_info: self.source_info,
495                 kind: TerminatorKind::SwitchInt {
496                     discr: Operand::Move(discr),
497                     switch_ty: discr_ty,
498                     values: From::from(values.to_owned()),
499                     targets: blocks,
500                 }
501             }),
502             is_cleanup: unwind.is_cleanup(),
503         };
504         let switch_block = self.elaborator.patch().new_block(switch_block);
505         self.drop_flag_test_block(switch_block, succ, unwind)
506     }
507
508     fn destructor_call_block(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
509         debug!("destructor_call_block({:?}, {:?})", self, succ);
510         let tcx = self.tcx();
511         let drop_trait = tcx.lang_items().drop_trait().unwrap();
512         let drop_fn = tcx.associated_items(drop_trait).next().unwrap();
513         let ty = self.place_ty(self.place);
514         let substs = tcx.mk_substs_trait(ty, &[]);
515
516         let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
517             ty,
518             mutbl: hir::Mutability::MutMutable
519         });
520         let ref_place = self.new_temp(ref_ty);
521         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
522
523         let result = BasicBlockData {
524             statements: vec![self.assign(
525                 &Place::from(ref_place),
526                 Rvalue::Ref(tcx.lifetimes.re_erased,
527                             BorrowKind::Mut { allow_two_phase_borrow: false },
528                             self.place.clone())
529             )],
530             terminator: Some(Terminator {
531                 kind: TerminatorKind::Call {
532                     func: Operand::function_handle(tcx, drop_fn.def_id, substs,
533                                                    self.source_info.span),
534                     args: vec![Operand::Move(Place::from(ref_place))],
535                     destination: Some((unit_temp, succ)),
536                     cleanup: unwind.into_option(),
537                     from_hir_call: true,
538                 },
539                 source_info: self.source_info,
540             }),
541             is_cleanup: unwind.is_cleanup(),
542         };
543         self.elaborator.patch().new_block(result)
544     }
545
546     /// Create a loop that drops an array:
547     ///
548     /// ```text
549     /// loop-block:
550     ///    can_go = cur == length_or_end
551     ///    if can_go then succ else drop-block
552     /// drop-block:
553     ///    if ptr_based {
554     ///        ptr = &mut *cur
555     ///        cur = cur.offset(1)
556     ///    } else {
557     ///        ptr = &mut P[cur]
558     ///        cur = cur + 1
559     ///    }
560     ///    drop(ptr)
561     /// ```
562     fn drop_loop(
563         &mut self,
564         succ: BasicBlock,
565         cur: Local,
566         length_or_end: &Place<'tcx>,
567         ety: Ty<'tcx>,
568         unwind: Unwind,
569         ptr_based: bool,
570     ) -> BasicBlock {
571         let copy = |place: &Place<'tcx>| Operand::Copy(place.clone());
572         let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
573         let tcx = self.tcx();
574
575         let ref_ty = tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
576             ty: ety,
577             mutbl: hir::Mutability::MutMutable
578         });
579         let ptr = &Place::from(self.new_temp(ref_ty));
580         let can_go = &Place::from(self.new_temp(tcx.types.bool));
581
582         let one = self.constant_usize(1);
583         let (ptr_next, cur_next) = if ptr_based {
584             (Rvalue::Ref(
585                 tcx.lifetimes.re_erased,
586                 BorrowKind::Mut { allow_two_phase_borrow: false },
587                 Place {
588                     base: PlaceBase::Local(cur),
589                     projection: Some(Box::new(Projection {
590                         base: None,
591                         elem: ProjectionElem::Deref,
592                     })),
593                 }
594              ),
595              Rvalue::BinaryOp(BinOp::Offset, move_(&Place::from(cur)), one))
596         } else {
597             (Rvalue::Ref(
598                  tcx.lifetimes.re_erased,
599                  BorrowKind::Mut { allow_two_phase_borrow: false },
600                  self.place.clone().index(cur)),
601              Rvalue::BinaryOp(BinOp::Add, move_(&Place::from(cur)), one))
602         };
603
604         let drop_block = BasicBlockData {
605             statements: vec![
606                 self.assign(ptr, ptr_next),
607                 self.assign(&Place::from(cur), cur_next)
608             ],
609             is_cleanup: unwind.is_cleanup(),
610             terminator: Some(Terminator {
611                 source_info: self.source_info,
612                 // this gets overwritten by drop elaboration.
613                 kind: TerminatorKind::Unreachable,
614             })
615         };
616         let drop_block = self.elaborator.patch().new_block(drop_block);
617
618         let loop_block = BasicBlockData {
619             statements: vec![
620                 self.assign(can_go, Rvalue::BinaryOp(BinOp::Eq,
621                                                      copy(&Place::from(cur)),
622                                                      copy(length_or_end)))
623             ],
624             is_cleanup: unwind.is_cleanup(),
625             terminator: Some(Terminator {
626                 source_info: self.source_info,
627                 kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block)
628             })
629         };
630         let loop_block = self.elaborator.patch().new_block(loop_block);
631
632         self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop {
633             location: ptr.clone().deref(),
634             target: loop_block,
635             unwind: unwind.into_option()
636         });
637
638         loop_block
639     }
640
641     fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
642         debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);
643
644         // if size_of::<ety>() == 0 {
645         //     index_based_loop
646         // } else {
647         //     ptr_based_loop
648         // }
649
650         if let Some(size) = opt_size {
651             let size: u32 = size.try_into().unwrap_or_else(|_| {
652                 bug!("move out check isn't implemented for array sizes bigger than u32::MAX");
653             });
654             let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size).map(|i| {
655                 (self.place.clone().elem(ProjectionElem::ConstantIndex{
656                     offset: i,
657                     min_length: size,
658                     from_end: false
659                 }),
660                  self.elaborator.array_subpath(self.path, i, size))
661             }).collect();
662
663             if fields.iter().any(|(_,path)| path.is_some()) {
664                 let (succ, unwind) = self.drop_ladder_bottom();
665                 return self.drop_ladder(fields, succ, unwind).0
666             }
667         }
668
669         let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
670         let tcx = self.tcx();
671         let elem_size = &Place::from(self.new_temp(tcx.types.usize));
672         let len = &Place::from(self.new_temp(tcx.types.usize));
673
674         static USIZE_SWITCH_ZERO: &[u128] = &[0];
675
676         let base_block = BasicBlockData {
677             statements: vec![
678                 self.assign(elem_size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
679                 self.assign(len, Rvalue::Len(self.place.clone())),
680             ],
681             is_cleanup: self.unwind.is_cleanup(),
682             terminator: Some(Terminator {
683                 source_info: self.source_info,
684                 kind: TerminatorKind::SwitchInt {
685                     discr: move_(elem_size),
686                     switch_ty: tcx.types.usize,
687                     values: From::from(USIZE_SWITCH_ZERO),
688                     targets: vec![
689                         self.drop_loop_pair(ety, false, len.clone()),
690                         self.drop_loop_pair(ety, true, len.clone()),
691                     ],
692                 },
693             })
694         };
695         self.elaborator.patch().new_block(base_block)
696     }
697
698     /// Ceates a pair of drop-loops of `place`, which drops its contents, even
699     /// in the case of 1 panic. If `ptr_based`, creates a pointer loop,
700     /// otherwise create an index loop.
701     fn drop_loop_pair(
702         &mut self,
703         ety: Ty<'tcx>,
704         ptr_based: bool,
705         length: Place<'tcx>,
706     ) -> BasicBlock {
707         debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
708         let tcx = self.tcx();
709         let iter_ty = if ptr_based {
710             tcx.mk_mut_ptr(ety)
711         } else {
712             tcx.types.usize
713         };
714
715         let cur = self.new_temp(iter_ty);
716         let length_or_end = if ptr_based {
717             // FIXME check if we want to make it return a `Place` directly
718             // if all use sites want a `Place::Base` anyway.
719             Place::from(self.new_temp(iter_ty))
720         } else {
721             length.clone()
722         };
723
724         let unwind = self.unwind.map(|unwind| {
725             self.drop_loop(unwind,
726                            cur,
727                            &length_or_end,
728                            ety,
729                            Unwind::InCleanup,
730                            ptr_based)
731         });
732
733         let loop_block = self.drop_loop(
734             self.succ,
735             cur,
736             &length_or_end,
737             ety,
738             unwind,
739             ptr_based);
740
741         let cur = Place::from(cur);
742         let drop_block_stmts = if ptr_based {
743             let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
744             let tmp = Place::from(self.new_temp(tmp_ty));
745             // tmp = &mut P;
746             // cur = tmp as *mut T;
747             // end = Offset(cur, len);
748             vec![
749                 self.assign(&tmp, Rvalue::Ref(
750                     tcx.lifetimes.re_erased,
751                     BorrowKind::Mut { allow_two_phase_borrow: false },
752                     self.place.clone()
753                 )),
754                 self.assign(
755                     &cur,
756                     Rvalue::Cast(CastKind::Misc, Operand::Move(tmp), iter_ty),
757                 ),
758                 self.assign(
759                     &length_or_end,
760                     Rvalue::BinaryOp(BinOp::Offset, Operand::Copy(cur), Operand::Move(length)
761                 )),
762             ]
763         } else {
764             // cur = 0 (length already pushed)
765             let zero = self.constant_usize(0);
766             vec![self.assign(&cur, Rvalue::Use(zero))]
767         };
768         let drop_block = self.elaborator.patch().new_block(BasicBlockData {
769             statements: drop_block_stmts,
770             is_cleanup: unwind.is_cleanup(),
771             terminator: Some(Terminator {
772                 source_info: self.source_info,
773                 kind: TerminatorKind::Goto { target: loop_block }
774             })
775         });
776
777         // FIXME(#34708): handle partially-dropped array/slice elements.
778         let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
779         self.drop_flag_test_block(reset_block, self.succ, unwind)
780     }
781
782     /// The slow-path - create an "open", elaborated drop for a type
783     /// which is moved-out-of only partially, and patch `bb` to a jump
784     /// to it. This must not be called on ADTs with a destructor,
785     /// as these can't be moved-out-of, except for `Box<T>`, which is
786     /// special-cased.
787     ///
788     /// This creates a "drop ladder" that drops the needed fields of the
789     /// ADT, both in the success case or if one of the destructors fail.
790     fn open_drop(&mut self) -> BasicBlock {
791         let ty = self.place_ty(self.place);
792         match ty.sty {
793             ty::Closure(def_id, substs) => {
794                 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
795                 self.open_drop_for_tuple(&tys)
796             }
797             // Note that `elaborate_drops` only drops the upvars of a generator,
798             // and this is ok because `open_drop` here can only be reached
799             // within that own generator's resume function.
800             // This should only happen for the self argument on the resume function.
801             // It effetively only contains upvars until the generator transformation runs.
802             // See librustc_body/transform/generator.rs for more details.
803             ty::Generator(def_id, substs, _) => {
804                 let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
805                 self.open_drop_for_tuple(&tys)
806             }
807             ty::Tuple(..) => {
808                 let tys: Vec<_> = ty.tuple_fields().collect();
809                 self.open_drop_for_tuple(&tys)
810             }
811             ty::Adt(def, substs) => {
812                 if def.is_box() {
813                     self.open_drop_for_box(def, substs)
814                 } else {
815                     self.open_drop_for_adt(def, substs)
816                 }
817             }
818             ty::Dynamic(..) => {
819                 let unwind = self.unwind; // FIXME(#43234)
820                 let succ = self.succ;
821                 self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
822             }
823             ty::Array(ety, size) => {
824                 let size = size.try_eval_usize(self.tcx(), self.elaborator.param_env());
825                 self.open_drop_for_array(ety, size)
826             },
827             ty::Slice(ety) => self.open_drop_for_array(ety, None),
828
829             _ => bug!("open drop from non-ADT `{:?}`", ty)
830         }
831     }
832
833     /// Returns a basic block that drop a place using the context
834     /// and path in `c`. If `mode` is something, also clear `c`
835     /// according to it.
836     ///
837     /// if FLAG(self.path)
838     ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
839     ///     drop(self.place)
840     fn complete_drop(
841         &mut self,
842         drop_mode: Option<DropFlagMode>,
843         succ: BasicBlock,
844         unwind: Unwind,
845     ) -> BasicBlock {
846         debug!("complete_drop({:?},{:?})", self, drop_mode);
847
848         let drop_block = self.drop_block(succ, unwind);
849         let drop_block = if let Some(mode) = drop_mode {
850             self.drop_flag_reset_block(mode, drop_block, unwind)
851         } else {
852             drop_block
853         };
854
855         self.drop_flag_test_block(drop_block, succ, unwind)
856     }
857
858     fn drop_flag_reset_block(&mut self,
859                              mode: DropFlagMode,
860                              succ: BasicBlock,
861                              unwind: Unwind) -> BasicBlock
862     {
863         debug!("drop_flag_reset_block({:?},{:?})", self, mode);
864
865         let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
866         let block_start = Location { block: block, statement_index: 0 };
867         self.elaborator.clear_drop_flag(block_start, self.path, mode);
868         block
869     }
870
871     fn elaborated_drop_block(&mut self) -> BasicBlock {
872         debug!("elaborated_drop_block({:?})", self);
873         let unwind = self.unwind; // FIXME(#43234)
874         let succ = self.succ;
875         let blk = self.drop_block(succ, unwind);
876         self.elaborate_drop(blk);
877         blk
878     }
879
880     fn box_free_block(
881         &mut self,
882         adt: &'tcx ty::AdtDef,
883         substs: SubstsRef<'tcx>,
884         target: BasicBlock,
885         unwind: Unwind,
886     ) -> BasicBlock {
887         let block = self.unelaborated_free_block(adt, substs, target, unwind);
888         self.drop_flag_test_block(block, target, unwind)
889     }
890
891     fn unelaborated_free_block(
892         &mut self,
893         adt: &'tcx ty::AdtDef,
894         substs: SubstsRef<'tcx>,
895         target: BasicBlock,
896         unwind: Unwind,
897     ) -> BasicBlock {
898         let tcx = self.tcx();
899         let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
900         let free_func = tcx.require_lang_item(
901             lang_items::BoxFreeFnLangItem,
902             Some(self.source_info.span)
903         );
904         let args = adt.variants[VariantIdx::new(0)].fields.iter().enumerate().map(|(i, f)| {
905             let field = Field::new(i);
906             let field_ty = f.ty(self.tcx(), substs);
907             Operand::Move(self.place.clone().field(field, field_ty))
908         }).collect();
909
910         let call = TerminatorKind::Call {
911             func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
912             args: args,
913             destination: Some((unit_temp, target)),
914             cleanup: None,
915             from_hir_call: false,
916         }; // FIXME(#43234)
917         let free_block = self.new_block(unwind, call);
918
919         let block_start = Location { block: free_block, statement_index: 0 };
920         self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
921         free_block
922     }
923
924     fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
925         let block = TerminatorKind::Drop {
926             location: self.place.clone(),
927             target,
928             unwind: unwind.into_option()
929         };
930         self.new_block(unwind, block)
931     }
932
933     fn drop_flag_test_block(&mut self,
934                             on_set: BasicBlock,
935                             on_unset: BasicBlock,
936                             unwind: Unwind)
937                             -> BasicBlock
938     {
939         let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
940         debug!("drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
941                self, on_set, on_unset, unwind, style);
942
943         match style {
944             DropStyle::Dead => on_unset,
945             DropStyle::Static => on_set,
946             DropStyle::Conditional | DropStyle::Open => {
947                 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
948                 let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
949                 self.new_block(unwind, term)
950             }
951         }
952     }
953
954     fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
955         self.elaborator.patch().new_block(BasicBlockData {
956             statements: vec![],
957             terminator: Some(Terminator {
958                 source_info: self.source_info, kind: k
959             }),
960             is_cleanup: unwind.is_cleanup()
961         })
962     }
963
964     fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
965         self.elaborator.patch().new_temp(ty, self.source_info.span)
966     }
967
968     fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
969         let body = self.elaborator.body();
970         self.elaborator.patch().terminator_loc(body, bb)
971     }
972
973     fn constant_usize(&self, val: u16) -> Operand<'tcx> {
974         Operand::Constant(box Constant {
975             span: self.source_info.span,
976             user_ty: None,
977             literal: ty::Const::from_usize(self.tcx(), val.into()),
978         })
979     }
980
981     fn assign(&self, lhs: &Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
982         Statement {
983             source_info: self.source_info,
984             kind: StatementKind::Assign(lhs.clone(), box rhs)
985         }
986     }
987 }