Skip to content

Commit

Permalink
Avoid ref when using format! in compiler
Browse files Browse the repository at this point in the history
Clean up a few minor refs in `format!` macro, as it has a performance cost. Apparently the compiler is unable to inline `format!("{}", &variable)`, and does a run-time double-reference instead (format macro already does one level referencing).  Inlining format args prevents accidental `&` misuse.
  • Loading branch information
nyurik committed Jul 19, 2024
1 parent 0cd01aa commit aef0e34
Show file tree
Hide file tree
Showing 23 changed files with 61 additions and 65 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/src/abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
let nop_inst = fx.bcx.ins().nop();
fx.add_comment(
nop_inst,
format!("virtual call; self arg pass mode: {:?}", &fn_abi.args[0]),
format!("virtual call; self arg pass mode: {:?}", fn_abi.args[0]),
);
}

Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,7 @@ fn link_natively(
sess.dcx().abort_if_errors();

// Invoke the system linker
info!("{:?}", &cmd);
info!("{cmd:?}");
let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
let unknown_arg_regex =
Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
Expand Down Expand Up @@ -796,7 +796,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}

Expand All @@ -817,7 +817,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}

Expand Down Expand Up @@ -878,7 +878,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}

Expand Down Expand Up @@ -996,7 +996,7 @@ fn link_natively(
sess.dcx().emit_err(errors::UnableToExeLinker {
linker_path,
error: e,
command_formatted: format!("{:?}", &cmd),
command_formatted: format!("{cmd:?}"),
});
}

