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