Skip to content

Commit aca749e

Browse files
committed
Auto merge of rust-lang#121801 - zetanumbers:async_drop_glue, r=oli-obk
Add simple async drop glue generation This is a prototype of the async drop glue generation for some simple types. Async drop glue is intended to behave very similar to the regular drop glue except for being asynchronous. Currently it does not execute synchronous drops but only calls user implementations of `AsyncDrop::async_drop` associative function and awaits the returned future. It is not complete as it only recurses into arrays, slices, tuples, and structs and does not have same sensible restrictions as the old `Drop` trait implementation like having the same bounds as the type definition, while code assumes their existence (requires a future work). This current design uses a workaround as it does not create any custom async destructor state machine types for ADTs, but instead uses types defined in the std library called future combinators (deferred_async_drop, chain, ready_unit). Also I recommend reading my [explainer](https://zetanumbers.github.io/book/async-drop-design.html). This is a part of the [MCP: Low level components for async drop](rust-lang/compiler-team#727) work. Feature completeness: - [x] `AsyncDrop` trait - [ ] `async_drop_in_place_raw`/async drop glue generation support for - [x] Trivially destructible types (integers, bools, floats, string slices, pointers, references, etc.) - [x] Arrays and slices (array pointer is unsized into slice pointer) - [x] ADTs (enums, structs, unions) - [x] tuple-like types (tuples, closures) - [ ] Dynamic types (`dyn Trait`, see explainer's [proposed design](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#async-drop-glue-for-dyn-trait)) - [ ] coroutines (rust-lang#123948) - [x] Async drop glue includes sync drop glue code - [x] Cleanup branch generation for `async_drop_in_place_raw` - [ ] Union rejects non-trivially async destructible fields - [ ] `AsyncDrop` implementation requires same bounds as type definition - [ ] Skip trivially destructible fields (optimization) - [ ] New [`TyKind::AdtAsyncDestructor`](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#adt-async-destructor-types) and get rid of combinators - [ ] [Synchronously undroppable types](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#exclusively-async-drop) - [ ] Automatic async drop at the end of the scope in async context
2 parents 9cf10bc + 67980dd commit aca749e

File tree

44 files changed

+1916
-24
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1916
-24
lines changed

compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+41
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,24 @@ fn exported_symbols_provider_local(
363363
},
364364
));
365365
}
366+
MonoItem::Fn(Instance {
367+
def: InstanceDef::AsyncDropGlueCtorShim(def_id, Some(ty)),
368+
args,
369+
}) => {
370+
// A little sanity-check
371+
debug_assert_eq!(
372+
args.non_erasable_generics(tcx, def_id).skip(1).next(),
373+
Some(GenericArgKind::Type(ty))
374+
);
375+
symbols.push((
376+
ExportedSymbol::AsyncDropGlueCtorShim(ty),
377+
SymbolExportInfo {
378+
level: SymbolExportLevel::Rust,
379+
kind: SymbolExportKind::Text,
380+
used: false,
381+
},
382+
));
383+
}
366384
_ => {
367385
// Any other symbols don't qualify for sharing
368386
}
@@ -385,6 +403,7 @@ fn upstream_monomorphizations_provider(
385403
let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
386404

387405
let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
406+
let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
388407

389408
for &cnum in cnums.iter() {
390409
for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
@@ -399,6 +418,18 @@ fn upstream_monomorphizations_provider(
399418
continue;
400419
}
401420
}
421+
ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
422+
if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
423+
(
424+
async_drop_in_place_fn_def_id,
425+
tcx.mk_args(&[tcx.lifetimes.re_erased.into(), ty.into()]),
426+
)
427+
} else {
428+
// `drop_in_place` in place does not exist, don't try
429+
// to use it.
430+
continue;
431+
}
432+
}
402433
ExportedSymbol::NonGeneric(..)
403434
| ExportedSymbol::ThreadLocalShim(..)
404435
| ExportedSymbol::NoDefId(..) => {
@@ -534,6 +565,13 @@ pub fn symbol_name_for_instance_in_crate<'tcx>(
534565
Instance::resolve_drop_in_place(tcx, ty),
535566
instantiating_crate,
536567
),
568+
ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
569+
rustc_symbol_mangling::symbol_name_for_instance_in_crate(
570+
tcx,
571+
Instance::resolve_async_drop_in_place(tcx, ty),
572+
instantiating_crate,
573+
)
574+
}
537575
ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
538576
}
539577
}
@@ -582,6 +620,9 @@ pub fn linking_symbol_name_for_instance_in_crate<'tcx>(
582620
// DropGlue always use the Rust calling convention and thus follow the target's default
583621
// symbol decoration scheme.
584622
ExportedSymbol::DropGlue(..) => None,
623+
// AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
624+
// target's default symbol decoration scheme.
625+
ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
585626
// NoDefId always follow the target's default symbol decoration scheme.
586627
ExportedSymbol::NoDefId(..) => None,
587628
// ThreadLocalShim always follow the target's default symbol decoration scheme.

