Skip to content

Commit 65b6cdb

Browse files
committed
Auto merge of #144562 - matthiaskrgr:rollup-mlvn7qo, r=matthiaskrgr
Rollup of 7 pull requests Successful merges: - #144072 (update `Atomic*::from_ptr` and `Atomic*::as_ptr` docs) - #144151 (`tests/ui/issues/`: The Issues Strike Back [1/N]) - #144300 (Clippy fixes for miropt-test-tools) - #144399 (Add a ratchet for moving all standard library tests to separate packages) - #144472 (str: Mark unstable `round_char_boundary` feature functions as const) - #144503 (Various refactors to the codegen coordinator code (part 3)) - #144530 (coverage: Infer `instances_used` from `pgo_func_name_var_map`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents d242a8b + c462895 commit 65b6cdb

File tree

68 files changed

+351
-325
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

68 files changed

+351
-325
lines changed

compiler/rustc_codegen_gcc/src/back/write.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use gccjit::{Context, OutputKind};
44
use rustc_codegen_ssa::back::link::ensure_removed;
55
use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
66
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
7-
use rustc_errors::DiagCtxtHandle;
87
use rustc_fs_util::link_or_copy;
98
use rustc_session::config::OutputType;
109
use rustc_span::fatal_error::FatalError;
@@ -258,14 +257,6 @@ pub(crate) fn codegen(
258257
))
259258
}
260259

261-
pub(crate) fn link(
262-
_cgcx: &CodegenContext<GccCodegenBackend>,
263-
_dcx: DiagCtxtHandle<'_>,
264-
mut _modules: Vec<ModuleCodegen<GccContext>>,
265-
) -> Result<ModuleCodegen<GccContext>, FatalError> {
266-
unimplemented!();
267-
}
268-
269260
pub(crate) fn save_temp_bitcode(
270261
cgcx: &CodegenContext<GccCodegenBackend>,
271262
_module: &ModuleCodegen<GccContext>,

compiler/rustc_codegen_gcc/src/lib.rs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -426,14 +426,6 @@ impl WriteBackendMethods for GccCodegenBackend {
426426
fn serialize_module(_module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
427427
unimplemented!();
428428
}
429-
430-
fn run_link(
431-
cgcx: &CodegenContext<Self>,
432-
dcx: DiagCtxtHandle<'_>,
433-
modules: Vec<ModuleCodegen<Self::Module>>,
434-
) -> Result<ModuleCodegen<Self::Module>, FatalError> {
435-
back::write::link(cgcx, dcx, modules)
436-
}
437429
}
438430

439431
/// This is the entrypoint for a hot plugged rustc_codegen_gccjit

compiler/rustc_codegen_llvm/messages.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ codegen_llvm_from_llvm_optimization_diag = {$filename}:{$line}:{$column} {$pass_
1212
codegen_llvm_load_bitcode = failed to load bitcode of module "{$name}"
1313
codegen_llvm_load_bitcode_with_llvm_err = failed to load bitcode of module "{$name}": {$llvm_err}
1414
15-
codegen_llvm_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$llvm_err})
15+
codegen_llvm_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$err})
1616
1717
codegen_llvm_mismatch_data_layout =
1818
data-layout for target `{$rustc_target}`, `{$rustc_layout}`, differs from LLVM target's `{$llvm_target}` default layout, `{$llvm_layout}`

compiler/rustc_codegen_llvm/src/back/lto.rs

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use std::sync::Arc;
77
use std::{io, iter, slice};
88

99
use object::read::archive::ArchiveFile;
10+
use object::{Object, ObjectSection};
1011
use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared};
1112
use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput};
1213
use rustc_codegen_ssa::traits::*;
@@ -105,31 +106,15 @@ fn get_bitcode_slice_from_object_data<'a>(
105106
// name" which in the public API for sections gets treated as part of the section name, but
106107
// internally in MachOObjectFile.cpp gets treated separately.
107108
let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
108-
let mut len = 0;
109-
let data = unsafe {
110-
llvm::LLVMRustGetSliceFromObjectDataByName(
111-
obj.as_ptr(),
112-
obj.len(),
113-
section_name.as_ptr(),
114-
section_name.len(),
115-
&mut len,
116-
)
117-
};
118-
if !data.is_null() {
119-
assert!(len != 0);
120-
let bc = unsafe { slice::from_raw_parts(data, len) };
121109

122-
// `bc` must be a sub-slice of `obj`.
123-
assert!(obj.as_ptr() <= bc.as_ptr());
124-
assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr());
110+
let obj =
111+
object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
125112

126-
Ok(bc)
127-
} else {
128-
assert!(len == 0);
129-
Err(LtoBitcodeFromRlib {
130-
llvm_err: llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string()),
131-
})
132-
}
113+
let section = obj
114+
.section_by_name(section_name)
115+
.ok_or_else(|| LtoBitcodeFromRlib { err: format!("Can't find section {section_name}") })?;
116+
117+
section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
133118
}
134119

135120
/// Performs fat LTO by merging all modules into a single one and returning it

