]>
Commit | Line | Data |
---|---|---|
dfeec247 XL |
1 | use rustc_hir as hir; |
2 | use rustc_hir::def_id::DefId; | |
3dfed10e | 3 | use rustc_hir::lang_items::LangItem; |
ba9703b0 XL |
4 | use rustc_middle::mir::*; |
5 | use rustc_middle::ty::query::Providers; | |
6 | use rustc_middle::ty::subst::{InternalSubsts, Subst}; | |
3dfed10e | 7 | use rustc_middle::ty::{self, Ty, TyCtxt}; |
ba9703b0 | 8 | use rustc_target::abi::VariantIdx; |
cc61c64b | 9 | |
dfeec247 | 10 | use rustc_index::vec::{Idx, IndexVec}; |
cc61c64b | 11 | |
ba9703b0 | 12 | use rustc_span::Span; |
83c7162d | 13 | use rustc_target::spec::abi::Abi; |
cc61c64b | 14 | |
cc61c64b XL |
15 | use std::fmt; |
16 | use std::iter; | |
cc61c64b | 17 | |
c295e0f8 XL |
18 | use crate::util::expand_aggregate; |
19 | use crate::{ | |
a2a8927a XL |
20 | abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, marker, pass_manager as pm, |
21 | remove_noop_landing_pads, simplify, | |
9fa01778 | 22 | }; |
c295e0f8 XL |
23 | use rustc_middle::mir::patch::MirPatch; |
24 | use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle}; | |
9fa01778 | 25 | |
f035d41b | 26 | pub fn provide(providers: &mut Providers) { |
cc61c64b XL |
27 | providers.mir_shims = make_shim; |
28 | } | |
29 | ||
f9f354fc | 30 | fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> { |
cc61c64b | 31 | debug!("make_shim({:?})", instance); |
cc61c64b XL |
32 | |
33 | let mut result = match instance { | |
dfeec247 | 34 | ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance), |
f035d41b | 35 | ty::InstanceDef::VtableShim(def_id) => { |
1b1a35ee | 36 | build_call_shim(tcx, instance, Some(Adjustment::Deref), CallKind::Direct(def_id)) |
f035d41b | 37 | } |
cc61c64b XL |
38 | ty::InstanceDef::FnPtrShim(def_id, ty) => { |
39 | let trait_ = tcx.trait_of_item(def_id).unwrap(); | |
74b04a01 | 40 | let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) { |
cc61c64b | 41 | Some(ty::ClosureKind::FnOnce) => Adjustment::Identity, |
ba9703b0 | 42 | Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref, |
dfeec247 | 43 | None => bug!("fn pointer {:?} is not an fn", ty), |
cc61c64b | 44 | }; |
1b1a35ee XL |
45 | |
46 | build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty)) | |
cc61c64b | 47 | } |
e74abb32 | 48 | // We are generating a call back to our def-id, which the |
60c5eb7d XL |
49 | // codegen backend knows to turn to an actual call, be it |
50 | // a virtual call, or a direct call to a function for which | |
51 | // indirect calls must be codegen'd differently than direct ones | |
52 | // (such as `#[track_caller]`). | |
e74abb32 | 53 | ty::InstanceDef::ReifyShim(def_id) => { |
1b1a35ee | 54 | build_call_shim(tcx, instance, None, CallKind::Direct(def_id)) |
cc61c64b | 55 | } |
c295e0f8 | 56 | ty::InstanceDef::ClosureOnceShim { call_once: _, track_caller: _ } => { |
3dfed10e | 57 | let fn_mut = tcx.require_lang_item(LangItem::FnMut, None); |
e74abb32 | 58 | let call_mut = tcx |
cc61c64b | 59 | .associated_items(fn_mut) |
74b04a01 | 60 | .in_definition_order() |
ba9703b0 | 61 | .find(|it| it.kind == ty::AssocKind::Fn) |
dfeec247 XL |
62 | .unwrap() |
63 | .def_id; | |
cc61c64b | 64 | |
1b1a35ee | 65 | build_call_shim(tcx, instance, Some(Adjustment::RefMut), CallKind::Direct(call_mut)) |
cc61c64b | 66 | } |
a2a8927a XL |
67 | |
68 | ty::InstanceDef::DropGlue(def_id, ty) => { | |
69 | // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end | |
70 | // of this function. Is this intentional? | |
71 | if let Some(ty::Generator(gen_def_id, substs, _)) = ty.map(ty::TyS::kind) { | |
72 | let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap(); | |
73 | let body = body.clone().subst(tcx, substs); | |
74 | debug!("make_shim({:?}) = {:?}", instance, body); | |
75 | return body; | |
76 | } | |
77 | ||
78 | build_drop_shim(tcx, def_id, ty) | |
79 | } | |
3dfed10e | 80 | ty::InstanceDef::CloneShim(def_id, ty) => build_clone_shim(tcx, def_id, ty), |
60c5eb7d XL |
81 | ty::InstanceDef::Virtual(..) => { |
82 | bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance) | |
83 | } | |
cc61c64b XL |
84 | ty::InstanceDef::Intrinsic(_) => { |
85 | bug!("creating shims from intrinsics ({:?}) is unsupported", instance) | |
86 | } | |
87 | }; | |
3b2f2976 | 88 | debug!("make_shim({:?}) = untransformed {:?}", instance, result); |
9fa01778 | 89 | |
a2a8927a | 90 | pm::run_passes( |
dfeec247 XL |
91 | tcx, |
92 | &mut result, | |
a2a8927a | 93 | &[ |
dfeec247 | 94 | &add_moves_for_packed_drops::AddMovesForPackedDrops, |
dfeec247 XL |
95 | &remove_noop_landing_pads::RemoveNoopLandingPads, |
96 | &simplify::SimplifyCfg::new("make_shim"), | |
97 | &add_call_guards::CriticalCallEdges, | |
94222f64 | 98 | &abort_unwinding_calls::AbortUnwindingCalls, |
a2a8927a XL |
99 | &marker::PhaseChange(MirPhase::Const), |
100 | ], | |
dfeec247 | 101 | ); |
9fa01778 | 102 | |
cc61c64b XL |
103 | debug!("make_shim({:?}) = {:?}", instance, result); |
104 | ||
f9f354fc | 105 | result |
cc61c64b XL |
106 | } |
107 | ||
108 | #[derive(Copy, Clone, Debug, PartialEq)] | |
109 | enum Adjustment { | |
f035d41b | 110 | /// Pass the receiver as-is. |
cc61c64b | 111 | Identity, |
f035d41b XL |
112 | |
113 | /// We get passed `&[mut] self` and call the target with `*self`. | |
114 | /// | |
115 | /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it | |
116 | /// (for `VtableShim`, which effectively is passed `&own Self`). | |
cc61c64b | 117 | Deref, |
f035d41b XL |
118 | |
119 | /// We get passed `self: Self` and call the target with `&mut self`. | |
120 | /// | |
121 | /// In this case we need to ensure that the `Self` is dropped after the call, as the callee | |
122 | /// won't do it for us. | |
cc61c64b XL |
123 | RefMut, |
124 | } | |
125 | ||
126 | #[derive(Copy, Clone, Debug, PartialEq)] | |
f035d41b XL |
127 | enum CallKind<'tcx> { |
128 | /// Call the `FnPtr` that was passed as the receiver. | |
129 | Indirect(Ty<'tcx>), | |
130 | ||
131 | /// Call a known `FnDef`. | |
cc61c64b XL |
132 | Direct(DefId), |
133 | } | |
134 | ||
dfeec247 XL |
135 | fn local_decls_for_sig<'tcx>( |
136 | sig: &ty::FnSig<'tcx>, | |
137 | span: Span, | |
138 | ) -> IndexVec<Local, LocalDecl<'tcx>> { | |
f9f354fc XL |
139 | iter::once(LocalDecl::new(sig.output(), span)) |
140 | .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable())) | |
cc61c64b XL |
141 | .collect() |
142 | } | |
143 | ||
f9f354fc | 144 | fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> { |
cc61c64b XL |
145 | debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty); |
146 | ||
a2a8927a | 147 | assert!(!matches!(ty, Some(ty) if ty.is_generator())); |
ea8adc8c | 148 | |
cc61c64b | 149 | let substs = if let Some(ty) = ty { |
94b46f34 | 150 | tcx.intern_substs(&[ty.into()]) |
cc61c64b | 151 | } else { |
532ac7d7 | 152 | InternalSubsts::identity_for_item(tcx, def_id) |
cc61c64b | 153 | }; |
041b39d2 | 154 | let sig = tcx.fn_sig(def_id).subst(tcx, substs); |
fc512014 | 155 | let sig = tcx.erase_late_bound_regions(sig); |
cc61c64b XL |
156 | let span = tcx.def_span(def_id); |
157 | ||
f9f354fc | 158 | let source_info = SourceInfo::outermost(span); |
cc61c64b XL |
159 | |
160 | let return_block = BasicBlock::new(1); | |
a1dfa0c6 | 161 | let mut blocks = IndexVec::with_capacity(2); |
cc61c64b XL |
162 | let block = |blocks: &mut IndexVec<_, _>, kind| { |
163 | blocks.push(BasicBlockData { | |
164 | statements: vec![], | |
165 | terminator: Some(Terminator { source_info, kind }), | |
dfeec247 | 166 | is_cleanup: false, |
cc61c64b XL |
167 | }) |
168 | }; | |
169 | block(&mut blocks, TerminatorKind::Goto { target: return_block }); | |
170 | block(&mut blocks, TerminatorKind::Return); | |
171 | ||
29967ef6 XL |
172 | let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty)); |
173 | let mut body = | |
94222f64 | 174 | new_body(tcx, source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span); |
cc61c64b | 175 | |
5869c6ff | 176 | if ty.is_some() { |
a1dfa0c6 | 177 | // The first argument (index 0), but add 1 for the return value. |
dfeec247 | 178 | let dropee_ptr = Place::from(Local::new(1 + 0)); |
a1dfa0c6 | 179 | if tcx.sess.opts.debugging_opts.mir_emit_retag { |
0731742a | 180 | // Function arguments should be retagged, and we make this one raw. |
dfeec247 XL |
181 | body.basic_blocks_mut()[START_BLOCK].statements.insert( |
182 | 0, | |
183 | Statement { | |
184 | source_info, | |
94222f64 | 185 | kind: StatementKind::Retag(RetagKind::Raw, Box::new(dropee_ptr)), |
dfeec247 XL |
186 | }, |
187 | ); | |
a1dfa0c6 | 188 | } |
cc61c64b | 189 | let patch = { |
3dfed10e | 190 | let param_env = tcx.param_env_reveal_all_normalized(def_id); |
dfeec247 XL |
191 | let mut elaborator = |
192 | DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env }; | |
e74abb32 | 193 | let dropee = tcx.mk_place_deref(dropee_ptr); |
cc61c64b XL |
194 | let resume_block = elaborator.patch.resume_block(); |
195 | elaborate_drops::elaborate_drop( | |
196 | &mut elaborator, | |
197 | source_info, | |
ba9703b0 | 198 | dropee, |
cc61c64b XL |
199 | (), |
200 | return_block, | |
7cac9316 | 201 | elaborate_drops::Unwind::To(resume_block), |
dfeec247 | 202 | START_BLOCK, |
cc61c64b XL |
203 | ); |
204 | elaborator.patch | |
205 | }; | |
dc9dc135 | 206 | patch.apply(&mut body); |
cc61c64b XL |
207 | } |
208 | ||
dc9dc135 | 209 | body |
cc61c64b XL |
210 | } |
211 | ||
60c5eb7d | 212 | fn new_body<'tcx>( |
94222f64 | 213 | tcx: TyCtxt<'tcx>, |
29967ef6 | 214 | source: MirSource<'tcx>, |
60c5eb7d XL |
215 | basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, |
216 | local_decls: IndexVec<Local, LocalDecl<'tcx>>, | |
217 | arg_count: usize, | |
218 | span: Span, | |
219 | ) -> Body<'tcx> { | |
220 | Body::new( | |
94222f64 | 221 | tcx, |
29967ef6 | 222 | source, |
60c5eb7d XL |
223 | basic_blocks, |
224 | IndexVec::from_elem_n( | |
29967ef6 XL |
225 | SourceScopeData { |
226 | span, | |
227 | parent_scope: None, | |
228 | inlined: None, | |
229 | inlined_parent_scope: None, | |
230 | local_data: ClearCrossCrate::Clear, | |
231 | }, | |
60c5eb7d XL |
232 | 1, |
233 | ), | |
234 | local_decls, | |
235 | IndexVec::new(), | |
236 | arg_count, | |
237 | vec![], | |
238 | span, | |
60c5eb7d XL |
239 | None, |
240 | ) | |
241 | } | |
242 | ||
dc9dc135 XL |
243 | pub struct DropShimElaborator<'a, 'tcx> { |
244 | pub body: &'a Body<'tcx>, | |
ea8adc8c | 245 | pub patch: MirPatch<'tcx>, |
dc9dc135 | 246 | pub tcx: TyCtxt<'tcx>, |
ea8adc8c | 247 | pub param_env: ty::ParamEnv<'tcx>, |
cc61c64b XL |
248 | } |
249 | ||
a2a8927a | 250 | impl fmt::Debug for DropShimElaborator<'_, '_> { |
9fa01778 | 251 | fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { |
cc61c64b XL |
252 | Ok(()) |
253 | } | |
254 | } | |
255 | ||
256 | impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> { | |
257 | type Path = (); | |
258 | ||
dfeec247 XL |
259 | fn patch(&mut self) -> &mut MirPatch<'tcx> { |
260 | &mut self.patch | |
261 | } | |
262 | fn body(&self) -> &'a Body<'tcx> { | |
263 | self.body | |
264 | } | |
dc9dc135 XL |
265 | fn tcx(&self) -> TyCtxt<'tcx> { |
266 | self.tcx | |
dfeec247 XL |
267 | } |
268 | fn param_env(&self) -> ty::ParamEnv<'tcx> { | |
269 | self.param_env | |
270 | } | |
cc61c64b XL |
271 | |
272 | fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle { | |
f9f354fc XL |
273 | match mode { |
274 | DropFlagMode::Shallow => { | |
275 | // Drops for the contained fields are "shallow" and "static" - they will simply call | |
276 | // the field's own drop glue. | |
277 | DropStyle::Static | |
278 | } | |
279 | DropFlagMode::Deep => { | |
280 | // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder | |
281 | // dropping each field contained in the value. | |
282 | DropStyle::Open | |
283 | } | |
284 | } | |
cc61c64b XL |
285 | } |
286 | ||
287 | fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> { | |
288 | None | |
289 | } | |
290 | ||
dfeec247 | 291 | fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {} |
cc61c64b XL |
292 | |
293 | fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> { | |
294 | None | |
295 | } | |
296 | fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> { | |
297 | None | |
298 | } | |
a1dfa0c6 | 299 | fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> { |
cc61c64b XL |
300 | Some(()) |
301 | } | |
1b1a35ee | 302 | fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> { |
ff7c6d11 XL |
303 | None |
304 | } | |
cc61c64b XL |
305 | } |
306 | ||
9fa01778 | 307 | /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`. |
f9f354fc | 308 | fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> { |
3b2f2976 XL |
309 | debug!("build_clone_shim(def_id={:?})", def_id); |
310 | ||
416331ca XL |
311 | let param_env = tcx.param_env(def_id); |
312 | ||
2c00a5a8 | 313 | let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty); |
f035d41b | 314 | let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env); |
3b2f2976 | 315 | |
e1599b0c | 316 | let dest = Place::return_place(); |
dfeec247 | 317 | let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0))); |
2c00a5a8 | 318 | |
1b1a35ee | 319 | match self_ty.kind() { |
3b2f2976 | 320 | _ if is_copy => builder.copy_shim(), |
ba9703b0 XL |
321 | ty::Closure(_, substs) => { |
322 | builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys()) | |
ea8adc8c | 323 | } |
416331ca | 324 | ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), |
dfeec247 | 325 | _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty), |
3b2f2976 XL |
326 | }; |
327 | ||
f9f354fc | 328 | builder.into_mir() |
3b2f2976 XL |
329 | } |
330 | ||
dc9dc135 XL |
331 | struct CloneShimBuilder<'tcx> { |
332 | tcx: TyCtxt<'tcx>, | |
3b2f2976 XL |
333 | def_id: DefId, |
334 | local_decls: IndexVec<Local, LocalDecl<'tcx>>, | |
335 | blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, | |
336 | span: Span, | |
337 | sig: ty::FnSig<'tcx>, | |
338 | } | |
339 | ||
a2a8927a | 340 | impl<'tcx> CloneShimBuilder<'tcx> { |
dc9dc135 | 341 | fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self { |
2c00a5a8 XL |
342 | // we must subst the self_ty because it's |
343 | // otherwise going to be TySelf and we can't index | |
344 | // or access fields of a Place of type TySelf. | |
345 | let substs = tcx.mk_substs_trait(self_ty, &[]); | |
346 | let sig = tcx.fn_sig(def_id).subst(tcx, substs); | |
fc512014 | 347 | let sig = tcx.erase_late_bound_regions(sig); |
3b2f2976 XL |
348 | let span = tcx.def_span(def_id); |
349 | ||
350 | CloneShimBuilder { | |
351 | tcx, | |
352 | def_id, | |
353 | local_decls: local_decls_for_sig(&sig, span), | |
354 | blocks: IndexVec::new(), | |
355 | span, | |
356 | sig, | |
357 | } | |
358 | } | |
359 | ||
dc9dc135 | 360 | fn into_mir(self) -> Body<'tcx> { |
29967ef6 XL |
361 | let source = MirSource::from_instance(ty::InstanceDef::CloneShim( |
362 | self.def_id, | |
363 | self.sig.inputs_and_output[0], | |
364 | )); | |
94222f64 XL |
365 | new_body( |
366 | self.tcx, | |
367 | source, | |
368 | self.blocks, | |
369 | self.local_decls, | |
370 | self.sig.inputs().len(), | |
371 | self.span, | |
372 | ) | |
3b2f2976 XL |
373 | } |
374 | ||
375 | fn source_info(&self) -> SourceInfo { | |
f9f354fc | 376 | SourceInfo::outermost(self.span) |
3b2f2976 XL |
377 | } |
378 | ||
379 | fn block( | |
380 | &mut self, | |
381 | statements: Vec<Statement<'tcx>>, | |
382 | kind: TerminatorKind<'tcx>, | |
dfeec247 | 383 | is_cleanup: bool, |
3b2f2976 XL |
384 | ) -> BasicBlock { |
385 | let source_info = self.source_info(); | |
386 | self.blocks.push(BasicBlockData { | |
387 | statements, | |
388 | terminator: Some(Terminator { source_info, kind }), | |
389 | is_cleanup, | |
390 | }) | |
391 | } | |
392 | ||
2c00a5a8 XL |
393 | /// Gives the index of an upcoming BasicBlock, with an offset. |
394 | /// offset=0 will give you the index of the next BasicBlock, | |
395 | /// offset=1 will give the index of the next-to-next block, | |
396 | /// offset=-1 will give you the index of the last-created block | |
397 | fn block_index_offset(&mut self, offset: usize) -> BasicBlock { | |
398 | BasicBlock::new(self.blocks.len() + offset) | |
399 | } | |
400 | ||
3b2f2976 | 401 | fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> { |
dfeec247 | 402 | Statement { source_info: self.source_info(), kind } |
3b2f2976 XL |
403 | } |
404 | ||
405 | fn copy_shim(&mut self) { | |
dfeec247 | 406 | let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0))); |
94222f64 | 407 | let ret_statement = self.make_statement(StatementKind::Assign(Box::new(( |
dfeec247 XL |
408 | Place::return_place(), |
409 | Rvalue::Use(Operand::Copy(rcvr)), | |
94222f64 | 410 | )))); |
3b2f2976 XL |
411 | self.block(vec![ret_statement], TerminatorKind::Return, false); |
412 | } | |
413 | ||
ff7c6d11 | 414 | fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> { |
3b2f2976 | 415 | let span = self.span; |
f9f354fc XL |
416 | let mut local = LocalDecl::new(ty, span); |
417 | if mutability == Mutability::Not { | |
418 | local = local.immutable(); | |
419 | } | |
420 | Place::from(self.local_decls.push(local)) | |
3b2f2976 XL |
421 | } |
422 | ||
423 | fn make_clone_call( | |
424 | &mut self, | |
2c00a5a8 XL |
425 | dest: Place<'tcx>, |
426 | src: Place<'tcx>, | |
ea8adc8c | 427 | ty: Ty<'tcx>, |
3b2f2976 | 428 | next: BasicBlock, |
dfeec247 | 429 | cleanup: BasicBlock, |
2c00a5a8 | 430 | ) { |
3b2f2976 XL |
431 | let tcx = self.tcx; |
432 | ||
532ac7d7 | 433 | let substs = tcx.mk_substs_trait(ty, &[]); |
3b2f2976 XL |
434 | |
435 | // `func == Clone::clone(&ty) -> ty` | |
ea8adc8c | 436 | let func_ty = tcx.mk_fn_def(self.def_id, substs); |
94222f64 | 437 | let func = Operand::Constant(Box::new(Constant { |
3b2f2976 | 438 | span: self.span, |
b7449926 | 439 | user_ty: None, |
6a06907d | 440 | literal: ty::Const::zero_sized(tcx, func_ty).into(), |
94222f64 | 441 | })); |
3b2f2976 | 442 | |
ff7c6d11 | 443 | let ref_loc = self.make_place( |
3b2f2976 | 444 | Mutability::Not, |
dfeec247 | 445 | tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }), |
3b2f2976 XL |
446 | ); |
447 | ||
2c00a5a8 | 448 | // `let ref_loc: &ty = &src;` |
94222f64 | 449 | let statement = self.make_statement(StatementKind::Assign(Box::new(( |
dfeec247 XL |
450 | ref_loc, |
451 | Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src), | |
94222f64 | 452 | )))); |
3b2f2976 XL |
453 | |
454 | // `let loc = Clone::clone(ref_loc);` | |
dfeec247 XL |
455 | self.block( |
456 | vec![statement], | |
457 | TerminatorKind::Call { | |
458 | func, | |
459 | args: vec![Operand::Move(ref_loc)], | |
460 | destination: Some((dest, next)), | |
461 | cleanup: Some(cleanup), | |
462 | from_hir_call: true, | |
f035d41b | 463 | fn_span: self.span, |
dfeec247 XL |
464 | }, |
465 | false, | |
466 | ); | |
3b2f2976 XL |
467 | } |
468 | ||
dfeec247 XL |
469 | fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I) |
470 | where | |
471 | I: Iterator<Item = Ty<'tcx>>, | |
472 | { | |
2c00a5a8 XL |
473 | let mut previous_field = None; |
474 | for (i, ity) in tys.enumerate() { | |
475 | let field = Field::new(i); | |
ba9703b0 | 476 | let src_field = self.tcx.mk_place_field(src, field, ity); |
ea8adc8c | 477 | |
ba9703b0 | 478 | let dest_field = self.tcx.mk_place_field(dest, field, ity); |
3b2f2976 | 479 | |
2c00a5a8 XL |
480 | // #(2i + 1) is the cleanup block for the previous clone operation |
481 | let cleanup_block = self.block_index_offset(1); | |
482 | // #(2i + 2) is the next cloning block | |
483 | // (or the Return terminator if this is the last block) | |
484 | let next_block = self.block_index_offset(2); | |
3b2f2976 XL |
485 | |
486 | // BB #(2i) | |
2c00a5a8 | 487 | // `dest.i = Clone::clone(&src.i);` |
3b2f2976 | 488 | // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens. |
ba9703b0 | 489 | self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block); |
3b2f2976 XL |
490 | |
491 | // BB #(2i + 1) (cleanup) | |
2c00a5a8 | 492 | if let Some((previous_field, previous_cleanup)) = previous_field.take() { |
3b2f2976 | 493 | // Drop previous field and goto previous cleanup block. |
dfeec247 XL |
494 | self.block( |
495 | vec![], | |
496 | TerminatorKind::Drop { | |
f035d41b | 497 | place: previous_field, |
dfeec247 XL |
498 | target: previous_cleanup, |
499 | unwind: None, | |
500 | }, | |
501 | true, | |
502 | ); | |
2c00a5a8 XL |
503 | } else { |
504 | // Nothing to drop, just resume. | |
505 | self.block(vec![], TerminatorKind::Resume, true); | |
3b2f2976 | 506 | } |
2c00a5a8 XL |
507 | |
508 | previous_field = Some((dest_field, cleanup_block)); | |
3b2f2976 XL |
509 | } |
510 | ||
2c00a5a8 | 511 | self.block(vec![], TerminatorKind::Return, false); |
3b2f2976 XL |
512 | } |
513 | } | |
514 | ||
1b1a35ee XL |
515 | /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`, |
516 | /// first adjusting its first argument according to `rcvr_adjustment`. | |
dc9dc135 XL |
517 | fn build_call_shim<'tcx>( |
518 | tcx: TyCtxt<'tcx>, | |
60c5eb7d | 519 | instance: ty::InstanceDef<'tcx>, |
dfeec247 | 520 | rcvr_adjustment: Option<Adjustment>, |
f035d41b | 521 | call_kind: CallKind<'tcx>, |
f9f354fc | 522 | ) -> Body<'tcx> { |
dfeec247 | 523 | debug!( |
1b1a35ee XL |
524 | "build_call_shim(instance={:?}, rcvr_adjustment={:?}, call_kind={:?})", |
525 | instance, rcvr_adjustment, call_kind | |
dfeec247 | 526 | ); |
cc61c64b | 527 | |
1b1a35ee XL |
528 | // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used |
529 | // to substitute into the signature of the shim. It is not necessary for users of this | |
530 | // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`). | |
531 | let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance { | |
fc512014 | 532 | let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx)); |
1b1a35ee XL |
533 | |
534 | let untuple_args = sig.inputs(); | |
535 | ||
536 | // Create substitutions for the `Self` and `Args` generic parameters of the shim body. | |
537 | let arg_tup = tcx.mk_tup(untuple_args.iter()); | |
538 | let sig_substs = tcx.mk_substs_trait(ty, &[ty::subst::GenericArg::from(arg_tup)]); | |
539 | ||
540 | (Some(sig_substs), Some(untuple_args)) | |
541 | } else { | |
542 | (None, None) | |
543 | }; | |
544 | ||
60c5eb7d | 545 | let def_id = instance.def_id(); |
041b39d2 | 546 | let sig = tcx.fn_sig(def_id); |
fc512014 | 547 | let mut sig = tcx.erase_late_bound_regions(sig); |
60c5eb7d | 548 | |
1b1a35ee XL |
549 | assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body()); |
550 | if let Some(sig_substs) = sig_substs { | |
551 | sig = sig.subst(tcx, sig_substs); | |
552 | } | |
553 | ||
f035d41b XL |
554 | if let CallKind::Indirect(fnty) = call_kind { |
555 | // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This | |
556 | // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from | |
557 | // the implemented `FnX` trait. | |
558 | ||
559 | // Apply the opposite adjustment to the MIR input. | |
560 | let mut inputs_and_output = sig.inputs_and_output.to_vec(); | |
561 | ||
562 | // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the | |
563 | // fn arguments. `Self` may be passed via (im)mutable reference or by-value. | |
564 | assert_eq!(inputs_and_output.len(), 3); | |
565 | ||
566 | // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for | |
567 | // `FnDef` and `FnPtr` callees, not the `Self` type param. | |
568 | let self_arg = &mut inputs_and_output[0]; | |
569 | *self_arg = match rcvr_adjustment.unwrap() { | |
570 | Adjustment::Identity => fnty, | |
571 | Adjustment::Deref => tcx.mk_imm_ptr(fnty), | |
572 | Adjustment::RefMut => tcx.mk_mut_ptr(fnty), | |
573 | }; | |
574 | sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output); | |
575 | } | |
576 | ||
60c5eb7d XL |
577 | // FIXME(eddyb) avoid having this snippet both here and in |
578 | // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?). | |
579 | if let ty::InstanceDef::VtableShim(..) = instance { | |
580 | // Modify fn(self, ...) to fn(self: *mut Self, ...) | |
581 | let mut inputs_and_output = sig.inputs_and_output.to_vec(); | |
582 | let self_arg = &mut inputs_and_output[0]; | |
583 | debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param); | |
584 | *self_arg = tcx.mk_mut_ptr(*self_arg); | |
585 | sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output); | |
586 | } | |
587 | ||
cc61c64b XL |
588 | let span = tcx.def_span(def_id); |
589 | ||
590 | debug!("build_call_shim: sig={:?}", sig); | |
591 | ||
592 | let mut local_decls = local_decls_for_sig(&sig, span); | |
f9f354fc | 593 | let source_info = SourceInfo::outermost(span); |
cc61c64b | 594 | |
dfeec247 XL |
595 | let rcvr_place = || { |
596 | assert!(rcvr_adjustment.is_some()); | |
597 | Place::from(Local::new(1 + 0)) | |
598 | }; | |
cc61c64b XL |
599 | let mut statements = vec![]; |
600 | ||
dfeec247 XL |
601 | let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment { |
602 | Adjustment::Identity => Operand::Move(rcvr_place()), | |
f035d41b | 603 | Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())), |
cc61c64b XL |
604 | Adjustment::RefMut => { |
605 | // let rcvr = &mut rcvr; | |
f9f354fc XL |
606 | let ref_rcvr = local_decls.push( |
607 | LocalDecl::new( | |
608 | tcx.mk_ref( | |
609 | tcx.lifetimes.re_erased, | |
610 | ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut }, | |
611 | ), | |
612 | span, | |
613 | ) | |
614 | .immutable(), | |
615 | ); | |
dfeec247 | 616 | let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false }; |
cc61c64b | 617 | statements.push(Statement { |
3b2f2976 | 618 | source_info, |
94222f64 | 619 | kind: StatementKind::Assign(Box::new(( |
dfeec247 XL |
620 | Place::from(ref_rcvr), |
621 | Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()), | |
94222f64 | 622 | ))), |
cc61c64b | 623 | }); |
dc9dc135 | 624 | Operand::Move(Place::from(ref_rcvr)) |
cc61c64b | 625 | } |
dfeec247 | 626 | }); |
cc61c64b XL |
627 | |
628 | let (callee, mut args) = match call_kind { | |
f035d41b XL |
629 | // `FnPtr` call has no receiver. Args are untupled below. |
630 | CallKind::Indirect(_) => (rcvr.unwrap(), vec![]), | |
631 | ||
632 | // `FnDef` call with optional receiver. | |
ea8adc8c XL |
633 | CallKind::Direct(def_id) => { |
634 | let ty = tcx.type_of(def_id); | |
dfeec247 | 635 | ( |
94222f64 | 636 | Operand::Constant(Box::new(Constant { |
dfeec247 XL |
637 | span, |
638 | user_ty: None, | |
6a06907d | 639 | literal: ty::Const::zero_sized(tcx, ty).into(), |
94222f64 | 640 | })), |
dfeec247 XL |
641 | rcvr.into_iter().collect::<Vec<_>>(), |
642 | ) | |
ea8adc8c | 643 | } |
cc61c64b XL |
644 | }; |
645 | ||
dfeec247 XL |
646 | let mut arg_range = 0..sig.inputs().len(); |
647 | ||
648 | // Take the `self` ("receiver") argument out of the range (it's adjusted above). | |
649 | if rcvr_adjustment.is_some() { | |
650 | arg_range.start += 1; | |
651 | } | |
652 | ||
653 | // Take the last argument, if we need to untuple it (handled below). | |
654 | if untuple_args.is_some() { | |
655 | arg_range.end -= 1; | |
656 | } | |
657 | ||
658 | // Pass all of the non-special arguments directly. | |
659 | args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i))))); | |
660 | ||
661 | // Untuple the last argument, if we have to. | |
cc61c64b | 662 | if let Some(untuple_args) = untuple_args { |
dfeec247 | 663 | let tuple_arg = Local::new(1 + (sig.inputs().len() - 1)); |
cc61c64b | 664 | args.extend(untuple_args.iter().enumerate().map(|(i, ity)| { |
dfeec247 | 665 | Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity)) |
cc61c64b XL |
666 | })); |
667 | } | |
668 | ||
dfeec247 | 669 | let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 }; |
a1dfa0c6 | 670 | let mut blocks = IndexVec::with_capacity(n_blocks); |
cc61c64b XL |
671 | let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| { |
672 | blocks.push(BasicBlockData { | |
673 | statements, | |
674 | terminator: Some(Terminator { source_info, kind }), | |
dfeec247 | 675 | is_cleanup, |
cc61c64b XL |
676 | }) |
677 | }; | |
678 | ||
679 | // BB #0 | |
dfeec247 XL |
680 | block( |
681 | &mut blocks, | |
682 | statements, | |
683 | TerminatorKind::Call { | |
684 | func: callee, | |
685 | args, | |
686 | destination: Some((Place::return_place(), BasicBlock::new(1))), | |
687 | cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment { | |
688 | Some(BasicBlock::new(3)) | |
689 | } else { | |
690 | None | |
691 | }, | |
692 | from_hir_call: true, | |
f035d41b | 693 | fn_span: span, |
0bf4aa26 | 694 | }, |
dfeec247 XL |
695 | false, |
696 | ); | |
cc61c64b | 697 | |
dfeec247 | 698 | if let Some(Adjustment::RefMut) = rcvr_adjustment { |
cc61c64b | 699 | // BB #1 - drop for Self |
dfeec247 XL |
700 | block( |
701 | &mut blocks, | |
702 | vec![], | |
f035d41b | 703 | TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None }, |
dfeec247 XL |
704 | false, |
705 | ); | |
cc61c64b XL |
706 | } |
707 | // BB #1/#2 - return | |
708 | block(&mut blocks, vec![], TerminatorKind::Return, false); | |
dfeec247 | 709 | if let Some(Adjustment::RefMut) = rcvr_adjustment { |
cc61c64b | 710 | // BB #3 - drop if closure panics |
dfeec247 XL |
711 | block( |
712 | &mut blocks, | |
713 | vec![], | |
f035d41b | 714 | TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None }, |
dfeec247 XL |
715 | true, |
716 | ); | |
cc61c64b XL |
717 | |
718 | // BB #4 - resume | |
719 | block(&mut blocks, vec![], TerminatorKind::Resume, true); | |
720 | } | |
721 | ||
94222f64 XL |
722 | let mut body = new_body( |
723 | tcx, | |
724 | MirSource::from_instance(instance), | |
725 | blocks, | |
726 | local_decls, | |
727 | sig.inputs().len(), | |
728 | span, | |
729 | ); | |
60c5eb7d | 730 | |
cc61c64b | 731 | if let Abi::RustCall = sig.abi { |
dc9dc135 | 732 | body.spread_arg = Some(Local::new(sig.inputs().len())); |
cc61c64b | 733 | } |
f9f354fc XL |
734 | |
735 | body | |
cc61c64b XL |
736 | } |
737 | ||
f9f354fc | 738 | pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { |
dc9dc135 XL |
739 | debug_assert!(tcx.is_constructor(ctor_id)); |
740 | ||
dfeec247 XL |
741 | let span = |
742 | tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id)); | |
dc9dc135 XL |
743 | |
744 | let param_env = tcx.param_env(ctor_id); | |
ff7c6d11 | 745 | |
0531ce1d | 746 | // Normalize the sig. |
dfeec247 | 747 | let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature"); |
dc9dc135 | 748 | let sig = tcx.normalize_erasing_regions(param_env, sig); |
cc61c64b | 749 | |
1b1a35ee | 750 | let (adt_def, substs) = match sig.output().kind() { |
b7449926 | 751 | ty::Adt(adt_def, substs) => (adt_def, substs), |
dfeec247 | 752 | _ => bug!("unexpected type for ADT ctor {:?}", sig.output()), |
cc61c64b XL |
753 | }; |
754 | ||
dc9dc135 | 755 | debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig); |
cc61c64b XL |
756 | |
757 | let local_decls = local_decls_for_sig(&sig, span); | |
758 | ||
f9f354fc | 759 | let source_info = SourceInfo::outermost(span); |
cc61c64b | 760 | |
dc9dc135 XL |
761 | let variant_index = if adt_def.is_enum() { |
762 | adt_def.variant_index_with_ctor_id(ctor_id) | |
cc61c64b | 763 | } else { |
a1dfa0c6 | 764 | VariantIdx::new(0) |
cc61c64b XL |
765 | }; |
766 | ||
dc9dc135 XL |
767 | // Generate the following MIR: |
768 | // | |
769 | // (return as Variant).field0 = arg0; | |
770 | // (return as Variant).field1 = arg1; | |
771 | // | |
772 | // return; | |
773 | debug!("build_ctor: variant_index={:?}", variant_index); | |
774 | ||
775 | let statements = expand_aggregate( | |
e1599b0c | 776 | Place::return_place(), |
dfeec247 XL |
777 | adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| { |
778 | (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs)) | |
779 | }), | |
a2a8927a | 780 | AggregateKind::Adt(adt_def.did, variant_index, substs, None, None), |
dc9dc135 | 781 | source_info, |
e74abb32 | 782 | tcx, |
dfeec247 XL |
783 | ) |
784 | .collect(); | |
dc9dc135 | 785 | |
cc61c64b | 786 | let start_block = BasicBlockData { |
dc9dc135 | 787 | statements, |
dfeec247 XL |
788 | terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }), |
789 | is_cleanup: false, | |
cc61c64b XL |
790 | }; |
791 | ||
29967ef6 XL |
792 | let source = MirSource::item(ctor_id); |
793 | let body = new_body( | |
94222f64 | 794 | tcx, |
29967ef6 XL |
795 | source, |
796 | IndexVec::from_elem_n(start_block, 1), | |
797 | local_decls, | |
798 | sig.inputs().len(), | |
799 | span, | |
dc9dc135 XL |
800 | ); |
801 | ||
c295e0f8 | 802 | rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(())); |
29967ef6 | 803 | |
f9f354fc | 804 | body |
cc61c64b | 805 | } |