]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
add -Z pre-link-arg{,s} to rustc
[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 span = tcx.def_span(did);
45     let param_env = tcx.construct_parameter_environment(span, did, None);
46
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)
57             };
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();
66
67             build_call_shim(
68                 tcx,
69                 &param_env,
70                 def_id,
71                 adjustment,
72                 CallKind::Indirect,
73                 Some(arg_tys)
74             )
75         }
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.
79             build_call_shim(
80                 tcx,
81                 &param_env,
82                 def_id,
83                 Adjustment::Identity,
84                 CallKind::Direct(def_id),
85                 None
86             )
87         }
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)
93                 .unwrap().def_id;
94
95             build_call_shim(
96                 tcx,
97                 &param_env,
98                 call_once,
99                 Adjustment::RefMut,
100                 CallKind::Direct(call_mut),
101                 None
102             )
103         }
104         ty::InstanceDef::DropGlue(def_id, ty) => {
105             build_drop_shim(tcx, &param_env, def_id, ty)
106         }
107         ty::InstanceDef::Intrinsic(_) => {
108             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
109         }
110     };
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);
116
117     tcx.alloc_mir(result)
118 }
119
120 #[derive(Copy, Clone, Debug, PartialEq)]
121 enum Adjustment {
122     Identity,
123     Deref,
124     RefMut,
125 }
126
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum CallKind {
129     Indirect,
130     Direct(DefId),
131 }
132
133 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
134     LocalDecl {
135         mutability, ty, name: None,
136         source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
137         is_user_variable: false
138     }
139 }
140
141 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
142     -> IndexVec<Local, LocalDecl<'tcx>>
143 {
144     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
145         .chain(sig.inputs().iter().map(
146             |ity| temp_decl(Mutability::Not, ity, span)))
147         .collect()
148 }
149
150 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
151                              param_env: &ty::ParameterEnvironment<'tcx>,
152                              def_id: DefId,
153                              ty: Option<Ty<'tcx>>)
154                              -> Mir<'tcx>
155 {
156     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
157
158     let substs = if let Some(ty) = ty {
159         tcx.mk_substs(iter::once(Kind::from(ty)))
160     } else {
161         param_env.free_substs
162     };
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);
166
167     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
168
169     let return_block = BasicBlock::new(1);
170     let mut blocks = IndexVec::new();
171     let block = |blocks: &mut IndexVec<_, _>, kind| {
172         blocks.push(BasicBlockData {
173             statements: vec![],
174             terminator: Some(Terminator { source_info, kind }),
175             is_cleanup: false
176         })
177     };
178     block(&mut blocks, TerminatorKind::Goto { target: return_block });
179     block(&mut blocks, TerminatorKind::Return);
180
181     let mut mir = Mir::new(
182         blocks,
183         IndexVec::from_elem_n(
184             VisibilityScopeData { span: span, parent_scope: None }, 1
185         ),
186         IndexVec::new(),
187         sig.output(),
188         local_decls_for_sig(&sig, span),
189         sig.inputs().len(),
190         vec![],
191         span
192     );
193
194     if let Some(..) = ty {
195         let patch = {
196             let mut elaborator = DropShimElaborator {
197                 mir: &mir,
198                 patch: MirPatch::new(&mir),
199                 tcx, param_env
200             };
201             let dropee = Lvalue::Local(Local::new(1+0)).deref();
202             let resume_block = elaborator.patch.resume_block();
203             elaborate_drops::elaborate_drop(
204                 &mut elaborator,
205                 source_info,
206                 false,
207                 &dropee,
208                 (),
209                 return_block,
210                 Some(resume_block),
211                 START_BLOCK
212             );
213             elaborator.patch
214         };
215         patch.apply(&mut mir);
216     }
217
218     mir
219 }
220
221 pub struct DropShimElaborator<'a, 'tcx: 'a> {
222     mir: &'a Mir<'tcx>,
223     patch: MirPatch<'tcx>,
224     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
225     param_env: &'a ty::ParameterEnvironment<'tcx>,
226 }
227
228 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
229     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
230         Ok(())
231     }
232 }
233
234 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
235     type Path = ();
236
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 }
241
242     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
243         if let DropFlagMode::Shallow = mode {
244             DropStyle::Static
245         } else {
246             DropStyle::Open
247         }
248     }
249
250     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
251         None
252     }
253
254     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
255     }
256
257     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
258         None
259     }
260     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
261         None
262     }
263     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
264         Some(())
265     }
266 }
267
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`.
271 ///
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>,
276                              def_id: DefId,
277                              rcvr_adjustment: Adjustment,
278                              call_kind: CallKind,
279                              untuple_args: Option<&[Ty<'tcx>]>)
280                              -> Mir<'tcx>
281 {
282     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
283             call_kind={:?}, untuple_args={:?})",
284            def_id, rcvr_adjustment, call_kind, untuple_args);
285
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);
289
290     debug!("build_call_shim: sig={:?}", sig);
291
292     let mut local_decls = local_decls_for_sig(&sig, span);
293     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
294
295     let rcvr_arg = Local::new(1+0);
296     let rcvr_l = Lvalue::Local(rcvr_arg);
297     let mut statements = vec![];
298
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(
305                 Mutability::Not,
306                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
307                     ty: sig.inputs()[0],
308                     mutbl: hir::Mutability::MutMutable
309                 }),
310                 span
311             ));
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)
317                 )
318             });
319             Operand::Consume(Lvalue::Local(ref_rcvr))
320         }
321     };
322
323     let (callee, mut args) = match call_kind {
324         CallKind::Indirect => (rcvr, vec![]),
325         CallKind::Direct(def_id) => (
326             Operand::Constant(box Constant {
327                 span: span,
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),
331                 },
332             }),
333             vec![rcvr]
334         )
335     };
336
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))
341         }));
342     } else {
343         args.extend((1..sig.inputs().len()).map(|i| {
344             Operand::Consume(Lvalue::Local(Local::new(1+i)))
345         }));
346     }
347
348     let mut blocks = IndexVec::new();
349     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
350         blocks.push(BasicBlockData {
351             statements,
352             terminator: Some(Terminator { source_info, kind }),
353             is_cleanup
354         })
355     };
356
357     // BB #0
358     block(&mut blocks, statements, TerminatorKind::Call {
359         func: callee,
360         args: args,
361         destination: Some((Lvalue::Local(RETURN_POINTER),
362                            BasicBlock::new(1))),
363         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
364             Some(BasicBlock::new(3))
365         } else {
366             None
367         }
368     }, false);
369
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),
375             unwind: None
376         }, false);
377     }
378     // BB #1/#2 - return
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),
385             unwind: None
386         }, true);
387
388         // BB #4 - resume
389         block(&mut blocks, vec![], TerminatorKind::Resume, true);
390     }
391
392     let mut mir = Mir::new(
393         blocks,
394         IndexVec::from_elem_n(
395             VisibilityScopeData { span: span, parent_scope: None }, 1
396         ),
397         IndexVec::new(),
398         sig.output(),
399         local_decls,
400         sig.inputs().len(),
401         vec![],
402         span
403     );
404     if let Abi::RustCall = sig.abi {
405         mir.spread_arg = Some(Local::new(sig.inputs().len()));
406     }
407     mir
408 }
409
410 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
411                                       ctor_id: ast::NodeId,
412                                       fields: &[hir::StructField],
413                                       span: Span)
414                                       -> (Mir<'tcx>, MirSource)
415 {
416     let tcx = infcx.tcx;
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)
422     };
423     let sig = tcx.erase_regions(&sig);
424
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())
428     };
429
430     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
431
432     let local_decls = local_decls_for_sig(&sig, span);
433
434     let source_info = SourceInfo {
435         span: span,
436         scope: ARGUMENT_VISIBILITY_SCOPE
437     };
438
439     let variant_no = if adt_def.is_enum() {
440         adt_def.variant_index_with_id(def_id)
441     } else {
442         0
443     };
444
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),
451                 Rvalue::Aggregate(
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)))
455                     }).collect()
456                 )
457             )
458         }],
459         terminator: Some(Terminator {
460             source_info: source_info,
461             kind: TerminatorKind::Return,
462         }),
463         is_cleanup: false
464     };
465
466     let mir = Mir::new(
467         IndexVec::from_elem_n(start_block, 1),
468         IndexVec::from_elem_n(
469             VisibilityScopeData { span: span, parent_scope: None }, 1
470         ),
471         IndexVec::new(),
472         sig.output(),
473         local_decls,
474         sig.inputs().len(),
475         vec![],
476         span
477     );
478     (mir, MirSource::Fn(ctor_id))
479 }