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