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::mir::transform::MirSource;
17 use rustc::ty::{self, Ty};
18 use rustc::ty::subst::{Kind, Subst};
19 use rustc::ty::maps::Providers;
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: ty::TyCtxt<'a, 'tcx, 'tcx>,
39 instance: ty::InstanceDef<'tcx>)
42 debug!("make_shim({:?})", instance);
43 let did = instance.def_id();
44 let span = tcx.def_span(did);
45 let param_env = tcx.construct_parameter_environment(span, did, None);
47 let mut result = match instance {
48 ty::InstanceDef::Item(..) =>
49 bug!("item {:?} passed to make_shim", instance),
50 ty::InstanceDef::FnPtrShim(def_id, ty) => {
51 let trait_ = tcx.trait_of_item(def_id).unwrap();
52 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
53 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
54 Some(ty::ClosureKind::FnMut) |
55 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
56 None => bug!("fn pointer {:?} is not an fn", ty)
58 // HACK: we need the "real" argument types for the MIR,
59 // but because our substs are (Self, Args), where Args
60 // is a tuple, we must include the *concrete* argument
61 // types in the MIR. They will be substituted again with
62 // the param-substs, but because they are concrete, this
63 // will not do any harm.
64 let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
65 let arg_tys = sig.inputs();
76 ty::InstanceDef::Virtual(def_id, _) => {
77 // We are translating a call back to our def-id, which
78 // trans::mir knows to turn to an actual virtual call.
84 CallKind::Direct(def_id),
88 ty::InstanceDef::ClosureOnceShim { call_once } => {
89 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
90 let call_mut = tcx.global_tcx()
91 .associated_items(fn_mut)
92 .find(|it| it.kind == ty::AssociatedKind::Method)
100 CallKind::Direct(call_mut),
104 ty::InstanceDef::DropGlue(def_id, ty) => {
105 build_drop_shim(tcx, ¶m_env, def_id, ty)
107 ty::InstanceDef::Intrinsic(_) => {
108 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
111 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
112 no_landing_pads::no_landing_pads(tcx, &mut result);
113 simplify::simplify_cfg(&mut result);
114 add_call_guards::add_call_guards(&mut result);
115 debug!("make_shim({:?}) = {:?}", instance, result);
117 tcx.alloc_mir(result)
120 #[derive(Copy, Clone, Debug, PartialEq)]
127 #[derive(Copy, Clone, Debug, PartialEq)]
133 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
135 mutability, ty, name: None,
136 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
137 is_user_variable: false
141 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
142 -> IndexVec<Local, LocalDecl<'tcx>>
144 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
145 .chain(sig.inputs().iter().map(
146 |ity| temp_decl(Mutability::Not, ity, span)))
150 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
151 param_env: &ty::ParameterEnvironment<'tcx>,
153 ty: Option<Ty<'tcx>>)
156 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
158 let substs = if let Some(ty) = ty {
159 tcx.mk_substs(iter::once(Kind::from(ty)))
161 param_env.free_substs
163 let fn_ty = tcx.type_of(def_id).subst(tcx, substs);
164 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
165 let span = tcx.def_span(def_id);
167 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
169 let return_block = BasicBlock::new(1);
170 let mut blocks = IndexVec::new();
171 let block = |blocks: &mut IndexVec<_, _>, kind| {
172 blocks.push(BasicBlockData {
174 terminator: Some(Terminator { source_info, kind }),
178 block(&mut blocks, TerminatorKind::Goto { target: return_block });
179 block(&mut blocks, TerminatorKind::Return);
181 let mut mir = Mir::new(
183 IndexVec::from_elem_n(
184 VisibilityScopeData { span: span, parent_scope: None }, 1
188 local_decls_for_sig(&sig, span),
194 if let Some(..) = ty {
196 let mut elaborator = DropShimElaborator {
198 patch: MirPatch::new(&mir),
201 let dropee = Lvalue::Local(Local::new(1+0)).deref();
202 let resume_block = elaborator.patch.resume_block();
203 elaborate_drops::elaborate_drop(
215 patch.apply(&mut mir);
221 pub struct DropShimElaborator<'a, 'tcx: 'a> {
223 patch: MirPatch<'tcx>,
224 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
225 param_env: &'a ty::ParameterEnvironment<'tcx>,
228 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
229 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
234 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
237 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
238 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
239 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
240 fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
242 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
243 if let DropFlagMode::Shallow = mode {
250 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
254 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
257 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
260 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
263 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
268 /// Build a "call" shim for `def_id`. The shim calls the
269 /// function specified by `call_kind`, first adjusting its first
270 /// argument according to `rcvr_adjustment`.
272 /// If `untuple_args` is a vec of types, the second argument of the
273 /// function will be untupled as these types.
274 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
275 param_env: &ty::ParameterEnvironment<'tcx>,
277 rcvr_adjustment: Adjustment,
279 untuple_args: Option<&[Ty<'tcx>]>)
282 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
283 call_kind={:?}, untuple_args={:?})",
284 def_id, rcvr_adjustment, call_kind, untuple_args);
286 let fn_ty = tcx.type_of(def_id).subst(tcx, param_env.free_substs);
287 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
288 let span = tcx.def_span(def_id);
290 debug!("build_call_shim: sig={:?}", sig);
292 let mut local_decls = local_decls_for_sig(&sig, span);
293 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
295 let rcvr_arg = Local::new(1+0);
296 let rcvr_l = Lvalue::Local(rcvr_arg);
297 let mut statements = vec![];
299 let rcvr = match rcvr_adjustment {
300 Adjustment::Identity => Operand::Consume(rcvr_l),
301 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
302 Adjustment::RefMut => {
303 // let rcvr = &mut rcvr;
304 let ref_rcvr = local_decls.push(temp_decl(
306 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
308 mutbl: hir::Mutability::MutMutable
312 statements.push(Statement {
313 source_info: source_info,
314 kind: StatementKind::Assign(
315 Lvalue::Local(ref_rcvr),
316 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
319 Operand::Consume(Lvalue::Local(ref_rcvr))
323 let (callee, mut args) = match call_kind {
324 CallKind::Indirect => (rcvr, vec![]),
325 CallKind::Direct(def_id) => (
326 Operand::Constant(box Constant {
328 ty: tcx.type_of(def_id).subst(tcx, param_env.free_substs),
329 literal: Literal::Value {
330 value: ConstVal::Function(def_id, param_env.free_substs),
337 if let Some(untuple_args) = untuple_args {
338 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
339 let arg_lv = Lvalue::Local(Local::new(1+1));
340 Operand::Consume(arg_lv.field(Field::new(i), *ity))
343 args.extend((1..sig.inputs().len()).map(|i| {
344 Operand::Consume(Lvalue::Local(Local::new(1+i)))
348 let mut blocks = IndexVec::new();
349 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
350 blocks.push(BasicBlockData {
352 terminator: Some(Terminator { source_info, kind }),
358 block(&mut blocks, statements, TerminatorKind::Call {
361 destination: Some((Lvalue::Local(RETURN_POINTER),
362 BasicBlock::new(1))),
363 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
364 Some(BasicBlock::new(3))
370 if let Adjustment::RefMut = rcvr_adjustment {
371 // BB #1 - drop for Self
372 block(&mut blocks, vec![], TerminatorKind::Drop {
373 location: Lvalue::Local(rcvr_arg),
374 target: BasicBlock::new(2),
379 block(&mut blocks, vec![], TerminatorKind::Return, false);
380 if let Adjustment::RefMut = rcvr_adjustment {
381 // BB #3 - drop if closure panics
382 block(&mut blocks, vec![], TerminatorKind::Drop {
383 location: Lvalue::Local(rcvr_arg),
384 target: BasicBlock::new(4),
389 block(&mut blocks, vec![], TerminatorKind::Resume, true);
392 let mut mir = Mir::new(
394 IndexVec::from_elem_n(
395 VisibilityScopeData { span: span, parent_scope: None }, 1
404 if let Abi::RustCall = sig.abi {
405 mir.spread_arg = Some(Local::new(sig.inputs().len()));
410 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
411 ctor_id: ast::NodeId,
412 fields: &[hir::StructField],
414 -> (Mir<'tcx>, MirSource)
417 let def_id = tcx.hir.local_def_id(ctor_id);
418 let sig = match tcx.type_of(def_id).sty {
419 ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
420 .expect("LBR in ADT constructor signature"),
421 _ => bug!("unexpected type for ctor {:?}", def_id)
423 let sig = tcx.erase_regions(&sig);
425 let (adt_def, substs) = match sig.output().sty {
426 ty::TyAdt(adt_def, substs) => (adt_def, substs),
427 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
430 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
432 let local_decls = local_decls_for_sig(&sig, span);
434 let source_info = SourceInfo {
436 scope: ARGUMENT_VISIBILITY_SCOPE
439 let variant_no = if adt_def.is_enum() {
440 adt_def.variant_index_with_id(def_id)
445 // return = ADT(arg0, arg1, ...); return
446 let start_block = BasicBlockData {
447 statements: vec![Statement {
448 source_info: source_info,
449 kind: StatementKind::Assign(
450 Lvalue::Local(RETURN_POINTER),
452 box AggregateKind::Adt(adt_def, variant_no, substs, None),
453 (1..sig.inputs().len()+1).map(|i| {
454 Operand::Consume(Lvalue::Local(Local::new(i)))
459 terminator: Some(Terminator {
460 source_info: source_info,
461 kind: TerminatorKind::Return,
467 IndexVec::from_elem_n(start_block, 1),
468 IndexVec::from_elem_n(
469 VisibilityScopeData { span: span, parent_scope: None }, 1
478 (mir, MirSource::Fn(ctor_id))