compiler/rustc_codegen_ssa/src/mir/block.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -835,7 +835,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
835835

836836
let def = instance.map(|i| i.def);
837837

838-
if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
838+
if let Some(
839+
ty::InstanceDef::DropGlue(_, None) | ty::InstanceDef::AsyncDropGlueCtorShim(_, None),
840+
) = def
841+
{
839842
// Empty drop glue; a no-op.
840843
let target = target.unwrap();
841844
return helper.funclet_br(self, bx, target, mergeable_succ);

compiler/rustc_const_eval/src/interpret/terminator.rs

+1
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
558558
| ty::InstanceDef::CloneShim(..)
559559
| ty::InstanceDef::FnPtrAddrShim(..)
560560
| ty::InstanceDef::ThreadLocalShim(..)
561+
| ty::InstanceDef::AsyncDropGlueCtorShim(..)
561562
| ty::InstanceDef::Item(_) => {
562563
// We need MIR for this fn
563564
let Some((body, instance)) = M::find_mir_or_eval_fn(

compiler/rustc_hir/src/lang_items.rs

+13
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,18 @@ language_item_table! {
162162
Drop, sym::drop, drop_trait, Target::Trait, GenericRequirement::None;
163163
Destruct, sym::destruct, destruct_trait, Target::Trait, GenericRequirement::None;
164164

165+
AsyncDrop, sym::async_drop, async_drop_trait, Target::Trait, GenericRequirement::Exact(0);
166+
AsyncDestruct, sym::async_destruct, async_destruct_trait, Target::Trait, GenericRequirement::Exact(0);
167+
AsyncDropInPlace, sym::async_drop_in_place, async_drop_in_place_fn, Target::Fn, GenericRequirement::Exact(1);
168+
SurfaceAsyncDropInPlace, sym::surface_async_drop_in_place, surface_async_drop_in_place_fn, Target::Fn, GenericRequirement::Exact(1);
169+
AsyncDropSurfaceDropInPlace, sym::async_drop_surface_drop_in_place, async_drop_surface_drop_in_place_fn, Target::Fn, GenericRequirement::Exact(1);
170+
AsyncDropSlice, sym::async_drop_slice, async_drop_slice_fn, Target::Fn, GenericRequirement::Exact(1);
171+
AsyncDropChain, sym::async_drop_chain, async_drop_chain_fn, Target::Fn, GenericRequirement::Exact(2);
172+
AsyncDropNoop, sym::async_drop_noop, async_drop_noop_fn, Target::Fn, GenericRequirement::Exact(0);
173+
AsyncDropFuse, sym::async_drop_fuse, async_drop_fuse_fn, Target::Fn, GenericRequirement::Exact(1);
174+
AsyncDropDefer, sym::async_drop_defer, async_drop_defer_fn, Target::Fn, GenericRequirement::Exact(1);
175+
AsyncDropEither, sym::async_drop_either, async_drop_either_fn, Target::Fn, GenericRequirement::Exact(3);
176+
165177
CoerceUnsized, sym::coerce_unsized, coerce_unsized_trait, Target::Trait, GenericRequirement::Minimum(1);
166178
DispatchFromDyn, sym::dispatch_from_dyn, dispatch_from_dyn_trait, Target::Trait, GenericRequirement::Minimum(1);
167179

@@ -281,6 +293,7 @@ language_item_table! {
281293

282294
ExchangeMalloc, sym::exchange_malloc, exchange_malloc_fn, Target::Fn, GenericRequirement::None;
283295
DropInPlace, sym::drop_in_place, drop_in_place_fn, Target::Fn, GenericRequirement::Minimum(1);
296+
FallbackSurfaceDrop, sym::fallback_surface_drop, fallback_surface_drop_fn, Target::Fn, GenericRequirement::None;
284297
AllocLayout, sym::alloc_layout, alloc_layout, Target::Struct, GenericRequirement::None;
285298

286299
Start, sym::start, start_fn, Target::Fn, GenericRequirement::Exact(1);

compiler/rustc_hir_typeck/src/callee.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,11 @@ pub fn check_legal_trait_for_method_call(
3838
receiver: Option<Span>,
3939
expr_span: Span,
4040
trait_id: DefId,
41+
body_id: DefId,
4142
) -> Result<(), ErrorGuaranteed> {
42-
if tcx.lang_items().drop_trait() == Some(trait_id) {
43+
if tcx.lang_items().drop_trait() == Some(trait_id)
44+
&& tcx.lang_items().fallback_surface_drop_fn() != Some(body_id)
45+
{
4346
let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
4447
errors::ExplicitDestructorCallSugg::Snippet {
4548
lo: expr_span.shrink_to_lo(),

compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
11311131
None,
11321132
span,
11331133
container_id,
1134+
self.body_id.to_def_id(),
11341135
) {
11351136
self.set_tainted_by_errors(e);
11361137
}

compiler/rustc_hir_typeck/src/method/confirm.rs

+1
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
628628
Some(self.self_expr.span),
629629
self.call_expr.span,
630630
trait_def_id,
631+
self.body_id.to_def_id(),
631632
) {
632633
self.set_tainted_by_errors(e);
633634
}

compiler/rustc_middle/src/middle/exported_symbols.rs

+4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ pub enum ExportedSymbol<'tcx> {
4343
NonGeneric(DefId),
4444
Generic(DefId, GenericArgsRef<'tcx>),
4545
DropGlue(Ty<'tcx>),
46+
AsyncDropGlueCtorShim(Ty<'tcx>),
4647
ThreadLocalShim(DefId),
4748
NoDefId(ty::SymbolName<'tcx>),
4849
}
@@ -59,6 +60,9 @@ impl<'tcx> ExportedSymbol<'tcx> {
5960
ExportedSymbol::DropGlue(ty) => {
6061
tcx.symbol_name(ty::Instance::resolve_drop_in_place(tcx, ty))
6162
}
63+
ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
64+
tcx.symbol_name(ty::Instance::resolve_async_drop_in_place(tcx, ty))
65+
}
6266
ExportedSymbol::ThreadLocalShim(def_id) => tcx.symbol_name(ty::Instance {
6367
def: ty::InstanceDef::ThreadLocalShim(def_id),
6468
args: ty::GenericArgs::empty(),

compiler/rustc_middle/src/mir/mono.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ impl<'tcx> MonoItem<'tcx> {
6565
match instance.def {
6666
// "Normal" functions size estimate: the number of
6767
// statements, plus one for the terminator.
68-
InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
68+
InstanceDef::Item(..)
69+
| InstanceDef::DropGlue(..)
70+
| InstanceDef::AsyncDropGlueCtorShim(..) => {
6971
let mir = tcx.instance_mir(instance.def);
7072
mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
7173
}
@@ -406,7 +408,8 @@ impl<'tcx> CodegenUnit<'tcx> {
406408
| InstanceDef::DropGlue(..)
407409
| InstanceDef::CloneShim(..)
408410
| InstanceDef::ThreadLocalShim(..)
409-
| InstanceDef::FnPtrAddrShim(..) => None,
411+
| InstanceDef::FnPtrAddrShim(..)
412+
| InstanceDef::AsyncDropGlueCtorShim(..) => None,
410413
}
411414
}
412415
MonoItem::Static(def_id) => def_id.as_local().map(Idx::index),

compiler/rustc_middle/src/mir/pretty.rs

+11
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,17 @@ fn dump_path<'tcx>(
187187
}));
188188
s
189189
}
190+
ty::InstanceDef::AsyncDropGlueCtorShim(_, Some(ty)) => {
191+
// Unfortunately, pretty-printed typed are not very filename-friendly.
192+
// We dome some filtering.
193+
let mut s = ".".to_owned();
194+
s.extend(ty.to_string().chars().filter_map(|c| match c {
195+
' ' => None,
196+
':' | '<' | '>' => Some('_'),
197+
c => Some(c),
198+
}));
199+
s
200+
}
190201
_ => String::new(),
191202
};
192203

compiler/rustc_middle/src/mir/visit.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -350,12 +350,14 @@ macro_rules! make_mir_visitor {
350350
receiver_by_ref: _,
351351
} |
352352
ty::InstanceDef::CoroutineKindShim { coroutine_def_id: _def_id } |
353+
ty::InstanceDef::AsyncDropGlueCtorShim(_def_id, None) |
353354
ty::InstanceDef::DropGlue(_def_id, None) => {}
354355

355356
ty::InstanceDef::FnPtrShim(_def_id, ty) |
356357
ty::InstanceDef::DropGlue(_def_id, Some(ty)) |
357358
ty::InstanceDef::CloneShim(_def_id, ty) |
358-
ty::InstanceDef::FnPtrAddrShim(_def_id, ty) => {
359+
ty::InstanceDef::FnPtrAddrShim(_def_id, ty) |
360+
ty::InstanceDef::AsyncDropGlueCtorShim(_def_id, Some(ty)) => {
359361
// FIXME(eddyb) use a better `TyContext` here.
360362
self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
361363
}

compiler/rustc_middle/src/query/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1344,6 +1344,14 @@ rustc_queries! {
13441344
query is_unpin_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
13451345
desc { "computing whether `{}` is `Unpin`", env.value }
13461346
}
1347+
/// Query backing `Ty::has_surface_async_drop`.
1348+
query has_surface_async_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
1349+
desc { "computing whether `{}` has `AsyncDrop` implementation", env.value }
1350+
}
1351+
/// Query backing `Ty::has_surface_drop`.
1352+
query has_surface_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
1353+
desc { "computing whether `{}` has `Drop` implementation", env.value }
1354+
}
13471355
/// Query backing `Ty::needs_drop`.
13481356
query needs_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
13491357
desc { "computing whether `{}` needs drop", env.value }

compiler/rustc_middle/src/ty/instance.rs

+26-6
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,12 @@ pub enum InstanceDef<'tcx> {
168168
///
169169
/// The `DefId` is for `FnPtr::addr`, the `Ty` is the type `T`.
170170
FnPtrAddrShim(DefId, Ty<'tcx>),
171+
172+
/// `core::future::async_drop::async_drop_in_place::<'_, T>`.
173+
///
174+
/// The `DefId` is for `core::future::async_drop::async_drop_in_place`, the `Ty`
175+
/// is the type `T`.
176+
AsyncDropGlueCtorShim(DefId, Option<Ty<'tcx>>),
171177
}
172178

173179
impl<'tcx> Instance<'tcx> {
@@ -210,7 +216,9 @@ impl<'tcx> Instance<'tcx> {
210216
InstanceDef::Item(def) => tcx
211217
.upstream_monomorphizations_for(def)
212218
.and_then(|monos| monos.get(&self.args).cloned()),
213-
InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.args),
219+
InstanceDef::DropGlue(_, Some(_)) | InstanceDef::AsyncDropGlueCtorShim(_, _) => {
220+
tcx.upstream_drop_glue_for(self.args)
221+
}
214222
_ => None,
215223
}
216224
}
@@ -235,17 +243,18 @@ impl<'tcx> InstanceDef<'tcx> {
235243
| ty::InstanceDef::CoroutineKindShim { coroutine_def_id: def_id }
236244
| InstanceDef::DropGlue(def_id, _)
237245
| InstanceDef::CloneShim(def_id, _)
238-
| InstanceDef::FnPtrAddrShim(def_id, _) => def_id,
246+
| InstanceDef::FnPtrAddrShim(def_id, _)
247+
| InstanceDef::AsyncDropGlueCtorShim(def_id, _) => def_id,
239248
}
240249
}
241250

242251
/// Returns the `DefId` of instances which might not require codegen locally.
243252
pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
244253
match self {
245254
ty::InstanceDef::Item(def) => Some(def),
246-
ty::InstanceDef::DropGlue(def_id, Some(_)) | InstanceDef::ThreadLocalShim(def_id) => {
247-
Some(def_id)
248-
}
255+
ty::InstanceDef::DropGlue(def_id, Some(_))
256+
| InstanceDef::AsyncDropGlueCtorShim(def_id, _)
257+
| InstanceDef::ThreadLocalShim(def_id) => Some(def_id),
249258
InstanceDef::VTableShim(..)
250259
| InstanceDef::ReifyShim(..)
251260
| InstanceDef::FnPtrShim(..)
@@ -279,6 +288,7 @@ impl<'tcx> InstanceDef<'tcx> {
279288
let def_id = match *self {
280289
ty::InstanceDef::Item(def) => def,
281290
ty::InstanceDef::DropGlue(_, Some(_)) => return false,
291+
ty::InstanceDef::AsyncDropGlueCtorShim(_, Some(_)) => return false,
282292
ty::InstanceDef::ThreadLocalShim(_) => return false,
283293
_ => return true,
284294
};
@@ -347,11 +357,13 @@ impl<'tcx> InstanceDef<'tcx> {
347357
| InstanceDef::ThreadLocalShim(..)
348358
| InstanceDef::FnPtrAddrShim(..)
349359
| InstanceDef::FnPtrShim(..)
350-
| InstanceDef::DropGlue(_, Some(_)) => false,
360+
| InstanceDef::DropGlue(_, Some(_))
361+
| InstanceDef::AsyncDropGlueCtorShim(_, Some(_)) => false,
351362
InstanceDef::ClosureOnceShim { .. }
352363
| InstanceDef::ConstructCoroutineInClosureShim { .. }
353364
| InstanceDef::CoroutineKindShim { .. }
354365
| InstanceDef::DropGlue(..)
366+
| InstanceDef::AsyncDropGlueCtorShim(..)
355367
| InstanceDef::Item(_)
356368
| InstanceDef::Intrinsic(..)
357369
| InstanceDef::ReifyShim(..)
@@ -396,6 +408,8 @@ fn fmt_instance(
396408
InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"),
397409
InstanceDef::CloneShim(_, ty) => write!(f, " - shim({ty})"),
398410
InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({ty})"),
411+
InstanceDef::AsyncDropGlueCtorShim(_, None) => write!(f, " - shim(None)"),
412+
InstanceDef::AsyncDropGlueCtorShim(_, Some(ty)) => write!(f, " - shim(Some({ty}))"),
399413
}
400414
}
401415

@@ -638,6 +652,12 @@ impl<'tcx> Instance<'tcx> {
638652
Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, args)
639653
}
640654

655+
pub fn resolve_async_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
656+
let def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, None);
657+
let args = tcx.mk_args(&[ty.into()]);
658+
Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, args)
659+
}
660+
641661
#[instrument(level = "debug", skip(tcx), ret)]
642662
pub fn fn_once_adapter_instance(
643663
tcx: TyCtxt<'tcx>,

compiler/rustc_middle/src/ty/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1797,7 +1797,8 @@ impl<'tcx> TyCtxt<'tcx> {
17971797
| ty::InstanceDef::DropGlue(..)
17981798
| ty::InstanceDef::CloneShim(..)
17991799
| ty::InstanceDef::ThreadLocalShim(..)
1800-
| ty::InstanceDef::FnPtrAddrShim(..) => self.mir_shims(instance),
1800+
| ty::InstanceDef::FnPtrAddrShim(..)
1801+
| ty::InstanceDef::AsyncDropGlueCtorShim(..) => self.mir_shims(instance),
18011802
}
18021803
}
18031804

0 commit comments

Comments
 (0)