Skip to content

Commit 523a1b1

Browse files
committed
Auto merge of #94062 - Mark-Simulacrum:drop-print-cfg, r=oli-obk
Move ty::print methods to Drop-based scope guards Primary goal is reducing codegen of the TLS access for each closure, which shaves ~3 seconds of bootstrap time over rustc as a whole.
2 parents c1aa854 + 9763486 commit 523a1b1

File tree

30 files changed

+140
-140
lines changed

30 files changed

+140
-140
lines changed

compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs

+21-15
Original file line numberDiff line numberDiff line change
@@ -779,29 +779,35 @@ pub(crate) fn codegen_intrinsic_call<'tcx>(
779779
assert_inhabited | assert_zero_valid | assert_uninit_valid, <T> () {
780780
let layout = fx.layout_of(T);
781781
if layout.abi.is_uninhabited() {
782-
with_no_trimmed_paths(|| crate::base::codegen_panic(
783-
fx,
784-
&format!("attempted to instantiate uninhabited type `{}`", T),
785-
span,
786-
));
782+
with_no_trimmed_paths!({
783+
crate::base::codegen_panic(
784+
fx,
785+
&format!("attempted to instantiate uninhabited type `{}`", T),
786+
span,
787+
)
788+
});
787789
return;
788790
}
789791

790792
if intrinsic == sym::assert_zero_valid && !layout.might_permit_raw_init(fx, /*zero:*/ true) {
791-
with_no_trimmed_paths(|| crate::base::codegen_panic(
792-
fx,
793-
&format!("attempted to zero-initialize type `{}`, which is invalid", T),
794-
span,
795-
));
793+
with_no_trimmed_paths!({
794+
crate::base::codegen_panic(
795+
fx,
796+
&format!("attempted to zero-initialize type `{}`, which is invalid", T),
797+
span,
798+
);
799+
});
796800
return;
797801
}
798802

799803
if intrinsic == sym::assert_uninit_valid && !layout.might_permit_raw_init(fx, /*zero:*/ false) {
800-
with_no_trimmed_paths(|| crate::base::codegen_panic(
801-
fx,
802-
&format!("attempted to leave type `{}` uninitialized, which is invalid", T),
803-
span,
804-
));
804+
with_no_trimmed_paths!({
805+
crate::base::codegen_panic(
806+
fx,
807+
&format!("attempted to leave type `{}` uninitialized, which is invalid", T),
808+
span,
809+
)
810+
});
805811
return;
806812
}
807813
};

