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