Skip to content

Commit a4c4937

Browse files
committed
Restrict From<S> for {D,Subd}iagnosticMessage.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static, str>`, which are reasonable. It also includes `&String`, which is pretty weird, and results in many places making unnecessary allocations for patterns like this: ``` self.fatal(&format!(...)) ``` This creates a string with `format!`, takes a reference, passes the reference to `fatal`, which does an `into()`, which clones the reference, doing a second allocation. Two allocations for a single string, bleh. This commit changes the `From` impls so that you can only create a `{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static, str>`. This requires changing all the places that currently create one from a `&String`. Most of these are of the `&format!(...)` form described above; each one removes an unnecessary static `&`, plus an allocation when executed. There are also a few places where the existing use of `&String` was more reasonable; these now just use `clone()` at the call site. As well as making the code nicer and more efficient, this is a step towards possibly using `Cow<'static, str>` in `{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing the `From<&'a str>` impls to `From<&'static str>`, which is doable, but I'm not yet sure if it's worthwhile.
1 parent 249a6f8 commit a4c4937

File tree

14 files changed

+37
-38
lines changed

14 files changed

+37
-38
lines changed

src/abi/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,10 @@ pub(crate) fn import_function<'tcx>(
8888
let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst);
8989
match module.declare_function(name, Linkage::Import, &sig) {
9090
Ok(func_id) => func_id,
91-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
91+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
9292
"attempt to declare `{name}` as function, but it was already declared as static"
9393
)),
94-
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(&format!(
94+
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(format!(
9595
"attempt to declare `{name}` with signature {new_sig:?}, \
9696
but it was already declared with signature {prev_sig:?}"
9797
)),
@@ -548,7 +548,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
548548
if !matches!(fn_sig.abi(), Abi::C { .. }) {
549549
fx.tcx.sess.span_fatal(
550550
source_info.span,
551-
&format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
551+
format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
552552
);
553553
}
554554
let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap();
@@ -560,7 +560,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
560560
// FIXME set %al to upperbound on float args once floats are supported
561561
fx.tcx.sess.span_fatal(
562562
source_info.span,
563-
&format!("Non int ty {:?} for variadic call", ty),
563+
format!("Non int ty {:?} for variadic call", ty),
564564
);
565565
}
566566
AbiParam::new(ty)

src/base.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,13 +220,13 @@ pub(crate) fn verify_func(
220220
match cranelift_codegen::verify_function(&func, &flags) {
221221
Ok(_) => {}
222222
Err(err) => {
223-
tcx.sess.err(&format!("{:?}", err));
223+
tcx.sess.err(format!("{:?}", err));
224224
let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
225225
&func,
226226
Some(Box::new(writer)),
227227
err,
228228
);
229-
tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
229+
tcx.sess.fatal(format!("cranelift verify error:\n{}", pretty_error));
230230
}
231231
}
232232
});

