about summary refs log tree commit diff
path: root/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs
blob: d3a815fabe7a985ef4586f3fd2a3254d1305a8f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! For each function that was instrumented for coverage, we need to embed its
//! corresponding coverage mapping metadata inside the `__llvm_covfun`[^win]
//! linker section of the final binary.
//!
//! [^win]: On Windows the section name is `.lcovfun`.

use std::ffi::CString;
use std::sync::Arc;

use rustc_abi::Align;
use rustc_codegen_ssa::traits::{
    BaseTypeCodegenMethods as _, ConstCodegenMethods, StaticCodegenMethods,
};
use rustc_index::IndexVec;
use rustc_middle::mir::coverage::{
    BasicCoverageBlock, CovTerm, CoverageIdsInfo, Expression, FunctionCoverageInfo, Mapping,
    MappingKind, Op,
};
use rustc_middle::ty::{Instance, TyCtxt};
use rustc_span::{SourceFile, Span};
use rustc_target::spec::HasTargetSpec;
use tracing::debug;

use crate::common::CodegenCx;
use crate::coverageinfo::mapgen::{GlobalFileTable, VirtualFileMapping, spans};
use crate::coverageinfo::{ffi, llvm_cov};
use crate::llvm;

/// Intermediate coverage metadata for a single function, used to help build
/// the final record that will be embedded in the `__llvm_covfun` section.
#[derive(Debug)]
pub(crate) struct CovfunRecord<'tcx> {
    mangled_function_name: &'tcx str,
    source_hash: u64,
    is_used: bool,

    virtual_file_mapping: VirtualFileMapping,
    expressions: Vec<ffi::CounterExpression>,
    regions: ffi::Regions,
}

impl<'tcx> CovfunRecord<'tcx> {
    /// Iterator that yields all source files referred to by this function's
    /// coverage mappings. Used to build the global file table for the CGU.
    pub(crate) fn all_source_files(&self) -> impl Iterator<Item = &SourceFile> {
        self.virtual_file_mapping.local_file_table.iter().map(Arc::as_ref)
    }
}

pub(crate) fn prepare_covfun_record<'tcx>(
    tcx: TyCtxt<'tcx>,
    instance: Instance<'tcx>,
    is_used: bool,
) -> Option<CovfunRecord<'tcx>> {
    let fn_cov_info = tcx.instance_mir(instance.def).function_coverage_info.as_deref()?;
    let ids_info = tcx.coverage_ids_info(instance.def)?;

    let expressions = prepare_expressions(ids_info);

    let mut covfun = CovfunRecord {
        mangled_function_name: tcx.symbol_name(instance).name,
        source_hash: if is_used { fn_cov_info.function_source_hash } else { 0 },
        is_used,
        virtual_file_mapping: VirtualFileMapping::default(),
        expressions,
        regions: ffi::Regions::default(),
    };

    fill_region_tables(tcx, fn_cov_info, ids_info, &mut covfun);

    if covfun.regions.has_no_regions() {
        debug!(?covfun, "function has no mappings to embed; skipping");
        return None;
    }

    Some(covfun)
}

/// Convert the function's coverage-counter expressions into a form suitable for FFI.
fn prepare_expressions(ids_info: &CoverageIdsInfo) -> Vec<ffi::CounterExpression> {
    let counter_for_term = ffi::Counter::from_term;

    // We know that LLVM will optimize out any unused expressions before
    // producing the final coverage map, so there's no need to do the same
    // thing on the Rust side unless we're confident we can do much better.
    // (See `CounterExpressionsMinimizer` in `CoverageMappingWriter.cpp`.)
    ids_info
        .expressions
        .iter()
        .map(move |&Expression { lhs, op, rhs }| ffi::CounterExpression {
            lhs: counter_for_term(lhs),
            kind: match op {
                Op::Add => ffi::ExprKind::Add,
                Op::Subtract => ffi::ExprKind::Subtract,
            },
            rhs: counter_for_term(rhs),
        })
        .collect::<Vec<_>>()
}