compiler/rustc_codegen_gcc/src/type_of.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub fn uncached_gcc_type<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, layout: TyAndLa
5252
ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str
5353
if !cx.sess().fewer_names() =>
5454
{
55-
let mut name = with_no_trimmed_paths(|| layout.ty.to_string());
55+
let mut name = with_no_trimmed_paths!(layout.ty.to_string());
5656
if let (&ty::Adt(def, _), &Variants::Single { index }) =
5757
(layout.ty.kind(), &layout.variants)
5858
{

compiler/rustc_codegen_llvm/src/type_of.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ fn uncached_llvm_type<'a, 'tcx>(
4343
// in problematically distinct types due to HRTB and subtyping (see #47638).
4444
// ty::Dynamic(..) |
4545
ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str => {
46-
let mut name =
47-
with_no_visible_paths(|| with_no_trimmed_paths(|| layout.ty.to_string()));
46+
let mut name = with_no_visible_paths!(with_no_trimmed_paths!(layout.ty.to_string()));
4847
if let (&ty::Adt(def, _), &Variants::Single { index }) =
4948
(layout.ty.kind(), &layout.variants)
5049
{

compiler/rustc_codegen_ssa/src/mir/block.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -549,8 +549,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
549549
UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false),
550550
};
551551
if do_panic {
552-
let msg_str = with_no_visible_paths(|| {
553-
with_no_trimmed_paths(|| {
552+
let msg_str = with_no_visible_paths!({
553+
with_no_trimmed_paths!({
554554
if layout.abi.is_uninhabited() {
555555
// Use this error even for the other intrinsics as it is more precise.
556556
format!("attempted to instantiate uninhabited type `{}`", ty)

compiler/rustc_const_eval/src/const_eval/eval_queries.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
5353

5454
trace!(
5555
"eval_body_using_ecx: pushing stack frame for global: {}{}",
56-
with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
56+
with_no_trimmed_paths!(ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
5757
cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
5858
);
5959

@@ -274,7 +274,7 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
274274
// The next two lines concatenated contain some discussion:
275275
// https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
276276
// subject/anon_const_instance_printing/near/135980032
277-
let instance = with_no_trimmed_paths(|| key.value.instance.to_string());
277+
let instance = with_no_trimmed_paths!(key.value.instance.to_string());
278278
trace!("const eval: {:?} ({})", key, instance);
279279
}
280280

@@ -317,7 +317,7 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
317317
// the expression, leading to the const eval error.
318318
let instance = &key.value.instance;
319319
if !instance.substs.is_empty() {
320-
let instance = with_no_trimmed_paths(|| instance.to_string());
320+
let instance = with_no_trimmed_paths!(instance.to_string());
321321
let msg = format!("evaluation of `{}` failed", instance);
322322
Cow::from(msg)
323323
} else {

compiler/rustc_const_eval/src/interpret/validity.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ macro_rules! throw_validation_failure {
3333
msg.push_str(", but expected ");
3434
write!(&mut msg, $($expected_fmt),+).unwrap();
3535
)?
36-
let path = rustc_middle::ty::print::with_no_trimmed_paths(|| {
36+
let path = rustc_middle::ty::print::with_no_trimmed_paths!({
3737
let where_ = &$where;
3838
if !where_.is_empty() {
3939
let mut path = String::new();

compiler/rustc_const_eval/src/transform/check_consts/ops.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,10 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
108108
.as_ref()
109109
.and_then(|node| node.generics())
110110
{
111-
let constraint = with_no_trimmed_paths(|| {
112-
format!("~const {}", trait_ref.print_only_trait_path())
113-
});
111+
let constraint = with_no_trimmed_paths!(format!(
112+
"~const {}",
113+
trait_ref.print_only_trait_path()
114+
));
114115
suggest_constraining_type_param(
115116
tcx,
116117
generics,

compiler/rustc_lint/src/builtin.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2634,7 +2634,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue {
26342634
// We are extremely conservative with what we warn about.
26352635
let conjured_ty = cx.typeck_results().expr_ty(expr);
26362636
if let Some((msg, span)) =
2637-
with_no_trimmed_paths(|| ty_find_init_error(cx.tcx, conjured_ty, init))
2637+
with_no_trimmed_paths!(ty_find_init_error(cx.tcx, conjured_ty, init))
26382638
{
26392639
cx.struct_span_lint(INVALID_VALUE, expr.span, |lint| {
26402640
let mut err = lint.build(&format!(

compiler/rustc_lint/src/context.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -993,7 +993,7 @@ impl<'tcx> LateContext<'tcx> {
993993
}
994994

995995
// This shouldn't ever be needed, but just in case:
996-
with_no_trimmed_paths(|| {
996+
with_no_trimmed_paths!({
997997
Ok(vec![match trait_ref {
998998
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
999999
None => Symbol::intern(&format!("<{}>", self_ty)),
@@ -1012,15 +1012,15 @@ impl<'tcx> LateContext<'tcx> {
10121012

10131013
// This shouldn't ever be needed, but just in case:
10141014
path.push(match trait_ref {
1015-
Some(trait_ref) => with_no_trimmed_paths(|| {
1016-
Symbol::intern(&format!(
1015+
Some(trait_ref) => {
1016+
with_no_trimmed_paths!(Symbol::intern(&format!(
10171017
"<impl {} for {}>",
10181018
trait_ref.print_only_trait_path(),
10191019
self_ty
1020-
))
1021-
}),
1020+
)))
1021+
}
10221022
None => {
1023-
with_no_trimmed_paths(|| Symbol::intern(&format!("<impl {}>", self_ty)))
1023+
with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
10241024
}
10251025
});
10261026

compiler/rustc_macros/src/query.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,9 @@ fn add_query_description_impl(
434434
#[allow(unused_variables)]
435435
fn describe(tcx: QueryCtxt<$tcx>, key: Self::Key) -> String {
436436
let (#tcx, #key) = (*tcx, key);
437-
::rustc_middle::ty::print::with_no_trimmed_paths(|| format!(#desc).into())
437+
::rustc_middle::ty::print::with_no_trimmed_paths!(
438+
format!(#desc)
439+
)
438440
}
439441
};
440442

compiler/rustc_middle/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
#![feature(try_reserve_kind)]
5656
#![feature(nonzero_ops)]
5757
#![feature(unwrap_infallible)]
58+
#![feature(decl_macro)]
5859
#![recursion_limit = "512"]
5960
#![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
6061

compiler/rustc_middle/src/middle/stability.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ impl<'tcx> TyCtxt<'tcx> {
367367
let is_in_effect = deprecation_in_effect(depr_attr);
368368
let lint = deprecation_lint(is_in_effect);
369369
if self.lint_level_at_node(lint, id).0 != Level::Allow {
370-
let def_path = &with_no_trimmed_paths(|| self.def_path_str(def_id));
370+
let def_path = with_no_trimmed_paths!(self.def_path_str(def_id));
371371
let def_kind = self.def_kind(def_id).descr(def_id);
372372

373373
late_report_deprecation(
@@ -377,7 +377,7 @@ impl<'tcx> TyCtxt<'tcx> {
377377
depr_attr.since,
378378
depr_attr.note,
379379
def_kind,
380-
def_path,
380+
&def_path,
381381
),
382382
depr_attr.suggestion,
383383
lint,

compiler/rustc_middle/src/mir/interpret/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ pub struct GlobalId<'tcx> {
147147

148148
impl<'tcx> GlobalId<'tcx> {
149149
pub fn display(self, tcx: TyCtxt<'tcx>) -> String {
150-
let instance_name = with_no_trimmed_paths(|| tcx.def_path_str(self.instance.def.def_id()));
150+
let instance_name = with_no_trimmed_paths!(tcx.def_path_str(self.instance.def.def_id()));
151151
if let Some(promoted) = self.promoted {
152152
format!("{}::{:?}", instance_name, promoted)
153153
} else {

compiler/rustc_middle/src/mir/pretty.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,8 @@ pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) ->
9292
let Some(ref filters) = tcx.sess.opts.debugging_opts.dump_mir else {
9393
return false;
9494
};
95-
let node_path = ty::print::with_forced_impl_filename_line(|| {
96-
// see notes on #41697 below
97-
tcx.def_path_str(def_id)
98-
});
95+
// see notes on #41697 below
96+
let node_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(def_id));
9997
filters.split('|').any(|or_filter| {
10098
or_filter.split('&').all(|and_filter| {
10199
let and_filter_trimmed = and_filter.trim();
@@ -123,10 +121,9 @@ fn dump_matched_mir_node<'tcx, F>(
123121
let _: io::Result<()> = try {
124122
let mut file =
125123
create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
126-
let def_path = ty::print::with_forced_impl_filename_line(|| {
127-
// see notes on #41697 above
128-
tcx.def_path_str(body.source.def_id())
129-
});
124+
// see notes on #41697 above
125+
let def_path =
126+
ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
130127
write!(file, "// MIR for `{}", def_path)?;
131128
match body.source.promoted {
132129
None => write!(file, "`")?,
@@ -969,10 +966,10 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res
969966
_ => bug!("Unexpected def kind {:?}", kind),
970967
}
971968

972-
ty::print::with_forced_impl_filename_line(|| {
969+
ty::print::with_forced_impl_filename_line! {
973970
// see notes on #41697 elsewhere
974-
write!(w, "{}", tcx.def_path_str(def_id))
975-
})?;
971+
write!(w, "{}", tcx.def_path_str(def_id))?
972+
}
976973

977974
if body.source.promoted.is_none() && is_function {
978975
write!(w, "(")?;

compiler/rustc_middle/src/ty/print/pretty.rs

+51-58
Original file line numberDiff line numberDiff line change
@@ -63,66 +63,59 @@ thread_local! {
6363
static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
6464
}
6565

66-
/// Avoids running any queries during any prints that occur
67-
/// during the closure. This may alter the appearance of some
68-
/// types (e.g. forcing verbose printing for opaque types).
69-
/// This method is used during some queries (e.g. `explicit_item_bounds`
70-
/// for opaque types), to ensure that any debug printing that
71-
/// occurs during the query computation does not end up recursively
72-
/// calling the same query.
73-
pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
74-
NO_QUERIES.with(|no_queries| {
75-
let old = no_queries.replace(true);
76-
let result = f();
77-
no_queries.set(old);
78-
result
79-
})
80-
}
81-
82-
/// Force us to name impls with just the filename/line number. We
83-
/// normally try to use types. But at some points, notably while printing
84-
/// cycle errors, this can result in extra or suboptimal error output,
85-
/// so this variable disables that check.
86-
pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
87-
FORCE_IMPL_FILENAME_LINE.with(|force| {
88-
let old = force.replace(true);
89-
let result = f();
90-
force.set(old);
91-
result
92-
})
93-
}
66+
macro_rules! define_helper {
67+
($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
68+
$(
69+
#[must_use]
70+
pub struct $helper(bool);
71+
72+
impl $helper {
73+
pub fn new() -> $helper {
74+
$helper($tl.with(|c| c.replace(true)))
75+
}
76+
}
9477

95-
/// Adds the `crate::` prefix to paths where appropriate.
96-
pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
97-
SHOULD_PREFIX_WITH_CRATE.with(|flag| {
98-
let old = flag.replace(true);
99-
let result = f();
100-
flag.set(old);
101-
result
102-
})
103-
}
78+
$(#[$a])*
79+
pub macro $name($e:expr) {
80+
{
81+
let _guard = $helper::new();
82+
$e
83+
}
84+
}
10485

105-
/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
106-
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
107-
/// if no other `Vec` is found.
108-
pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
109-
NO_TRIMMED_PATH.with(|flag| {
110-
let old = flag.replace(true);
111-
let result = f();
112-
flag.set(old);
113-
result
114-
})
86+
impl Drop for $helper {
87+
fn drop(&mut self) {
88+
$tl.with(|c| c.set(self.0))
89+
}
90+
}
91+
)+
92+
}
11593
}
11694

117-
/// Prevent selection of visible paths. `Display` impl of DefId will prefer visible (public) reexports of types as paths.
118-
pub fn with_no_visible_paths<F: FnOnce() -> R, R>(f: F) -> R {
119-
NO_VISIBLE_PATH.with(|flag| {
120-
let old = flag.replace(true);
121-
let result = f();
122-
flag.set(old);
123-
result
124-
})
125-
}
95+
define_helper!(
96+
/// Avoids running any queries during any prints that occur
97+
/// during the closure. This may alter the appearance of some
98+
/// types (e.g. forcing verbose printing for opaque types).
99+
/// This method is used during some queries (e.g. `explicit_item_bounds`
100+
/// for opaque types), to ensure that any debug printing that
101+
/// occurs during the query computation does not end up recursively
102+
/// calling the same query.
103+
fn with_no_queries(NoQueriesGuard, NO_QUERIES);
104+
/// Force us to name impls with just the filename/line number. We
105+
/// normally try to use types. But at some points, notably while printing
106+
/// cycle errors, this can result in extra or suboptimal error output,
107+
/// so this variable disables that check.
108+
fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
109+
/// Adds the `crate::` prefix to paths where appropriate.
110+
fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
111+
/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
112+
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
113+
/// if no other `Vec` is found.
114+
fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
115+
/// Prevent selection of visible paths. `Display` impl of DefId will prefer
116+
/// visible (public) reexports of types as paths.
117+
fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
118+
);
126119

127120
/// The "region highlights" are used to control region printing during
128121
/// specific error messages. When a "region highlight" is enabled, it
@@ -379,7 +372,7 @@ pub trait PrettyPrinter<'tcx>:
379372
// in cases where the `extern crate foo` has non-trivial
380373
// parents, e.g. it's nested in `impl foo::Trait for Bar`
381374
// (see also issues #55779 and #87932).
382-
self = with_no_visible_paths(|| self.print_def_path(def_id, &[]))?;
375+
self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
383376

384377
return Ok((self, true));
385378
}
@@ -654,7 +647,7 @@ pub trait PrettyPrinter<'tcx>:
654647
return Ok(self);
655648
}
656649

657-
return with_no_queries(|| {
650+
return with_no_queries!({
658651
let def_key = self.tcx().def_key(def_id);
659652
if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
660653
p!(write("{}", name));

0 commit comments

Comments
 (0)