Expand Down Expand Up @@ -1567,7 +1567,7 @@ fn print_native_static_libs(
sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
// Prefix for greppability
// Note: This must not be translated as tools are allowed to depend on this exact string.
sess.dcx().note(format!("native-static-libs: {}", &lib_args.join(" ")));
sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
sym::link_section => {
if let Some(val) = attr.value_str() {
if val.as_str().bytes().any(|b| b == 0) {
let msg = format!("illegal null byte in link_section value: `{}`", &val);
let msg = format!("illegal null byte in link_section value: `{val}`");
tcx.dcx().span_err(attr.span, msg);
} else {
codegen_fn_attrs.link_section = Some(val);
Expand Down Expand Up @@ -726,7 +726,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
if *ordinal <= u16::MAX as u128 {
Some(ordinal.get() as u16)
} else {
let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
let msg = format!("ordinal value in `link_ordinal` is too large: `{ordinal}`");
tcx.dcx()
.struct_span_err(attr.span, msg)
.with_note("the value may not exceed `u16::MAX`")
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/mono_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {

let symbol_name = self.symbol_name(cx.tcx()).name;

debug!("symbol {}", &symbol_name);
debug!("symbol {symbol_name}");

match *self {
MonoItem::Static(def_id) => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_fluent_macro/src/fluent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok

for Attribute { id: Identifier { name: attr_name }, .. } in attributes {
let snake_name = Ident::new(
&format!("{}{}", &crate_prefix, &attr_name.replace('-', "_")),
&format!("{crate_prefix}{}", attr_name.replace('-', "_")),
resource_str.span(),
);
if !previous_attrs.insert(snake_name.clone()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
self.path_segment.hir_id,
num_params_to_take,
);
debug!("suggested_args: {:?}", &suggested_args);
debug!("suggested_args: {suggested_args:?}");

match self.angle_brackets {
AngleBrackets::Missing => {
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ fn check_explicit_predicates<'tcx>(
let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);

for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
debug!("outlives_predicate = {:?}", &outlives_predicate);
debug!("outlives_predicate = {outlives_predicate:?}");

// Careful: If we are inferring the effects of a `dyn Trait<..>`
// type, then when we look up the predicates for `Trait`,
Expand Down Expand Up @@ -289,12 +289,12 @@ fn check_explicit_predicates<'tcx>(
&& let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
&& ty.walk().any(|arg| arg == self_ty.into())
{
debug!("skipping self ty = {:?}", &ty);
debug!("skipping self ty = {ty:?}");
continue;
}

let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args);
debug!("predicate = {:?}", &predicate);
debug!("predicate = {predicate:?}");
insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1265,9 +1265,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
(
match parent_pred {
None => format!("`{}`", &p),
None => format!("`{p}`"),
Some(parent_pred) => match format_pred(*parent_pred) {
None => format!("`{}`", &p),
None => format!("`{p}`"),
Some((parent_p, _)) => {
if !suggested
&& !suggested_bounds.contains(pred)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/middle/stability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ pub fn report_unstable(
) {
let msg = match reason {
Some(r) => format!("use of unstable library feature '{feature}': {r}"),
None => format!("use of unstable library feature '{}'", &feature),
None => format!("use of unstable library feature '{feature}'"),
};

if is_soft {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2627,7 +2627,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> {
self.prepare_region_info(value);
}

debug!("self.used_region_names: {:?}", &self.used_region_names);
debug!("self.used_region_names: {:?}", self.used_region_names);

let mut empty = true;
let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/util/find_self_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn find_self_call<'tcx>(
local: Local,
block: BasicBlock,
) -> Option<(DefId, GenericArgsRef<'tcx>)> {
debug!("find_self_call(local={:?}): terminator={:?}", local, &body[block].terminator);
debug!("find_self_call(local={:?}): terminator={:?}", local, body[block].terminator);
if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) =
&body[block].terminator
{
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_dataflow/src/impls/initialized.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for EverInitializedPlaces<'_, '_, 'tcx> {
let init_loc_map = &move_data.init_loc_map;
let rev_lookup = &move_data.rev_lookup;

debug!("initializes move_indexes {:?}", &init_loc_map[location]);
debug!("initializes move_indexes {:?}", init_loc_map[location]);
trans.gen_all(init_loc_map[location].iter().copied());

if let mir::StatementKind::StorageDead(local) = stmt.kind {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/dead_store_elimination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub fn eliminate<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
| StatementKind::Nop => (),

StatementKind::FakeRead(_) | StatementKind::AscribeUserType(_, _) => {
bug!("{:?} not found in this MIR phase!", &statement.kind)
bug!("{:?} not found in this MIR phase!", statement.kind)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_mir_transform/src/early_otherwise_branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,11 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch {
let parent = BasicBlock::from_usize(i);
let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { continue };

if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_data)) {
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {opt_data:?}")) {
break;
}

trace!("SUCCESS: found optimization possibility to apply: {:?}", &opt_data);
trace!("SUCCESS: found optimization possibility to apply: {opt_data:?}");

should_cleanup = true;

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_pattern_analysis/src/constructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ impl<Cx: PatCx> Constructor<Cx> {
// be careful to detect strings here. However a string literal pattern will never
// be reported as a non-exhaustiveness witness, so we can ignore this issue.
Ref => {
write!(f, "&{:?}", &fields.next().unwrap())?;
write!(f, "&{:?}", fields.next().unwrap())?;
}
Slice(slice) => {
write!(f, "[")?;
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
BuiltinLintDiag::AmbiguousGlobImports { diag },
);
} else {
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", &diag.msg);
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
report_ambiguity_error(&mut err, diag);
err.emit();
}
Expand Down Expand Up @@ -798,7 +798,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}
ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
let mut err =
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {}", &label);
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
err.span_label(span, label);

if let Some((suggestions, msg, applicability)) = suggestion {
Expand Down Expand Up @@ -2893,7 +2893,7 @@ fn show_candidates(
""
};
candidate.0 =
format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
}

match mode {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
.collect::<Vec<_>>();
let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);

let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{}", &msg);
let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");

if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
diag.note(note.clone());
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/rustdoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGen
}
}

debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
debug!("path_str: {path_str:?}\nstripped segments: {stripped_segments:?}");

let stripped_path = stripped_segments.join("::");

Expand Down
28 changes: 14 additions & 14 deletions compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,12 @@ fn encode_predicate<'tcx>(
match predicate.as_ref().skip_binder() {
ty::ExistentialPredicate::Trait(trait_ref) => {
let name = encode_ty_name(tcx, trait_ref.def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
}
ty::ExistentialPredicate::Projection(projection) => {
let name = encode_ty_name(tcx, projection.def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
match projection.term.unpack() {
TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
Expand All @@ -258,7 +258,7 @@ fn encode_predicate<'tcx>(
}
ty::ExistentialPredicate::AutoTrait(def_id) => {
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
}
};
compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
Expand Down Expand Up @@ -416,7 +416,7 @@ pub fn encode_ty<'tcx>(
// A<array-length><element-type>
let len = len.eval_target_usize(tcx, ty::ParamEnv::reveal_all());
let mut s = String::from("A");
let _ = write!(s, "{}", &len);
let _ = write!(s, "{len}");
s.push_str(&encode_ty(tcx, *ty0, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
Expand Down Expand Up @@ -492,13 +492,13 @@ pub fn encode_ty<'tcx>(
// calling convention (or extern types [i.e., ty::Foreign]) as <length><name>, where
// <name> is <unscoped-name>.
let name = tcx.item_name(def_id).to_string();
let _ = write!(s, "{}{}", name.len(), &name);
let _ = write!(s, "{}{}", name.len(), name);
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
} else {
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is
// <subst>, as vendor extended type.
let name = encode_ty_name(tcx, def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
}
Expand Down Expand Up @@ -530,7 +530,7 @@ pub fn encode_ty<'tcx>(
}
} else {
let name = tcx.item_name(*def_id).to_string();
let _ = write!(s, "{}{}", name.len(), &name);
let _ = write!(s, "{}{}", name.len(), name);
}
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
Expand All @@ -542,7 +542,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
Expand All @@ -553,7 +553,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
Expand All @@ -565,7 +565,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
// Encode parent args only
s.push_str(&encode_args(
tcx,
Expand All @@ -588,7 +588,7 @@ pub fn encode_ty<'tcx>(
s.push('E');
compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
if ty.is_mutable_ptr() {
s = format!("{}{}", "U3mut", &s);
s = format!("{}{}", "U3mut", s);
compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
}
typeid.push_str(&s);
Expand All @@ -600,10 +600,10 @@ pub fn encode_ty<'tcx>(
let mut s = String::new();
s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
if !ty.is_mutable_ptr() {
s = format!("{}{}", "K", &s);
s = format!("{}{}", "K", s);
compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
};
s = format!("{}{}", "P", &s);
s = format!("{}{}", "P", s);
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
}
Expand Down Expand Up @@ -722,7 +722,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
s.push('C');
s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
let crate_name = tcx.crate_name(def_path.krate).to_string();
let _ = write!(s, "{}{}", crate_name.len(), &crate_name);
let _ = write!(s, "{}{}", crate_name.len(), crate_name);

// Disambiguators and names
def_path.data.reverse();
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_type_ir/src/const_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,13 @@ impl<I: Interner> fmt::Debug for ConstKind<I> {

match self {
Param(param) => write!(f, "{param:?}"),
Infer(var) => write!(f, "{:?}", &var),
Infer(var) => write!(f, "{var:?}"),
Bound(debruijn, var) => crate::debug_bound_var(f, *debruijn, var),
Placeholder(placeholder) => write!(f, "{placeholder:?}"),
Unevaluated(uv) => {
write!(f, "{:?}", &uv)
}
Value(ty, valtree) => write!(f, "({valtree:?}: {:?})", &ty),
Unevaluated(uv) => write!(f, "{uv:?}"),
Value(ty, valtree) => write!(f, "({valtree:?}: {ty:?})"),
Error(_) => write!(f, "{{const error}}"),
Expr(expr) => write!(f, "{:?}", &expr),
Expr(expr) => write!(f, "{expr:?}"),
}
}
}
Expand Down
Loading

0 comments on commit aef0e34

Please sign in to comment.