1//! Mono Item Collection
2//! ====================
3//!
4//! This module is responsible for discovering all items that will contribute
5//! to code generation of the crate. The important part here is that it not only
6//! needs to find syntax-level items (functions, structs, etc) but also all
7//! their monomorphized instantiations. Every non-generic, non-const function
8//! maps to one LLVM artifact. Every generic function can produce
9//! from zero to N artifacts, depending on the sets of type arguments it
10//! is instantiated with.
11//! This also applies to generic items from other crates: A generic definition
12//! in crate X might produce monomorphizations that are compiled into crate Y.
13//! We also have to collect these here.
14//!
15//! The following kinds of "mono items" are handled here:
16//!
17//! - Functions
18//! - Methods
19//! - Closures
20//! - Statics
21//! - Drop glue
22//!
23//! The following things also result in LLVM artifacts, but are not collected
24//! here, since we instantiate them locally on demand when needed in a given
25//! codegen unit:
26//!
27//! - Constants
28//! - VTables
29//! - Object Shims
30//!
31//! The main entry point is `collect_crate_mono_items`, at the bottom of this file.
32//!
33//! General Algorithm
34//! -----------------
35//! Let's define some terms first:
36//!
37//! - A "mono item" is something that results in a function or global in
38//! the LLVM IR of a codegen unit. Mono items do not stand on their
39//! own, they can use other mono items. For example, if function
40//! `foo()` calls function `bar()` then the mono item for `foo()`
41//! uses the mono item for function `bar()`. In general, the
42//! definition for mono item A using a mono item B is that
43//! the LLVM artifact produced for A uses the LLVM artifact produced
44//! for B.
45//!
46//! - Mono items and the uses between them form a directed graph,
47//! where the mono items are the nodes and uses form the edges.
48//! Let's call this graph the "mono item graph".
49//!
50//! - The mono item graph for a program contains all mono items
51//! that are needed in order to produce the complete LLVM IR of the program.
52//!
53//! The purpose of the algorithm implemented in this module is to build the
54//! mono item graph for the current crate. It runs in two phases:
55//!
56//! 1. Discover the roots of the graph by traversing the HIR of the crate.
57//! 2. Starting from the roots, find uses by inspecting the MIR
58//! representation of the item corresponding to a given node, until no more
59//! new nodes are found.
60//!
61//! ### Discovering roots
62//! The roots of the mono item graph correspond to the public non-generic
63//! syntactic items in the source code. We find them by walking the HIR of the
64//! crate, and whenever we hit upon a public function, method, or static item,
65//! we create a mono item consisting of the items DefId and, since we only
66//! consider non-generic items, an empty type-parameters set. (In eager
67//! collection mode, during incremental compilation, all non-generic functions
68//! are considered as roots, as well as when the `-Clink-dead-code` option is
69//! specified. Functions marked `#[no_mangle]` and functions called by inlinable
70//! functions also always act as roots.)
71//!
72//! ### Finding uses
73//! Given a mono item node, we can discover uses by inspecting its MIR. We walk
74//! the MIR to find other mono items used by each mono item. Since the mono
75//! item we are currently at is always monomorphic, we also know the concrete
76//! type arguments of its used mono items. The specific forms a use can take in
77//! MIR are quite diverse. Here is an overview:
78//!
79//! #### Calling Functions/Methods
80//! The most obvious way for one mono item to use another is a
81//! function or method call (represented by a CALL terminator in MIR). But
82//! calls are not the only thing that might introduce a use between two
83//! function mono items, and as we will see below, they are just a
84//! specialization of the form described next, and consequently will not get any
85//! special treatment in the algorithm.
86//!
87//! #### Taking a reference to a function or method
88//! A function does not need to actually be called in order to be used by
89//! another function. It suffices to just take a reference in order to introduce
90//! an edge. Consider the following example:
91//!
92//! ```
93//! # use core::fmt::Display;
94//! fn print_val<T: Display>(x: T) {
95//! println!("{}", x);
96//! }
97//!
98//! fn call_fn(f: &dyn Fn(i32), x: i32) {
99//! f(x);
100//! }
101//!
102//! fn main() {
103//! let print_i32 = print_val::<i32>;
104//! call_fn(&print_i32, 0);
105//! }
106//! ```
107//! The MIR of none of these functions will contain an explicit call to
108//! `print_val::<i32>`. Nonetheless, in order to mono this program, we need
109//! an instance of this function. Thus, whenever we encounter a function or
110//! method in operand position, we treat it as a use of the current
111//! mono item. Calls are just a special case of that.
112//!
113//! #### Drop glue
114//! Drop glue mono items are introduced by MIR drop-statements. The
115//! generated mono item will have additional drop-glue item uses if the
116//! type to be dropped contains nested values that also need to be dropped. It
117//! might also have a function item use for the explicit `Drop::drop`
118//! implementation of its type.
119//!
120//! #### Unsizing Casts
121//! A subtle way of introducing use edges is by casting to a trait object.
122//! Since the resulting wide-pointer contains a reference to a vtable, we need to
123//! instantiate all dyn-compatible methods of the trait, as we need to store
124//! pointers to these functions even if they never get called anywhere. This can
125//! be seen as a special case of taking a function reference.
126//!
127//!
128//! Interaction with Cross-Crate Inlining
129//! -------------------------------------
130//! The binary of a crate will not only contain machine code for the items
131//! defined in the source code of that crate. It will also contain monomorphic
132//! instantiations of any extern generic functions and of functions marked with
133//! `#[inline]`.
134//! The collection algorithm handles this more or less mono. If it is
135//! about to create a mono item for something with an external `DefId`,
136//! it will take a look if the MIR for that item is available, and if so just
137//! proceed normally. If the MIR is not available, it assumes that the item is
138//! just linked to and no node is created; which is exactly what we want, since
139//! no machine code should be generated in the current crate for such an item.
140//!
141//! Eager and Lazy Collection Strategy
142//! ----------------------------------
143//! Mono item collection can be performed with one of two strategies:
144//!
145//! - Lazy strategy means that items will only be instantiated when actually
146//! used. The goal is to produce the least amount of machine code
147//! possible.
148//!
149//! - Eager strategy is meant to be used in conjunction with incremental compilation
150//! where a stable set of mono items is more important than a minimal
151//! one. Thus, eager strategy will instantiate drop-glue for every drop-able type
152//! in the crate, even if no drop call for that type exists (yet). It will
153//! also instantiate default implementations of trait methods, something that
154//! otherwise is only done on demand.
155//!
156//! Collection-time const evaluation and "mentioned" items
157//! ------------------------------------------------------
158//!
159//! One important role of collection is to evaluate all constants that are used by all the items
160//! which are being collected. Codegen can then rely on only encountering constants that evaluate
161//! successfully, and if a constant fails to evaluate, the collector has much better context to be
162//! able to show where this constant comes up.
163//!
164//! However, the exact set of "used" items (collected as described above), and therefore the exact
165//! set of used constants, can depend on optimizations. Optimizing away dead code may optimize away
166//! a function call that uses a failing constant, so an unoptimized build may fail where an
167//! optimized build succeeds. This is undesirable.
168//!
169//! To avoid this, the collector has the concept of "mentioned" items. Some time during the MIR
170//! pipeline, before any optimization-level-dependent optimizations, we compute a list of all items
171//! that syntactically appear in the code. These are considered "mentioned", and even if they are in
172//! dead code and get optimized away (which makes them no longer "used"), they are still
173//! "mentioned". For every used item, the collector ensures that all mentioned items, recursively,
174//! do not use a failing constant. This is reflected via the [`CollectionMode`], which determines
175//! whether we are visiting a used item or merely a mentioned item.
176//!
177//! The collector and "mentioned items" gathering (which lives in `rustc_mir_transform::mentioned_items`)
178//! need to stay in sync in the following sense:
179//!
180//! - For every item that the collector gather that could eventually lead to build failure (most
181//! likely due to containing a constant that fails to evaluate), a corresponding mentioned item
182//! must be added. This should use the exact same strategy as the ecollector to make sure they are
183//! in sync. However, while the collector works on monomorphized types, mentioned items are
184//! collected on generic MIR -- so any time the collector checks for a particular type (such as
185//! `ty::FnDef`), we have to just onconditionally add this as a mentioned item.
186//! - In `visit_mentioned_item`, we then do with that mentioned item exactly what the collector
187//! would have done during regular MIR visiting. Basically you can think of the collector having
188//! two stages, a pre-monomorphization stage and a post-monomorphization stage (usually quite
189//! literally separated by a call to `self.monomorphize`); the pre-monomorphizationn stage is
190//! duplicated in mentioned items gathering and the post-monomorphization stage is duplicated in
191//! `visit_mentioned_item`.
192//! - Finally, as a performance optimization, the collector should fill `used_mentioned_item` during
193//! its MIR traversal with exactly what mentioned item gathering would have added in the same
194//! situation. This detects mentioned items that have *not* been optimized away and hence don't
195//! need a dedicated traversal.
196//!
197//! Open Issues
198//! -----------
199//! Some things are not yet fully implemented in the current version of this
200//! module.
201//!
202//! ### Const Fns
203//! Ideally, no mono item should be generated for const fns unless there
204//! is a call to them that cannot be evaluated at compile time. At the moment
205//! this is not implemented however: a mono item will be produced
206//! regardless of whether it is actually needed or not.
207208use std::cell::OnceCell;
209use std::ops::ControlFlow;
210211use rustc_data_structures::fx::FxIndexMap;
212use rustc_data_structures::sync::{Lock, par_for_each_in};
213use rustc_data_structures::unord::{UnordMap, UnordSet};
214use rustc_hiras hir;
215use rustc_hir::attrs::InlineAttr;
216use rustc_hir::def::DefKind;
217use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
218use rustc_hir::lang_items::LangItem;
219use rustc_hir::limit::Limit;
220use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
221use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar};
222use rustc_middle::mir::mono::{
223CollectionMode, InstantiationMode, MonoItem, NormalizationErrorInMono,
224};
225use rustc_middle::mir::visit::Visitoras MirVisitor;
226use rustc_middle::mir::{self, Body, Location, MentionedItem, traversal};
227use rustc_middle::query::TyCtxtAt;
228use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion};
229use rustc_middle::ty::layout::ValidityRequirement;
230use rustc_middle::ty::{
231self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Ty, TyCtxt, TypeFoldable,
232TypeVisitable, TypeVisitableExt, TypeVisitor, VtblEntry,
233};
234use rustc_middle::util::Providers;
235use rustc_middle::{bug, span_bug};
236use rustc_session::config::{DebugInfo, EntryFnType};
237use rustc_span::{DUMMY_SP, Span, Spanned, dummy_spanned, respan};
238use tracing::{debug, instrument, trace};
239240use crate::errors::{
241self, EncounteredErrorWhileInstantiating, EncounteredErrorWhileInstantiatingGlobalAsm,
242NoOptimizedMir, RecursionLimit,
243};
244245#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MonoItemCollectionStrategy {
#[inline]
fn eq(&self, other: &MonoItemCollectionStrategy) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
246pub(crate) enum MonoItemCollectionStrategy {
247 Eager,
248 Lazy,
249}
250251/// The state that is shared across the concurrent threads that are doing collection.
252struct SharedState<'tcx> {
253/// Items that have been or are currently being recursively collected.
254visited: Lock<UnordSet<MonoItem<'tcx>>>,
255/// Items that have been or are currently being recursively treated as "mentioned", i.e., their
256 /// consts are evaluated but nothing is added to the collection.
257mentioned: Lock<UnordSet<MonoItem<'tcx>>>,
258/// Which items are being used where, for better errors.
259usage_map: Lock<UsageMap<'tcx>>,
260}
261262pub(crate) struct UsageMap<'tcx> {
263// Maps every mono item to the mono items used by it.
264pub used_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
265266// Maps each mono item with users to the mono items that use it.
267 // Be careful: subsets `used_map`, so unused items are vacant.
268user_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
269}
270271impl<'tcx> UsageMap<'tcx> {
272fn new() -> UsageMap<'tcx> {
273UsageMap { used_map: Default::default(), user_map: Default::default() }
274 }
275276fn record_used<'a>(&mut self, user_item: MonoItem<'tcx>, used_items: &'a MonoItems<'tcx>)
277where
278'tcx: 'a,
279 {
280for used_item in used_items.items() {
281self.user_map.entry(used_item).or_default().push(user_item);
282 }
283284if !self.used_map.insert(user_item, used_items.items().collect()).is_none() {
::core::panicking::panic("assertion failed: self.used_map.insert(user_item, used_items.items().collect()).is_none()")
};assert!(self.used_map.insert(user_item, used_items.items().collect()).is_none());
285 }
286287pub(crate) fn get_user_items(&self, item: MonoItem<'tcx>) -> &[MonoItem<'tcx>] {
288self.user_map.get(&item).map(|items| items.as_slice()).unwrap_or(&[])
289 }
290291/// Internally iterate over all inlined items used by `item`.
292pub(crate) fn for_each_inlined_used_item<F>(
293&self,
294 tcx: TyCtxt<'tcx>,
295 item: MonoItem<'tcx>,
296mut f: F,
297 ) where
298F: FnMut(MonoItem<'tcx>),
299 {
300let used_items = self.used_map.get(&item).unwrap();
301for used_item in used_items.iter() {
302let is_inlined = used_item.instantiation_mode(tcx) == InstantiationMode::LocalCopy;
303if is_inlined {
304 f(*used_item);
305 }
306 }
307 }
308}
309310struct MonoItems<'tcx> {
311// We want a set of MonoItem + Span where trying to re-insert a MonoItem with a different Span
312 // is ignored. Map does that, but it looks odd.
313items: FxIndexMap<MonoItem<'tcx>, Span>,
314}
315316impl<'tcx> MonoItems<'tcx> {
317fn new() -> Self {
318Self { items: FxIndexMap::default() }
319 }
320321fn is_empty(&self) -> bool {
322self.items.is_empty()
323 }
324325fn push(&mut self, item: Spanned<MonoItem<'tcx>>) {
326// Insert only if the entry does not exist. A normal insert would stomp the first span that
327 // got inserted.
328self.items.entry(item.node).or_insert(item.span);
329 }
330331fn items(&self) -> impl Iterator<Item = MonoItem<'tcx>> {
332self.items.keys().cloned()
333 }
334}
335336impl<'tcx> IntoIteratorfor MonoItems<'tcx> {
337type Item = Spanned<MonoItem<'tcx>>;
338type IntoIter = impl Iterator<Item = Spanned<MonoItem<'tcx>>>;
339340fn into_iter(self) -> Self::IntoIter {
341self.items.into_iter().map(|(item, span)| respan(span, item))
342 }
343}
344345impl<'tcx> Extend<Spanned<MonoItem<'tcx>>> for MonoItems<'tcx> {
346fn extend<I>(&mut self, iter: I)
347where
348I: IntoIterator<Item = Spanned<MonoItem<'tcx>>>,
349 {
350for item in iter {
351self.push(item)
352 }
353 }
354}
355356fn collect_items_root<'tcx>(
357 tcx: TyCtxt<'tcx>,
358 starting_item: Spanned<MonoItem<'tcx>>,
359 state: &SharedState<'tcx>,
360 recursion_limit: Limit,
361) {
362if !state.visited.lock().insert(starting_item.node) {
363// We've been here already, no need to search again.
364return;
365 }
366let mut recursion_depths = DefIdMap::default();
367collect_items_rec(
368tcx,
369starting_item,
370state,
371&mut recursion_depths,
372recursion_limit,
373 CollectionMode::UsedItems,
374 );
375}
376377/// Collect all monomorphized items reachable from `starting_point`, and emit a note diagnostic if a
378/// post-monomorphization error is encountered during a collection step.
379///
380/// `mode` determined whether we are scanning for [used items][CollectionMode::UsedItems]
381/// or [mentioned items][CollectionMode::MentionedItems].
382#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("collect_items_rec",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(382u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["starting_item",
"mode"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&starting_item)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let mut used_items = MonoItems::new();
let mut mentioned_items = MonoItems::new();
let recursion_depth_reset;
let error_count = tcx.dcx().err_count();
match starting_item.node {
MonoItem::Static(def_id) => {
recursion_depth_reset = None;
if mode == CollectionMode::UsedItems {
let instance = Instance::mono(tcx, def_id);
if true {
if !tcx.should_codegen_locally(instance) {
::core::panicking::panic("assertion failed: tcx.should_codegen_locally(instance)")
};
};
let DefKind::Static { nested, .. } =
tcx.def_kind(def_id) else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
if !nested {
let ty =
instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
visit_drop_use(tcx, ty, true, starting_item.span,
&mut used_items);
}
if let Ok(alloc) = tcx.eval_static_initializer(def_id) {
for &prov in alloc.inner().provenance().ptrs().values() {
collect_alloc(tcx, prov.alloc_id(), &mut used_items);
}
}
if tcx.needs_thread_local_shim(def_id) {
used_items.push(respan(starting_item.span,
MonoItem::Fn(Instance {
def: InstanceKind::ThreadLocalShim(def_id),
args: GenericArgs::empty(),
})));
}
}
}
MonoItem::Fn(instance) => {
if true {
if !tcx.should_codegen_locally(instance) {
::core::panicking::panic("assertion failed: tcx.should_codegen_locally(instance)")
};
};
recursion_depth_reset =
Some(check_recursion_limit(tcx, instance,
starting_item.span, recursion_depths, recursion_limit));
rustc_data_structures::stack::ensure_sufficient_stack(||
{
let Ok((used, mentioned)) =
tcx.items_of_instance((instance,
mode)) else {
let def_id = instance.def_id();
let def_span = tcx.def_span(def_id);
let def_path_str = tcx.def_path_str(def_id);
tcx.dcx().emit_fatal(RecursionLimit {
span: starting_item.span,
instance,
def_span,
def_path_str,
});
};
used_items.extend(used.into_iter().copied());
mentioned_items.extend(mentioned.into_iter().copied());
});
}
MonoItem::GlobalAsm(item_id) => {
if !(mode == CollectionMode::UsedItems) {
{
::core::panicking::panic_fmt(format_args!("should never encounter global_asm when collecting mentioned items"));
}
};
recursion_depth_reset = None;
let item = tcx.hir_item(item_id);
if let hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
for (op, op_sp) in asm.operands {
match *op {
hir::InlineAsmOperand::Const { .. } => {}
hir::InlineAsmOperand::SymFn { expr } => {
let fn_ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
visit_fn_use(tcx, fn_ty, false, *op_sp, &mut used_items);
}
hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
let instance = Instance::mono(tcx, def_id);
if tcx.should_codegen_locally(instance) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:520",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(520u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting static {0:?}",
def_id) as &dyn Value))])
});
} else { ; }
};
used_items.push(dummy_spanned(MonoItem::Static(def_id)));
}
}
hir::InlineAsmOperand::In { .. } |
hir::InlineAsmOperand::Out { .. } |
hir::InlineAsmOperand::InOut { .. } |
hir::InlineAsmOperand::SplitInOut { .. } |
hir::InlineAsmOperand::Label { .. } => {
::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("invalid operand type for global_asm!"))
}
}
}
} else {
::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("Mismatch between hir::Item type and MonoItem type"))
}
}
};
if tcx.dcx().err_count() > error_count &&
starting_item.node.is_generic_fn() &&
starting_item.node.is_user_defined() {
match starting_item.node {
MonoItem::Fn(instance) =>
tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
span: starting_item.span,
kind: "fn",
instance,
}),
MonoItem::Static(def_id) =>
tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
span: starting_item.span,
kind: "static",
instance: Instance::new_raw(def_id, GenericArgs::empty()),
}),
MonoItem::GlobalAsm(_) => {
tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
span: starting_item.span,
})
}
}
}
if mode == CollectionMode::UsedItems {
state.usage_map.lock().record_used(starting_item.node,
&used_items);
}
{
let mut visited = OnceCell::default();
if mode == CollectionMode::UsedItems {
used_items.items.retain(|k, _|
visited.get_mut_or_init(||
state.visited.lock()).insert(*k));
}
let mut mentioned = OnceCell::default();
mentioned_items.items.retain(|k, _|
{
!visited.get_or_init(|| state.visited.lock()).contains(k) &&
mentioned.get_mut_or_init(||
state.mentioned.lock()).insert(*k)
});
}
if mode == CollectionMode::MentionedItems {
if !used_items.is_empty() {
{
::core::panicking::panic_fmt(format_args!("\'mentioned\' collection should never encounter used items"));
}
};
} else {
for used_item in used_items {
collect_items_rec(tcx, used_item, state, recursion_depths,
recursion_limit, CollectionMode::UsedItems);
}
}
for mentioned_item in mentioned_items {
collect_items_rec(tcx, mentioned_item, state,
recursion_depths, recursion_limit,
CollectionMode::MentionedItems);
}
if let Some((def_id, depth)) = recursion_depth_reset {
recursion_depths.insert(def_id, depth);
}
}
}
}#[instrument(skip(tcx, state, recursion_depths, recursion_limit), level = "debug")]383fn collect_items_rec<'tcx>(
384 tcx: TyCtxt<'tcx>,
385 starting_item: Spanned<MonoItem<'tcx>>,
386 state: &SharedState<'tcx>,
387 recursion_depths: &mut DefIdMap<usize>,
388 recursion_limit: Limit,
389 mode: CollectionMode,
390) {
391let mut used_items = MonoItems::new();
392let mut mentioned_items = MonoItems::new();
393let recursion_depth_reset;
394395// Post-monomorphization errors MVP
396 //
397 // We can encounter errors while monomorphizing an item, but we don't have a good way of
398 // showing a complete stack of spans ultimately leading to collecting the erroneous one yet.
399 // (It's also currently unclear exactly which diagnostics and information would be interesting
400 // to report in such cases)
401 //
402 // This leads to suboptimal error reporting: a post-monomorphization error (PME) will be
403 // shown with just a spanned piece of code causing the error, without information on where
404 // it was called from. This is especially obscure if the erroneous mono item is in a
405 // dependency. See for example issue #85155, where, before minimization, a PME happened two
406 // crates downstream from libcore's stdarch, without a way to know which dependency was the
407 // cause.
408 //
409 // If such an error occurs in the current crate, its span will be enough to locate the
410 // source. If the cause is in another crate, the goal here is to quickly locate which mono
411 // item in the current crate is ultimately responsible for causing the error.
412 //
413 // To give at least _some_ context to the user: while collecting mono items, we check the
414 // error count. If it has changed, a PME occurred, and we trigger some diagnostics about the
415 // current step of mono items collection.
416 //
417 // FIXME: don't rely on global state, instead bubble up errors. Note: this is very hard to do.
418let error_count = tcx.dcx().err_count();
419420// In `mentioned_items` we collect items that were mentioned in this MIR but possibly do not
421 // need to be monomorphized. This is done to ensure that optimizing away function calls does not
422 // hide const-eval errors that those calls would otherwise have triggered.
423match starting_item.node {
424 MonoItem::Static(def_id) => {
425 recursion_depth_reset = None;
426427// Statics always get evaluated (which is possible because they can't be generic), so for
428 // `MentionedItems` collection there's nothing to do here.
429if mode == CollectionMode::UsedItems {
430let instance = Instance::mono(tcx, def_id);
431432// Sanity check whether this ended up being collected accidentally
433debug_assert!(tcx.should_codegen_locally(instance));
434435let DefKind::Static { nested, .. } = tcx.def_kind(def_id) else { bug!() };
436// Nested statics have no type.
437if !nested {
438let ty = instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
439 visit_drop_use(tcx, ty, true, starting_item.span, &mut used_items);
440 }
441442if let Ok(alloc) = tcx.eval_static_initializer(def_id) {
443for &prov in alloc.inner().provenance().ptrs().values() {
444 collect_alloc(tcx, prov.alloc_id(), &mut used_items);
445 }
446 }
447448if tcx.needs_thread_local_shim(def_id) {
449 used_items.push(respan(
450 starting_item.span,
451 MonoItem::Fn(Instance {
452 def: InstanceKind::ThreadLocalShim(def_id),
453 args: GenericArgs::empty(),
454 }),
455 ));
456 }
457 }
458459// mentioned_items stays empty since there's no codegen for statics. statics don't get
460 // optimized, and if they did then the const-eval interpreter would have to worry about
461 // mentioned_items.
462}
463 MonoItem::Fn(instance) => {
464// Sanity check whether this ended up being collected accidentally
465debug_assert!(tcx.should_codegen_locally(instance));
466467// Keep track of the monomorphization recursion depth
468recursion_depth_reset = Some(check_recursion_limit(
469 tcx,
470 instance,
471 starting_item.span,
472 recursion_depths,
473 recursion_limit,
474 ));
475476 rustc_data_structures::stack::ensure_sufficient_stack(|| {
477let Ok((used, mentioned)) = tcx.items_of_instance((instance, mode)) else {
478// Normalization errors here are usually due to trait solving overflow.
479 // FIXME: I assume that there are few type errors at post-analysis stage, but not
480 // entirely sure.
481 // We have to emit the error outside of `items_of_instance` to access the
482 // span of the `starting_item`.
483let def_id = instance.def_id();
484let def_span = tcx.def_span(def_id);
485let def_path_str = tcx.def_path_str(def_id);
486 tcx.dcx().emit_fatal(RecursionLimit {
487 span: starting_item.span,
488 instance,
489 def_span,
490 def_path_str,
491 });
492 };
493 used_items.extend(used.into_iter().copied());
494 mentioned_items.extend(mentioned.into_iter().copied());
495 });
496 }
497 MonoItem::GlobalAsm(item_id) => {
498assert!(
499 mode == CollectionMode::UsedItems,
500"should never encounter global_asm when collecting mentioned items"
501);
502 recursion_depth_reset = None;
503504let item = tcx.hir_item(item_id);
505if let hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
506for (op, op_sp) in asm.operands {
507match *op {
508 hir::InlineAsmOperand::Const { .. } => {
509// Only constants which resolve to a plain integer
510 // are supported. Therefore the value should not
511 // depend on any other items.
512}
513 hir::InlineAsmOperand::SymFn { expr } => {
514let fn_ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
515 visit_fn_use(tcx, fn_ty, false, *op_sp, &mut used_items);
516 }
517 hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
518let instance = Instance::mono(tcx, def_id);
519if tcx.should_codegen_locally(instance) {
520trace!("collecting static {:?}", def_id);
521 used_items.push(dummy_spanned(MonoItem::Static(def_id)));
522 }
523 }
524 hir::InlineAsmOperand::In { .. }
525 | hir::InlineAsmOperand::Out { .. }
526 | hir::InlineAsmOperand::InOut { .. }
527 | hir::InlineAsmOperand::SplitInOut { .. }
528 | hir::InlineAsmOperand::Label { .. } => {
529span_bug!(*op_sp, "invalid operand type for global_asm!")
530 }
531 }
532 }
533 } else {
534span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
535 }
536537// mention_items stays empty as nothing gets optimized here.
538}
539 };
540541// Check for PMEs and emit a diagnostic if one happened. To try to show relevant edges of the
542 // mono item graph.
543if tcx.dcx().err_count() > error_count
544 && starting_item.node.is_generic_fn()
545 && starting_item.node.is_user_defined()
546 {
547match starting_item.node {
548 MonoItem::Fn(instance) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
549 span: starting_item.span,
550 kind: "fn",
551 instance,
552 }),
553 MonoItem::Static(def_id) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
554 span: starting_item.span,
555 kind: "static",
556 instance: Instance::new_raw(def_id, GenericArgs::empty()),
557 }),
558 MonoItem::GlobalAsm(_) => {
559 tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
560 span: starting_item.span,
561 })
562 }
563 }
564 }
565// Only updating `usage_map` for used items as otherwise we may be inserting the same item
566 // multiple times (if it is first 'mentioned' and then later actually used), and the usage map
567 // logic does not like that.
568 // This is part of the output of collection and hence only relevant for "used" items.
569 // ("Mentioned" items are only considered internally during collection.)
570if mode == CollectionMode::UsedItems {
571 state.usage_map.lock().record_used(starting_item.node, &used_items);
572 }
573574 {
575let mut visited = OnceCell::default();
576if mode == CollectionMode::UsedItems {
577 used_items
578 .items
579 .retain(|k, _| visited.get_mut_or_init(|| state.visited.lock()).insert(*k));
580 }
581582let mut mentioned = OnceCell::default();
583 mentioned_items.items.retain(|k, _| {
584 !visited.get_or_init(|| state.visited.lock()).contains(k)
585 && mentioned.get_mut_or_init(|| state.mentioned.lock()).insert(*k)
586 });
587 }
588if mode == CollectionMode::MentionedItems {
589assert!(used_items.is_empty(), "'mentioned' collection should never encounter used items");
590 } else {
591for used_item in used_items {
592 collect_items_rec(
593 tcx,
594 used_item,
595 state,
596 recursion_depths,
597 recursion_limit,
598 CollectionMode::UsedItems,
599 );
600 }
601 }
602603// Walk over mentioned items *after* used items, so that if an item is both mentioned and used then
604 // the loop above has fully collected it, so this loop will skip it.
605for mentioned_item in mentioned_items {
606 collect_items_rec(
607 tcx,
608 mentioned_item,
609 state,
610 recursion_depths,
611 recursion_limit,
612 CollectionMode::MentionedItems,
613 );
614 }
615616if let Some((def_id, depth)) = recursion_depth_reset {
617 recursion_depths.insert(def_id, depth);
618 }
619}
620621// Check whether we can normalize every type in the instantiated MIR body.
622fn check_normalization_error<'tcx>(
623 tcx: TyCtxt<'tcx>,
624 instance: Instance<'tcx>,
625 body: &Body<'tcx>,
626) -> Result<(), NormalizationErrorInMono> {
627struct NormalizationChecker<'tcx> {
628 tcx: TyCtxt<'tcx>,
629 instance: Instance<'tcx>,
630 }
631impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for NormalizationChecker<'tcx> {
632type Result = ControlFlow<()>;
633634fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
635match self.instance.try_instantiate_mir_and_normalize_erasing_regions(
636self.tcx,
637 ty::TypingEnv::fully_monomorphized(),
638 ty::EarlyBinder::bind(t),
639 ) {
640Ok(_) => ControlFlow::Continue(()),
641Err(_) => ControlFlow::Break(()),
642 }
643 }
644 }
645646let mut checker = NormalizationChecker { tcx, instance };
647if body.visit_with(&mut checker).is_break() { Err(NormalizationErrorInMono) } else { Ok(()) }
648}
649650fn check_recursion_limit<'tcx>(
651 tcx: TyCtxt<'tcx>,
652 instance: Instance<'tcx>,
653 span: Span,
654 recursion_depths: &mut DefIdMap<usize>,
655 recursion_limit: Limit,
656) -> (DefId, usize) {
657let def_id = instance.def_id();
658let recursion_depth = recursion_depths.get(&def_id).cloned().unwrap_or(0);
659{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:659",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(659u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" => recursion depth={0}",
recursion_depth) as &dyn Value))])
});
} else { ; }
};debug!(" => recursion depth={}", recursion_depth);
660661let adjusted_recursion_depth = if tcx.is_lang_item(def_id, LangItem::DropInPlace) {
662// HACK: drop_in_place creates tight monomorphization loops. Give
663 // it more margin.
664recursion_depth / 4
665} else {
666recursion_depth667 };
668669// Code that needs to instantiate the same function recursively
670 // more than the recursion limit is assumed to be causing an
671 // infinite expansion.
672if !recursion_limit.value_within_limit(adjusted_recursion_depth) {
673let def_span = tcx.def_span(def_id);
674let def_path_str = tcx.def_path_str(def_id);
675tcx.dcx().emit_fatal(RecursionLimit { span, instance, def_span, def_path_str });
676 }
677678recursion_depths.insert(def_id, recursion_depth + 1);
679680 (def_id, recursion_depth)
681}
682683struct MirUsedCollector<'a, 'tcx> {
684 tcx: TyCtxt<'tcx>,
685 body: &'a mir::Body<'tcx>,
686 used_items: &'a mut MonoItems<'tcx>,
687/// See the comment in `collect_items_of_instance` for the purpose of this set.
688 /// Note that this contains *not-monomorphized* items!
689used_mentioned_items: &'a mut UnordSet<MentionedItem<'tcx>>,
690 instance: Instance<'tcx>,
691}
692693impl<'a, 'tcx> MirUsedCollector<'a, 'tcx> {
694fn monomorphize<T>(&self, value: T) -> T
695where
696T: TypeFoldable<TyCtxt<'tcx>>,
697 {
698{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:698",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(698u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("monomorphize: self.instance={0:?}",
self.instance) as &dyn Value))])
});
} else { ; }
};trace!("monomorphize: self.instance={:?}", self.instance);
699self.instance.instantiate_mir_and_normalize_erasing_regions(
700self.tcx,
701 ty::TypingEnv::fully_monomorphized(),
702 ty::EarlyBinder::bind(value),
703 )
704 }
705706/// Evaluates a *not yet monomorphized* constant.
707fn eval_constant(&mut self, constant: &mir::ConstOperand<'tcx>) -> Option<mir::ConstValue> {
708let const_ = self.monomorphize(constant.const_);
709// Evaluate the constant. This makes const eval failure a collection-time error (rather than
710 // a codegen-time error). rustc stops after collection if there was an error, so this
711 // ensures codegen never has to worry about failing consts.
712 // (codegen relies on this and ICEs will happen if this is violated.)
713match const_.eval(self.tcx, ty::TypingEnv::fully_monomorphized(), constant.span) {
714Ok(v) => Some(v),
715Err(ErrorHandled::TooGeneric(..)) => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
format_args!("collection encountered polymorphic constant: {0:?}",
const_))span_bug!(
716constant.span,
717"collection encountered polymorphic constant: {:?}",
718 const_
719 ),
720Err(err @ ErrorHandled::Reported(..)) => {
721err.emit_note(self.tcx);
722return None;
723 }
724 }
725 }
726}
727728impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> {
729fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
730{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:730",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(730u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("visiting rvalue {0:?}",
*rvalue) as &dyn Value))])
});
} else { ; }
};debug!("visiting rvalue {:?}", *rvalue);
731732let span = self.body.source_info(location).span;
733734match *rvalue {
735// When doing an cast from a regular pointer to a wide pointer, we
736 // have to instantiate all methods of the trait being cast to, so we
737 // can build the appropriate vtable.
738mir::Rvalue::Cast(
739 mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
740ref operand,
741 target_ty,
742 ) => {
743let source_ty = operand.ty(self.body, self.tcx);
744// *Before* monomorphizing, record that we already handled this mention.
745self.used_mentioned_items
746 .insert(MentionedItem::UnsizeCast { source_ty, target_ty });
747let target_ty = self.monomorphize(target_ty);
748let source_ty = self.monomorphize(source_ty);
749let (source_ty, target_ty) =
750find_tails_for_unsizing(self.tcx.at(span), source_ty, target_ty);
751// This could also be a different Unsize instruction, like
752 // from a fixed sized array to a slice. But we are only
753 // interested in things that produce a vtable.
754if target_ty.is_trait() && !source_ty.is_trait() {
755create_mono_items_for_vtable_methods(
756self.tcx,
757target_ty,
758source_ty,
759span,
760self.used_items,
761 );
762 }
763 }
764 mir::Rvalue::Cast(
765 mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _),
766ref operand,
767_,
768 ) => {
769let fn_ty = operand.ty(self.body, self.tcx);
770// *Before* monomorphizing, record that we already handled this mention.
771self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
772let fn_ty = self.monomorphize(fn_ty);
773visit_fn_use(self.tcx, fn_ty, false, span, self.used_items);
774 }
775 mir::Rvalue::Cast(
776 mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _),
777ref operand,
778_,
779 ) => {
780let source_ty = operand.ty(self.body, self.tcx);
781// *Before* monomorphizing, record that we already handled this mention.
782self.used_mentioned_items.insert(MentionedItem::Closure(source_ty));
783let source_ty = self.monomorphize(source_ty);
784if let ty::Closure(def_id, args) = *source_ty.kind() {
785let instance =
786Instance::resolve_closure(self.tcx, def_id, args, ty::ClosureKind::FnOnce);
787if self.tcx.should_codegen_locally(instance) {
788self.used_items.push(create_fn_mono_item(self.tcx, instance, span));
789 }
790 } else {
791::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()792 }
793 }
794 mir::Rvalue::ThreadLocalRef(def_id) => {
795if !self.tcx.is_thread_local_static(def_id) {
::core::panicking::panic("assertion failed: self.tcx.is_thread_local_static(def_id)")
};assert!(self.tcx.is_thread_local_static(def_id));
796let instance = Instance::mono(self.tcx, def_id);
797if self.tcx.should_codegen_locally(instance) {
798{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:798",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(798u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting thread-local static {0:?}",
def_id) as &dyn Value))])
});
} else { ; }
};trace!("collecting thread-local static {:?}", def_id);
799self.used_items.push(respan(span, MonoItem::Static(def_id)));
800 }
801 }
802_ => { /* not interesting */ }
803 }
804805self.super_rvalue(rvalue, location);
806 }
807808/// This does not walk the MIR of the constant as that is not needed for codegen, all we need is
809 /// to ensure that the constant evaluates successfully and walk the result.
810#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("visit_const_operand",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(810u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["constant",
"_location"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constant)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&_location)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let Some(val) = self.eval_constant(constant) else { return };
collect_const_value(self.tcx, val, self.used_items);
}
}
}#[instrument(skip(self), level = "debug")]811fn visit_const_operand(&mut self, constant: &mir::ConstOperand<'tcx>, _location: Location) {
812// No `super_constant` as we don't care about `visit_ty`/`visit_ty_const`.
813let Some(val) = self.eval_constant(constant) else { return };
814 collect_const_value(self.tcx, val, self.used_items);
815 }
816817fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) {
818{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:818",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(818u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("visiting terminator {0:?} @ {1:?}",
terminator, location) as &dyn Value))])
});
} else { ; }
};debug!("visiting terminator {:?} @ {:?}", terminator, location);
819let source = self.body.source_info(location).span;
820821let tcx = self.tcx;
822let push_mono_lang_item = |this: &mut Self, lang_item: LangItem| {
823let instance = Instance::mono(tcx, tcx.require_lang_item(lang_item, source));
824if tcx.should_codegen_locally(instance) {
825this.used_items.push(create_fn_mono_item(tcx, instance, source));
826 }
827 };
828829match terminator.kind {
830 mir::TerminatorKind::Call { ref func, .. }
831 | mir::TerminatorKind::TailCall { ref func, .. } => {
832let callee_ty = func.ty(self.body, tcx);
833// *Before* monomorphizing, record that we already handled this mention.
834self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty));
835let callee_ty = self.monomorphize(callee_ty);
836837// HACK(explicit_tail_calls): collect tail calls to `#[track_caller]` functions as indirect,
838 // because we later call them as such, to prevent issues with ABI incompatibility.
839 // Ideally we'd replace such tail calls with normal call + return, but this requires
840 // post-mono MIR optimizations, which we don't yet have.
841let force_indirect_call =
842if #[allow(non_exhaustive_omitted_patterns)] match terminator.kind {
mir::TerminatorKind::TailCall { .. } => true,
_ => false,
}matches!(terminator.kind, mir::TerminatorKind::TailCall { .. })843 && let &ty::FnDef(def_id, args) = callee_ty.kind()
844 && let instance = ty::Instance::expect_resolve(
845self.tcx,
846 ty::TypingEnv::fully_monomorphized(),
847def_id,
848args,
849source,
850 )
851 && instance.def.requires_caller_location(self.tcx)
852 {
853true
854} else {
855false
856};
857858visit_fn_use(
859self.tcx,
860callee_ty,
861 !force_indirect_call,
862source,
863&mut self.used_items,
864 )
865 }
866 mir::TerminatorKind::Drop { ref place, .. } => {
867let ty = place.ty(self.body, self.tcx).ty;
868// *Before* monomorphizing, record that we already handled this mention.
869self.used_mentioned_items.insert(MentionedItem::Drop(ty));
870let ty = self.monomorphize(ty);
871visit_drop_use(self.tcx, ty, true, source, self.used_items);
872 }
873 mir::TerminatorKind::InlineAsm { ref operands, .. } => {
874for op in operands {
875match *op {
876 mir::InlineAsmOperand::SymFn { ref value } => {
877let fn_ty = value.const_.ty();
878// *Before* monomorphizing, record that we already handled this mention.
879self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
880let fn_ty = self.monomorphize(fn_ty);
881 visit_fn_use(self.tcx, fn_ty, false, source, self.used_items);
882 }
883 mir::InlineAsmOperand::SymStatic { def_id } => {
884let instance = Instance::mono(self.tcx, def_id);
885if self.tcx.should_codegen_locally(instance) {
886{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:886",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(886u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting asm sym static {0:?}",
def_id) as &dyn Value))])
});
} else { ; }
};trace!("collecting asm sym static {:?}", def_id);
887self.used_items.push(respan(source, MonoItem::Static(def_id)));
888 }
889 }
890_ => {}
891 }
892 }
893 }
894 mir::TerminatorKind::Assert { ref msg, .. } => match &**msg {
895 mir::AssertKind::BoundsCheck { .. } => {
896push_mono_lang_item(self, LangItem::PanicBoundsCheck);
897 }
898 mir::AssertKind::MisalignedPointerDereference { .. } => {
899push_mono_lang_item(self, LangItem::PanicMisalignedPointerDereference);
900 }
901 mir::AssertKind::NullPointerDereference => {
902push_mono_lang_item(self, LangItem::PanicNullPointerDereference);
903 }
904 mir::AssertKind::InvalidEnumConstruction(_) => {
905push_mono_lang_item(self, LangItem::PanicInvalidEnumConstruction);
906 }
907_ => {
908push_mono_lang_item(self, msg.panic_function());
909 }
910 },
911 mir::TerminatorKind::UnwindTerminate(reason) => {
912push_mono_lang_item(self, reason.lang_item());
913 }
914 mir::TerminatorKind::Goto { .. }
915 | mir::TerminatorKind::SwitchInt { .. }
916 | mir::TerminatorKind::UnwindResume917 | mir::TerminatorKind::Return918 | mir::TerminatorKind::Unreachable => {}
919 mir::TerminatorKind::CoroutineDrop920 | mir::TerminatorKind::Yield { .. }
921 | mir::TerminatorKind::FalseEdge { .. }
922 | mir::TerminatorKind::FalseUnwind { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
923 }
924925if let Some(mir::UnwindAction::Terminate(reason)) = terminator.unwind() {
926push_mono_lang_item(self, reason.lang_item());
927 }
928929self.super_terminator(terminator, location);
930 }
931}
932933fn visit_drop_use<'tcx>(
934 tcx: TyCtxt<'tcx>,
935 ty: Ty<'tcx>,
936 is_direct_call: bool,
937 source: Span,
938 output: &mut MonoItems<'tcx>,
939) {
940let instance = Instance::resolve_drop_in_place(tcx, ty);
941visit_instance_use(tcx, instance, is_direct_call, source, output);
942}
943944/// For every call of this function in the visitor, make sure there is a matching call in the
945/// `mentioned_items` pass!
946fn visit_fn_use<'tcx>(
947 tcx: TyCtxt<'tcx>,
948 ty: Ty<'tcx>,
949 is_direct_call: bool,
950 source: Span,
951 output: &mut MonoItems<'tcx>,
952) {
953if let ty::FnDef(def_id, args) = *ty.kind() {
954let instance = if is_direct_call {
955 ty::Instance::expect_resolve(
956tcx,
957 ty::TypingEnv::fully_monomorphized(),
958def_id,
959args,
960source,
961 )
962 } else {
963match ty::Instance::resolve_for_fn_ptr(
964tcx,
965 ty::TypingEnv::fully_monomorphized(),
966def_id,
967args,
968 ) {
969Some(instance) => instance,
970_ => ::rustc_middle::util::bug::bug_fmt(format_args!("failed to resolve instance for {0}",
ty))bug!("failed to resolve instance for {ty}"),
971 }
972 };
973visit_instance_use(tcx, instance, is_direct_call, source, output);
974 }
975}
976977fn visit_instance_use<'tcx>(
978 tcx: TyCtxt<'tcx>,
979 instance: ty::Instance<'tcx>,
980 is_direct_call: bool,
981 source: Span,
982 output: &mut MonoItems<'tcx>,
983) {
984{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:984",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(984u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("visit_item_use({0:?}, is_direct_call={1:?})",
instance, is_direct_call) as &dyn Value))])
});
} else { ; }
};debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
985if !tcx.should_codegen_locally(instance) {
986return;
987 }
988if let Some(intrinsic) = tcx.intrinsic(instance.def_id()) {
989if let Some(_requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) {
990// The intrinsics assert_inhabited, assert_zero_valid, and assert_mem_uninitialized_valid will
991 // be lowered in codegen to nothing or a call to panic_nounwind. So if we encounter any
992 // of those intrinsics, we need to include a mono item for panic_nounwind, else we may try to
993 // codegen a call to that function without generating code for the function itself.
994let def_id = tcx.require_lang_item(LangItem::PanicNounwind, source);
995let panic_instance = Instance::mono(tcx, def_id);
996if tcx.should_codegen_locally(panic_instance) {
997output.push(create_fn_mono_item(tcx, panic_instance, source));
998 }
999 } else if !intrinsic.must_be_overridden
1000 && !tcx.sess.replaced_intrinsics.contains(&intrinsic.name)
1001 {
1002// Codegen the fallback body of intrinsics with fallback bodies.
1003 // We have to skip this otherwise as there's no body to codegen.
1004 // We also skip intrinsics the backend handles, to reduce monomorphizations.
1005let instance = ty::Instance::new_raw(instance.def_id(), instance.args);
1006if tcx.should_codegen_locally(instance) {
1007output.push(create_fn_mono_item(tcx, instance, source));
1008 }
1009 }
1010 }
10111012match instance.def {
1013 ty::InstanceKind::Virtual(..) | ty::InstanceKind::Intrinsic(_) => {
1014if !is_direct_call {
1015::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} being reified",
instance));bug!("{:?} being reified", instance);
1016 }
1017 }
1018 ty::InstanceKind::ThreadLocalShim(..) => {
1019::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} being reified",
instance));bug!("{:?} being reified", instance);
1020 }
1021 ty::InstanceKind::DropGlue(_, None) => {
1022// Don't need to emit noop drop glue if we are calling directly.
1023 //
1024 // Note that we also optimize away the call to visit_instance_use in vtable construction
1025 // (see create_mono_items_for_vtable_methods).
1026if !is_direct_call {
1027output.push(create_fn_mono_item(tcx, instance, source));
1028 }
1029 }
1030 ty::InstanceKind::DropGlue(_, Some(_))
1031 | ty::InstanceKind::FutureDropPollShim(..)
1032 | ty::InstanceKind::AsyncDropGlue(_, _)
1033 | ty::InstanceKind::AsyncDropGlueCtorShim(_, _)
1034 | ty::InstanceKind::VTableShim(..)
1035 | ty::InstanceKind::ReifyShim(..)
1036 | ty::InstanceKind::ClosureOnceShim { .. }
1037 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1038 | ty::InstanceKind::Item(..)
1039 | ty::InstanceKind::FnPtrShim(..)
1040 | ty::InstanceKind::CloneShim(..)
1041 | ty::InstanceKind::FnPtrAddrShim(..) => {
1042output.push(create_fn_mono_item(tcx, instance, source));
1043 }
1044 }
1045}
10461047/// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we
1048/// can just link to the upstream crate and therefore don't need a mono item.
1049fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
1050let Some(def_id) = instance.def.def_id_if_not_guaranteed_local_codegen() else {
1051return true;
1052 };
10531054if tcx.is_foreign_item(def_id) {
1055// Foreign items are always linked against, there's no way of instantiating them.
1056return false;
1057 }
10581059if tcx.def_kind(def_id).has_codegen_attrs()
1060 && #[allow(non_exhaustive_omitted_patterns)] match tcx.codegen_fn_attrs(def_id).inline
{
InlineAttr::Force { .. } => true,
_ => false,
}matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })1061 {
1062// `#[rustc_force_inline]` items should never be codegened. This should be caught by
1063 // the MIR validator.
1064tcx.dcx().delayed_bug("attempt to codegen `#[rustc_force_inline]` item");
1065 }
10661067if def_id.is_local() {
1068// Local items cannot be referred to locally without monomorphizing them locally.
1069return true;
1070 }
10711072if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(tcx).is_some() {
1073// We can link to the item in question, no instance needed in this crate.
1074return false;
1075 }
10761077if let DefKind::Static { .. } = tcx.def_kind(def_id) {
1078// We cannot monomorphize statics from upstream crates.
1079return false;
1080 }
10811082// See comment in should_encode_mir in rustc_metadata for why we don't report
1083 // an error for constructors.
1084if !tcx.is_mir_available(def_id) && !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(tcx.def_kind(def_id), DefKind::Ctor(..)) {
1085tcx.dcx().emit_fatal(NoOptimizedMir {
1086 span: tcx.def_span(def_id),
1087 crate_name: tcx.crate_name(def_id.krate),
1088 instance: instance.to_string(),
1089 });
1090 }
10911092true
1093}
10941095/// For a given pair of source and target type that occur in an unsizing coercion,
1096/// this function finds the pair of types that determines the vtable linking
1097/// them.
1098///
1099/// For example, the source type might be `&SomeStruct` and the target type
1100/// might be `&dyn SomeTrait` in a cast like:
1101///
1102/// ```rust,ignore (not real code)
1103/// let src: &SomeStruct = ...;
1104/// let target = src as &dyn SomeTrait;
1105/// ```
1106///
1107/// Then the output of this function would be (SomeStruct, SomeTrait) since for
1108/// constructing the `target` wide-pointer we need the vtable for that pair.
1109///
1110/// Things can get more complicated though because there's also the case where
1111/// the unsized type occurs as a field:
1112///
1113/// ```rust
1114/// struct ComplexStruct<T: ?Sized> {
1115/// a: u32,
1116/// b: f64,
1117/// c: T
1118/// }
1119/// ```
1120///
1121/// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
1122/// is unsized, `&SomeStruct` is a wide pointer, and the vtable it points to is
1123/// for the pair of `T` (which is a trait) and the concrete type that `T` was
1124/// originally coerced from:
1125///
1126/// ```rust,ignore (not real code)
1127/// let src: &ComplexStruct<SomeStruct> = ...;
1128/// let target = src as &ComplexStruct<dyn SomeTrait>;
1129/// ```
1130///
1131/// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
1132/// `(SomeStruct, SomeTrait)`.
1133///
1134/// Finally, there is also the case of custom unsizing coercions, e.g., for
1135/// smart pointers such as `Rc` and `Arc`.
1136fn find_tails_for_unsizing<'tcx>(
1137 tcx: TyCtxtAt<'tcx>,
1138 source_ty: Ty<'tcx>,
1139 target_ty: Ty<'tcx>,
1140) -> (Ty<'tcx>, Ty<'tcx>) {
1141let typing_env = ty::TypingEnv::fully_monomorphized();
1142if true {
if !!source_ty.has_param() {
{
::core::panicking::panic_fmt(format_args!("{0} should be fully monomorphic",
source_ty));
}
};
};debug_assert!(!source_ty.has_param(), "{source_ty} should be fully monomorphic");
1143if true {
if !!target_ty.has_param() {
{
::core::panicking::panic_fmt(format_args!("{0} should be fully monomorphic",
target_ty));
}
};
};debug_assert!(!target_ty.has_param(), "{target_ty} should be fully monomorphic");
11441145match (source_ty.kind(), target_ty.kind()) {
1146 (&ty::Pat(source, _), &ty::Pat(target, _)) => find_tails_for_unsizing(tcx, source, target),
1147 (
1148&ty::Ref(_, source_pointee, _),
1149&ty::Ref(_, target_pointee, _) | &ty::RawPtr(target_pointee, _),
1150 )
1151 | (&ty::RawPtr(source_pointee, _), &ty::RawPtr(target_pointee, _)) => {
1152tcx.struct_lockstep_tails_for_codegen(source_pointee, target_pointee, typing_env)
1153 }
11541155// `Box<T>` could go through the ADT code below, b/c it'll unpeel to `Unique<T>`,
1156 // and eventually bottom out in a raw ref, but we can micro-optimize it here.
1157(_, _)
1158if let Some(source_boxed) = source_ty.boxed_ty()
1159 && let Some(target_boxed) = target_ty.boxed_ty() =>
1160 {
1161tcx.struct_lockstep_tails_for_codegen(source_boxed, target_boxed, typing_env)
1162 }
11631164 (&ty::Adt(source_adt_def, source_args), &ty::Adt(target_adt_def, target_args)) => {
1165match (&source_adt_def, &target_adt_def) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(source_adt_def, target_adt_def);
1166let CustomCoerceUnsized::Struct(coerce_index) =
1167match crate::custom_coerce_unsize_info(tcx, source_ty, target_ty) {
1168Ok(ccu) => ccu,
1169Err(e) => {
1170let e = Ty::new_error(tcx.tcx, e);
1171return (e, e);
1172 }
1173 };
1174let coerce_field = &source_adt_def.non_enum_variant().fields[coerce_index];
1175// We're getting a possibly unnormalized type, so normalize it.
1176let source_field =
1177tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, source_args));
1178let target_field =
1179tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, target_args));
1180find_tails_for_unsizing(tcx, source_field, target_field)
1181 }
11821183_ => ::rustc_middle::util::bug::bug_fmt(format_args!("find_vtable_types_for_unsizing: invalid coercion {0:?} -> {1:?}",
source_ty, target_ty))bug!(
1184"find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
1185 source_ty,
1186 target_ty
1187 ),
1188 }
1189}
11901191x;#[instrument(skip(tcx), level = "debug", ret)]1192fn create_fn_mono_item<'tcx>(
1193 tcx: TyCtxt<'tcx>,
1194 instance: Instance<'tcx>,
1195 source: Span,
1196) -> Spanned<MonoItem<'tcx>> {
1197let def_id = instance.def_id();
1198if tcx.sess.opts.unstable_opts.profile_closures
1199 && def_id.is_local()
1200 && tcx.is_closure_like(def_id)
1201 {
1202crate::util::dump_closure_profile(tcx, instance);
1203 }
12041205 respan(source, MonoItem::Fn(instance))
1206}
12071208/// Creates a `MonoItem` for each method that is referenced by the vtable for
1209/// the given trait/impl pair.
1210fn create_mono_items_for_vtable_methods<'tcx>(
1211 tcx: TyCtxt<'tcx>,
1212 trait_ty: Ty<'tcx>,
1213 impl_ty: Ty<'tcx>,
1214 source: Span,
1215 output: &mut MonoItems<'tcx>,
1216) {
1217if !(!trait_ty.has_escaping_bound_vars() &&
!impl_ty.has_escaping_bound_vars()) {
::core::panicking::panic("assertion failed: !trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars()")
};assert!(!trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars());
12181219let ty::Dynamic(trait_ty, ..) = trait_ty.kind() else {
1220::rustc_middle::util::bug::bug_fmt(format_args!("create_mono_items_for_vtable_methods: {0:?} not a trait type",
trait_ty));bug!("create_mono_items_for_vtable_methods: {trait_ty:?} not a trait type");
1221 };
1222if let Some(principal) = trait_ty.principal() {
1223let trait_ref =
1224tcx.instantiate_bound_regions_with_erased(principal.with_self_ty(tcx, impl_ty));
1225if !!trait_ref.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !trait_ref.has_escaping_bound_vars()")
};assert!(!trait_ref.has_escaping_bound_vars());
12261227// Walk all methods of the trait, including those of its supertraits
1228let entries = tcx.vtable_entries(trait_ref);
1229{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1229",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1229u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["entries"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&entries) as
&dyn Value))])
});
} else { ; }
};debug!(?entries);
1230let methods = entries1231 .iter()
1232 .filter_map(|entry| match entry {
1233 VtblEntry::MetadataDropInPlace1234 | VtblEntry::MetadataSize1235 | VtblEntry::MetadataAlign1236 | VtblEntry::Vacant => None,
1237 VtblEntry::TraitVPtr(_) => {
1238// all super trait items already covered, so skip them.
1239None1240 }
1241 VtblEntry::Method(instance) => {
1242Some(*instance).filter(|instance| tcx.should_codegen_locally(*instance))
1243 }
1244 })
1245 .map(|item| create_fn_mono_item(tcx, item, source));
1246output.extend(methods);
1247 }
12481249// Also add the destructor, if it's necessary.
1250 //
1251 // This matches the check in vtable_allocation_provider in middle/ty/vtable.rs,
1252 // if we don't need drop we're not adding an actual pointer to the vtable.
1253if impl_ty.needs_drop(tcx, ty::TypingEnv::fully_monomorphized()) {
1254visit_drop_use(tcx, impl_ty, false, source, output);
1255 }
1256}
12571258/// Scans the CTFE alloc in order to find function pointers and statics that must be monomorphized.
1259fn collect_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut MonoItems<'tcx>) {
1260match tcx.global_alloc(alloc_id) {
1261 GlobalAlloc::Static(def_id) => {
1262if !!tcx.is_thread_local_static(def_id) {
::core::panicking::panic("assertion failed: !tcx.is_thread_local_static(def_id)")
};assert!(!tcx.is_thread_local_static(def_id));
1263let instance = Instance::mono(tcx, def_id);
1264if tcx.should_codegen_locally(instance) {
1265{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1265",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1265u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting static {0:?}",
def_id) as &dyn Value))])
});
} else { ; }
};trace!("collecting static {:?}", def_id);
1266output.push(dummy_spanned(MonoItem::Static(def_id)));
1267 }
1268 }
1269 GlobalAlloc::Memory(alloc) => {
1270{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1270",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1270u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting {0:?} with {1:#?}",
alloc_id, alloc) as &dyn Value))])
});
} else { ; }
};trace!("collecting {:?} with {:#?}", alloc_id, alloc);
1271let ptrs = alloc.inner().provenance().ptrs();
1272// avoid `ensure_sufficient_stack` in the common case of "no pointers"
1273if !ptrs.is_empty() {
1274 rustc_data_structures::stack::ensure_sufficient_stack(move || {
1275for &prov in ptrs.values() {
1276 collect_alloc(tcx, prov.alloc_id(), output);
1277 }
1278 });
1279 }
1280 }
1281 GlobalAlloc::Function { instance, .. } => {
1282if tcx.should_codegen_locally(instance) {
1283{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1283",
"rustc_monomorphize::collector", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1283u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting {0:?} with {1:#?}",
alloc_id, instance) as &dyn Value))])
});
} else { ; }
};trace!("collecting {:?} with {:#?}", alloc_id, instance);
1284output.push(create_fn_mono_item(tcx, instance, DUMMY_SP));
1285 }
1286 }
1287 GlobalAlloc::VTable(ty, dyn_ty) => {
1288let alloc_id = tcx.vtable_allocation((
1289ty,
1290dyn_ty1291 .principal()
1292 .map(|principal| tcx.instantiate_bound_regions_with_erased(principal)),
1293 ));
1294collect_alloc(tcx, alloc_id, output)
1295 }
1296 GlobalAlloc::TypeId { .. } => {}
1297 }
1298}
12991300/// Scans the MIR in order to find function calls, closures, and drop-glue.
1301///
1302/// Anything that's found is added to `output`. Furthermore the "mentioned items" of the MIR are returned.
1303#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("collect_items_of_instance",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1303u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["instance", "mode"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(MonoItems<'tcx>, MonoItems<'tcx>),
NormalizationErrorInMono> = loop {};
return __tracing_attr_fake_return;
}
{
let body = tcx.instance_mir(instance.def);
check_normalization_error(tcx, instance, body)?;
tcx.ensure_ok().check_mono_item(instance);
let mut used_items = MonoItems::new();
let mut mentioned_items = MonoItems::new();
let mut used_mentioned_items = Default::default();
let mut collector =
MirUsedCollector {
tcx,
body,
used_items: &mut used_items,
used_mentioned_items: &mut used_mentioned_items,
instance,
};
if mode == CollectionMode::UsedItems {
if tcx.sess.opts.debuginfo == DebugInfo::Full {
for var_debug_info in &body.var_debug_info {
collector.visit_var_debug_info(var_debug_info);
}
}
for (bb, data) in
traversal::mono_reachable(body, tcx, instance) {
collector.visit_basic_block_data(bb, data)
}
}
for const_op in body.required_consts() {
if let Some(val) = collector.eval_constant(const_op) {
collect_const_value(tcx, val, &mut mentioned_items);
}
}
for item in body.mentioned_items() {
if !collector.used_mentioned_items.contains(&item.node) {
let item_mono = collector.monomorphize(item.node);
visit_mentioned_item(tcx, &item_mono, item.span,
&mut mentioned_items);
}
}
Ok((used_items, mentioned_items))
}
}
}#[instrument(skip(tcx), level = "debug")]1304fn collect_items_of_instance<'tcx>(
1305 tcx: TyCtxt<'tcx>,
1306 instance: Instance<'tcx>,
1307 mode: CollectionMode,
1308) -> Result<(MonoItems<'tcx>, MonoItems<'tcx>), NormalizationErrorInMono> {
1309// This item is getting monomorphized, do mono-time checks.
1310let body = tcx.instance_mir(instance.def);
1311// Plenty of code paths later assume that everything can be normalized. So we have to check
1312 // normalization first.
1313 // We choose to emit the error outside to provide helpful diagnostics.
1314check_normalization_error(tcx, instance, body)?;
1315 tcx.ensure_ok().check_mono_item(instance);
13161317// Naively, in "used" collection mode, all functions get added to *both* `used_items` and
1318 // `mentioned_items`. Mentioned items processing will then notice that they have already been
1319 // visited, but at that point each mentioned item has been monomorphized, added to the
1320 // `mentioned_items` worklist, and checked in the global set of visited items. To remove that
1321 // overhead, we have a special optimization that avoids adding items to `mentioned_items` when
1322 // they are already added in `used_items`. We could just scan `used_items`, but that's a linear
1323 // scan and not very efficient. Furthermore we can only do that *after* monomorphizing the
1324 // mentioned item. So instead we collect all pre-monomorphized `MentionedItem` that were already
1325 // added to `used_items` in a hash set, which can efficiently query in the
1326 // `body.mentioned_items` loop below without even having to monomorphize the item.
1327let mut used_items = MonoItems::new();
1328let mut mentioned_items = MonoItems::new();
1329let mut used_mentioned_items = Default::default();
1330let mut collector = MirUsedCollector {
1331 tcx,
1332 body,
1333 used_items: &mut used_items,
1334 used_mentioned_items: &mut used_mentioned_items,
1335 instance,
1336 };
13371338if mode == CollectionMode::UsedItems {
1339if tcx.sess.opts.debuginfo == DebugInfo::Full {
1340for var_debug_info in &body.var_debug_info {
1341 collector.visit_var_debug_info(var_debug_info);
1342 }
1343 }
1344for (bb, data) in traversal::mono_reachable(body, tcx, instance) {
1345 collector.visit_basic_block_data(bb, data)
1346 }
1347 }
13481349// Always visit all `required_consts`, so that we evaluate them and abort compilation if any of
1350 // them errors.
1351for const_op in body.required_consts() {
1352if let Some(val) = collector.eval_constant(const_op) {
1353 collect_const_value(tcx, val, &mut mentioned_items);
1354 }
1355 }
13561357// Always gather mentioned items. We try to avoid processing items that we have already added to
1358 // `used_items` above.
1359for item in body.mentioned_items() {
1360if !collector.used_mentioned_items.contains(&item.node) {
1361let item_mono = collector.monomorphize(item.node);
1362 visit_mentioned_item(tcx, &item_mono, item.span, &mut mentioned_items);
1363 }
1364 }
13651366Ok((used_items, mentioned_items))
1367}
13681369fn items_of_instance<'tcx>(
1370 tcx: TyCtxt<'tcx>,
1371 (instance, mode): (Instance<'tcx>, CollectionMode),
1372) -> Result<
1373 (&'tcx [Spanned<MonoItem<'tcx>>], &'tcx [Spanned<MonoItem<'tcx>>]),
1374NormalizationErrorInMono,
1375> {
1376let (used_items, mentioned_items) = collect_items_of_instance(tcx, instance, mode)?;
13771378let used_items = tcx.arena.alloc_from_iter(used_items);
1379let mentioned_items = tcx.arena.alloc_from_iter(mentioned_items);
13801381Ok((used_items, mentioned_items))
1382}
13831384/// `item` must be already monomorphized.
1385#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("visit_mentioned_item",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1385u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["item"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match *item {
MentionedItem::Fn(ty) => {
if let ty::FnDef(def_id, args) = *ty.kind() {
let instance =
Instance::expect_resolve(tcx,
ty::TypingEnv::fully_monomorphized(), def_id, args, span);
visit_instance_use(tcx, instance, true, span, output);
}
}
MentionedItem::Drop(ty) => {
visit_drop_use(tcx, ty, true, span, output);
}
MentionedItem::UnsizeCast { source_ty, target_ty } => {
let (source_ty, target_ty) =
find_tails_for_unsizing(tcx.at(span), source_ty, target_ty);
if target_ty.is_trait() && !source_ty.is_trait() {
create_mono_items_for_vtable_methods(tcx, target_ty,
source_ty, span, output);
}
}
MentionedItem::Closure(source_ty) => {
if let ty::Closure(def_id, args) = *source_ty.kind() {
let instance =
Instance::resolve_closure(tcx, def_id, args,
ty::ClosureKind::FnOnce);
if tcx.should_codegen_locally(instance) {
output.push(create_fn_mono_item(tcx, instance, span));
}
} else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
}
}
}
}
}
}#[instrument(skip(tcx, span, output), level = "debug")]1386fn visit_mentioned_item<'tcx>(
1387 tcx: TyCtxt<'tcx>,
1388 item: &MentionedItem<'tcx>,
1389 span: Span,
1390 output: &mut MonoItems<'tcx>,
1391) {
1392match *item {
1393 MentionedItem::Fn(ty) => {
1394if let ty::FnDef(def_id, args) = *ty.kind() {
1395let instance = Instance::expect_resolve(
1396 tcx,
1397 ty::TypingEnv::fully_monomorphized(),
1398 def_id,
1399 args,
1400 span,
1401 );
1402// `visit_instance_use` was written for "used" item collection but works just as well
1403 // for "mentioned" item collection.
1404 // We can set `is_direct_call`; that just means we'll skip a bunch of shims that anyway
1405 // can't have their own failing constants.
1406visit_instance_use(tcx, instance, /*is_direct_call*/ true, span, output);
1407 }
1408 }
1409 MentionedItem::Drop(ty) => {
1410 visit_drop_use(tcx, ty, /*is_direct_call*/ true, span, output);
1411 }
1412 MentionedItem::UnsizeCast { source_ty, target_ty } => {
1413let (source_ty, target_ty) =
1414 find_tails_for_unsizing(tcx.at(span), source_ty, target_ty);
1415// This could also be a different Unsize instruction, like
1416 // from a fixed sized array to a slice. But we are only
1417 // interested in things that produce a vtable.
1418if target_ty.is_trait() && !source_ty.is_trait() {
1419 create_mono_items_for_vtable_methods(tcx, target_ty, source_ty, span, output);
1420 }
1421 }
1422 MentionedItem::Closure(source_ty) => {
1423if let ty::Closure(def_id, args) = *source_ty.kind() {
1424let instance =
1425 Instance::resolve_closure(tcx, def_id, args, ty::ClosureKind::FnOnce);
1426if tcx.should_codegen_locally(instance) {
1427 output.push(create_fn_mono_item(tcx, instance, span));
1428 }
1429 } else {
1430bug!()
1431 }
1432 }
1433 }
1434}
14351436#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("collect_const_value",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1436u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match value {
mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => {
collect_alloc(tcx, ptr.provenance.alloc_id(), output)
}
mir::ConstValue::Indirect { alloc_id, .. } |
mir::ConstValue::Slice { alloc_id, meta: _ } =>
collect_alloc(tcx, alloc_id, output),
_ => {}
}
}
}
}#[instrument(skip(tcx, output), level = "debug")]1437fn collect_const_value<'tcx>(
1438 tcx: TyCtxt<'tcx>,
1439 value: mir::ConstValue,
1440 output: &mut MonoItems<'tcx>,
1441) {
1442match value {
1443 mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => {
1444 collect_alloc(tcx, ptr.provenance.alloc_id(), output)
1445 }
1446 mir::ConstValue::Indirect { alloc_id, .. }
1447 | mir::ConstValue::Slice { alloc_id, meta: _ } => collect_alloc(tcx, alloc_id, output),
1448_ => {}
1449 }
1450}
14511452//=-----------------------------------------------------------------------------
1453// Root Collection
1454//=-----------------------------------------------------------------------------
14551456// Find all non-generic items by walking the HIR. These items serve as roots to
1457// start monomorphizing from.
1458#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("collect_roots",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1458u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Vec<MonoItem<'_>> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1460",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1460u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collecting roots")
as &dyn Value))])
});
} else { ; }
};
let mut roots = MonoItems::new();
{
let entry_fn = tcx.entry_fn(());
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1466",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1466u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("collect_roots: entry_fn = {0:?}",
entry_fn) as &dyn Value))])
});
} else { ; }
};
let mut collector =
RootCollector {
tcx,
strategy: mode,
entry_fn,
output: &mut roots,
};
let crate_items = tcx.hir_crate_items(());
for id in crate_items.free_items() {
collector.process_item(id);
}
for id in crate_items.impl_items() {
collector.process_impl_item(id);
}
for id in crate_items.nested_bodies() {
collector.process_nested_body(id);
}
collector.push_extra_entry_roots();
}
roots.into_iter().filter_map(|Spanned { node: mono_item, .. }|
{
mono_item.is_instantiable(tcx).then_some(mono_item)
}).collect()
}
}
}#[instrument(skip(tcx, mode), level = "debug")]1459fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionStrategy) -> Vec<MonoItem<'_>> {
1460debug!("collecting roots");
1461let mut roots = MonoItems::new();
14621463 {
1464let entry_fn = tcx.entry_fn(());
14651466debug!("collect_roots: entry_fn = {:?}", entry_fn);
14671468let mut collector = RootCollector { tcx, strategy: mode, entry_fn, output: &mut roots };
14691470let crate_items = tcx.hir_crate_items(());
14711472for id in crate_items.free_items() {
1473 collector.process_item(id);
1474 }
14751476for id in crate_items.impl_items() {
1477 collector.process_impl_item(id);
1478 }
14791480for id in crate_items.nested_bodies() {
1481 collector.process_nested_body(id);
1482 }
14831484 collector.push_extra_entry_roots();
1485 }
14861487// We can only codegen items that are instantiable - items all of
1488 // whose predicates hold. Luckily, items that aren't instantiable
1489 // can't actually be used, so we can just skip codegenning them.
1490roots
1491 .into_iter()
1492 .filter_map(|Spanned { node: mono_item, .. }| {
1493 mono_item.is_instantiable(tcx).then_some(mono_item)
1494 })
1495 .collect()
1496}
14971498struct RootCollector<'a, 'tcx> {
1499 tcx: TyCtxt<'tcx>,
1500 strategy: MonoItemCollectionStrategy,
1501 output: &'a mut MonoItems<'tcx>,
1502 entry_fn: Option<(DefId, EntryFnType)>,
1503}
15041505impl<'v> RootCollector<'_, 'v> {
1506fn process_item(&mut self, id: hir::ItemId) {
1507match self.tcx.def_kind(id.owner_id) {
1508 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1509if self.strategy == MonoItemCollectionStrategy::Eager1510 && !self.tcx.generics_of(id.owner_id).requires_monomorphization(self.tcx)
1511 {
1512{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1512",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1512u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ADT drop-glue for `{0:?}`",
id) as &dyn Value))])
});
} else { ; }
};debug!("RootCollector: ADT drop-glue for `{id:?}`",);
1513let id_args =
1514 ty::GenericArgs::for_item(self.tcx, id.owner_id.to_def_id(), |param, _| {
1515match param.kind {
1516 GenericParamDefKind::Lifetime => {
1517self.tcx.lifetimes.re_erased.into()
1518 }
1519 GenericParamDefKind::Type { .. }
1520 | GenericParamDefKind::Const { .. } => {
1521{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`own_requires_monomorphization` check means that we should have no type/const params")));
}unreachable!(
1522"`own_requires_monomorphization` check means that \
1523 we should have no type/const params"
1524)1525 }
1526 }
1527 });
15281529// This type is impossible to instantiate, so we should not try to
1530 // generate a `drop_in_place` instance for it.
1531if self.tcx.instantiate_and_check_impossible_predicates((
1532id.owner_id.to_def_id(),
1533id_args,
1534 )) {
1535return;
1536 }
15371538let ty =
1539self.tcx.type_of(id.owner_id.to_def_id()).instantiate(self.tcx, id_args);
1540if !!ty.has_non_region_param() {
::core::panicking::panic("assertion failed: !ty.has_non_region_param()")
};assert!(!ty.has_non_region_param());
1541visit_drop_use(self.tcx, ty, true, DUMMY_SP, self.output);
1542 }
1543 }
1544 DefKind::GlobalAsm => {
1545{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1545",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1545u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ItemKind::GlobalAsm({0})",
self.tcx.def_path_str(id.owner_id)) as &dyn Value))])
});
} else { ; }
};debug!(
1546"RootCollector: ItemKind::GlobalAsm({})",
1547self.tcx.def_path_str(id.owner_id)
1548 );
1549self.output.push(dummy_spanned(MonoItem::GlobalAsm(id)));
1550 }
1551 DefKind::Static { .. } => {
1552let def_id = id.owner_id.to_def_id();
1553{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1553",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1553u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ItemKind::Static({0})",
self.tcx.def_path_str(def_id)) as &dyn Value))])
});
} else { ; }
};debug!("RootCollector: ItemKind::Static({})", self.tcx.def_path_str(def_id));
1554self.output.push(dummy_spanned(MonoItem::Static(def_id)));
1555 }
1556 DefKind::Const { .. } => {
1557// Const items only generate mono items if they are actually used somewhere.
1558 // Just declaring them is insufficient.
15591560 // If we're collecting items eagerly, then recurse into all constants.
1561 // Otherwise the value is only collected when explicitly mentioned in other items.
1562if self.strategy == MonoItemCollectionStrategy::Eager {
1563let def_id = id.owner_id.to_def_id();
1564// Type Consts don't have bodies to evaluate
1565 // nor do they make sense as a static.
1566if self.tcx.is_type_const(def_id) {
1567// FIXME(mgca): Is this actually what we want? We may want to
1568 // normalize to a ValTree then convert to a const allocation and
1569 // collect that?
1570return;
1571 }
1572if self.tcx.generics_of(id.owner_id).own_requires_monomorphization() {
1573return;
1574 }
1575let Ok(val) = self.tcx.const_eval_poly(def_id) else {
1576return;
1577 };
1578collect_const_value(self.tcx, val, self.output);
1579 }
1580 }
1581 DefKind::Impl { of_trait: true } => {
1582if self.strategy == MonoItemCollectionStrategy::Eager {
1583create_mono_items_for_default_impls(self.tcx, id, self.output);
1584 }
1585 }
1586 DefKind::Fn => {
1587self.push_if_root(id.owner_id.def_id);
1588 }
1589_ => {}
1590 }
1591 }
15921593fn process_impl_item(&mut self, id: hir::ImplItemId) {
1594if self.tcx.def_kind(id.owner_id) == DefKind::AssocFn {
1595self.push_if_root(id.owner_id.def_id);
1596 }
1597 }
15981599fn process_nested_body(&mut self, def_id: LocalDefId) {
1600match self.tcx.def_kind(def_id) {
1601 DefKind::Closure => {
1602// for 'pub async fn foo(..)' also trying to monomorphize foo::{closure}
1603let is_pub_fn_coroutine =
1604match *self.tcx.type_of(def_id).instantiate_identity().kind() {
1605 ty::Coroutine(cor_id, _args) => {
1606let tcx = self.tcx;
1607let parent_id = tcx.parent(cor_id);
1608tcx.def_kind(parent_id) == DefKind::Fn1609 && tcx.asyncness(parent_id).is_async()
1610 && tcx.visibility(parent_id).is_public()
1611 }
1612 ty::Closure(..) | ty::CoroutineClosure(..) => false,
1613_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1614 };
1615if (self.strategy == MonoItemCollectionStrategy::Eager || is_pub_fn_coroutine)
1616 && !self1617 .tcx
1618 .generics_of(self.tcx.typeck_root_def_id_local(def_id))
1619 .requires_monomorphization(self.tcx)
1620 {
1621let instance = match *self.tcx.type_of(def_id).instantiate_identity().kind() {
1622 ty::Closure(def_id, args)
1623 | ty::Coroutine(def_id, args)
1624 | ty::CoroutineClosure(def_id, args) => {
1625Instance::new_raw(def_id, self.tcx.erase_and_anonymize_regions(args))
1626 }
1627_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1628 };
1629let Ok(instance) = self.tcx.try_normalize_erasing_regions(
1630 ty::TypingEnv::fully_monomorphized(),
1631instance,
1632 ) else {
1633// Don't ICE on an impossible-to-normalize closure.
1634return;
1635 };
1636let mono_item = create_fn_mono_item(self.tcx, instance, DUMMY_SP);
1637if mono_item.node.is_instantiable(self.tcx) {
1638self.output.push(mono_item);
1639 }
1640 }
1641 }
1642_ => {}
1643 }
1644 }
16451646fn is_root(&self, def_id: LocalDefId) -> bool {
1647 !self.tcx.generics_of(def_id).requires_monomorphization(self.tcx)
1648 && match self.strategy {
1649 MonoItemCollectionStrategy::Eager => {
1650 !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.codegen_fn_attrs(def_id).inline
{
InlineAttr::Force { .. } => true,
_ => false,
}matches!(self.tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })1651 }
1652 MonoItemCollectionStrategy::Lazy => {
1653self.entry_fn.and_then(|(id, _)| id.as_local()) == Some(def_id)
1654 || self.tcx.is_reachable_non_generic(def_id)
1655 || {
1656let flags = self.tcx.codegen_fn_attrs(def_id).flags;
1657flags.intersects(
1658CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL1659 | CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM,
1660 )
1661 }
1662 }
1663 }
1664 }
16651666/// If `def_id` represents a root, pushes it onto the list of
1667 /// outputs. (Note that all roots must be monomorphic.)
1668#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("push_if_root",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1668u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if self.is_root(def_id) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1671",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1671u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("found root")
as &dyn Value))])
});
} else { ; }
};
let instance = Instance::mono(self.tcx, def_id.to_def_id());
self.output.push(create_fn_mono_item(self.tcx, instance,
DUMMY_SP));
}
}
}
}#[instrument(skip(self), level = "debug")]1669fn push_if_root(&mut self, def_id: LocalDefId) {
1670if self.is_root(def_id) {
1671debug!("found root");
16721673let instance = Instance::mono(self.tcx, def_id.to_def_id());
1674self.output.push(create_fn_mono_item(self.tcx, instance, DUMMY_SP));
1675 }
1676 }
16771678/// As a special case, when/if we encounter the
1679 /// `main()` function, we also have to generate a
1680 /// monomorphized copy of the start lang item based on
1681 /// the return type of `main`. This is not needed when
1682 /// the user writes their own `start` manually.
1683fn push_extra_entry_roots(&mut self) {
1684let Some((main_def_id, EntryFnType::Main { .. })) = self.entry_fn else {
1685return;
1686 };
16871688let main_instance = Instance::mono(self.tcx, main_def_id);
1689if self.tcx.should_codegen_locally(main_instance) {
1690self.output.push(create_fn_mono_item(
1691self.tcx,
1692main_instance,
1693self.tcx.def_span(main_def_id),
1694 ));
1695 }
16961697let Some(start_def_id) = self.tcx.lang_items().start_fn() else {
1698self.tcx.dcx().emit_fatal(errors::StartNotFound);
1699 };
1700let main_ret_ty = self.tcx.fn_sig(main_def_id).no_bound_vars().unwrap().output();
17011702// Given that `main()` has no arguments,
1703 // then its return type cannot have
1704 // late-bound regions, since late-bound
1705 // regions must appear in the argument
1706 // listing.
1707let main_ret_ty = self.tcx.normalize_erasing_regions(
1708 ty::TypingEnv::fully_monomorphized(),
1709main_ret_ty.no_bound_vars().unwrap(),
1710 );
17111712let start_instance = Instance::expect_resolve(
1713self.tcx,
1714 ty::TypingEnv::fully_monomorphized(),
1715start_def_id,
1716self.tcx.mk_args(&[main_ret_ty.into()]),
1717DUMMY_SP,
1718 );
17191720self.output.push(create_fn_mono_item(self.tcx, start_instance, DUMMY_SP));
1721 }
1722}
17231724#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("create_mono_items_for_default_impls",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1724u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["item"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let impl_ = tcx.impl_trait_header(item.owner_id);
if impl_.polarity == ty::ImplPolarity::Negative { return; }
if tcx.generics_of(item.owner_id).own_requires_monomorphization()
{
return;
}
let only_region_params =
|param: &ty::GenericParamDef, _: &_|
match param.kind {
GenericParamDefKind::Lifetime =>
tcx.lifetimes.re_erased.into(),
GenericParamDefKind::Type { .. } |
GenericParamDefKind::Const { .. } => {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`own_requires_monomorphization` check means that we should have no type/const params")));
}
}
};
let impl_args =
GenericArgs::for_item(tcx, item.owner_id.to_def_id(),
only_region_params);
let trait_ref = impl_.trait_ref.instantiate(tcx, impl_args);
if tcx.instantiate_and_check_impossible_predicates((item.owner_id.to_def_id(),
impl_args)) {
return;
}
let typing_env = ty::TypingEnv::fully_monomorphized();
let trait_ref =
tcx.normalize_erasing_regions(typing_env, trait_ref);
let overridden_methods =
tcx.impl_item_implementor_ids(item.owner_id);
for method in tcx.provided_trait_methods(trait_ref.def_id) {
if overridden_methods.contains_key(&method.def_id) {
continue;
}
if tcx.generics_of(method.def_id).own_requires_monomorphization()
{
continue;
}
let args =
trait_ref.args.extend_to(tcx, method.def_id,
only_region_params);
let instance =
ty::Instance::expect_resolve(tcx, typing_env, method.def_id,
args, DUMMY_SP);
let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP);
if mono_item.node.is_instantiable(tcx) &&
tcx.should_codegen_locally(instance) {
output.push(mono_item);
}
}
}
}
}#[instrument(level = "debug", skip(tcx, output))]1725fn create_mono_items_for_default_impls<'tcx>(
1726 tcx: TyCtxt<'tcx>,
1727 item: hir::ItemId,
1728 output: &mut MonoItems<'tcx>,
1729) {
1730let impl_ = tcx.impl_trait_header(item.owner_id);
17311732if impl_.polarity == ty::ImplPolarity::Negative {
1733return;
1734 }
17351736if tcx.generics_of(item.owner_id).own_requires_monomorphization() {
1737return;
1738 }
17391740// Lifetimes never affect trait selection, so we are allowed to eagerly
1741 // instantiate an instance of an impl method if the impl (and method,
1742 // which we check below) is only parameterized over lifetime. In that case,
1743 // we use the ReErased, which has no lifetime information associated with
1744 // it, to validate whether or not the impl is legal to instantiate at all.
1745let only_region_params = |param: &ty::GenericParamDef, _: &_| match param.kind {
1746 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1747 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
1748unreachable!(
1749"`own_requires_monomorphization` check means that \
1750 we should have no type/const params"
1751)
1752 }
1753 };
1754let impl_args = GenericArgs::for_item(tcx, item.owner_id.to_def_id(), only_region_params);
1755let trait_ref = impl_.trait_ref.instantiate(tcx, impl_args);
17561757// Unlike 'lazy' monomorphization that begins by collecting items transitively
1758 // called by `main` or other global items, when eagerly monomorphizing impl
1759 // items, we never actually check that the predicates of this impl are satisfied
1760 // in a empty param env (i.e. with no assumptions).
1761 //
1762 // Even though this impl has no type or const generic parameters, because we don't
1763 // consider higher-ranked predicates such as `for<'a> &'a mut [u8]: Copy` to
1764 // be trivially false. We must now check that the impl has no impossible-to-satisfy
1765 // predicates.
1766if tcx.instantiate_and_check_impossible_predicates((item.owner_id.to_def_id(), impl_args)) {
1767return;
1768 }
17691770let typing_env = ty::TypingEnv::fully_monomorphized();
1771let trait_ref = tcx.normalize_erasing_regions(typing_env, trait_ref);
1772let overridden_methods = tcx.impl_item_implementor_ids(item.owner_id);
1773for method in tcx.provided_trait_methods(trait_ref.def_id) {
1774if overridden_methods.contains_key(&method.def_id) {
1775continue;
1776 }
17771778if tcx.generics_of(method.def_id).own_requires_monomorphization() {
1779continue;
1780 }
17811782// As mentioned above, the method is legal to eagerly instantiate if it
1783 // only has lifetime generic parameters. This is validated by calling
1784 // `own_requires_monomorphization` on both the impl and method.
1785let args = trait_ref.args.extend_to(tcx, method.def_id, only_region_params);
1786let instance = ty::Instance::expect_resolve(tcx, typing_env, method.def_id, args, DUMMY_SP);
17871788let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP);
1789if mono_item.node.is_instantiable(tcx) && tcx.should_codegen_locally(instance) {
1790 output.push(mono_item);
1791 }
1792 }
1793}
17941795//=-----------------------------------------------------------------------------
1796// Top-level entry point, tying it all together
1797//=-----------------------------------------------------------------------------
17981799#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("collect_crate_mono_items",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1799u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
(Vec<MonoItem<'tcx>>, UsageMap<'tcx>) = loop {};
return __tracing_attr_fake_return;
}
{
let _prof_timer =
tcx.prof.generic_activity("monomorphization_collector");
let roots =
tcx.sess.time("monomorphization_collector_root_collections",
|| collect_roots(tcx, strategy));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1810",
"rustc_monomorphize::collector", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
::tracing_core::__macro_support::Option::Some(1810u32),
::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("building mono item graph, beginning at roots")
as &dyn Value))])
});
} else { ; }
};
let state =
SharedState {
visited: Lock::new(UnordSet::default()),
mentioned: Lock::new(UnordSet::default()),
usage_map: Lock::new(UsageMap::new()),
};
let recursion_limit = tcx.recursion_limit();
tcx.sess.time("monomorphization_collector_graph_walk",
||
{
par_for_each_in(roots,
|root|
{
collect_items_root(tcx, dummy_spanned(*root), &state,
recursion_limit);
});
});
let mono_items =
tcx.with_stable_hashing_context(move |ref hcx|
{ state.visited.into_inner().into_sorted(hcx, true) });
(mono_items, state.usage_map.into_inner())
}
}
}#[instrument(skip(tcx, strategy), level = "debug")]1800pub(crate) fn collect_crate_mono_items<'tcx>(
1801 tcx: TyCtxt<'tcx>,
1802 strategy: MonoItemCollectionStrategy,
1803) -> (Vec<MonoItem<'tcx>>, UsageMap<'tcx>) {
1804let _prof_timer = tcx.prof.generic_activity("monomorphization_collector");
18051806let roots = tcx
1807 .sess
1808 .time("monomorphization_collector_root_collections", || collect_roots(tcx, strategy));
18091810debug!("building mono item graph, beginning at roots");
18111812let state = SharedState {
1813 visited: Lock::new(UnordSet::default()),
1814 mentioned: Lock::new(UnordSet::default()),
1815 usage_map: Lock::new(UsageMap::new()),
1816 };
1817let recursion_limit = tcx.recursion_limit();
18181819 tcx.sess.time("monomorphization_collector_graph_walk", || {
1820 par_for_each_in(roots, |root| {
1821 collect_items_root(tcx, dummy_spanned(*root), &state, recursion_limit);
1822 });
1823 });
18241825// The set of MonoItems was created in an inherently indeterministic order because
1826 // of parallelism. We sort it here to ensure that the output is deterministic.
1827let mono_items = tcx.with_stable_hashing_context(move |ref hcx| {
1828 state.visited.into_inner().into_sorted(hcx, true)
1829 });
18301831 (mono_items, state.usage_map.into_inner())
1832}
18331834pub(crate) fn provide(providers: &mut Providers) {
1835providers.hooks.should_codegen_locally = should_codegen_locally;
1836providers.queries.items_of_instance = items_of_instance;
1837}