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_const_math::{ConstInt, ConstUsize};
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
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);
298 let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
301 _ if is_copy => builder.copy_shim(),
302 ty::TyArray(ty, len) => {
303 let len = len.val.to_const_int().unwrap().to_u64().unwrap();
304 builder.array_shim(ty, len)
306 ty::TyClosure(def_id, substs) => {
307 builder.tuple_like_shim(
308 &substs.upvar_tys(def_id, tcx).collect::<Vec<_>>(),
309 AggregateKind::Closure(def_id, substs)
312 ty::TyTuple(tys, _) => builder.tuple_like_shim(&**tys, AggregateKind::Tuple),
314 bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
321 struct CloneShimBuilder<'a, 'tcx: 'a> {
322 tcx: TyCtxt<'a, 'tcx, 'tcx>,
324 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
325 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
327 sig: ty::FnSig<'tcx>,
330 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
331 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Self {
332 let sig = tcx.fn_sig(def_id);
333 let sig = tcx.erase_late_bound_regions(&sig);
334 let span = tcx.def_span(def_id);
339 local_decls: local_decls_for_sig(&sig, span),
340 blocks: IndexVec::new(),
346 fn into_mir(self) -> Mir<'tcx> {
349 IndexVec::from_elem_n(
350 VisibilityScopeData { span: self.span, parent_scope: None }, 1
352 ClearCrossCrate::Clear,
356 self.sig.inputs().len(),
362 fn source_info(&self) -> SourceInfo {
363 SourceInfo { span: self.span, scope: ARGUMENT_VISIBILITY_SCOPE }
368 statements: Vec<Statement<'tcx>>,
369 kind: TerminatorKind<'tcx>,
372 let source_info = self.source_info();
373 self.blocks.push(BasicBlockData {
375 terminator: Some(Terminator { source_info, kind }),
380 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
382 source_info: self.source_info(),
387 fn copy_shim(&mut self) {
388 let rcvr = Place::Local(Local::new(1+0)).deref();
389 let ret_statement = self.make_statement(
390 StatementKind::Assign(
391 Place::Local(RETURN_PLACE),
392 Rvalue::Use(Operand::Copy(rcvr))
395 self.block(vec![ret_statement], TerminatorKind::Return, false);
398 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
399 let span = self.span;
401 self.local_decls.push(temp_decl(mutability, ty, span))
408 rcvr_field: Place<'tcx>,
414 let substs = Substs::for_item(
417 |_, _| tcx.types.re_erased,
421 // `func == Clone::clone(&ty) -> ty`
422 let func_ty = tcx.mk_fn_def(self.def_id, substs);
423 let func = Operand::Constant(box Constant {
426 literal: Literal::Value {
427 value: tcx.mk_const(ty::Const {
428 val: ConstVal::Function(self.def_id, substs),
434 let ref_loc = self.make_place(
436 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
438 mutbl: hir::Mutability::MutImmutable,
442 let loc = self.make_place(Mutability::Not, ty);
444 // `let ref_loc: &ty = &rcvr_field;`
445 let statement = self.make_statement(
446 StatementKind::Assign(
448 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, rcvr_field)
452 // `let loc = Clone::clone(ref_loc);`
453 self.block(vec![statement], TerminatorKind::Call {
455 args: vec![Operand::Move(ref_loc)],
456 destination: Some((loc.clone(), next)),
457 cleanup: Some(cleanup),
467 loop_body: BasicBlock,
468 loop_end: BasicBlock,
473 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
474 let compute_cond = self.make_statement(
475 StatementKind::Assign(
477 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
481 // `if end != beg { goto loop_body; } else { goto loop_end; }`
484 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
489 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
490 let value = ConstUsize::new(value, self.tcx.sess.target.usize_ty).unwrap();
493 ty: self.tcx.types.usize,
494 literal: Literal::Value {
495 value: self.tcx.mk_const(ty::Const {
496 val: ConstVal::Integral(ConstInt::Usize(value)),
497 ty: self.tcx.types.usize,
503 fn array_shim(&mut self, ty: Ty<'tcx>, len: u64) {
505 let span = self.span;
506 let rcvr = Place::Local(Local::new(1+0)).deref();
508 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
509 let end = self.make_place(Mutability::Not, tcx.types.usize);
510 let ret = self.make_place(Mutability::Mut, tcx.mk_array(ty, len));
513 // `let mut beg = 0;`
518 StatementKind::Assign(
520 Rvalue::Use(Operand::Constant(self.make_usize(0)))
524 StatementKind::Assign(
526 Rvalue::Use(Operand::Constant(self.make_usize(len)))
530 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
537 self.loop_header(Place::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
540 // `let cloned = Clone::clone(rcvr[beg])`;
541 // Goto #3 if ok, #5 if unwinding happens.
542 let rcvr_field = rcvr.clone().index(beg);
543 let cloned = self.make_clone_call(ty, rcvr_field, BasicBlock::new(3), BasicBlock::new(5));
546 // `ret[beg] = cloned;`
549 let ret_field = ret.clone().index(beg);
550 let statements = vec![
552 StatementKind::Assign(
554 Rvalue::Use(Operand::Move(cloned))
558 StatementKind::Assign(
562 Operand::Copy(Place::Local(beg)),
563 Operand::Constant(self.make_usize(1))
568 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
572 let ret_statement = self.make_statement(
573 StatementKind::Assign(
574 Place::Local(RETURN_PLACE),
575 Rvalue::Use(Operand::Move(ret.clone())),
578 self.block(vec![ret_statement], 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);
604 self.block(vec![], TerminatorKind::Drop {
605 location: ret.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(&mut self, tys: &[ty::Ty<'tcx>], kind: AggregateKind<'tcx>) {
631 AggregateKind::Tuple | AggregateKind::Closure(..) => (),
632 _ => bug!("only tuples and closures are accepted"),
635 let rcvr = Place::Local(Local::new(1+0)).deref();
637 let mut returns = Vec::new();
638 for (i, ity) in tys.iter().enumerate() {
639 let rcvr_field = rcvr.clone().field(Field::new(i), *ity);
642 // `returns[i] = Clone::clone(&rcvr.i);`
643 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
645 self.make_clone_call(
648 BasicBlock::new(2 * i + 2),
649 BasicBlock::new(2 * i + 1),
653 // BB #(2i + 1) (cleanup)
655 // Nothing to drop, just resume.
656 self.block(vec![], TerminatorKind::Resume, true);
658 // Drop previous field and goto previous cleanup block.
659 self.block(vec![], TerminatorKind::Drop {
660 location: returns[i - 1].clone(),
661 target: BasicBlock::new(2 * i - 1),
667 // `return kind(returns[0], returns[1], ..., returns[tys.len() - 1]);`
668 let ret_statement = self.make_statement(
669 StatementKind::Assign(
670 Place::Local(RETURN_PLACE),
673 returns.into_iter().map(Operand::Move).collect()
677 self.block(vec![ret_statement], TerminatorKind::Return, false);
681 /// Build a "call" shim for `def_id`. The shim calls the
682 /// function specified by `call_kind`, first adjusting its first
683 /// argument according to `rcvr_adjustment`.
685 /// If `untuple_args` is a vec of types, the second argument of the
686 /// function will be untupled as these types.
687 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
689 rcvr_adjustment: Adjustment,
691 untuple_args: Option<&[Ty<'tcx>]>)
694 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
695 call_kind={:?}, untuple_args={:?})",
696 def_id, rcvr_adjustment, call_kind, untuple_args);
698 let sig = tcx.fn_sig(def_id);
699 let sig = tcx.erase_late_bound_regions(&sig);
700 let span = tcx.def_span(def_id);
702 debug!("build_call_shim: sig={:?}", sig);
704 let mut local_decls = local_decls_for_sig(&sig, span);
705 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
707 let rcvr_arg = Local::new(1+0);
708 let rcvr_l = Place::Local(rcvr_arg);
709 let mut statements = vec![];
711 let rcvr = match rcvr_adjustment {
712 Adjustment::Identity => Operand::Move(rcvr_l),
713 Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
714 Adjustment::RefMut => {
715 // let rcvr = &mut rcvr;
716 let ref_rcvr = local_decls.push(temp_decl(
718 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
720 mutbl: hir::Mutability::MutMutable
724 statements.push(Statement {
726 kind: StatementKind::Assign(
727 Place::Local(ref_rcvr),
728 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
731 Operand::Move(Place::Local(ref_rcvr))
735 let (callee, mut args) = match call_kind {
736 CallKind::Indirect => (rcvr, vec![]),
737 CallKind::Direct(def_id) => {
738 let ty = tcx.type_of(def_id);
739 (Operand::Constant(box Constant {
742 literal: Literal::Value {
743 value: tcx.mk_const(ty::Const {
744 val: ConstVal::Function(def_id,
745 Substs::identity_for_item(tcx, def_id)),
754 if let Some(untuple_args) = untuple_args {
755 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
756 let arg_place = Place::Local(Local::new(1+1));
757 Operand::Move(arg_place.field(Field::new(i), *ity))
760 args.extend((1..sig.inputs().len()).map(|i| {
761 Operand::Move(Place::Local(Local::new(1+i)))
765 let mut blocks = IndexVec::new();
766 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
767 blocks.push(BasicBlockData {
769 terminator: Some(Terminator { source_info, kind }),
775 block(&mut blocks, statements, TerminatorKind::Call {
778 destination: Some((Place::Local(RETURN_PLACE),
779 BasicBlock::new(1))),
780 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
781 Some(BasicBlock::new(3))
787 if let Adjustment::RefMut = rcvr_adjustment {
788 // BB #1 - drop for Self
789 block(&mut blocks, vec![], TerminatorKind::Drop {
790 location: Place::Local(rcvr_arg),
791 target: BasicBlock::new(2),
796 block(&mut blocks, vec![], TerminatorKind::Return, false);
797 if let Adjustment::RefMut = rcvr_adjustment {
798 // BB #3 - drop if closure panics
799 block(&mut blocks, vec![], TerminatorKind::Drop {
800 location: Place::Local(rcvr_arg),
801 target: BasicBlock::new(4),
806 block(&mut blocks, vec![], TerminatorKind::Resume, true);
809 let mut mir = Mir::new(
811 IndexVec::from_elem_n(
812 VisibilityScopeData { span: span, parent_scope: None }, 1
814 ClearCrossCrate::Clear,
822 if let Abi::RustCall = sig.abi {
823 mir.spread_arg = Some(Local::new(sig.inputs().len()));
828 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
829 ctor_id: ast::NodeId,
830 fields: &[hir::StructField],
835 let gcx = tcx.global_tcx();
836 let def_id = tcx.hir.local_def_id(ctor_id);
837 let sig = gcx.fn_sig(def_id).no_late_bound_regions()
838 .expect("LBR in ADT constructor signature");
839 let sig = gcx.erase_regions(&sig);
840 let param_env = gcx.param_env(def_id);
842 // Normalize the sig now that we have liberated the late-bound
844 let sig = gcx.normalize_associated_type_in_env(&sig, param_env);
846 let (adt_def, substs) = match sig.output().sty {
847 ty::TyAdt(adt_def, substs) => (adt_def, substs),
848 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
851 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
853 let local_decls = local_decls_for_sig(&sig, span);
855 let source_info = SourceInfo {
857 scope: ARGUMENT_VISIBILITY_SCOPE
860 let variant_no = if adt_def.is_enum() {
861 adt_def.variant_index_with_id(def_id)
866 // return = ADT(arg0, arg1, ...); return
867 let start_block = BasicBlockData {
868 statements: vec![Statement {
870 kind: StatementKind::Assign(
871 Place::Local(RETURN_PLACE),
873 box AggregateKind::Adt(adt_def, variant_no, substs, None),
874 (1..sig.inputs().len()+1).map(|i| {
875 Operand::Move(Place::Local(Local::new(i)))
880 terminator: Some(Terminator {
882 kind: TerminatorKind::Return,
888 IndexVec::from_elem_n(start_block, 1),
889 IndexVec::from_elem_n(
890 VisibilityScopeData { span: span, parent_scope: None }, 1
892 ClearCrossCrate::Clear,