Skip to content

Commit

Permalink
Rollup merge of rust-lang#90132 - joshtriplett:stabilize-instrument-c…
Browse files Browse the repository at this point in the history
…overage, r=wesleywiser

Stabilize `-Z instrument-coverage` as `-C instrument-coverage`

(Tracking issue for `instrument-coverage`: rust-lang#79121)

This PR stabilizes support for instrumentation-based code coverage, previously provided via the `-Z instrument-coverage` option. (Continue supporting `-Z instrument-coverage` for compatibility for now, but show a deprecation warning for it.)

Many, many people have tested this support, and there are numerous reports of it working as expected.

Move the documentation from the unstable book to stable rustc documentation. Update uses and documentation to use the `-C` option.

Addressing questions raised in the tracking issue:

> If/when stabilized, will the compiler flag be updated to -C instrument-coverage? (If so, the -Z variant could also be supported for some time, to ease migrations for existing users and scripts.)

This stabilization PR updates the option to `-C` and keeps the `-Z` variant to ease migration.

> The Rust coverage implementation depends on (and automatically turns on) -Z symbol-mangling-version=v0. Will stabilizing this feature depend on stabilizing v0 symbol-mangling first? If so, what is the current status and timeline?

This stabilization PR depends on rust-lang#90128 , which stabilizes `-C symbol-mangling-version=v0` (but does not change the default symbol-mangling-version).

> The Rust coverage implementation implements the latest version of LLVM's Coverage Mapping Format (version 4), which forces a dependency on LLVM 11 or later. A compiler error is generated if attempting to compile with coverage, and using an older version of LLVM.

Given that LLVM 13 has now been released, requiring LLVM 11 for coverage support seems like a reasonable requirement. If people don't have at least LLVM 11, nothing else breaks; they just can't use coverage support. Given that coverage support currently requires a nightly compiler and LLVM 11 or newer, allowing it on a stable compiler built with LLVM 11 or newer seems like an improvement.

The [tracking issue](rust-lang#79121) and the [issue label A-code-coverage](https://github.com/rust-lang/rust/labels/A-code-coverage) link to a few open issues related to `instrument-coverage`, but none of them seem like showstoppers. All of them seem like improvements and refinements we can make after stabilization.

The original `-Z instrument-coverage` support went through a compiler-team MCP at rust-lang/compiler-team#278 . Based on that, `@pnkfelix` suggested that this needed a stabilization PR and a compiler-team FCP.
  • Loading branch information
matthiaskrgr authored Feb 4, 2022
2 parents cb18e83 + 3187f41 commit 2fe9a32
Show file tree
Hide file tree
Showing 26 changed files with 132 additions and 108 deletions.
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn finalize<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
// LLVM 12.
let version = coverageinfo::mapping_version();
if version < 4 {
tcx.sess.fatal("rustc option `-Z instrument-coverage` requires LLVM 12 or higher.");
tcx.sess.fatal("rustc option `-C instrument-coverage` requires LLVM 12 or higher.");
}

debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
Expand Down Expand Up @@ -274,7 +274,7 @@ fn save_function_record(
/// (functions referenced by other "used" or public items). Any other functions considered unused,
/// or "Unreachable", were still parsed and processed through the MIR stage, but were not
/// codegenned. (Note that `-Clink-dead-code` can force some unused code to be codegenned, but
/// that flag is known to cause other errors, when combined with `-Z instrument-coverage`; and
/// that flag is known to cause other errors, when combined with `-C instrument-coverage`; and
/// `-Clink-dead-code` will not generate code for unused generic functions.)
///
/// We can find the unused functions (including generic functions) by the set difference of all MIR
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ pub trait CoverageInfoMethods<'tcx>: BackendTypes {

pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes {
/// Returns true if the function source hash was added to the coverage map (even if it had
/// already been added, for this instance). Returns false *only* if `-Z instrument-coverage` is
/// already been added, for this instance). Returns false *only* if `-C instrument-coverage` is
/// not enabled (a coverage map is not being generated).
fn set_function_source_hash(
&mut self,
instance: Instance<'tcx>,
function_source_hash: u64,
) -> bool;

/// Returns true if the counter was added to the coverage map; false if `-Z instrument-coverage`
/// Returns true if the counter was added to the coverage map; false if `-C instrument-coverage`
/// is not enabled (a coverage map is not being generated).
fn add_coverage_counter(
&mut self,
Expand All @@ -40,7 +40,7 @@ pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes {
) -> bool;

/// Returns true if the expression was added to the coverage map; false if
/// `-Z instrument-coverage` is not enabled (a coverage map is not being generated).
/// `-C instrument-coverage` is not enabled (a coverage map is not being generated).
fn add_coverage_counter_expression(
&mut self,
instance: Instance<'tcx>,
Expand All @@ -51,7 +51,7 @@ pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes {
region: Option<CodeRegion>,
) -> bool;

/// Returns true if the region was added to the coverage map; false if `-Z instrument-coverage`
/// Returns true if the region was added to the coverage map; false if `-C instrument-coverage`
/// is not enabled (a coverage map is not being generated).
fn add_coverage_unreachable(&mut self, instance: Instance<'tcx>, region: CodeRegion) -> bool;
}
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ fn test_codegen_options_tracking_hash() {
tracked!(force_frame_pointers, Some(false));
tracked!(force_unwind_tables, Some(true));
tracked!(inline_threshold, Some(0xf007ba11));
tracked!(instrument_coverage, Some(InstrumentCoverage::All));
tracked!(linker_plugin_lto, LinkerPluginLto::LinkerPluginAuto);
tracked!(link_dead_code, Some(true));
tracked!(llvm_args, vec![String::from("1"), String::from("2")]);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1577,7 +1577,7 @@ pub enum StatementKind<'tcx> {
/// - `Bivariant` -- no effect
AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),

/// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
/// Marks the start of a "coverage region", injected with '-Cinstrument-coverage'. A
/// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
/// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
/// executable code, to increment a counter variable at runtime, each time the code region is
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ pub struct DestructuredConst<'tcx> {
}

/// Coverage information summarized from a MIR if instrumented for source code coverage (see
/// compiler option `-Zinstrument-coverage`). This information is generated by the
/// compiler option `-Cinstrument-coverage`). This information is generated by the
/// `InstrumentCoverage` MIR pass and can be retrieved via the `coverageinfo` query.
#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable)]
pub struct CoverageInfo {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ rustc_queries! {
}

/// Returns coverage summary info for a function, after executing the `InstrumentCoverage`
/// MIR pass (assuming the -Zinstrument-coverage option is enabled).
/// MIR pass (assuming the -Cinstrument-coverage option is enabled).
query coverageinfo(key: ty::InstanceDef<'tcx>) -> mir::CoverageInfo {
desc { |tcx| "retrieving coverage info from MIR for `{}`", tcx.def_path_str(key.def_id()) }
storage(ArenaCacheSelector<'tcx>)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/coverage/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//!
//! To enable coverage, include the rustc command line option:
//!
//! * `-Z instrument-coverage`
//! * `-C instrument-coverage`
//!
//! MIR Dump Files, with additional `CoverageGraph` graphviz and `CoverageSpan` spanview
//! ------------------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/simplify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ pub fn remove_dead_blocks<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
/// evaluation: `if false { ... }`.
///
/// Those statements are bypassed by redirecting paths in the CFG around the
/// `dead blocks`; but with `-Z instrument-coverage`, the dead blocks usually
/// `dead blocks`; but with `-C instrument-coverage`, the dead blocks usually
/// include `Coverage` statements representing the Rust source code regions to
/// be counted at runtime. Without these `Coverage` statements, the regions are
/// lost, and the Rust source code will show no coverage information.
Expand Down
54 changes: 40 additions & 14 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,16 @@ pub enum MirSpanview {
Block,
}

/// The different settings that the `-Z instrument-coverage` flag can have.
/// The different settings that the `-C instrument-coverage` flag can have.
///
/// Coverage instrumentation now supports combining `-Z instrument-coverage`
/// Coverage instrumentation now supports combining `-C instrument-coverage`
/// with compiler and linker optimization (enabled with `-O` or `-C opt-level=1`
/// and higher). Nevertheless, there are many variables, depending on options
/// selected, code structure, and enabled attributes. If errors are encountered,
/// either while compiling or when generating `llvm-cov show` reports, consider
/// lowering the optimization level, including or excluding `-C link-dead-code`,
/// or using `-Z instrument-coverage=except-unused-functions` or `-Z
/// instrument-coverage=except-unused-generics`.
/// or using `-Zunstable-options -C instrument-coverage=except-unused-functions`
/// or `-Zunstable-options -C instrument-coverage=except-unused-generics`.
///
/// Note that `ExceptUnusedFunctions` means: When `mapgen.rs` generates the
/// coverage map, it will not attempt to generate synthetic functions for unused
Expand All @@ -148,13 +148,13 @@ pub enum MirSpanview {
/// unless the function has type parameters.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum InstrumentCoverage {
/// Default `-Z instrument-coverage` or `-Z instrument-coverage=statement`
/// Default `-C instrument-coverage` or `-C instrument-coverage=statement`
All,
/// `-Z instrument-coverage=except-unused-generics`
/// `-Zunstable-options -C instrument-coverage=except-unused-generics`
ExceptUnusedGenerics,
/// `-Z instrument-coverage=except-unused-functions`
/// `-Zunstable-options -C instrument-coverage=except-unused-functions`
ExceptUnusedFunctions,
/// `-Z instrument-coverage=off` (or `no`, etc.)
/// `-C instrument-coverage=off` (or `no`, etc.)
Off,
}

Expand Down Expand Up @@ -2195,18 +2195,44 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
_ => {}
}

if debugging_opts.instrument_coverage.is_some()
&& debugging_opts.instrument_coverage != Some(InstrumentCoverage::Off)
{
// Handle both `-Z instrument-coverage` and `-C instrument-coverage`; the latter takes
// precedence.
match (cg.instrument_coverage, debugging_opts.instrument_coverage) {
(Some(ic_c), Some(ic_z)) if ic_c != ic_z => {
early_error(
error_format,
"incompatible values passed for `-C instrument-coverage` \
and `-Z instrument-coverage`",
);
}
(Some(InstrumentCoverage::Off | InstrumentCoverage::All), _) => {}
(Some(_), _) if !debugging_opts.unstable_options => {
early_error(
error_format,
"`-C instrument-coverage=except-*` requires `-Z unstable-options`",
);
}
(None, None) => {}
(None, ic) => {
early_warn(
error_format,
"`-Z instrument-coverage` is deprecated; use `-C instrument-coverage`",
);
cg.instrument_coverage = ic;
}
_ => {}
}

if cg.instrument_coverage.is_some() && cg.instrument_coverage != Some(InstrumentCoverage::Off) {
if cg.profile_generate.enabled() || cg.profile_use.is_some() {
early_error(
error_format,
"option `-Z instrument-coverage` is not compatible with either `-C profile-use` \
"option `-C instrument-coverage` is not compatible with either `-C profile-use` \
or `-C profile-generate`",
);
}

// `-Z instrument-coverage` implies `-C symbol-mangling-version=v0` - to ensure consistent
// `-C instrument-coverage` implies `-C symbol-mangling-version=v0` - to ensure consistent
// and reversible name mangling. Note, LLVM coverage tools can analyze coverage over
// multiple runs, including some changes to source code; so mangled names must be consistent
// across compilations.
Expand All @@ -2215,7 +2241,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
Some(SymbolManglingVersion::Legacy) => {
early_warn(
error_format,
"-Z instrument-coverage requires symbol mangling version `v0`, \
"-C instrument-coverage requires symbol mangling version `v0`, \
but `-C symbol-mangling-version=legacy` was specified",
);
}
Expand Down
15 changes: 11 additions & 4 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,16 @@ impl Options {
}

pub fn instrument_coverage(&self) -> bool {
self.debugging_opts.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
!= InstrumentCoverage::Off
self.cg.instrument_coverage.unwrap_or(InstrumentCoverage::Off) != InstrumentCoverage::Off
}

pub fn instrument_coverage_except_unused_generics(&self) -> bool {
self.debugging_opts.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
self.cg.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
== InstrumentCoverage::ExceptUnusedGenerics
}

pub fn instrument_coverage_except_unused_functions(&self) -> bool {
self.debugging_opts.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
self.cg.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
== InstrumentCoverage::ExceptUnusedFunctions
}
}
Expand Down Expand Up @@ -1031,6 +1030,14 @@ options! {
"enable incremental compilation"),
inline_threshold: Option<u32> = (None, parse_opt_number, [TRACKED],
"set the threshold for inlining a function"),
instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
"instrument the generated code to support LLVM source-based code coverage \
reports (note, the compiler build config must include `profiler = true`); \
implies `-C symbol-mangling-version=v0`. Optional values are:
`=all` (implicit value)
`=except-unused-generics`
`=except-unused-functions`
`=off` (default)"),
link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
"a single extra argument to append to the linker invocation (can be used several times)"),
link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
Expand Down
4 changes: 2 additions & 2 deletions config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ changelog-seen = 2
#sanitizers = false

# Build the profiler runtime (required when compiling with options that depend
# on this runtime, such as `-C profile-generate` or `-Z instrument-coverage`).
# on this runtime, such as `-C profile-generate` or `-C instrument-coverage`).
#profiler = false

# Indicates whether the native libraries linked into Cargo will be statically
Expand Down Expand Up @@ -671,7 +671,7 @@ changelog-seen = 2
#sanitizers = build.sanitizers (bool)

# Build the profiler runtime for this target(required when compiling with options that depend
# on this runtime, such as `-C profile-generate` or `-Z instrument-coverage`).
# on this runtime, such as `-C profile-generate` or `-C instrument-coverage`).
# This option will override the same option under [build] section.
#profiler = build.profiler (bool)

Expand Down
1 change: 1 addition & 0 deletions src/doc/rustc/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
- [Custom Targets](targets/custom.md)
- [Known Issues](targets/known-issues.md)
- [Profile-guided Optimization](profile-guided-optimization.md)
- [Instrumentation-based Code Coverage](instrument-coverage.md)
- [Linker-plugin based LTO](linker-plugin-lto.md)
- [Exploit Mitigations](exploit-mitigations.md)
- [Contributing to `rustc`](contributing.md)
10 changes: 10 additions & 0 deletions src/doc/rustc/src/codegen-options/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,15 @@ The default depends on the [opt-level](#opt-level):
| s | 75 |
| z | 25 |

## instrument-coverage

This option enables instrumentation-based code coverage support. See the
chapter on [instrumentation-based code coverage] for more information.

Note that while the `-C instrument-coverage` option is stable, the profile data
format produced by the resulting instrumentation may change, and may not work
with coverage tools other than those built and shipped with the compiler.

## link-arg

This flag lets you append a single extra argument to the linker invocation.
Expand Down Expand Up @@ -597,5 +606,6 @@ effective only for x86 targets.

[option-emit]: ../command-line-arguments.md#option-emit
[option-o-optimize]: ../command-line-arguments.md#option-o-optimize
[instrumentation-based code coverage]: ../instrument-coverage.md
[profile-guided optimization]: ../profile-guided-optimization.md
[option-g-debug]: ../command-line-arguments.md#option-g-debug
Loading

0 comments on commit 2fe9a32

Please sign in to comment.