1use std::env;
37use std::fs::{self, File};
38use std::io::Write;
39
40use rustc_data_structures::fx::FxIndexSet;
41use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING};
42use rustc_graphviz as dot;
43use rustc_hir as hir;
44use rustc_hir::Attribute;
45use rustc_hir::attrs::AttributeKind;
46use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
47use rustc_hir::intravisit::{self, Visitor};
48use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeFilter, EdgeFilter, RetainedDepGraph};
49use rustc_middle::hir::nested_filter;
50use rustc_middle::ty::TyCtxt;
51use rustc_span::{Span, Symbol, bug, sym};
52use tracing::debug;
53
54use crate::diagnostics;
55
56#[allow(missing_docs)]
57pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) {
58 tcx.dep_graph.with_ignore(|| {
59 let retained_dep_graph = tcx.dep_graph.retained_dep_graph();
62
63 if tcx.sess.opts.unstable_opts.dump_dep_graph {
64 if let Some(graph) = &retained_dep_graph {
65 dump_graph(graph);
66 }
67 }
68
69 if !tcx.sess.opts.unstable_opts.query_dep_graph {
70 return;
71 }
72
73 if !tcx.features().rustc_attrs() {
77 return;
78 }
79
80 let (if_this_changed, then_this_would_need) = {
82 let mut visitor =
83 IfThisChanged { tcx, if_this_changed: ::alloc::vec::Vec::new()vec![], then_this_would_need: ::alloc::vec::Vec::new()vec![] };
84 visitor.process_attrs(CRATE_DEF_ID);
85 tcx.hir_visit_all_item_likes_in_crate(&mut visitor);
86 (visitor.if_this_changed, visitor.then_this_would_need)
87 };
88
89 if !if_this_changed.is_empty() || !then_this_would_need.is_empty() {
90 if !tcx.sess.opts.unstable_opts.query_dep_graph {
{
::core::panicking::panic_fmt(format_args!("cannot use the `#[{0}]` or `#[{1}]` annotations without supplying `-Z query-dep-graph`",
sym::rustc_if_this_changed, sym::rustc_then_this_would_need));
}
};assert!(
91 tcx.sess.opts.unstable_opts.query_dep_graph,
92 "cannot use the `#[{}]` or `#[{}]` annotations \
93 without supplying `-Z query-dep-graph`",
94 sym::rustc_if_this_changed,
95 sym::rustc_then_this_would_need
96 );
97 }
98
99 check_paths(tcx, retained_dep_graph.as_ref(), &if_this_changed, &then_this_would_need);
101 })
102}
103
104type Sources = Vec<(Span, DefId, DepNode)>;
105type Targets = Vec<(Span, Symbol, hir::HirId, DepNode)>;
106
107struct IfThisChanged<'tcx> {
108 tcx: TyCtxt<'tcx>,
109 if_this_changed: Sources,
110 then_this_would_need: Targets,
111}
112
113impl<'tcx> IfThisChanged<'tcx> {
114 fn process_attrs(&mut self, def_id: LocalDefId) {
115 let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id());
116 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
117 let attrs = self.tcx.hir_attrs(hir_id);
118 for attr in attrs {
119 if let Attribute::Parsed(AttributeKind::RustcIfThisChanged(span, dep_node)) = *attr {
120 let dep_node = match dep_node {
121 None => {
122 DepNode::from_def_path_hash(self.tcx, def_path_hash, DepKind::hir_owner)
123 }
124 Some(n) => {
125 match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {
126 Ok(n) => n,
127 Err(()) => self
128 .tcx
129 .dcx()
130 .emit_fatal(diagnostics::UnrecognizedDepNode { span, name: n }),
131 }
132 }
133 };
134 self.if_this_changed.push((span, def_id.to_def_id(), dep_node));
135 } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed(dep_nodes)) = attr
136 {
137 for &n in dep_nodes {
138 let Ok(dep_node) =
139 DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash)
140 else {
141 self.tcx.dcx().emit_fatal(diagnostics::UnrecognizedDepNode {
142 span: n.span,
143 name: n.name,
144 });
145 };
146 self.then_this_would_need.push((n.span, n.name, hir_id, dep_node));
147 }
148 }
149 }
150 }
151}
152
153impl<'tcx> Visitor<'tcx> for IfThisChanged<'tcx> {
154 type NestedFilter = nested_filter::OnlyBodies;
155
156 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
157 self.tcx
158 }
159
160 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
161 self.process_attrs(item.owner_id.def_id);
162 intravisit::walk_item(self, item);
163 }
164
165 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
166 self.process_attrs(trait_item.owner_id.def_id);
167 intravisit::walk_trait_item(self, trait_item);
168 }
169
170 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
171 self.process_attrs(impl_item.owner_id.def_id);
172 intravisit::walk_impl_item(self, impl_item);
173 }
174
175 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
176 self.process_attrs(s.def_id);
177 intravisit::walk_field_def(self, s);
178 }
179}
180
181fn check_paths<'tcx>(
182 tcx: TyCtxt<'tcx>,
183 retained_dep_graph: Option<&RetainedDepGraph>,
184 if_this_changed: &Sources,
185 then_this_would_need: &Targets,
186) {
187 if if_this_changed.is_empty() {
188 for &(target_span, _, _, _) in then_this_would_need {
189 tcx.dcx().emit_err(diagnostics::MissingIfThisChanged { span: target_span });
190 }
191 return;
192 }
193 let Some(query) = retained_dep_graph else { return };
194 for &(_, source_def_id, ref source_dep_node) in if_this_changed {
195 let dependents = query.transitive_predecessors(source_dep_node);
196 for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
197 if !dependents.contains(&target_dep_node) {
198 tcx.dcx().emit_err(diagnostics::NoPath {
199 span: target_span,
200 source: tcx.def_path_str(source_def_id),
201 target: *target_pass,
202 });
203 } else {
204 tcx.dcx().emit_err(diagnostics::Ok { span: target_span });
205 }
206 }
207 }
208}
209
210fn dump_graph(graph: &RetainedDepGraph) {
211 let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
212
213 let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
214 Ok(string) => {
215 let edge_filter =
217 EdgeFilter::new(&string).unwrap_or_else(|e| bug_impl(None, format_args!("invalid filter: {0}", e), Location::caller())bug!("invalid filter: {}", e));
218 let sources = node_set(graph, &edge_filter.source);
219 let targets = node_set(graph, &edge_filter.target);
220 filter_nodes(graph, &sources, &targets)
221 }
222 Err(_) => graph.nodes().into_iter().map(|n| n.kind).collect(),
223 };
224 let edges = filter_edges(graph, &nodes);
225
226 {
227 let txt_path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.txt", path))
})format!("{path}.txt");
229 let mut file = File::create_buffered(&txt_path).unwrap();
230 for (source, target) in &edges {
231 file.write_fmt(format_args!("{0:?} -> {1:?}\n", source, target))write!(file, "{source:?} -> {target:?}\n").unwrap();
232 }
233 }
234
235 {
236 let dot_path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dot", path))
})format!("{path}.dot");
238 let mut v = Vec::new();
239 dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
240 fs::write(dot_path, v).unwrap();
241 }
242}
243
244#[allow(missing_docs)]
245struct GraphvizDepGraph(FxIndexSet<DepKind>, Vec<(DepKind, DepKind)>);
246
247impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph {
248 type Node = DepKind;
249 type Edge = (DepKind, DepKind);
250 fn nodes(&self) -> dot::Nodes<'_, DepKind> {
251 let nodes: Vec<_> = self.0.iter().cloned().collect();
252 nodes.into()
253 }
254 fn edges(&self) -> dot::Edges<'_, (DepKind, DepKind)> {
255 self.1[..].into()
256 }
257 fn source(&self, edge: &(DepKind, DepKind)) -> DepKind {
258 edge.0
259 }
260 fn target(&self, edge: &(DepKind, DepKind)) -> DepKind {
261 edge.1
262 }
263}
264
265impl<'a> dot::Labeller<'a> for GraphvizDepGraph {
266 type Node = DepKind;
267 type Edge = (DepKind, DepKind);
268 fn graph_id(&self) -> dot::Id<'_> {
269 dot::Id::new("DependencyGraph").unwrap()
270 }
271 fn node_id(&self, n: &DepKind) -> dot::Id<'_> {
272 let s: String = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", n))
})format!("{n:?}")
273 .chars()
274 .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
275 .collect();
276 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs:276",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(276u32),
::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_graph"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("n={0:?} s={1:?}",
n, s) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("n={:?} s={:?}", n, s);
277 dot::Id::new(s).unwrap()
278 }
279 fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> {
280 dot::LabelText::label(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", n))
})format!("{n:?}"))
281 }
282}
283
284fn node_set<'g>(
288 graph: &'g RetainedDepGraph,
289 filter: &DepNodeFilter,
290) -> Option<FxIndexSet<&'g DepNode>> {
291 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs:291",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(291u32),
::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_graph"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("node_set(filter={0:?})",
filter) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("node_set(filter={:?})", filter);
292
293 if filter.accepts_all() {
294 return None;
295 }
296
297 Some(graph.nodes().into_iter().filter(|n| filter.test(n)).collect())
298}
299
300fn filter_nodes<'g>(
301 graph: &'g RetainedDepGraph,
302 sources: &Option<FxIndexSet<&'g DepNode>>,
303 targets: &Option<FxIndexSet<&'g DepNode>>,
304) -> FxIndexSet<DepKind> {
305 if let Some(sources) = sources {
306 if let Some(targets) = targets {
307 walk_between(graph, sources, targets)
308 } else {
309 walk_nodes(graph, sources, OUTGOING)
310 }
311 } else if let Some(targets) = targets {
312 walk_nodes(graph, targets, INCOMING)
313 } else {
314 graph.nodes().into_iter().map(|n| n.kind).collect()
315 }
316}
317
318fn walk_nodes<'g>(
319 graph: &'g RetainedDepGraph,
320 starts: &FxIndexSet<&'g DepNode>,
321 direction: Direction,
322) -> FxIndexSet<DepKind> {
323 let mut set = FxIndexSet::default();
324 for &start in starts {
325 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs:325",
"rustc_incremental::assert_dep_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_incremental/src/assert_dep_graph.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_incremental::assert_dep_graph"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_nodes: start={0:?} outgoing?={1:?}",
start, direction == OUTGOING) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
326 if set.insert(start.kind) {
327 let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[graph.indices[start]]))vec![graph.indices[start]];
328 while let Some(index) = stack.pop() {
329 for (_, edge) in graph.inner.adjacent_edges(index, direction) {
330 let neighbor_index = edge.source_or_target(direction);
331 let neighbor = graph.inner.node_data(neighbor_index);
332 if set.insert(neighbor.kind) {
333 stack.push(neighbor_index);
334 }
335 }
336 }
337 }
338 }
339 set
340}
341
342fn walk_between<'g>(
343 graph: &'g RetainedDepGraph,
344 sources: &FxIndexSet<&'g DepNode>,
345 targets: &FxIndexSet<&'g DepNode>,
346) -> FxIndexSet<DepKind> {
347 #[derive(#[automatically_derived]
impl ::core::marker::Copy for State { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for State { }
#[automatically_derived]
impl ::core::clone::Clone for State {
#[inline]
fn clone(&self) -> State { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for State { }
#[automatically_derived]
impl ::core::cmp::PartialEq for State {
#[inline]
fn eq(&self, other: &State) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
353 enum State {
354 Undecided,
355 Deciding,
356 Included,
357 Excluded,
358 }
359
360 let mut node_states = ::alloc::vec::from_elem(State::Undecided, graph.inner.len_nodes())vec![State::Undecided; graph.inner.len_nodes()];
361
362 for &target in targets {
363 node_states[graph.indices[target].0] = State::Included;
364 }
365
366 for source in sources.iter().map(|&n| graph.indices[n]) {
367 recurse(graph, &mut node_states, source);
368 }
369
370 return graph
371 .nodes()
372 .into_iter()
373 .filter(|&n| {
374 let index = graph.indices[n];
375 node_states[index.0] == State::Included
376 })
377 .map(|n| n.kind)
378 .collect();
379
380 fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool {
381 match node_states[node.0] {
382 State::Included => return true,
384
385 State::Excluded => return false,
387
388 State::Deciding => return false,
390
391 State::Undecided => {}
392 }
393
394 node_states[node.0] = State::Deciding;
395
396 for neighbor_index in graph.inner.successor_nodes(node) {
397 if recurse(graph, node_states, neighbor_index) {
398 node_states[node.0] = State::Included;
399 }
400 }
401
402 if node_states[node.0] == State::Deciding {
404 node_states[node.0] = State::Excluded;
405 false
406 } else {
407 if !(node_states[node.0] == State::Included) {
::core::panicking::panic("assertion failed: node_states[node.0] == State::Included")
};assert!(node_states[node.0] == State::Included);
408 true
409 }
410 }
411}
412
413fn filter_edges(graph: &RetainedDepGraph, nodes: &FxIndexSet<DepKind>) -> Vec<(DepKind, DepKind)> {
414 let uniq: FxIndexSet<_> = graph
415 .edges()
416 .into_iter()
417 .map(|(s, t)| (s.kind, t.kind))
418 .filter(|(source, target)| nodes.contains(source) && nodes.contains(target))
419 .collect();
420 uniq.into_iter().collect()
421}