1 // Copyright 2016 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.
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.
12 use rustc::hir::def_id::DefId;
14 use rustc::middle::const_val::ConstVal;
16 use rustc::ty::{self, Ty, TyCtxt};
17 use rustc::ty::subst::{Kind, Subst, Substs};
18 use rustc::ty::maps::Providers;
19 use rustc::mir::interpret::{Value, PrimVal};
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
23 use rustc_target::spec::abi::Abi;
30 use transform::{add_moves_for_packed_drops, add_call_guards};
31 use transform::{remove_noop_landing_pads, no_landing_pads, simplify};
32 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
33 use util::patch::MirPatch;
35 pub fn provide(providers: &mut Providers) {
36 providers.mir_shims = make_shim;
39 fn make_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
40 instance: ty::InstanceDef<'tcx>)
43 debug!("make_shim({:?})", instance);
45 let mut result = match instance {
46 ty::InstanceDef::Item(..) =>
47 bug!("item {:?} passed to make_shim", instance),
48 ty::InstanceDef::FnPtrShim(def_id, ty) => {
49 let trait_ = tcx.trait_of_item(def_id).unwrap();
50 let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
51 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
52 Some(ty::ClosureKind::FnMut) |
53 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
54 None => bug!("fn pointer {:?} is not an fn", ty)
56 // HACK: we need the "real" argument types for the MIR,
57 // but because our substs are (Self, Args), where Args
58 // is a tuple, we must include the *concrete* argument
59 // types in the MIR. They will be substituted again with
60 // the param-substs, but because they are concrete, this
61 // will not do any harm.
62 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
63 let arg_tys = sig.inputs();
73 ty::InstanceDef::Virtual(def_id, _) => {
74 // We are translating a call back to our def-id, which
75 // trans::mir knows to turn to an actual virtual call.
80 CallKind::Direct(def_id),
84 ty::InstanceDef::ClosureOnceShim { call_once } => {
85 let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
86 let call_mut = tcx.global_tcx()
87 .associated_items(fn_mut)
88 .find(|it| it.kind == ty::AssociatedKind::Method)
95 CallKind::Direct(call_mut),
99 ty::InstanceDef::DropGlue(def_id, ty) => {
100 build_drop_shim(tcx, def_id, ty)
102 ty::InstanceDef::CloneShim(def_id, ty) => {
103 let name = tcx.item_name(def_id);
105 build_clone_shim(tcx, def_id, ty)
106 } else if name == "clone_from" {
107 debug!("make_shim({:?}: using default trait implementation", instance);
108 return tcx.optimized_mir(def_id);
110 bug!("builtin clone shim {:?} not supported", instance)
113 ty::InstanceDef::Intrinsic(_) => {
114 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
117 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
118 add_moves_for_packed_drops::add_moves_for_packed_drops(
119 tcx, &mut result, instance.def_id());
120 no_landing_pads::no_landing_pads(tcx, &mut result);
121 remove_noop_landing_pads::remove_noop_landing_pads(tcx, &mut result);
122 simplify::simplify_cfg(&mut result);
123 add_call_guards::CriticalCallEdges.add_call_guards(&mut result);
124 debug!("make_shim({:?}) = {:?}", instance, result);
126 tcx.alloc_mir(result)
129 #[derive(Copy, Clone, Debug, PartialEq)]
136 #[derive(Copy, Clone, Debug, PartialEq)]
142 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
144 mutability, ty, name: None,
145 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
146 syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
148 is_user_variable: false
152 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
153 -> IndexVec<Local, LocalDecl<'tcx>>
155 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
156 .chain(sig.inputs().iter().map(
157 |ity| temp_decl(Mutability::Not, ity, span)))
161 fn build_drop_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
163 ty: Option<Ty<'tcx>>)
166 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
168 // Check if this is a generator, if so, return the drop glue for it
169 if let Some(&ty::TyS { sty: ty::TyGenerator(gen_def_id, substs, _), .. }) = ty {
170 let mir = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
171 return mir.subst(tcx, substs.substs);
174 let substs = if let Some(ty) = ty {
175 tcx.mk_substs(iter::once(Kind::from(ty)))
177 Substs::identity_for_item(tcx, def_id)
179 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
180 let sig = tcx.erase_late_bound_regions(&sig);
181 let span = tcx.def_span(def_id);
183 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
185 let return_block = BasicBlock::new(1);
186 let mut blocks = IndexVec::new();
187 let block = |blocks: &mut IndexVec<_, _>, kind| {
188 blocks.push(BasicBlockData {
190 terminator: Some(Terminator { source_info, kind }),
194 block(&mut blocks, TerminatorKind::Goto { target: return_block });
195 block(&mut blocks, TerminatorKind::Return);
197 let mut mir = Mir::new(
199 IndexVec::from_elem_n(
200 VisibilityScopeData { span: span, parent_scope: None }, 1
202 ClearCrossCrate::Clear,
205 local_decls_for_sig(&sig, span),
211 if let Some(..) = ty {
213 let param_env = tcx.param_env(def_id);
214 let mut elaborator = DropShimElaborator {
216 patch: MirPatch::new(&mir),
220 let dropee = Place::Local(Local::new(1+0)).deref();
221 let resume_block = elaborator.patch.resume_block();
222 elaborate_drops::elaborate_drop(
228 elaborate_drops::Unwind::To(resume_block),
233 patch.apply(&mut mir);
239 pub struct DropShimElaborator<'a, 'tcx: 'a> {
240 pub mir: &'a Mir<'tcx>,
241 pub patch: MirPatch<'tcx>,
242 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
243 pub param_env: ty::ParamEnv<'tcx>,
246 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
247 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
252 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
255 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
256 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
257 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
258 fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
260 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
261 if let DropFlagMode::Shallow = mode {
268 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
272 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
275 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
278 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
281 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
284 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
289 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
290 fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
295 debug!("build_clone_shim(def_id={:?})", def_id);
297 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
298 let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
300 let dest = Place::Local(RETURN_PLACE);
301 let src = Place::Local(Local::new(1+0)).deref();
304 _ if is_copy => builder.copy_shim(),
305 ty::TyArray(ty, len) => {
306 let len = len.val.unwrap_u64();
307 builder.array_shim(dest, src, ty, len)
309 ty::TyClosure(def_id, substs) => {
310 builder.tuple_like_shim(
312 substs.upvar_tys(def_id, tcx)
315 ty::TyTuple(tys) => builder.tuple_like_shim(dest, src, tys.iter().cloned()),
317 bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
324 struct CloneShimBuilder<'a, 'tcx: 'a> {
325 tcx: TyCtxt<'a, 'tcx, 'tcx>,
327 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
328 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
330 sig: ty::FnSig<'tcx>,
333 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
334 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
336 self_ty: Ty<'tcx>) -> Self {
337 // we must subst the self_ty because it's
338 // otherwise going to be TySelf and we can't index
339 // or access fields of a Place of type TySelf.
340 let substs = tcx.mk_substs_trait(self_ty, &[]);
341 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
342 let sig = tcx.erase_late_bound_regions(&sig);
343 let span = tcx.def_span(def_id);
348 local_decls: local_decls_for_sig(&sig, span),
349 blocks: IndexVec::new(),
355 fn into_mir(self) -> Mir<'tcx> {
358 IndexVec::from_elem_n(
359 VisibilityScopeData { span: self.span, parent_scope: None }, 1
361 ClearCrossCrate::Clear,
365 self.sig.inputs().len(),
371 fn source_info(&self) -> SourceInfo {
372 SourceInfo { span: self.span, scope: ARGUMENT_VISIBILITY_SCOPE }
377 statements: Vec<Statement<'tcx>>,
378 kind: TerminatorKind<'tcx>,
381 let source_info = self.source_info();
382 self.blocks.push(BasicBlockData {
384 terminator: Some(Terminator { source_info, kind }),
389 /// Gives the index of an upcoming BasicBlock, with an offset.
390 /// offset=0 will give you the index of the next BasicBlock,
391 /// offset=1 will give the index of the next-to-next block,
392 /// offset=-1 will give you the index of the last-created block
393 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
394 BasicBlock::new(self.blocks.len() + offset)
397 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
399 source_info: self.source_info(),
404 fn copy_shim(&mut self) {
405 let rcvr = Place::Local(Local::new(1+0)).deref();
406 let ret_statement = self.make_statement(
407 StatementKind::Assign(
408 Place::Local(RETURN_PLACE),
409 Rvalue::Use(Operand::Copy(rcvr))
412 self.block(vec![ret_statement], TerminatorKind::Return, false);
415 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
416 let span = self.span;
418 self.local_decls.push(temp_decl(mutability, ty, span))
432 let substs = Substs::for_item(
435 |_, _| tcx.types.re_erased,
439 // `func == Clone::clone(&ty) -> ty`
440 let func_ty = tcx.mk_fn_def(self.def_id, substs);
441 let func = Operand::Constant(box Constant {
444 literal: Literal::Value {
445 value: tcx.mk_const(ty::Const {
447 val: ConstVal::Value(Value::ByVal(PrimVal::Undef)),
453 let ref_loc = self.make_place(
455 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
457 mutbl: hir::Mutability::MutImmutable,
461 // `let ref_loc: &ty = &src;`
462 let statement = self.make_statement(
463 StatementKind::Assign(
465 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, src)
469 // `let loc = Clone::clone(ref_loc);`
470 self.block(vec![statement], TerminatorKind::Call {
472 args: vec![Operand::Move(ref_loc)],
473 destination: Some((dest, next)),
474 cleanup: Some(cleanup),
482 loop_body: BasicBlock,
483 loop_end: BasicBlock,
488 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
489 let compute_cond = self.make_statement(
490 StatementKind::Assign(
492 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
496 // `if end != beg { goto loop_body; } else { goto loop_end; }`
499 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
504 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
507 ty: self.tcx.types.usize,
508 literal: Literal::Value {
509 value: self.tcx.mk_const(ty::Const {
510 val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(value.into()))),
511 ty: self.tcx.types.usize,
517 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
519 let span = self.span;
521 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
522 let end = self.make_place(Mutability::Not, tcx.types.usize);
525 // `let mut beg = 0;`
530 StatementKind::Assign(
532 Rvalue::Use(Operand::Constant(self.make_usize(0)))
536 StatementKind::Assign(
538 Rvalue::Use(Operand::Constant(self.make_usize(len)))
542 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
549 self.loop_header(Place::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
552 // `dest[i] = Clone::clone(src[beg])`;
553 // Goto #3 if ok, #5 if unwinding happens.
554 let dest_field = dest.clone().index(beg);
555 let src_field = src.clone().index(beg);
556 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
562 let statements = vec![
564 StatementKind::Assign(
568 Operand::Copy(Place::Local(beg)),
569 Operand::Constant(self.make_usize(1))
574 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
578 self.block(vec![], TerminatorKind::Return, false);
582 // `let mut beg = 0;`
585 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
586 let init = self.make_statement(
587 StatementKind::Assign(
589 Rvalue::Use(Operand::Constant(self.make_usize(0)))
592 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
594 // BB #6 (cleanup): loop {
599 self.loop_header(Place::Local(beg), Place::Local(end),
600 BasicBlock::new(7), BasicBlock::new(9), true);
603 // `drop(dest[beg])`;
604 self.block(vec![], TerminatorKind::Drop {
605 location: dest.index(beg),
606 target: BasicBlock::new(8),
613 let statement = self.make_statement(
614 StatementKind::Assign(
618 Operand::Copy(Place::Local(beg)),
619 Operand::Constant(self.make_usize(1))
623 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
626 self.block(vec![], TerminatorKind::Resume, true);
629 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
630 src: Place<'tcx>, tys: I)
631 where I: Iterator<Item = ty::Ty<'tcx>> {
632 let mut previous_field = None;
633 for (i, ity) in tys.enumerate() {
634 let field = Field::new(i);
635 let src_field = src.clone().field(field, ity);
637 let dest_field = dest.clone().field(field, ity);
639 // #(2i + 1) is the cleanup block for the previous clone operation
640 let cleanup_block = self.block_index_offset(1);
641 // #(2i + 2) is the next cloning block
642 // (or the Return terminator if this is the last block)
643 let next_block = self.block_index_offset(2);
646 // `dest.i = Clone::clone(&src.i);`
647 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
648 self.make_clone_call(
656 // BB #(2i + 1) (cleanup)
657 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
658 // Drop previous field and goto previous cleanup block.
659 self.block(vec![], TerminatorKind::Drop {
660 location: previous_field,
661 target: previous_cleanup,
665 // Nothing to drop, just resume.
666 self.block(vec![], TerminatorKind::Resume, true);
669 previous_field = Some((dest_field, cleanup_block));
672 self.block(vec![], TerminatorKind::Return, false);
676 /// Build a "call" shim for `def_id`. The shim calls the
677 /// function specified by `call_kind`, first adjusting its first
678 /// argument according to `rcvr_adjustment`.
680 /// If `untuple_args` is a vec of types, the second argument of the
681 /// function will be untupled as these types.
682 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
684 rcvr_adjustment: Adjustment,
686 untuple_args: Option<&[Ty<'tcx>]>)
689 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
690 call_kind={:?}, untuple_args={:?})",
691 def_id, rcvr_adjustment, call_kind, untuple_args);
693 let sig = tcx.fn_sig(def_id);
694 let sig = tcx.erase_late_bound_regions(&sig);
695 let span = tcx.def_span(def_id);
697 debug!("build_call_shim: sig={:?}", sig);
699 let mut local_decls = local_decls_for_sig(&sig, span);
700 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
702 let rcvr_arg = Local::new(1+0);
703 let rcvr_l = Place::Local(rcvr_arg);
704 let mut statements = vec![];
706 let rcvr = match rcvr_adjustment {
707 Adjustment::Identity => Operand::Move(rcvr_l),
708 Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
709 Adjustment::RefMut => {
710 // let rcvr = &mut rcvr;
711 let ref_rcvr = local_decls.push(temp_decl(
713 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
715 mutbl: hir::Mutability::MutMutable
719 let borrow_kind = BorrowKind::Mut {
720 allow_two_phase_borrow: false,
722 statements.push(Statement {
724 kind: StatementKind::Assign(
725 Place::Local(ref_rcvr),
726 Rvalue::Ref(tcx.types.re_erased, borrow_kind, rcvr_l)
729 Operand::Move(Place::Local(ref_rcvr))
733 let (callee, mut args) = match call_kind {
734 CallKind::Indirect => (rcvr, vec![]),
735 CallKind::Direct(def_id) => {
736 let ty = tcx.type_of(def_id);
737 (Operand::Constant(box Constant {
740 literal: Literal::Value {
741 value: tcx.mk_const(ty::Const {
743 val: ConstVal::Value(Value::ByVal(PrimVal::Undef)),
752 if let Some(untuple_args) = untuple_args {
753 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
754 let arg_place = Place::Local(Local::new(1+1));
755 Operand::Move(arg_place.field(Field::new(i), *ity))
758 args.extend((1..sig.inputs().len()).map(|i| {
759 Operand::Move(Place::Local(Local::new(1+i)))
763 let mut blocks = IndexVec::new();
764 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
765 blocks.push(BasicBlockData {
767 terminator: Some(Terminator { source_info, kind }),
773 block(&mut blocks, statements, TerminatorKind::Call {
776 destination: Some((Place::Local(RETURN_PLACE),
777 BasicBlock::new(1))),
778 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
779 Some(BasicBlock::new(3))
785 if let Adjustment::RefMut = rcvr_adjustment {
786 // BB #1 - drop for Self
787 block(&mut blocks, vec![], TerminatorKind::Drop {
788 location: Place::Local(rcvr_arg),
789 target: BasicBlock::new(2),
794 block(&mut blocks, vec![], TerminatorKind::Return, false);
795 if let Adjustment::RefMut = rcvr_adjustment {
796 // BB #3 - drop if closure panics
797 block(&mut blocks, vec![], TerminatorKind::Drop {
798 location: Place::Local(rcvr_arg),
799 target: BasicBlock::new(4),
804 block(&mut blocks, vec![], TerminatorKind::Resume, true);
807 let mut mir = Mir::new(
809 IndexVec::from_elem_n(
810 VisibilityScopeData { span: span, parent_scope: None }, 1
812 ClearCrossCrate::Clear,
820 if let Abi::RustCall = sig.abi {
821 mir.spread_arg = Some(Local::new(sig.inputs().len()));
826 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
827 ctor_id: ast::NodeId,
828 fields: &[hir::StructField],
833 let gcx = tcx.global_tcx();
834 let def_id = tcx.hir.local_def_id(ctor_id);
835 let param_env = gcx.param_env(def_id);
837 // Normalize the sig.
838 let sig = gcx.fn_sig(def_id).no_late_bound_regions().expect("LBR in ADT constructor signature");
839 let sig = gcx.normalize_erasing_regions(param_env, sig);
841 let (adt_def, substs) = match sig.output().sty {
842 ty::TyAdt(adt_def, substs) => (adt_def, substs),
843 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
846 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
848 let local_decls = local_decls_for_sig(&sig, span);
850 let source_info = SourceInfo {
852 scope: ARGUMENT_VISIBILITY_SCOPE
855 let variant_no = if adt_def.is_enum() {
856 adt_def.variant_index_with_id(def_id)
861 // return = ADT(arg0, arg1, ...); return
862 let start_block = BasicBlockData {
863 statements: vec![Statement {
865 kind: StatementKind::Assign(
866 Place::Local(RETURN_PLACE),
868 box AggregateKind::Adt(adt_def, variant_no, substs, None),
869 (1..sig.inputs().len()+1).map(|i| {
870 Operand::Move(Place::Local(Local::new(i)))
875 terminator: Some(Terminator {
877 kind: TerminatorKind::Return,
883 IndexVec::from_elem_n(start_block, 1),
884 IndexVec::from_elem_n(
885 VisibilityScopeData { span: span, parent_scope: None }, 1
887 ClearCrossCrate::Clear,