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_call_guards, no_landing_pads, simplify};
31 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
32 use util::patch::MirPatch;
34 pub fn provide(providers: &mut Providers) {
35 providers.mir_shims = make_shim;
38 fn make_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
39 instance: ty::InstanceDef<'tcx>)
42 debug!("make_shim({:?})", instance);
44 let mut result = match instance {
45 ty::InstanceDef::Item(..) =>
46 bug!("item {:?} passed to make_shim", instance),
47 ty::InstanceDef::FnPtrShim(def_id, ty) => {
48 let trait_ = tcx.trait_of_item(def_id).unwrap();
49 let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
50 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
51 Some(ty::ClosureKind::FnMut) |
52 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
53 None => bug!("fn pointer {:?} is not an fn", ty)
55 // HACK: we need the "real" argument types for the MIR,
56 // but because our substs are (Self, Args), where Args
57 // is a tuple, we must include the *concrete* argument
58 // types in the MIR. They will be substituted again with
59 // the param-substs, but because they are concrete, this
60 // will not do any harm.
61 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
62 let arg_tys = sig.inputs();
72 ty::InstanceDef::Virtual(def_id, _) => {
73 // We are translating a call back to our def-id, which
74 // trans::mir knows to turn to an actual virtual call.
79 CallKind::Direct(def_id),
83 ty::InstanceDef::ClosureOnceShim { call_once } => {
84 let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
85 let call_mut = tcx.global_tcx()
86 .associated_items(fn_mut)
87 .find(|it| it.kind == ty::AssociatedKind::Method)
94 CallKind::Direct(call_mut),
98 ty::InstanceDef::DropGlue(def_id, ty) => {
99 build_drop_shim(tcx, def_id, ty)
101 ty::InstanceDef::CloneShim(def_id, ty) => {
102 let name = tcx.item_name(def_id);
104 build_clone_shim(tcx, def_id, ty)
105 } else if name == "clone_from" {
106 debug!("make_shim({:?}: using default trait implementation", instance);
107 return tcx.optimized_mir(def_id);
109 bug!("builtin clone shim {:?} not supported", instance)
112 ty::InstanceDef::Intrinsic(_) => {
113 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
116 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
117 no_landing_pads::no_landing_pads(tcx, &mut result);
118 simplify::simplify_cfg(&mut result);
119 add_call_guards::CriticalCallEdges.add_call_guards(&mut result);
120 debug!("make_shim({:?}) = {:?}", instance, result);
122 tcx.alloc_mir(result)
125 #[derive(Copy, Clone, Debug, PartialEq)]
132 #[derive(Copy, Clone, Debug, PartialEq)]
138 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
140 mutability, ty, name: None,
141 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
142 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
144 is_user_variable: false
148 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
149 -> IndexVec<Local, LocalDecl<'tcx>>
151 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
152 .chain(sig.inputs().iter().map(
153 |ity| temp_decl(Mutability::Not, ity, span)))
157 fn build_drop_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
159 ty: Option<Ty<'tcx>>)
162 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
164 // Check if this is a generator, if so, return the drop glue for it
165 if let Some(&ty::TyS { sty: ty::TyGenerator(gen_def_id, substs, _), .. }) = ty {
166 let mir = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
167 return mir.subst(tcx, substs.substs);
170 let substs = if let Some(ty) = ty {
171 tcx.mk_substs(iter::once(Kind::from(ty)))
173 Substs::identity_for_item(tcx, def_id)
175 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
176 let sig = tcx.erase_late_bound_regions(&sig);
177 let span = tcx.def_span(def_id);
179 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
181 let return_block = BasicBlock::new(1);
182 let mut blocks = IndexVec::new();
183 let block = |blocks: &mut IndexVec<_, _>, kind| {
184 blocks.push(BasicBlockData {
186 terminator: Some(Terminator { source_info, kind }),
190 block(&mut blocks, TerminatorKind::Goto { target: return_block });
191 block(&mut blocks, TerminatorKind::Return);
193 let mut mir = Mir::new(
195 IndexVec::from_elem_n(
196 VisibilityScopeData { span: span, parent_scope: None }, 1
198 ClearOnDecode::Clear,
201 local_decls_for_sig(&sig, span),
207 if let Some(..) = ty {
209 let param_env = tcx.param_env(def_id);
210 let mut elaborator = DropShimElaborator {
212 patch: MirPatch::new(&mir),
216 let dropee = Lvalue::Local(Local::new(1+0)).deref();
217 let resume_block = elaborator.patch.resume_block();
218 elaborate_drops::elaborate_drop(
224 elaborate_drops::Unwind::To(resume_block),
229 patch.apply(&mut mir);
235 pub struct DropShimElaborator<'a, 'tcx: 'a> {
236 pub mir: &'a Mir<'tcx>,
237 pub patch: MirPatch<'tcx>,
238 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
239 pub param_env: ty::ParamEnv<'tcx>,
242 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
243 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
248 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
251 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
252 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
253 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
254 fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
256 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
257 if let DropFlagMode::Shallow = mode {
264 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
268 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
271 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
274 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
277 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
282 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
283 fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
288 debug!("build_clone_shim(def_id={:?})", def_id);
290 let mut builder = CloneShimBuilder::new(tcx, def_id);
291 let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
294 _ if is_copy => builder.copy_shim(),
295 ty::TyArray(ty, len) => {
296 let len = len.val.to_const_int().unwrap().to_u64().unwrap();
297 builder.array_shim(ty, len)
299 ty::TyClosure(def_id, substs) => {
300 builder.tuple_like_shim(
301 &substs.upvar_tys(def_id, tcx).collect::<Vec<_>>(),
302 AggregateKind::Closure(def_id, substs)
305 ty::TyTuple(tys, _) => builder.tuple_like_shim(&**tys, AggregateKind::Tuple),
307 bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
314 struct CloneShimBuilder<'a, 'tcx: 'a> {
315 tcx: TyCtxt<'a, 'tcx, 'tcx>,
317 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
318 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
320 sig: ty::FnSig<'tcx>,
323 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
324 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Self {
325 let sig = tcx.fn_sig(def_id);
326 let sig = tcx.erase_late_bound_regions(&sig);
327 let span = tcx.def_span(def_id);
332 local_decls: local_decls_for_sig(&sig, span),
333 blocks: IndexVec::new(),
339 fn into_mir(self) -> Mir<'tcx> {
342 IndexVec::from_elem_n(
343 VisibilityScopeData { span: self.span, parent_scope: None }, 1
345 ClearOnDecode::Clear,
349 self.sig.inputs().len(),
355 fn source_info(&self) -> SourceInfo {
356 SourceInfo { span: self.span, scope: ARGUMENT_VISIBILITY_SCOPE }
361 statements: Vec<Statement<'tcx>>,
362 kind: TerminatorKind<'tcx>,
365 let source_info = self.source_info();
366 self.blocks.push(BasicBlockData {
368 terminator: Some(Terminator { source_info, kind }),
373 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
375 source_info: self.source_info(),
380 fn copy_shim(&mut self) {
381 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
382 let ret_statement = self.make_statement(
383 StatementKind::Assign(
384 Lvalue::Local(RETURN_POINTER),
385 Rvalue::Use(Operand::Consume(rcvr))
388 self.block(vec![ret_statement], TerminatorKind::Return, false);
391 fn make_lvalue(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Lvalue<'tcx> {
392 let span = self.span;
394 self.local_decls.push(temp_decl(mutability, ty, span))
401 rcvr_field: Lvalue<'tcx>,
407 let substs = Substs::for_item(
410 |_, _| tcx.types.re_erased,
414 // `func == Clone::clone(&ty) -> ty`
415 let func_ty = tcx.mk_fn_def(self.def_id, substs);
416 let func = Operand::Constant(box Constant {
419 literal: Literal::Value {
420 value: tcx.mk_const(ty::Const {
421 val: ConstVal::Function(self.def_id, substs),
427 let ref_loc = self.make_lvalue(
429 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
431 mutbl: hir::Mutability::MutImmutable,
435 let loc = self.make_lvalue(Mutability::Not, ty);
437 // `let ref_loc: &ty = &rcvr_field;`
438 let statement = self.make_statement(
439 StatementKind::Assign(
441 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, rcvr_field)
445 // `let loc = Clone::clone(ref_loc);`
446 self.block(vec![statement], TerminatorKind::Call {
448 args: vec![Operand::Consume(ref_loc)],
449 destination: Some((loc.clone(), next)),
450 cleanup: Some(cleanup),
460 loop_body: BasicBlock,
461 loop_end: BasicBlock,
466 let cond = self.make_lvalue(Mutability::Mut, tcx.types.bool);
467 let compute_cond = self.make_statement(
468 StatementKind::Assign(
470 Rvalue::BinaryOp(BinOp::Ne, Operand::Consume(end), Operand::Consume(beg))
474 // `if end != beg { goto loop_body; } else { goto loop_end; }`
477 TerminatorKind::if_(tcx, Operand::Consume(cond), loop_body, loop_end),
482 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
483 let value = ConstUsize::new(value, self.tcx.sess.target.usize_ty).unwrap();
486 ty: self.tcx.types.usize,
487 literal: Literal::Value {
488 value: self.tcx.mk_const(ty::Const {
489 val: ConstVal::Integral(ConstInt::Usize(value)),
490 ty: self.tcx.types.usize,
496 fn array_shim(&mut self, ty: Ty<'tcx>, len: u64) {
498 let span = self.span;
499 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
501 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
502 let end = self.make_lvalue(Mutability::Not, tcx.types.usize);
503 let ret = self.make_lvalue(Mutability::Mut, tcx.mk_array(ty, len));
506 // `let mut beg = 0;`
511 StatementKind::Assign(
513 Rvalue::Use(Operand::Constant(self.make_usize(0)))
517 StatementKind::Assign(
519 Rvalue::Use(Operand::Constant(self.make_usize(len)))
523 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
530 self.loop_header(Lvalue::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
533 // `let cloned = Clone::clone(rcvr[beg])`;
534 // Goto #3 if ok, #5 if unwinding happens.
535 let rcvr_field = rcvr.clone().index(beg);
536 let cloned = self.make_clone_call(ty, rcvr_field, BasicBlock::new(3), BasicBlock::new(5));
539 // `ret[beg] = cloned;`
542 let ret_field = ret.clone().index(beg);
543 let statements = vec![
545 StatementKind::Assign(
547 Rvalue::Use(Operand::Consume(cloned))
551 StatementKind::Assign(
555 Operand::Consume(Lvalue::Local(beg)),
556 Operand::Constant(self.make_usize(1))
561 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
565 let ret_statement = self.make_statement(
566 StatementKind::Assign(
567 Lvalue::Local(RETURN_POINTER),
568 Rvalue::Use(Operand::Consume(ret.clone())),
571 self.block(vec![ret_statement], TerminatorKind::Return, false);
575 // `let mut beg = 0;`
578 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
579 let init = self.make_statement(
580 StatementKind::Assign(
582 Rvalue::Use(Operand::Constant(self.make_usize(0)))
585 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
587 // BB #6 (cleanup): loop {
592 self.loop_header(Lvalue::Local(beg), Lvalue::Local(end),
593 BasicBlock::new(7), BasicBlock::new(9), true);
597 self.block(vec![], TerminatorKind::Drop {
598 location: ret.index(beg),
599 target: BasicBlock::new(8),
606 let statement = self.make_statement(
607 StatementKind::Assign(
611 Operand::Consume(Lvalue::Local(beg)),
612 Operand::Constant(self.make_usize(1))
616 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
619 self.block(vec![], TerminatorKind::Resume, true);
622 fn tuple_like_shim(&mut self, tys: &[ty::Ty<'tcx>], kind: AggregateKind<'tcx>) {
624 AggregateKind::Tuple | AggregateKind::Closure(..) => (),
625 _ => bug!("only tuples and closures are accepted"),
628 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
630 let mut returns = Vec::new();
631 for (i, ity) in tys.iter().enumerate() {
632 let rcvr_field = rcvr.clone().field(Field::new(i), *ity);
635 // `returns[i] = Clone::clone(&rcvr.i);`
636 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
638 self.make_clone_call(
641 BasicBlock::new(2 * i + 2),
642 BasicBlock::new(2 * i + 1),
646 // BB #(2i + 1) (cleanup)
648 // Nothing to drop, just resume.
649 self.block(vec![], TerminatorKind::Resume, true);
651 // Drop previous field and goto previous cleanup block.
652 self.block(vec![], TerminatorKind::Drop {
653 location: returns[i - 1].clone(),
654 target: BasicBlock::new(2 * i - 1),
660 // `return kind(returns[0], returns[1], ..., returns[tys.len() - 1]);`
661 let ret_statement = self.make_statement(
662 StatementKind::Assign(
663 Lvalue::Local(RETURN_POINTER),
666 returns.into_iter().map(Operand::Consume).collect()
670 self.block(vec![ret_statement], TerminatorKind::Return, false);
674 /// Build a "call" shim for `def_id`. The shim calls the
675 /// function specified by `call_kind`, first adjusting its first
676 /// argument according to `rcvr_adjustment`.
678 /// If `untuple_args` is a vec of types, the second argument of the
679 /// function will be untupled as these types.
680 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
682 rcvr_adjustment: Adjustment,
684 untuple_args: Option<&[Ty<'tcx>]>)
687 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
688 call_kind={:?}, untuple_args={:?})",
689 def_id, rcvr_adjustment, call_kind, untuple_args);
691 let sig = tcx.fn_sig(def_id);
692 let sig = tcx.erase_late_bound_regions(&sig);
693 let span = tcx.def_span(def_id);
695 debug!("build_call_shim: sig={:?}", sig);
697 let mut local_decls = local_decls_for_sig(&sig, span);
698 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
700 let rcvr_arg = Local::new(1+0);
701 let rcvr_l = Lvalue::Local(rcvr_arg);
702 let mut statements = vec![];
704 let rcvr = match rcvr_adjustment {
705 Adjustment::Identity => Operand::Consume(rcvr_l),
706 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
707 Adjustment::RefMut => {
708 // let rcvr = &mut rcvr;
709 let ref_rcvr = local_decls.push(temp_decl(
711 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
713 mutbl: hir::Mutability::MutMutable
717 statements.push(Statement {
719 kind: StatementKind::Assign(
720 Lvalue::Local(ref_rcvr),
721 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
724 Operand::Consume(Lvalue::Local(ref_rcvr))
728 let (callee, mut args) = match call_kind {
729 CallKind::Indirect => (rcvr, vec![]),
730 CallKind::Direct(def_id) => {
731 let ty = tcx.type_of(def_id);
732 (Operand::Constant(box Constant {
735 literal: Literal::Value {
736 value: tcx.mk_const(ty::Const {
737 val: ConstVal::Function(def_id,
738 Substs::identity_for_item(tcx, def_id)),
747 if let Some(untuple_args) = untuple_args {
748 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
749 let arg_lv = Lvalue::Local(Local::new(1+1));
750 Operand::Consume(arg_lv.field(Field::new(i), *ity))
753 args.extend((1..sig.inputs().len()).map(|i| {
754 Operand::Consume(Lvalue::Local(Local::new(1+i)))
758 let mut blocks = IndexVec::new();
759 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
760 blocks.push(BasicBlockData {
762 terminator: Some(Terminator { source_info, kind }),
768 block(&mut blocks, statements, TerminatorKind::Call {
771 destination: Some((Lvalue::Local(RETURN_POINTER),
772 BasicBlock::new(1))),
773 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
774 Some(BasicBlock::new(3))
780 if let Adjustment::RefMut = rcvr_adjustment {
781 // BB #1 - drop for Self
782 block(&mut blocks, vec![], TerminatorKind::Drop {
783 location: Lvalue::Local(rcvr_arg),
784 target: BasicBlock::new(2),
789 block(&mut blocks, vec![], TerminatorKind::Return, false);
790 if let Adjustment::RefMut = rcvr_adjustment {
791 // BB #3 - drop if closure panics
792 block(&mut blocks, vec![], TerminatorKind::Drop {
793 location: Lvalue::Local(rcvr_arg),
794 target: BasicBlock::new(4),
799 block(&mut blocks, vec![], TerminatorKind::Resume, true);
802 let mut mir = Mir::new(
804 IndexVec::from_elem_n(
805 VisibilityScopeData { span: span, parent_scope: None }, 1
807 ClearOnDecode::Clear,
815 if let Abi::RustCall = sig.abi {
816 mir.spread_arg = Some(Local::new(sig.inputs().len()));
821 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
822 ctor_id: ast::NodeId,
823 fields: &[hir::StructField],
828 let gcx = tcx.global_tcx();
829 let def_id = tcx.hir.local_def_id(ctor_id);
830 let sig = gcx.no_late_bound_regions(&gcx.fn_sig(def_id))
831 .expect("LBR in ADT constructor signature");
832 let sig = gcx.erase_regions(&sig);
833 let param_env = gcx.param_env(def_id);
835 // Normalize the sig now that we have liberated the late-bound
837 let sig = gcx.normalize_associated_type_in_env(&sig, param_env);
839 let (adt_def, substs) = match sig.output().sty {
840 ty::TyAdt(adt_def, substs) => (adt_def, substs),
841 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
844 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
846 let local_decls = local_decls_for_sig(&sig, span);
848 let source_info = SourceInfo {
850 scope: ARGUMENT_VISIBILITY_SCOPE
853 let variant_no = if adt_def.is_enum() {
854 adt_def.variant_index_with_id(def_id)
859 // return = ADT(arg0, arg1, ...); return
860 let start_block = BasicBlockData {
861 statements: vec![Statement {
863 kind: StatementKind::Assign(
864 Lvalue::Local(RETURN_POINTER),
866 box AggregateKind::Adt(adt_def, variant_no, substs, None),
867 (1..sig.inputs().len()+1).map(|i| {
868 Operand::Consume(Lvalue::Local(Local::new(i)))
873 terminator: Some(Terminator {
875 kind: TerminatorKind::Return,
881 IndexVec::from_elem_n(start_block, 1),
882 IndexVec::from_elem_n(
883 VisibilityScopeData { span: span, parent_scope: None }, 1
885 ClearOnDecode::Clear,