src/common.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
481481
#[inline]
482482
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
483483
if let layout::LayoutError::SizeOverflow(_) = err {
484-
self.0.sess.span_fatal(span, &err.to_string())
484+
self.0.sess.span_fatal(span, err.to_string())
485485
} else {
486486
span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
487487
}
@@ -499,7 +499,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
499499
fn_abi_request: FnAbiRequest<'tcx>,
500500
) -> ! {
501501
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
502-
self.0.sess.span_fatal(span, &err.to_string())
502+
self.0.sess.span_fatal(span, err.to_string())
503503
} else {
504504
match fn_abi_request {
505505
FnAbiRequest::OfFnPtr { sig, extra_args } => {

src/concurrency_limiter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl ConcurrencyLimiter {
6565
// Make sure to drop the mutex guard first to prevent poisoning the mutex.
6666
drop(state);
6767
if let Some(err) = err {
68-
handler.fatal(&err).raise();
68+
handler.fatal(err).raise();
6969
} else {
7070
// The error was already emitted, but compilation continued. Raise a silent
7171
// fatal error.

src/constant.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ fn data_id_for_static(
308308
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
309309
) {
310310
Ok(data_id) => data_id,
311-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
311+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
312312
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
313313
)),
314314
Err(err) => Err::<_, _>(err).unwrap(),
@@ -356,7 +356,7 @@ fn data_id_for_static(
356356
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
357357
) {
358358
Ok(data_id) => data_id,
359-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
359+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
360360
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
361361
)),
362362
Err(err) => Err::<_, _>(err).unwrap(),
@@ -404,7 +404,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
404404
if let Some(names) = section_name.split_once(',') {
405405
names
406406
} else {
407-
tcx.sess.fatal(&format!(
407+
tcx.sess.fatal(format!(
408408
"#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
409409
section_name
410410
));
@@ -449,7 +449,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
449449
GlobalAlloc::Static(def_id) => {
450450
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
451451
{
452-
tcx.sess.fatal(&format!(
452+
tcx.sess.fatal(format!(
453453
"Allocation {:?} contains reference to TLS value {:?}",
454454
alloc_id, def_id
455455
));

src/driver/aot.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ impl OngoingCodegen {
6969

7070
let module_codegen_result = match module_codegen_result {
7171
Ok(module_codegen_result) => module_codegen_result,
72-
Err(err) => sess.fatal(&err),
72+
Err(err) => sess.fatal(err),
7373
};
7474
let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } =
7575
module_codegen_result;
@@ -468,7 +468,7 @@ pub(crate) fn run_aot(
468468
let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name);
469469

470470
if let Err(err) = std::fs::write(&tmp_file, obj) {
471-
tcx.sess.fatal(&format!("error writing metadata object file: {}", err));
471+
tcx.sess.fatal(format!("error writing metadata object file: {}", err));
472472
}
473473

474474
(metadata_cgu_name, tmp_file)

src/intrinsics/llvm.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
4242
_ => {
4343
fx.tcx
4444
.sess
45-
.warn(&format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
45+
.warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
4646
crate::trap::trap_unimplemented(fx, intrinsic);
4747
return;
4848
}

src/intrinsics/llvm_aarch64.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
207207
}
208208
*/
209209
_ => {
210-
fx.tcx.sess.warn(&format!(
210+
fx.tcx.sess.warn(format!(
211211
"unsupported AArch64 llvm intrinsic {}; replacing with trap",
212212
intrinsic
213213
));

src/intrinsics/llvm_x86.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
138138
llvm_add_sub(fx, BinOp::Sub, ret, b_in, a, b);
139139
}
140140
_ => {
141-
fx.tcx.sess.warn(&format!(
142-
"unsupported x86 llvm intrinsic {}; replacing with trap",
143-
intrinsic
144-
));
141+
fx.tcx
142+
.sess
143+
.warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic));
145144
crate::trap::trap_unimplemented(fx, intrinsic);
146145
return;
147146
}

src/intrinsics/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ fn report_atomic_type_validation_error<'tcx>(
4242
) {
4343
fx.tcx.sess.span_err(
4444
span,
45-
&format!(
45+
format!(
4646
"`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`",
4747
intrinsic, ty
4848
),
@@ -1202,7 +1202,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
12021202
_ => {
12031203
fx.tcx
12041204
.sess
1205-
.span_fatal(source_info.span, &format!("unsupported intrinsic {}", intrinsic));
1205+
.span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic));
12061206
}
12071207
}
12081208

src/intrinsics/simd.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ fn report_simd_type_validation_error(
1313
span: Span,
1414
ty: Ty<'_>,
1515
) {
16-
fx.tcx.sess.span_err(span, &format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
16+
fx.tcx.sess.span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
1717
// Prevent verifier error
1818
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
1919
}
@@ -150,7 +150,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
150150
_ => {
151151
fx.tcx.sess.span_err(
152152
span,
153-
&format!(
153+
format!(
154154
"simd_shuffle index must be an array of `u32`, got `{}`",
155155
idx_ty,
156156
),
@@ -248,7 +248,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
248248
if idx >= lane_count.into() {
249249
fx.tcx.sess.span_fatal(
250250
fx.mir.span,
251-
&format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
251+
format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
252252
);
253253
}
254254

@@ -296,7 +296,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
296296
if idx >= lane_count.into() {
297297
fx.tcx.sess.span_fatal(
298298
fx.mir.span,
299-
&format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
299+
format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
300300
);
301301
}
302302

@@ -699,7 +699,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
699699
_ => {
700700
fx.tcx.sess.span_fatal(
701701
span,
702-
&format!(
702+
format!(
703703
"invalid monomorphization of `simd_bitmask` intrinsic: \
704704
vector argument `{}`'s element type `{}`, expected integer element \
705705
type",
@@ -739,7 +739,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
739739
_ => {
740740
fx.tcx.sess.span_fatal(
741741
span,
742-
&format!(
742+
format!(
743743
"invalid monomorphization of `simd_bitmask` intrinsic: \
744744
cannot return `{}`, expected `u{}` or `[u8; {}]`",
745745
ret.layout().ty,
@@ -875,7 +875,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
875875
}
876876

877877
_ => {
878-
fx.tcx.sess.span_err(span, &format!("Unknown SIMD intrinsic {}", intrinsic));
878+
fx.tcx.sess.span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic));
879879
// Prevent verifier error
880880
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
881881
}

src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
185185
let mut config = self.config.borrow_mut();
186186
if config.is_none() {
187187
let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
188-
.unwrap_or_else(|err| sess.fatal(&err));
188+
.unwrap_or_else(|err| sess.fatal(err));
189189
*config = Some(new_config);
190190
}
191191
}
@@ -245,7 +245,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
245245
fn target_triple(sess: &Session) -> target_lexicon::Triple {
246246
match sess.target.llvm_target.parse() {
247247
Ok(triple) => triple,
248-
Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
248+
Err(err) => sess.fatal(format!("target not recognized: {}", err)),
249249
}
250250
}
251251

@@ -307,7 +307,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
307307
Some(value) => {
308308
let mut builder =
309309
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
310-
sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
310+
sess.fatal(format!("can't compile for {}: {}", target_triple, err));
311311
});
312312
if let Err(_) = builder.enable(value) {
313313
sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
@@ -317,7 +317,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
317317
None => {
318318
let mut builder =
319319
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
320-
sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
320+
sess.fatal(format!("can't compile for {}: {}", target_triple, err));
321321
});
322322
if target_triple.architecture == target_lexicon::Architecture::X86_64 {
323323
// Don't use "haswell" as the default, as it implies `has_lzcnt`.
@@ -330,7 +330,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
330330

331331
match isa_builder.finish(flags) {
332332
Ok(target_isa) => target_isa,
333-
Err(err) => sess.fatal(&format!("failed to build TargetIsa: {}", err)),
333+
Err(err) => sess.fatal(format!("failed to build TargetIsa: {}", err)),
334334
}
335335
}
336336

src/main_shim.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ pub(crate) fn maybe_create_entry_wrapper(
7575
Ok(func_id) => func_id,
7676
Err(err) => {
7777
tcx.sess
78-
.fatal(&format!("entry symbol `{entry_name}` declared multiple times: {err}"));
78+
.fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}"));
7979
}
8080
};
8181

@@ -171,7 +171,7 @@ pub(crate) fn maybe_create_entry_wrapper(
171171
}
172172

173173
if let Err(err) = m.define_function(cmain_func_id, &mut ctx) {
174-
tcx.sess.fatal(&format!("entry symbol `{entry_name}` defined multiple times: {err}"));
174+
tcx.sess.fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}"));
175175
}
176176

177177
unwind_context.add_function(cmain_func_id, &ctx, m.isa());

src/value_and_place.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ impl<'tcx> CPlace<'tcx> {
344344
if layout.size.bytes() >= u64::from(u32::MAX - 16) {
345345
fx.tcx
346346
.sess
347-
.fatal(&format!("values of type {} are too big to store on the stack", layout.ty));
347+
.fatal(format!("values of type {} are too big to store on the stack", layout.ty));
348348
}
349349

350350
let stack_slot = fx.bcx.create_sized_stack_slot(StackSlotData {

0 commit comments

Comments
 (0)