]>
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; | |
2b03887a | 6 | use rustc_middle::ty::InternalSubsts; |
f2b60f7d | 7 | use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, 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 | 18 | use crate::{ |
2b03887a | 19 | abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator, |
f2b60f7d | 20 | pass_manager as pm, remove_noop_landing_pads, simplify, |
9fa01778 | 21 | }; |
c295e0f8 XL |
22 | use rustc_middle::mir::patch::MirPatch; |
23 | use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle}; | |
9fa01778 | 24 | |
f035d41b | 25 | pub fn provide(providers: &mut Providers) { |
cc61c64b XL |
26 | providers.mir_shims = make_shim; |
27 | } | |
28 | ||
f9f354fc | 29 | fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> { |
cc61c64b | 30 | debug!("make_shim({:?})", instance); |
cc61c64b XL |
31 | |
32 | let mut result = match instance { | |
dfeec247 | 33 | ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance), |
064997fb | 34 | ty::InstanceDef::VTableShim(def_id) => { |
1b1a35ee | 35 | build_call_shim(tcx, instance, Some(Adjustment::Deref), CallKind::Direct(def_id)) |
f035d41b | 36 | } |
cc61c64b XL |
37 | ty::InstanceDef::FnPtrShim(def_id, ty) => { |
38 | let trait_ = tcx.trait_of_item(def_id).unwrap(); | |
487cf647 | 39 | let adjustment = match tcx.fn_trait_kind_from_def_id(trait_) { |
cc61c64b | 40 | Some(ty::ClosureKind::FnOnce) => Adjustment::Identity, |
ba9703b0 | 41 | Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref, |
dfeec247 | 42 | None => bug!("fn pointer {:?} is not an fn", ty), |
cc61c64b | 43 | }; |
1b1a35ee XL |
44 | |
45 | build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty)) | |
cc61c64b | 46 | } |
e74abb32 | 47 | // We are generating a call back to our def-id, which the |
60c5eb7d XL |
48 | // codegen backend knows to turn to an actual call, be it |
49 | // a virtual call, or a direct call to a function for which | |
50 | // indirect calls must be codegen'd differently than direct ones | |
51 | // (such as `#[track_caller]`). | |
e74abb32 | 52 | ty::InstanceDef::ReifyShim(def_id) => { |
1b1a35ee | 53 | build_call_shim(tcx, instance, None, CallKind::Direct(def_id)) |
cc61c64b | 54 | } |
c295e0f8 | 55 | ty::InstanceDef::ClosureOnceShim { call_once: _, track_caller: _ } => { |
3dfed10e | 56 | let fn_mut = tcx.require_lang_item(LangItem::FnMut, None); |
e74abb32 | 57 | let call_mut = tcx |
cc61c64b | 58 | .associated_items(fn_mut) |
74b04a01 | 59 | .in_definition_order() |
ba9703b0 | 60 | .find(|it| it.kind == ty::AssocKind::Fn) |
dfeec247 XL |
61 | .unwrap() |
62 | .def_id; | |
cc61c64b | 63 | |
1b1a35ee | 64 | build_call_shim(tcx, instance, Some(Adjustment::RefMut), CallKind::Direct(call_mut)) |
cc61c64b | 65 | } |
a2a8927a XL |
66 | |
67 | ty::InstanceDef::DropGlue(def_id, ty) => { | |
68 | // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end | |
69 | // of this function. Is this intentional? | |
5099ac24 | 70 | if let Some(ty::Generator(gen_def_id, substs, _)) = ty.map(Ty::kind) { |
a2a8927a | 71 | let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap(); |
04454e1e | 72 | let body = EarlyBinder(body.clone()).subst(tcx, substs); |
a2a8927a XL |
73 | debug!("make_shim({:?}) = {:?}", instance, body); |
74 | return body; | |
75 | } | |
76 | ||
77 | build_drop_shim(tcx, def_id, ty) | |
78 | } | |
3dfed10e | 79 | ty::InstanceDef::CloneShim(def_id, ty) => build_clone_shim(tcx, def_id, ty), |
60c5eb7d XL |
80 | ty::InstanceDef::Virtual(..) => { |
81 | bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance) | |
82 | } | |
cc61c64b XL |
83 | ty::InstanceDef::Intrinsic(_) => { |
84 | bug!("creating shims from intrinsics ({:?}) is unsupported", instance) | |
85 | } | |
86 | }; | |
3b2f2976 | 87 | debug!("make_shim({:?}) = untransformed {:?}", instance, result); |
9fa01778 | 88 | |
a2a8927a | 89 | pm::run_passes( |
dfeec247 XL |
90 | tcx, |
91 | &mut result, | |
a2a8927a | 92 | &[ |
dfeec247 | 93 | &add_moves_for_packed_drops::AddMovesForPackedDrops, |
f2b60f7d | 94 | &deref_separator::Derefer, |
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 | 99 | ], |
2b03887a | 100 | Some(MirPhase::Runtime(RuntimePhase::Optimized)), |
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 | |
064997fb | 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 | 139 | iter::once(LocalDecl::new(sig.output(), span)) |
5099ac24 | 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 { |
9ffffee4 | 150 | tcx.mk_substs(&[ty.into()]) |
cc61c64b | 151 | } else { |
532ac7d7 | 152 | InternalSubsts::identity_for_item(tcx, def_id) |
cc61c64b | 153 | }; |
9ffffee4 | 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 = | |
5099ac24 | 174 | new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span); |
cc61c64b | 175 | |
9c376795 FG |
176 | // The first argument (index 0), but add 1 for the return value. |
177 | let mut dropee_ptr = Place::from(Local::new(1 + 0)); | |
178 | if tcx.sess.opts.unstable_opts.mir_emit_retag { | |
179 | // We want to treat the function argument as if it was passed by `&mut`. As such, we | |
180 | // generate | |
181 | // ``` | |
182 | // temp = &mut *arg; | |
183 | // Retag(temp, FnEntry) | |
184 | // ``` | |
185 | // It's important that we do this first, before anything that depends on `dropee_ptr` | |
186 | // has been put into the body. | |
187 | let reborrow = Rvalue::Ref( | |
188 | tcx.lifetimes.re_erased, | |
189 | BorrowKind::Mut { allow_two_phase_borrow: false }, | |
190 | tcx.mk_place_deref(dropee_ptr), | |
191 | ); | |
192 | let ref_ty = reborrow.ty(body.local_decls(), tcx); | |
193 | dropee_ptr = body.local_decls.push(LocalDecl::new(ref_ty, span)).into(); | |
194 | let new_statements = [ | |
195 | StatementKind::Assign(Box::new((dropee_ptr, reborrow))), | |
196 | StatementKind::Retag(RetagKind::FnEntry, Box::new(dropee_ptr)), | |
197 | ]; | |
198 | for s in new_statements { | |
199 | body.basic_blocks_mut()[START_BLOCK] | |
200 | .statements | |
201 | .push(Statement { source_info, kind: s }); | |
202 | } | |
203 | } | |
204 | ||
5869c6ff | 205 | if ty.is_some() { |
cc61c64b | 206 | let patch = { |
3dfed10e | 207 | let param_env = tcx.param_env_reveal_all_normalized(def_id); |
dfeec247 XL |
208 | let mut elaborator = |
209 | DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env }; | |
e74abb32 | 210 | let dropee = tcx.mk_place_deref(dropee_ptr); |
cc61c64b XL |
211 | let resume_block = elaborator.patch.resume_block(); |
212 | elaborate_drops::elaborate_drop( | |
213 | &mut elaborator, | |
214 | source_info, | |
ba9703b0 | 215 | dropee, |
cc61c64b XL |
216 | (), |
217 | return_block, | |
7cac9316 | 218 | elaborate_drops::Unwind::To(resume_block), |
dfeec247 | 219 | START_BLOCK, |
cc61c64b XL |
220 | ); |
221 | elaborator.patch | |
222 | }; | |
dc9dc135 | 223 | patch.apply(&mut body); |
cc61c64b XL |
224 | } |
225 | ||
dc9dc135 | 226 | body |
cc61c64b XL |
227 | } |
228 | ||
60c5eb7d | 229 | fn new_body<'tcx>( |
29967ef6 | 230 | source: MirSource<'tcx>, |
60c5eb7d XL |
231 | basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, |
232 | local_decls: IndexVec<Local, LocalDecl<'tcx>>, | |
233 | arg_count: usize, | |
234 | span: Span, | |
235 | ) -> Body<'tcx> { | |
236 | Body::new( | |
29967ef6 | 237 | source, |
60c5eb7d XL |
238 | basic_blocks, |
239 | IndexVec::from_elem_n( | |
29967ef6 XL |
240 | SourceScopeData { |
241 | span, | |
242 | parent_scope: None, | |
243 | inlined: None, | |
244 | inlined_parent_scope: None, | |
245 | local_data: ClearCrossCrate::Clear, | |
246 | }, | |
60c5eb7d XL |
247 | 1, |
248 | ), | |
249 | local_decls, | |
250 | IndexVec::new(), | |
251 | arg_count, | |
252 | vec![], | |
253 | span, | |
60c5eb7d | 254 | None, |
5099ac24 FG |
255 | // FIXME(compiler-errors): is this correct? |
256 | None, | |
60c5eb7d XL |
257 | ) |
258 | } | |
259 | ||
dc9dc135 XL |
260 | pub struct DropShimElaborator<'a, 'tcx> { |
261 | pub body: &'a Body<'tcx>, | |
ea8adc8c | 262 | pub patch: MirPatch<'tcx>, |
dc9dc135 | 263 | pub tcx: TyCtxt<'tcx>, |
ea8adc8c | 264 | pub param_env: ty::ParamEnv<'tcx>, |
cc61c64b XL |
265 | } |
266 | ||
a2a8927a | 267 | impl fmt::Debug for DropShimElaborator<'_, '_> { |
9fa01778 | 268 | fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { |
cc61c64b XL |
269 | Ok(()) |
270 | } | |
271 | } | |
272 | ||
273 | impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> { | |
274 | type Path = (); | |
275 | ||
dfeec247 XL |
276 | fn patch(&mut self) -> &mut MirPatch<'tcx> { |
277 | &mut self.patch | |
278 | } | |
279 | fn body(&self) -> &'a Body<'tcx> { | |
280 | self.body | |
281 | } | |
dc9dc135 XL |
282 | fn tcx(&self) -> TyCtxt<'tcx> { |
283 | self.tcx | |
dfeec247 XL |
284 | } |
285 | fn param_env(&self) -> ty::ParamEnv<'tcx> { | |
286 | self.param_env | |
287 | } | |
cc61c64b XL |
288 | |
289 | fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle { | |
f9f354fc XL |
290 | match mode { |
291 | DropFlagMode::Shallow => { | |
292 | // Drops for the contained fields are "shallow" and "static" - they will simply call | |
293 | // the field's own drop glue. | |
294 | DropStyle::Static | |
295 | } | |
296 | DropFlagMode::Deep => { | |
297 | // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder | |
298 | // dropping each field contained in the value. | |
299 | DropStyle::Open | |
300 | } | |
301 | } | |
cc61c64b XL |
302 | } |
303 | ||
304 | fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> { | |
305 | None | |
306 | } | |
307 | ||
dfeec247 | 308 | fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {} |
cc61c64b XL |
309 | |
310 | fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> { | |
311 | None | |
312 | } | |
313 | fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> { | |
314 | None | |
315 | } | |
a1dfa0c6 | 316 | fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> { |
cc61c64b XL |
317 | Some(()) |
318 | } | |
1b1a35ee | 319 | fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> { |
ff7c6d11 XL |
320 | None |
321 | } | |
cc61c64b XL |
322 | } |
323 | ||
9fa01778 | 324 | /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`. |
f9f354fc | 325 | fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> { |
3b2f2976 XL |
326 | debug!("build_clone_shim(def_id={:?})", def_id); |
327 | ||
416331ca XL |
328 | let param_env = tcx.param_env(def_id); |
329 | ||
2c00a5a8 | 330 | let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty); |
2b03887a | 331 | let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env); |
3b2f2976 | 332 | |
e1599b0c | 333 | let dest = Place::return_place(); |
dfeec247 | 334 | let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0))); |
2c00a5a8 | 335 | |
1b1a35ee | 336 | match self_ty.kind() { |
3b2f2976 | 337 | _ if is_copy => builder.copy_shim(), |
ba9703b0 XL |
338 | ty::Closure(_, substs) => { |
339 | builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys()) | |
ea8adc8c | 340 | } |
416331ca | 341 | ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), |
f2b60f7d FG |
342 | ty::Generator(gen_def_id, substs, hir::Movability::Movable) => { |
343 | builder.generator_shim(dest, src, *gen_def_id, substs.as_generator()) | |
344 | } | |
dfeec247 | 345 | _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty), |
3b2f2976 XL |
346 | }; |
347 | ||
f9f354fc | 348 | builder.into_mir() |
3b2f2976 XL |
349 | } |
350 | ||
dc9dc135 XL |
351 | struct CloneShimBuilder<'tcx> { |
352 | tcx: TyCtxt<'tcx>, | |
3b2f2976 XL |
353 | def_id: DefId, |
354 | local_decls: IndexVec<Local, LocalDecl<'tcx>>, | |
355 | blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>, | |
356 | span: Span, | |
357 | sig: ty::FnSig<'tcx>, | |
358 | } | |
359 | ||
a2a8927a | 360 | impl<'tcx> CloneShimBuilder<'tcx> { |
dc9dc135 | 361 | fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self { |
2c00a5a8 XL |
362 | // we must subst the self_ty because it's |
363 | // otherwise going to be TySelf and we can't index | |
364 | // or access fields of a Place of type TySelf. | |
9ffffee4 | 365 | let sig = tcx.fn_sig(def_id).subst(tcx, &[self_ty.into()]); |
fc512014 | 366 | let sig = tcx.erase_late_bound_regions(sig); |
3b2f2976 XL |
367 | let span = tcx.def_span(def_id); |
368 | ||
369 | CloneShimBuilder { | |
370 | tcx, | |
371 | def_id, | |
372 | local_decls: local_decls_for_sig(&sig, span), | |
373 | blocks: IndexVec::new(), | |
374 | span, | |
375 | sig, | |
376 | } | |
377 | } | |
378 | ||
dc9dc135 | 379 | fn into_mir(self) -> Body<'tcx> { |
29967ef6 XL |
380 | let source = MirSource::from_instance(ty::InstanceDef::CloneShim( |
381 | self.def_id, | |
382 | self.sig.inputs_and_output[0], | |
383 | )); | |
5099ac24 | 384 | new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span) |
3b2f2976 XL |
385 | } |
386 | ||
387 | fn source_info(&self) -> SourceInfo { | |
f9f354fc | 388 | SourceInfo::outermost(self.span) |
3b2f2976 XL |
389 | } |
390 | ||
391 | fn block( | |
392 | &mut self, | |
393 | statements: Vec<Statement<'tcx>>, | |
394 | kind: TerminatorKind<'tcx>, | |
dfeec247 | 395 | is_cleanup: bool, |
3b2f2976 XL |
396 | ) -> BasicBlock { |
397 | let source_info = self.source_info(); | |
398 | self.blocks.push(BasicBlockData { | |
399 | statements, | |
400 | terminator: Some(Terminator { source_info, kind }), | |
401 | is_cleanup, | |
402 | }) | |
403 | } | |
404 | ||
2c00a5a8 XL |
405 | /// Gives the index of an upcoming BasicBlock, with an offset. |
406 | /// offset=0 will give you the index of the next BasicBlock, | |
407 | /// offset=1 will give the index of the next-to-next block, | |
408 | /// offset=-1 will give you the index of the last-created block | |
f2b60f7d | 409 | fn block_index_offset(&self, offset: usize) -> BasicBlock { |
2c00a5a8 XL |
410 | BasicBlock::new(self.blocks.len() + offset) |
411 | } | |
412 | ||
3b2f2976 | 413 | fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> { |
dfeec247 | 414 | Statement { source_info: self.source_info(), kind } |
3b2f2976 XL |
415 | } |
416 | ||
417 | fn copy_shim(&mut self) { | |
dfeec247 | 418 | let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0))); |
94222f64 | 419 | let ret_statement = self.make_statement(StatementKind::Assign(Box::new(( |
dfeec247 XL |
420 | Place::return_place(), |
421 | Rvalue::Use(Operand::Copy(rcvr)), | |
94222f64 | 422 | )))); |
3b2f2976 XL |
423 | self.block(vec![ret_statement], TerminatorKind::Return, false); |
424 | } | |
425 | ||
ff7c6d11 | 426 | fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> { |
3b2f2976 | 427 | let span = self.span; |
f9f354fc | 428 | let mut local = LocalDecl::new(ty, span); |
9ffffee4 | 429 | if mutability.is_not() { |
f9f354fc XL |
430 | local = local.immutable(); |
431 | } | |
432 | Place::from(self.local_decls.push(local)) | |
3b2f2976 XL |
433 | } |
434 | ||
435 | fn make_clone_call( | |
436 | &mut self, | |
2c00a5a8 XL |
437 | dest: Place<'tcx>, |
438 | src: Place<'tcx>, | |
ea8adc8c | 439 | ty: Ty<'tcx>, |
3b2f2976 | 440 | next: BasicBlock, |
dfeec247 | 441 | cleanup: BasicBlock, |
2c00a5a8 | 442 | ) { |
3b2f2976 XL |
443 | let tcx = self.tcx; |
444 | ||
3b2f2976 | 445 | // `func == Clone::clone(&ty) -> ty` |
9c376795 | 446 | let func_ty = tcx.mk_fn_def(self.def_id, [ty]); |
94222f64 | 447 | let func = Operand::Constant(Box::new(Constant { |
3b2f2976 | 448 | span: self.span, |
b7449926 | 449 | user_ty: None, |
923072b8 | 450 | literal: ConstantKind::zero_sized(func_ty), |
94222f64 | 451 | })); |
3b2f2976 | 452 | |
ff7c6d11 | 453 | let ref_loc = self.make_place( |
3b2f2976 | 454 | Mutability::Not, |
dfeec247 | 455 | tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }), |
3b2f2976 XL |
456 | ); |
457 | ||
2c00a5a8 | 458 | // `let ref_loc: &ty = &src;` |
94222f64 | 459 | let statement = self.make_statement(StatementKind::Assign(Box::new(( |
dfeec247 XL |
460 | ref_loc, |
461 | Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src), | |
94222f64 | 462 | )))); |
3b2f2976 XL |
463 | |
464 | // `let loc = Clone::clone(ref_loc);` | |
dfeec247 XL |
465 | self.block( |
466 | vec![statement], | |
467 | TerminatorKind::Call { | |
468 | func, | |
469 | args: vec![Operand::Move(ref_loc)], | |
923072b8 FG |
470 | destination: dest, |
471 | target: Some(next), | |
dfeec247 XL |
472 | cleanup: Some(cleanup), |
473 | from_hir_call: true, | |
f035d41b | 474 | fn_span: self.span, |
dfeec247 XL |
475 | }, |
476 | false, | |
477 | ); | |
3b2f2976 XL |
478 | } |
479 | ||
f2b60f7d FG |
480 | fn clone_fields<I>( |
481 | &mut self, | |
482 | dest: Place<'tcx>, | |
483 | src: Place<'tcx>, | |
484 | target: BasicBlock, | |
485 | mut unwind: BasicBlock, | |
486 | tys: I, | |
487 | ) -> BasicBlock | |
dfeec247 | 488 | where |
5e7ed085 | 489 | I: IntoIterator<Item = Ty<'tcx>>, |
dfeec247 | 490 | { |
f2b60f7d | 491 | // For an iterator of length n, create 2*n + 1 blocks. |
5e7ed085 | 492 | for (i, ity) in tys.into_iter().enumerate() { |
f2b60f7d FG |
493 | // Each iteration creates two blocks, referred to here as block 2*i and block 2*i + 1. |
494 | // | |
495 | // Block 2*i attempts to clone the field. If successful it branches to 2*i + 2 (the | |
496 | // next clone block). If unsuccessful it branches to the previous unwind block, which | |
497 | // is initially the `unwind` argument passed to this function. | |
498 | // | |
499 | // Block 2*i + 1 is the unwind block for this iteration. It drops the cloned value | |
500 | // created by block 2*i. We store this block in `unwind` so that the next clone block | |
501 | // will unwind to it if cloning fails. | |
502 | ||
2c00a5a8 | 503 | let field = Field::new(i); |
ba9703b0 | 504 | let src_field = self.tcx.mk_place_field(src, field, ity); |
ea8adc8c | 505 | |
ba9703b0 | 506 | let dest_field = self.tcx.mk_place_field(dest, field, ity); |
3b2f2976 | 507 | |
f2b60f7d | 508 | let next_unwind = self.block_index_offset(1); |
2c00a5a8 | 509 | let next_block = self.block_index_offset(2); |
f2b60f7d FG |
510 | self.make_clone_call(dest_field, src_field, ity, next_block, unwind); |
511 | self.block( | |
512 | vec![], | |
513 | TerminatorKind::Drop { place: dest_field, target: unwind, unwind: None }, | |
514 | true, | |
515 | ); | |
516 | unwind = next_unwind; | |
517 | } | |
518 | // If all clones succeed then we end up here. | |
519 | self.block(vec![], TerminatorKind::Goto { target }, false); | |
520 | unwind | |
521 | } | |
3b2f2976 | 522 | |
f2b60f7d FG |
523 | fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I) |
524 | where | |
525 | I: IntoIterator<Item = Ty<'tcx>>, | |
526 | { | |
527 | self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false); | |
528 | let unwind = self.block(vec![], TerminatorKind::Resume, true); | |
529 | let target = self.block(vec![], TerminatorKind::Return, false); | |
2c00a5a8 | 530 | |
f2b60f7d FG |
531 | let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, tys); |
532 | } | |
3b2f2976 | 533 | |
f2b60f7d FG |
534 | fn generator_shim( |
535 | &mut self, | |
536 | dest: Place<'tcx>, | |
537 | src: Place<'tcx>, | |
538 | gen_def_id: DefId, | |
539 | substs: GeneratorSubsts<'tcx>, | |
540 | ) { | |
541 | self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false); | |
542 | let unwind = self.block(vec![], TerminatorKind::Resume, true); | |
543 | // This will get overwritten with a switch once we know the target blocks | |
544 | let switch = self.block(vec![], TerminatorKind::Unreachable, false); | |
545 | let unwind = self.clone_fields(dest, src, switch, unwind, substs.upvar_tys()); | |
546 | let target = self.block(vec![], TerminatorKind::Return, false); | |
547 | let unreachable = self.block(vec![], TerminatorKind::Unreachable, false); | |
548 | let mut cases = Vec::with_capacity(substs.state_tys(gen_def_id, self.tcx).count()); | |
549 | for (index, state_tys) in substs.state_tys(gen_def_id, self.tcx).enumerate() { | |
550 | let variant_index = VariantIdx::new(index); | |
551 | let dest = self.tcx.mk_place_downcast_unnamed(dest, variant_index); | |
552 | let src = self.tcx.mk_place_downcast_unnamed(src, variant_index); | |
553 | let clone_block = self.block_index_offset(1); | |
554 | let start_block = self.block( | |
555 | vec![self.make_statement(StatementKind::SetDiscriminant { | |
556 | place: Box::new(Place::return_place()), | |
557 | variant_index, | |
558 | })], | |
559 | TerminatorKind::Goto { target: clone_block }, | |
560 | false, | |
561 | ); | |
562 | cases.push((index as u128, start_block)); | |
563 | let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, state_tys); | |
564 | } | |
565 | let discr_ty = substs.discr_ty(self.tcx); | |
566 | let temp = self.make_place(Mutability::Mut, discr_ty); | |
567 | let rvalue = Rvalue::Discriminant(src); | |
568 | let statement = self.make_statement(StatementKind::Assign(Box::new((temp, rvalue)))); | |
569 | match &mut self.blocks[switch] { | |
570 | BasicBlockData { statements, terminator: Some(Terminator { kind, .. }), .. } => { | |
571 | statements.push(statement); | |
572 | *kind = TerminatorKind::SwitchInt { | |
573 | discr: Operand::Move(temp), | |
f2b60f7d FG |
574 | targets: SwitchTargets::new(cases.into_iter(), unreachable), |
575 | }; | |
576 | } | |
577 | BasicBlockData { terminator: None, .. } => unreachable!(), | |
578 | } | |
3b2f2976 XL |
579 | } |
580 | } | |
581 | ||
1b1a35ee XL |
582 | /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`, |
583 | /// first adjusting its first argument according to `rcvr_adjustment`. | |
487cf647 | 584 | #[instrument(level = "debug", skip(tcx), ret)] |
dc9dc135 XL |
585 | fn build_call_shim<'tcx>( |
586 | tcx: TyCtxt<'tcx>, | |
60c5eb7d | 587 | instance: ty::InstanceDef<'tcx>, |
dfeec247 | 588 | rcvr_adjustment: Option<Adjustment>, |
f035d41b | 589 | call_kind: CallKind<'tcx>, |
f9f354fc | 590 | ) -> Body<'tcx> { |
1b1a35ee XL |
591 | // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used |
592 | // to substitute into the signature of the shim. It is not necessary for users of this | |
593 | // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`). | |
594 | let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance { | |
fc512014 | 595 | let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx)); |
1b1a35ee XL |
596 | |
597 | let untuple_args = sig.inputs(); | |
598 | ||
599 | // Create substitutions for the `Self` and `Args` generic parameters of the shim body. | |
9ffffee4 | 600 | let arg_tup = tcx.mk_tup(untuple_args); |
1b1a35ee | 601 | |
9c376795 | 602 | (Some([ty.into(), arg_tup.into()]), Some(untuple_args)) |
1b1a35ee XL |
603 | } else { |
604 | (None, None) | |
605 | }; | |
606 | ||
60c5eb7d | 607 | let def_id = instance.def_id(); |
9ffffee4 | 608 | let sig = tcx.fn_sig(def_id); |
064997fb | 609 | let sig = sig.map_bound(|sig| tcx.erase_late_bound_regions(sig)); |
60c5eb7d | 610 | |
1b1a35ee | 611 | assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body()); |
064997fb | 612 | let mut sig = |
9c376795 | 613 | if let Some(sig_substs) = sig_substs { sig.subst(tcx, &sig_substs) } else { sig.0 }; |
1b1a35ee | 614 | |
f035d41b XL |
615 | if let CallKind::Indirect(fnty) = call_kind { |
616 | // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This | |
617 | // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from | |
618 | // the implemented `FnX` trait. | |
619 | ||
620 | // Apply the opposite adjustment to the MIR input. | |
621 | let mut inputs_and_output = sig.inputs_and_output.to_vec(); | |
622 | ||
623 | // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the | |
624 | // fn arguments. `Self` may be passed via (im)mutable reference or by-value. | |
625 | assert_eq!(inputs_and_output.len(), 3); | |
626 | ||
627 | // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for | |
628 | // `FnDef` and `FnPtr` callees, not the `Self` type param. | |
629 | let self_arg = &mut inputs_and_output[0]; | |
630 | *self_arg = match rcvr_adjustment.unwrap() { | |
631 | Adjustment::Identity => fnty, | |
632 | Adjustment::Deref => tcx.mk_imm_ptr(fnty), | |
633 | Adjustment::RefMut => tcx.mk_mut_ptr(fnty), | |
634 | }; | |
9ffffee4 | 635 | sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output); |
f035d41b XL |
636 | } |
637 | ||
60c5eb7d XL |
638 | // FIXME(eddyb) avoid having this snippet both here and in |
639 | // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?). | |
064997fb | 640 | if let ty::InstanceDef::VTableShim(..) = instance { |
60c5eb7d XL |
641 | // Modify fn(self, ...) to fn(self: *mut Self, ...) |
642 | let mut inputs_and_output = sig.inputs_and_output.to_vec(); | |
643 | let self_arg = &mut inputs_and_output[0]; | |
644 | debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param); | |
645 | *self_arg = tcx.mk_mut_ptr(*self_arg); | |
9ffffee4 | 646 | sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output); |
60c5eb7d XL |
647 | } |
648 | ||
cc61c64b XL |
649 | let span = tcx.def_span(def_id); |
650 | ||
487cf647 | 651 | debug!(?sig); |
cc61c64b XL |
652 | |
653 | let mut local_decls = local_decls_for_sig(&sig, span); | |
f9f354fc | 654 | let source_info = SourceInfo::outermost(span); |
cc61c64b | 655 | |
dfeec247 XL |
656 | let rcvr_place = || { |
657 | assert!(rcvr_adjustment.is_some()); | |
658 | Place::from(Local::new(1 + 0)) | |
659 | }; | |
cc61c64b XL |
660 | let mut statements = vec![]; |
661 | ||
dfeec247 XL |
662 | let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment { |
663 | Adjustment::Identity => Operand::Move(rcvr_place()), | |
f035d41b | 664 | Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())), |
cc61c64b XL |
665 | Adjustment::RefMut => { |
666 | // let rcvr = &mut rcvr; | |
f9f354fc XL |
667 | let ref_rcvr = local_decls.push( |
668 | LocalDecl::new( | |
669 | tcx.mk_ref( | |
670 | tcx.lifetimes.re_erased, | |
671 | ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut }, | |
672 | ), | |
673 | span, | |
674 | ) | |
675 | .immutable(), | |
676 | ); | |
dfeec247 | 677 | let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false }; |
cc61c64b | 678 | statements.push(Statement { |
3b2f2976 | 679 | source_info, |
94222f64 | 680 | kind: StatementKind::Assign(Box::new(( |
dfeec247 XL |
681 | Place::from(ref_rcvr), |
682 | Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()), | |
94222f64 | 683 | ))), |
cc61c64b | 684 | }); |
dc9dc135 | 685 | Operand::Move(Place::from(ref_rcvr)) |
cc61c64b | 686 | } |
dfeec247 | 687 | }); |
cc61c64b XL |
688 | |
689 | let (callee, mut args) = match call_kind { | |
f035d41b XL |
690 | // `FnPtr` call has no receiver. Args are untupled below. |
691 | CallKind::Indirect(_) => (rcvr.unwrap(), vec![]), | |
692 | ||
693 | // `FnDef` call with optional receiver. | |
ea8adc8c | 694 | CallKind::Direct(def_id) => { |
9ffffee4 | 695 | let ty = tcx.type_of(def_id).subst_identity(); |
dfeec247 | 696 | ( |
94222f64 | 697 | Operand::Constant(Box::new(Constant { |
dfeec247 XL |
698 | span, |
699 | user_ty: None, | |
923072b8 | 700 | literal: ConstantKind::zero_sized(ty), |
94222f64 | 701 | })), |
dfeec247 XL |
702 | rcvr.into_iter().collect::<Vec<_>>(), |
703 | ) | |
ea8adc8c | 704 | } |
cc61c64b XL |
705 | }; |
706 | ||
dfeec247 XL |
707 | let mut arg_range = 0..sig.inputs().len(); |
708 | ||
709 | // Take the `self` ("receiver") argument out of the range (it's adjusted above). | |
710 | if rcvr_adjustment.is_some() { | |
711 | arg_range.start += 1; | |
712 | } | |
713 | ||
714 | // Take the last argument, if we need to untuple it (handled below). | |
715 | if untuple_args.is_some() { | |
716 | arg_range.end -= 1; | |
717 | } | |
718 | ||
719 | // Pass all of the non-special arguments directly. | |
720 | args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i))))); | |
721 | ||
722 | // Untuple the last argument, if we have to. | |
cc61c64b | 723 | if let Some(untuple_args) = untuple_args { |
dfeec247 | 724 | let tuple_arg = Local::new(1 + (sig.inputs().len() - 1)); |
cc61c64b | 725 | args.extend(untuple_args.iter().enumerate().map(|(i, ity)| { |
dfeec247 | 726 | Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity)) |
cc61c64b XL |
727 | })); |
728 | } | |
729 | ||
dfeec247 | 730 | let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 }; |
a1dfa0c6 | 731 | let mut blocks = IndexVec::with_capacity(n_blocks); |
cc61c64b XL |
732 | let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| { |
733 | blocks.push(BasicBlockData { | |
734 | statements, | |
735 | terminator: Some(Terminator { source_info, kind }), | |
dfeec247 | 736 | is_cleanup, |
cc61c64b XL |
737 | }) |
738 | }; | |
739 | ||
740 | // BB #0 | |
dfeec247 XL |
741 | block( |
742 | &mut blocks, | |
743 | statements, | |
744 | TerminatorKind::Call { | |
745 | func: callee, | |
746 | args, | |
923072b8 FG |
747 | destination: Place::return_place(), |
748 | target: Some(BasicBlock::new(1)), | |
dfeec247 XL |
749 | cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment { |
750 | Some(BasicBlock::new(3)) | |
751 | } else { | |
752 | None | |
753 | }, | |
754 | from_hir_call: true, | |
f035d41b | 755 | fn_span: span, |
0bf4aa26 | 756 | }, |
dfeec247 XL |
757 | false, |
758 | ); | |
cc61c64b | 759 | |
dfeec247 | 760 | if let Some(Adjustment::RefMut) = rcvr_adjustment { |
cc61c64b | 761 | // BB #1 - drop for Self |
dfeec247 XL |
762 | block( |
763 | &mut blocks, | |
764 | vec![], | |
f035d41b | 765 | TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None }, |
dfeec247 XL |
766 | false, |
767 | ); | |
cc61c64b XL |
768 | } |
769 | // BB #1/#2 - return | |
770 | block(&mut blocks, vec![], TerminatorKind::Return, false); | |
dfeec247 | 771 | if let Some(Adjustment::RefMut) = rcvr_adjustment { |
cc61c64b | 772 | // BB #3 - drop if closure panics |
dfeec247 XL |
773 | block( |
774 | &mut blocks, | |
775 | vec![], | |
f035d41b | 776 | TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None }, |
dfeec247 XL |
777 | true, |
778 | ); | |
cc61c64b XL |
779 | |
780 | // BB #4 - resume | |
781 | block(&mut blocks, vec![], TerminatorKind::Resume, true); | |
782 | } | |
783 | ||
5099ac24 FG |
784 | let mut body = |
785 | new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span); | |
60c5eb7d | 786 | |
cc61c64b | 787 | if let Abi::RustCall = sig.abi { |
dc9dc135 | 788 | body.spread_arg = Some(Local::new(sig.inputs().len())); |
cc61c64b | 789 | } |
f9f354fc XL |
790 | |
791 | body | |
cc61c64b XL |
792 | } |
793 | ||
f9f354fc | 794 | pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { |
dc9dc135 XL |
795 | debug_assert!(tcx.is_constructor(ctor_id)); |
796 | ||
dc9dc135 | 797 | let param_env = tcx.param_env(ctor_id); |
ff7c6d11 | 798 | |
0531ce1d | 799 | // Normalize the sig. |
9ffffee4 FG |
800 | let sig = tcx |
801 | .fn_sig(ctor_id) | |
802 | .subst_identity() | |
803 | .no_bound_vars() | |
804 | .expect("LBR in ADT constructor signature"); | |
dc9dc135 | 805 | let sig = tcx.normalize_erasing_regions(param_env, sig); |
cc61c64b | 806 | |
5e7ed085 FG |
807 | let ty::Adt(adt_def, substs) = sig.output().kind() else { |
808 | bug!("unexpected type for ADT ctor {:?}", sig.output()); | |
cc61c64b XL |
809 | }; |
810 | ||
dc9dc135 | 811 | debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig); |
cc61c64b | 812 | |
04454e1e FG |
813 | let span = tcx.def_span(ctor_id); |
814 | ||
cc61c64b XL |
815 | let local_decls = local_decls_for_sig(&sig, span); |
816 | ||
f9f354fc | 817 | let source_info = SourceInfo::outermost(span); |
cc61c64b | 818 | |
dc9dc135 XL |
819 | let variant_index = if adt_def.is_enum() { |
820 | adt_def.variant_index_with_ctor_id(ctor_id) | |
cc61c64b | 821 | } else { |
a1dfa0c6 | 822 | VariantIdx::new(0) |
cc61c64b XL |
823 | }; |
824 | ||
dc9dc135 XL |
825 | // Generate the following MIR: |
826 | // | |
827 | // (return as Variant).field0 = arg0; | |
828 | // (return as Variant).field1 = arg1; | |
829 | // | |
830 | // return; | |
831 | debug!("build_ctor: variant_index={:?}", variant_index); | |
832 | ||
9ffffee4 FG |
833 | let kind = AggregateKind::Adt(adt_def.did(), variant_index, substs, None, None); |
834 | let variant = adt_def.variant(variant_index); | |
835 | let statement = Statement { | |
836 | kind: StatementKind::Assign(Box::new(( | |
837 | Place::return_place(), | |
838 | Rvalue::Aggregate( | |
839 | Box::new(kind), | |
840 | (0..variant.fields.len()) | |
841 | .map(|idx| Operand::Move(Place::from(Local::new(idx + 1)))) | |
842 | .collect(), | |
843 | ), | |
844 | ))), | |
dc9dc135 | 845 | source_info, |
9ffffee4 | 846 | }; |
dc9dc135 | 847 | |
cc61c64b | 848 | let start_block = BasicBlockData { |
9ffffee4 | 849 | statements: vec![statement], |
dfeec247 XL |
850 | terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }), |
851 | is_cleanup: false, | |
cc61c64b XL |
852 | }; |
853 | ||
29967ef6 XL |
854 | let source = MirSource::item(ctor_id); |
855 | let body = new_body( | |
856 | source, | |
857 | IndexVec::from_elem_n(start_block, 1), | |
858 | local_decls, | |
859 | sig.inputs().len(), | |
860 | span, | |
dc9dc135 XL |
861 | ); |
862 | ||
487cf647 | 863 | crate::pass_manager::dump_mir_for_phase_change(tcx, &body); |
29967ef6 | 864 | |
f9f354fc | 865 | body |
cc61c64b | 866 | } |