/// Populates the mapping region tables in the current function's covfun record.
fn fill_region_tables<'tcx>(
    tcx: TyCtxt<'tcx>,
    fn_cov_info: &'tcx FunctionCoverageInfo,
    ids_info: &'tcx CoverageIdsInfo,
    covfun: &mut CovfunRecord<'tcx>,
) {
    // If this function is unused, replace all counters with zero.
    let counter_for_bcb = |bcb: BasicCoverageBlock| -> ffi::Counter {
        let term = if covfun.is_used {
            ids_info.term_for_bcb[bcb].expect("every BCB in a mapping was given a term")
        } else {
            CovTerm::Zero
        };
        ffi::Counter::from_term(term)
    };

    // Currently a function's mappings must all be in the same file, so use the
    // first mapping's span to determine the file.
    let source_map = tcx.sess.source_map();
    let Some(first_span) = (try { fn_cov_info.mappings.first()?.span }) else {
        debug_assert!(false, "function has no mappings: {:?}", covfun.mangled_function_name);
        return;
    };
    let source_file = source_map.lookup_source_file(first_span.lo());

    let local_file_id = covfun.virtual_file_mapping.push_file(&source_file);

    // If this testing flag is set, add an extra unused entry to the local
    // file table, to help test the code for detecting unused file IDs.
    if tcx.sess.coverage_inject_unused_local_file() {
        covfun.virtual_file_mapping.push_file(&source_file);
    }

    // In rare cases, _all_ of a function's spans are discarded, and coverage
    // codegen needs to handle that gracefully to avoid #133606.
    // It's hard for tests to trigger this organically, so instead we set
    // `-Zcoverage-options=discard-all-spans-in-codegen` to force it to occur.
    let discard_all = tcx.sess.coverage_discard_all_spans_in_codegen();
    let make_coords = |span: Span| {
        if discard_all { None } else { spans::make_coords(source_map, &source_file, span) }
    };

    let ffi::Regions {
        code_regions,
        expansion_regions: _, // FIXME(Zalathar): Fill out support for expansion regions
        branch_regions,
        mcdc_branch_regions,
        mcdc_decision_regions,
    } = &mut covfun.regions;

    // For each counter/region pair in this function+file, convert it to a
    // form suitable for FFI.
    for &Mapping { ref kind, span } in &fn_cov_info.mappings {
        let Some(coords) = make_coords(span) else { continue };
        let cov_span = coords.make_coverage_span(local_file_id);

        match *kind {
            MappingKind::Code { bcb } => {
                code_regions.push(ffi::CodeRegion { cov_span, counter: counter_for_bcb(bcb) });
            }
            MappingKind::Branch { true_bcb, false_bcb } => {
                branch_regions.push(ffi::BranchRegion {
                    cov_span,
                    true_counter: counter_for_bcb(true_bcb),
                    false_counter: counter_for_bcb(false_bcb),
                });
            }
            MappingKind::MCDCBranch { true_bcb, false_bcb, mcdc_params } => {
                mcdc_branch_regions.push(ffi::MCDCBranchRegion {
                    cov_span,
                    true_counter: counter_for_bcb(true_bcb),
                    false_counter: counter_for_bcb(false_bcb),
                    mcdc_branch_params: ffi::mcdc::BranchParameters::from(mcdc_params),
                });
            }
            MappingKind::MCDCDecision(mcdc_decision_params) => {
                mcdc_decision_regions.push(ffi::MCDCDecisionRegion {
                    cov_span,
                    mcdc_decision_params: ffi::mcdc::DecisionParameters::from(mcdc_decision_params),
                });
            }
        }
    }
}

/// LLVM requires all local file IDs to have at least one mapping region.
/// If that's not the case, skip this function, to avoid an assertion failure
/// (or worse) in LLVM.
fn check_local_file_table(covfun: &CovfunRecord<'_>) -> bool {
    let mut local_file_id_seen =
        IndexVec::<u32, _>::from_elem_n(false, covfun.virtual_file_mapping.local_file_table.len());
    for cov_span in covfun.regions.all_cov_spans() {
        local_file_id_seen[cov_span.file_id] = true;
    }

    local_file_id_seen.into_iter().all(|seen| seen)
}

/// Generates the contents of the covfun record for this function, which
/// contains the function's coverage mapping data. The record is then stored
/// as a global variable in the `__llvm_covfun` section.
pub(crate) fn generate_covfun_record<'tcx>(
    cx: &CodegenCx<'_, 'tcx>,
    global_file_table: &GlobalFileTable,
    covfun: &CovfunRecord<'tcx>,
) {
    if !check_local_file_table(covfun) {
        return;
    }

    let &CovfunRecord {
        mangled_function_name,
        source_hash,
        is_used,
        ref virtual_file_mapping,
        ref expressions,
        ref regions,
    } = covfun;

    let Some(local_file_table) = virtual_file_mapping.resolve_all(global_file_table) else {
        debug_assert!(
            false,
            "all local files should be present in the global file table: \
                global_file_table = {global_file_table:?}, \
                virtual_file_mapping = {virtual_file_mapping:?}"
        );
        return;
    };

    // Encode the function's coverage mappings into a buffer.
    let coverage_mapping_buffer =
        llvm_cov::write_function_mappings_to_buffer(&local_file_table, expressions, regions);

    // A covfun record consists of four target-endian integers, followed by the
    // encoded mapping data in bytes. Note that the length field is 32 bits.
    // <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
    // See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp` and
    // `COVMAP_V3` in `src/llvm-project/llvm/include/llvm/ProfileData/InstrProfData.inc`.
    let func_name_hash = llvm_cov::hash_bytes(mangled_function_name.as_bytes());
    let covfun_record = cx.const_struct(
        &[
            cx.const_u64(func_name_hash),
            cx.const_u32(coverage_mapping_buffer.len() as u32),
            cx.const_u64(source_hash),
            cx.const_u64(global_file_table.filenames_hash),
            cx.const_bytes(&coverage_mapping_buffer),
        ],
        // This struct needs to be packed, so that the 32-bit length field
        // doesn't have unexpected padding.
        true,
    );

    // Choose a variable name to hold this function's covfun data.
    // Functions that are used have a suffix ("u") to distinguish them from
    // unused copies of the same function (from different CGUs), so that if a
    // linker sees both it won't discard the used copy's data.
    let u = if is_used { "u" } else { "" };
    let covfun_var_name = CString::new(format!("__covrec_{func_name_hash:X}{u}")).unwrap();
    debug!("function record var name: {covfun_var_name:?}");

    let covfun_global = llvm::add_global(cx.llmod, cx.val_ty(covfun_record), &covfun_var_name);
    llvm::set_initializer(covfun_global, covfun_record);
    llvm::set_global_constant(covfun_global, true);
    llvm::set_linkage(covfun_global, llvm::Linkage::LinkOnceODRLinkage);
    llvm::set_visibility(covfun_global, llvm::Visibility::Hidden);
    llvm::set_section(covfun_global, cx.covfun_section_name());
    // LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
    // <https://llvm.org/docs/CoverageMappingFormat.html>
    llvm::set_alignment(covfun_global, Align::EIGHT);
    if cx.target_spec().supports_comdat() {
        llvm::set_comdat(cx.llmod, covfun_global, &covfun_var_name);
    }

    cx.add_used_global(covfun_global);
}