compiler/rustc_codegen_llvm/src/back/write.rs

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -796,29 +796,6 @@ pub(crate) fn optimize(
796796
Ok(())
797797
}
798798

799-
pub(crate) fn link(
800-
cgcx: &CodegenContext<LlvmCodegenBackend>,
801-
dcx: DiagCtxtHandle<'_>,
802-
mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
803-
) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
804-
use super::lto::{Linker, ModuleBuffer};
805-
// Sort the modules by name to ensure deterministic behavior.
806-
modules.sort_by(|a, b| a.name.cmp(&b.name));
807-
let (first, elements) =
808-
modules.split_first().expect("Bug! modules must contain at least one module.");
809-
810-
let mut linker = Linker::new(first.module_llvm.llmod());
811-
for module in elements {
812-
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
813-
let buffer = ModuleBuffer::new(module.module_llvm.llmod());
814-
linker
815-
.add(buffer.data())
816-
.map_err(|()| llvm_err(dcx, LlvmError::SerializeModule { name: &module.name }))?;
817-
}
818-
drop(linker);
819-
Ok(modules.remove(0))
820-
}
821-
822799
pub(crate) fn codegen(
823800
cgcx: &CodegenContext<LlvmCodegenBackend>,
824801
module: ModuleCodegen<ModuleLlvm>,

compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,21 +46,17 @@ pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) {
4646
debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
4747

4848
// FIXME(#132395): Can this be none even when coverage is enabled?
49-
let instances_used = match cx.coverage_cx {
50-
Some(ref cx) => cx.instances_used.borrow(),
51-
None => return,
52-
};
49+
let Some(ref coverage_cx) = cx.coverage_cx else { return };
5350

54-
let mut covfun_records = instances_used
55-
.iter()
56-
.copied()
51+
let mut covfun_records = coverage_cx
52+
.instances_used()
53+
.into_iter()
5754
// Sort by symbol name, so that the global file table is built in an
5855
// order that doesn't depend on the stable-hash-based order in which
5956
// instances were visited during codegen.
6057
.sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
6158
.filter_map(|instance| prepare_covfun_record(tcx, instance, true))
6259
.collect::<Vec<_>>();
63-
drop(instances_used);
6460

6561
// In a single designated CGU, also prepare covfun records for functions
6662
// in this crate that were instrumented for coverage, but are unused.

compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use rustc_abi::Size;
55
use rustc_codegen_ssa::traits::{
66
BuilderMethods, ConstCodegenMethods, CoverageInfoBuilderMethods, MiscCodegenMethods,
77
};
8-
use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
8+
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
99
use rustc_middle::mir::coverage::CoverageKind;
1010
use rustc_middle::ty::Instance;
1111
use tracing::{debug, instrument};
@@ -20,9 +20,14 @@ mod mapgen;
2020

2121
/// Extra per-CGU context/state needed for coverage instrumentation.
2222
pub(crate) struct CguCoverageContext<'ll, 'tcx> {
23-
/// Coverage data for each instrumented function identified by DefId.
24-
pub(crate) instances_used: RefCell<FxIndexSet<Instance<'tcx>>>,
25-
pub(crate) pgo_func_name_var_map: RefCell<FxHashMap<Instance<'tcx>, &'ll llvm::Value>>,
23+
/// Associates function instances with an LLVM global that holds the
24+
/// function's symbol name, as needed by LLVM coverage intrinsics.
25+
///
26+
/// Instances in this map are also considered "used" for the purposes of
27+
/// emitting covfun records. Every covfun record holds a hash of its
28+
/// symbol name, and `llvm-cov` will exit fatally if it can't resolve that
29+
/// hash back to an entry in the binary's `__llvm_prf_names` linker section.
30+
pub(crate) pgo_func_name_var_map: RefCell<FxIndexMap<Instance<'tcx>, &'ll llvm::Value>>,
2631
pub(crate) mcdc_condition_bitmap_map: RefCell<FxHashMap<Instance<'tcx>, Vec<&'ll llvm::Value>>>,
2732

2833
covfun_section_name: OnceCell<CString>,
@@ -31,7 +36,6 @@ pub(crate) struct CguCoverageContext<'ll, 'tcx> {
3136
impl<'ll, 'tcx> CguCoverageContext<'ll, 'tcx> {
3237
pub(crate) fn new() -> Self {
3338
Self {
34-
instances_used: RefCell::<FxIndexSet<_>>::default(),
3539
pgo_func_name_var_map: Default::default(),
3640
mcdc_condition_bitmap_map: Default::default(),
3741
covfun_section_name: Default::default(),
@@ -53,6 +57,14 @@ impl<'ll, 'tcx> CguCoverageContext<'ll, 'tcx> {
5357
.and_then(|bitmap_map| bitmap_map.get(decision_depth as usize))
5458
.copied() // Dereference Option<&&Value> to Option<&Value>
5559
}
60+
61+
/// Returns the list of instances considered "used" in this CGU, as
62+
/// inferred from the keys of `pgo_func_name_var_map`.
63+
pub(crate) fn instances_used(&self) -> Vec<Instance<'tcx>> {
64+
// Collecting into a Vec is way easier than trying to juggle RefCell
65+
// projections, and this should only run once per CGU anyway.
66+
self.pgo_func_name_var_map.borrow().keys().copied().collect::<Vec<_>>()
67+
}
5668
}
5769

5870
impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
@@ -78,7 +90,10 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
7890
/// string, to hold the function name passed to LLVM intrinsic
7991
/// `instrprof.increment()`. The `Value` is only created once per instance.
8092
/// Multiple invocations with the same instance return the same `Value`.
81-
fn get_pgo_func_name_var(&self, instance: Instance<'tcx>) -> &'ll llvm::Value {
93+
///
94+
/// This has the side-effect of causing coverage codegen to consider this
95+
/// function "used", making it eligible to emit an associated covfun record.
96+
fn ensure_pgo_func_name_var(&self, instance: Instance<'tcx>) -> &'ll llvm::Value {
8297
debug!("getting pgo_func_name_var for instance={:?}", instance);
8398
let mut pgo_func_name_var_map = self.coverage_cx().pgo_func_name_var_map.borrow_mut();
8499
pgo_func_name_var_map.entry(instance).or_insert_with(|| {
@@ -102,7 +117,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
102117
return;
103118
}
104119

105-
let fn_name = self.get_pgo_func_name_var(instance);
120+
let fn_name = self.ensure_pgo_func_name_var(instance);
106121
let hash = self.const_u64(function_coverage_info.function_source_hash);
107122
let bitmap_bits = self.const_u32(function_coverage_info.mcdc_bitmap_bits as u32);
108123
self.mcdc_parameters(fn_name, hash, bitmap_bits);
@@ -151,19 +166,14 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
151166
return;
152167
};
153168

154-
// Mark the instance as used in this CGU, for coverage purposes.
155-
// This includes functions that were not partitioned into this CGU,
156-
// but were MIR-inlined into one of this CGU's functions.
157-
coverage_cx.instances_used.borrow_mut().insert(instance);
158-
159169
match *kind {
160170
CoverageKind::SpanMarker | CoverageKind::BlockMarker { .. } => unreachable!(
161171
"marker statement {kind:?} should have been removed by CleanupPostBorrowck"
162172
),
163173
CoverageKind::VirtualCounter { bcb }
164174
if let Some(&id) = ids_info.phys_counter_for_node.get(&bcb) =>
165175
{
166-
let fn_name = bx.get_pgo_func_name_var(instance);
176+
let fn_name = bx.ensure_pgo_func_name_var(instance);
167177
let hash = bx.const_u64(function_coverage_info.function_source_hash);
168178
let num_counters = bx.const_u32(ids_info.num_counters);
169179
let index = bx.const_u32(id.as_u32());
@@ -193,7 +203,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
193203
"bitmap index of the decision out of range"
194204
);
195205

196-
let fn_name = bx.get_pgo_func_name_var(instance);
206+
let fn_name = bx.ensure_pgo_func_name_var(instance);
197207
let hash = bx.const_u64(function_coverage_info.function_source_hash);
198208
let bitmap_index = bx.const_u32(bitmap_idx);
199209
bx.mcdc_tvbitmap_update(fn_name, hash, bitmap_index, cond_bitmap);

compiler/rustc_codegen_llvm/src/errors.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub(crate) struct AutoDiffWithoutEnable;
3939
#[derive(Diagnostic)]
4040
#[diag(codegen_llvm_lto_bitcode_from_rlib)]
4141
pub(crate) struct LtoBitcodeFromRlib {
42-
pub llvm_err: String,
42+
pub err: String,
4343
}
4444

4545
#[derive(Diagnostic)]

compiler/rustc_codegen_llvm/src/lib.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,13 +168,6 @@ impl WriteBackendMethods for LlvmCodegenBackend {
168168
let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
169169
print!("{stats}");
170170
}
171-
fn run_link(
172-
cgcx: &CodegenContext<Self>,
173-
dcx: DiagCtxtHandle<'_>,
174-
modules: Vec<ModuleCodegen<Self::Module>>,
175-
) -> Result<ModuleCodegen<Self::Module>, FatalError> {
176-
back::write::link(cgcx, dcx, modules)
177-
}
178171
fn run_and_optimize_fat_lto(
179172
cgcx: &CodegenContext<Self>,
180173
exported_symbols_for_lto: &[String],

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2612,13 +2612,6 @@ unsafe extern "C" {
26122612
len: usize,
26132613
Identifier: *const c_char,
26142614
) -> Option<&Module>;
2615-
pub(crate) fn LLVMRustGetSliceFromObjectDataByName(
2616-
data: *const u8,
2617-
len: usize,
2618-
name: *const u8,
2619-
name_len: usize,
2620-
out_len: &mut usize,
2621-
) -> *const u8;
26222615

26232616
pub(crate) fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
26242617
pub(crate) fn LLVMRustLinkerAdd(

0 commit comments

Comments
 (0)