]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
f2a550ec23a8e2abb04cea2d2dd1a7c433bed7e0
[rust.git] / src / librustc_mir / shim.rs
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.
4 //
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.
10
11 use rustc::hir;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer;
14 use rustc::middle::const_val::ConstVal;
15 use rustc::mir::*;
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;
20
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
22
23 use syntax::abi::Abi;
24 use syntax::ast;
25 use syntax_pos::Span;
26
27 use std::cell::RefCell;
28 use std::fmt;
29 use std::iter;
30 use std::mem;
31
32 use transform::{add_call_guards, no_landing_pads, simplify};
33 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
34 use util::patch::MirPatch;
35
36 pub fn provide(providers: &mut Providers) {
37     providers.mir_shims = make_shim;
38 }
39
40 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
41                        instance: ty::InstanceDef<'tcx>)
42                        -> &'tcx RefCell<Mir<'tcx>>
43 {
44     debug!("make_shim({:?})", instance);
45     let did = instance.def_id();
46     let span = tcx.def_span(did);
47     let param_env = tcx.construct_parameter_environment(span, did, None);
48
49     let mut result = match instance {
50         ty::InstanceDef::Item(..) =>
51             bug!("item {:?} passed to make_shim", instance),
52         ty::InstanceDef::FnPtrShim(def_id, ty) => {
53             let trait_ = tcx.trait_of_item(def_id).unwrap();
54             let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
55                 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
56                 Some(ty::ClosureKind::FnMut) |
57                 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
58                 None => bug!("fn pointer {:?} is not an fn", ty)
59             };
60             // HACK: we need the "real" argument types for the MIR,
61             // but because our substs are (Self, Args), where Args
62             // is a tuple, we must include the *concrete* argument
63             // types in the MIR. They will be substituted again with
64             // the param-substs, but because they are concrete, this
65             // will not do any harm.
66             let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
67             let arg_tys = sig.inputs();
68
69             build_call_shim(
70                 tcx,
71                 &param_env,
72                 def_id,
73                 adjustment,
74                 CallKind::Indirect,
75                 Some(arg_tys)
76             )
77         }
78         ty::InstanceDef::Virtual(def_id, _) => {
79             // We are translating a call back to our def-id, which
80             // trans::mir knows to turn to an actual virtual call.
81             build_call_shim(
82                 tcx,
83                 &param_env,
84                 def_id,
85                 Adjustment::Identity,
86                 CallKind::Direct(def_id),
87                 None
88             )
89         }
90         ty::InstanceDef::ClosureOnceShim { call_once } => {
91             let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
92             let call_mut = tcx.global_tcx()
93                 .associated_items(fn_mut)
94                 .find(|it| it.kind == ty::AssociatedKind::Method)
95                 .unwrap().def_id;
96
97             build_call_shim(
98                 tcx,
99                 &param_env,
100                 call_once,
101                 Adjustment::RefMut,
102                 CallKind::Direct(call_mut),
103                 None
104             )
105         }
106         ty::InstanceDef::DropGlue(def_id, ty) => {
107             build_drop_shim(tcx, &param_env, def_id, ty)
108         }
109         ty::InstanceDef::Intrinsic(_) => {
110             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
111         }
112     };
113         debug!("make_shim({:?}) = untransformed {:?}", instance, result);
114         no_landing_pads::no_landing_pads(tcx, &mut result);
115         simplify::simplify_cfg(&mut result);
116         add_call_guards::add_call_guards(&mut result);
117     debug!("make_shim({:?}) = {:?}", instance, result);
118
119     let result = tcx.alloc_mir(result);
120     // Perma-borrow MIR from shims to prevent mutation.
121     mem::forget(result.borrow());
122     result
123 }
124
125 #[derive(Copy, Clone, Debug, PartialEq)]
126 enum Adjustment {
127     Identity,
128     Deref,
129     RefMut,
130 }
131
132 #[derive(Copy, Clone, Debug, PartialEq)]
133 enum CallKind {
134     Indirect,
135     Direct(DefId),
136 }
137
138 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
139     LocalDecl {
140         mutability, ty, name: None,
141         source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
142         is_user_variable: false
143     }
144 }
145
146 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
147     -> IndexVec<Local, LocalDecl<'tcx>>
148 {
149     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
150         .chain(sig.inputs().iter().map(
151             |ity| temp_decl(Mutability::Not, ity, span)))
152         .collect()
153 }
154
155 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
156                              param_env: &ty::ParameterEnvironment<'tcx>,
157                              def_id: DefId,
158                              ty: Option<Ty<'tcx>>)
159                              -> Mir<'tcx>
160 {
161     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
162
163     let substs = if let Some(ty) = ty {
164         tcx.mk_substs(iter::once(Kind::from(ty)))
165     } else {
166         param_env.free_substs
167     };
168     let fn_ty = tcx.type_of(def_id).subst(tcx, substs);
169     let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
170     let span = tcx.def_span(def_id);
171
172     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
173
174     let return_block = BasicBlock::new(1);
175     let mut blocks = IndexVec::new();
176     let block = |blocks: &mut IndexVec<_, _>, kind| {
177         blocks.push(BasicBlockData {
178             statements: vec![],
179             terminator: Some(Terminator { source_info, kind }),
180             is_cleanup: false
181         })
182     };
183     block(&mut blocks, TerminatorKind::Goto { target: return_block });
184     block(&mut blocks, TerminatorKind::Return);
185
186     let mut mir = Mir::new(
187         blocks,
188         IndexVec::from_elem_n(
189             VisibilityScopeData { span: span, parent_scope: None }, 1
190         ),
191         IndexVec::new(),
192         sig.output(),
193         local_decls_for_sig(&sig, span),
194         sig.inputs().len(),
195         vec![],
196         span
197     );
198
199     if let Some(..) = ty {
200         let patch = {
201             let mut elaborator = DropShimElaborator {
202                 mir: &mir,
203                 patch: MirPatch::new(&mir),
204                 tcx, param_env
205             };
206             let dropee = Lvalue::Local(Local::new(1+0)).deref();
207             let resume_block = elaborator.patch.resume_block();
208             elaborate_drops::elaborate_drop(
209                 &mut elaborator,
210                 source_info,
211                 false,
212                 &dropee,
213                 (),
214                 return_block,
215                 Some(resume_block),
216                 START_BLOCK
217             );
218             elaborator.patch
219         };
220         patch.apply(&mut mir);
221     }
222
223     mir
224 }
225
226 pub struct DropShimElaborator<'a, 'tcx: 'a> {
227     mir: &'a Mir<'tcx>,
228     patch: MirPatch<'tcx>,
229     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
230     param_env: &'a ty::ParameterEnvironment<'tcx>,
231 }
232
233 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
234     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
235         Ok(())
236     }
237 }
238
239 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
240     type Path = ();
241
242     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
243     fn mir(&self) -> &'a Mir<'tcx> { self.mir }
244     fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
245     fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
246
247     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
248         if let DropFlagMode::Shallow = mode {
249             DropStyle::Static
250         } else {
251             DropStyle::Open
252         }
253     }
254
255     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
256         None
257     }
258
259     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
260     }
261
262     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
263         None
264     }
265     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
266         None
267     }
268     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
269         Some(())
270     }
271 }
272
273 /// Build a "call" shim for `def_id`. The shim calls the
274 /// function specified by `call_kind`, first adjusting its first
275 /// argument according to `rcvr_adjustment`.
276 ///
277 /// If `untuple_args` is a vec of types, the second argument of the
278 /// function will be untupled as these types.
279 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
280                              param_env: &ty::ParameterEnvironment<'tcx>,
281                              def_id: DefId,
282                              rcvr_adjustment: Adjustment,
283                              call_kind: CallKind,
284                              untuple_args: Option<&[Ty<'tcx>]>)
285                              -> Mir<'tcx>
286 {
287     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
288             call_kind={:?}, untuple_args={:?})",
289            def_id, rcvr_adjustment, call_kind, untuple_args);
290
291     let fn_ty = tcx.type_of(def_id).subst(tcx, param_env.free_substs);
292     let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
293     let span = tcx.def_span(def_id);
294
295     debug!("build_call_shim: sig={:?}", sig);
296
297     let mut local_decls = local_decls_for_sig(&sig, span);
298     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
299
300     let rcvr_arg = Local::new(1+0);
301     let rcvr_l = Lvalue::Local(rcvr_arg);
302     let mut statements = vec![];
303
304     let rcvr = match rcvr_adjustment {
305         Adjustment::Identity => Operand::Consume(rcvr_l),
306         Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
307         Adjustment::RefMut => {
308             // let rcvr = &mut rcvr;
309             let ref_rcvr = local_decls.push(temp_decl(
310                 Mutability::Not,
311                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
312                     ty: sig.inputs()[0],
313                     mutbl: hir::Mutability::MutMutable
314                 }),
315                 span
316             ));
317             statements.push(Statement {
318                 source_info: source_info,
319                 kind: StatementKind::Assign(
320                     Lvalue::Local(ref_rcvr),
321                     Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
322                 )
323             });
324             Operand::Consume(Lvalue::Local(ref_rcvr))
325         }
326     };
327
328     let (callee, mut args) = match call_kind {
329         CallKind::Indirect => (rcvr, vec![]),
330         CallKind::Direct(def_id) => (
331             Operand::Constant(Constant {
332                 span: span,
333                 ty: tcx.type_of(def_id).subst(tcx, param_env.free_substs),
334                 literal: Literal::Value {
335                     value: ConstVal::Function(def_id, param_env.free_substs),
336                 },
337             }),
338             vec![rcvr]
339         )
340     };
341
342     if let Some(untuple_args) = untuple_args {
343         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
344             let arg_lv = Lvalue::Local(Local::new(1+1));
345             Operand::Consume(arg_lv.field(Field::new(i), *ity))
346         }));
347     } else {
348         args.extend((1..sig.inputs().len()).map(|i| {
349             Operand::Consume(Lvalue::Local(Local::new(1+i)))
350         }));
351     }
352
353     let mut blocks = IndexVec::new();
354     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
355         blocks.push(BasicBlockData {
356             statements,
357             terminator: Some(Terminator { source_info, kind }),
358             is_cleanup
359         })
360     };
361
362     // BB #0
363     block(&mut blocks, statements, TerminatorKind::Call {
364         func: callee,
365         args: args,
366         destination: Some((Lvalue::Local(RETURN_POINTER),
367                            BasicBlock::new(1))),
368         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
369             Some(BasicBlock::new(3))
370         } else {
371             None
372         }
373     }, false);
374
375     if let Adjustment::RefMut = rcvr_adjustment {
376         // BB #1 - drop for Self
377         block(&mut blocks, vec![], TerminatorKind::Drop {
378             location: Lvalue::Local(rcvr_arg),
379             target: BasicBlock::new(2),
380             unwind: None
381         }, false);
382     }
383     // BB #1/#2 - return
384     block(&mut blocks, vec![], TerminatorKind::Return, false);
385     if let Adjustment::RefMut = rcvr_adjustment {
386         // BB #3 - drop if closure panics
387         block(&mut blocks, vec![], TerminatorKind::Drop {
388             location: Lvalue::Local(rcvr_arg),
389             target: BasicBlock::new(4),
390             unwind: None
391         }, true);
392
393         // BB #4 - resume
394         block(&mut blocks, vec![], TerminatorKind::Resume, true);
395     }
396
397     let mut mir = Mir::new(
398         blocks,
399         IndexVec::from_elem_n(
400             VisibilityScopeData { span: span, parent_scope: None }, 1
401         ),
402         IndexVec::new(),
403         sig.output(),
404         local_decls,
405         sig.inputs().len(),
406         vec![],
407         span
408     );
409     if let Abi::RustCall = sig.abi {
410         mir.spread_arg = Some(Local::new(sig.inputs().len()));
411     }
412     mir
413 }
414
415 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
416                                       ctor_id: ast::NodeId,
417                                       fields: &[hir::StructField],
418                                       span: Span)
419                                       -> (Mir<'tcx>, MirSource)
420 {
421     let tcx = infcx.tcx;
422     let def_id = tcx.hir.local_def_id(ctor_id);
423     let sig = match tcx.type_of(def_id).sty {
424         ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
425             .expect("LBR in ADT constructor signature"),
426         _ => bug!("unexpected type for ctor {:?}", def_id)
427     };
428     let sig = tcx.erase_regions(&sig);
429
430     let (adt_def, substs) = match sig.output().sty {
431         ty::TyAdt(adt_def, substs) => (adt_def, substs),
432         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
433     };
434
435     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
436
437     let local_decls = local_decls_for_sig(&sig, span);
438
439     let source_info = SourceInfo {
440         span: span,
441         scope: ARGUMENT_VISIBILITY_SCOPE
442     };
443
444     let variant_no = if adt_def.is_enum() {
445         adt_def.variant_index_with_id(def_id)
446     } else {
447         0
448     };
449
450     // return = ADT(arg0, arg1, ...); return
451     let start_block = BasicBlockData {
452         statements: vec![Statement {
453             source_info: source_info,
454             kind: StatementKind::Assign(
455                 Lvalue::Local(RETURN_POINTER),
456                 Rvalue::Aggregate(
457                     AggregateKind::Adt(adt_def, variant_no, substs, None),
458                     (1..sig.inputs().len()+1).map(|i| {
459                         Operand::Consume(Lvalue::Local(Local::new(i)))
460                     }).collect()
461                 )
462             )
463         }],
464         terminator: Some(Terminator {
465             source_info: source_info,
466             kind: TerminatorKind::Return,
467         }),
468         is_cleanup: false
469     };
470
471     let mir = Mir::new(
472         IndexVec::from_elem_n(start_block, 1),
473         IndexVec::from_elem_n(
474             VisibilityScopeData { span: span, parent_scope: None }, 1
475         ),
476         IndexVec::new(),
477         sig.output(),
478         local_decls,
479         sig.inputs().len(),
480         vec![],
481         span
482     );
483     (mir, MirSource::Fn(ctor_id))
484 }