Path: blob/main/contrib/llvm-project/llvm/tools/llvm-cov/CoverageExporterJson.cpp
35231 views
//===- CoverageExporterJson.cpp - Code coverage export --------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements export of code coverage data to JSON.9//10//===----------------------------------------------------------------------===//1112//===----------------------------------------------------------------------===//13//14// The json code coverage export follows the following format15// Root: dict => Root Element containing metadata16// -- Data: array => Homogeneous array of one or more export objects17// -- Export: dict => Json representation of one CoverageMapping18// -- Files: array => List of objects describing coverage for files19// -- File: dict => Coverage for a single file20// -- Branches: array => List of Branches in the file21// -- Branch: dict => Describes a branch of the file with counters22// -- MCDC Records: array => List of MCDC records in the file23// -- MCDC Values: array => List of T/F covered condition values24// -- Segments: array => List of Segments contained in the file25// -- Segment: dict => Describes a segment of the file with a counter26// -- Expansions: array => List of expansion records27// -- Expansion: dict => Object that descibes a single expansion28// -- CountedRegion: dict => The region to be expanded29// -- TargetRegions: array => List of Regions in the expansion30// -- CountedRegion: dict => Single Region in the expansion31// -- Branches: array => List of Branches in the expansion32// -- Branch: dict => Describes a branch in expansion and counters33// -- Summary: dict => Object summarizing the coverage for this file34// -- LineCoverage: dict => Object summarizing line coverage35// -- FunctionCoverage: dict => Object summarizing function coverage36// -- RegionCoverage: dict => Object summarizing region coverage37// -- BranchCoverage: dict => Object summarizing branch coverage38// -- MCDCCoverage: dict => Object summarizing MC/DC coverage39// -- Functions: array => List of objects describing coverage for functions40// -- Function: dict => Coverage info for a single function41// -- Filenames: array => List of filenames that the function relates to42// -- Summary: dict => Object summarizing the coverage for the entire binary43// -- LineCoverage: dict => Object summarizing line coverage44// -- FunctionCoverage: dict => Object summarizing function coverage45// -- InstantiationCoverage: dict => Object summarizing inst. coverage46// -- RegionCoverage: dict => Object summarizing region coverage47// -- BranchCoverage: dict => Object summarizing branch coverage48// -- MCDCCoverage: dict => Object summarizing MC/DC coverage49//50//===----------------------------------------------------------------------===//5152#include "CoverageExporterJson.h"53#include "CoverageReport.h"54#include "llvm/ADT/StringRef.h"55#include "llvm/Support/JSON.h"56#include "llvm/Support/ThreadPool.h"57#include "llvm/Support/Threading.h"58#include <algorithm>59#include <limits>60#include <mutex>61#include <utility>6263/// The semantic version combined as a string.64#define LLVM_COVERAGE_EXPORT_JSON_STR "2.0.1"6566/// Unique type identifier for JSON coverage export.67#define LLVM_COVERAGE_EXPORT_JSON_TYPE_STR "llvm.coverage.json.export"6869using namespace llvm;7071namespace {7273// The JSON library accepts int64_t, but profiling counts are stored as uint64_t.74// Therefore we need to explicitly convert from unsigned to signed, since a naive75// cast is implementation-defined behavior when the unsigned value cannot be76// represented as a signed value. We choose to clamp the values to preserve the77// invariant that counts are always >= 0.78int64_t clamp_uint64_to_int64(uint64_t u) {79return std::min(u, static_cast<uint64_t>(std::numeric_limits<int64_t>::max()));80}8182json::Array renderSegment(const coverage::CoverageSegment &Segment) {83return json::Array({Segment.Line, Segment.Col,84clamp_uint64_to_int64(Segment.Count), Segment.HasCount,85Segment.IsRegionEntry, Segment.IsGapRegion});86}8788json::Array renderRegion(const coverage::CountedRegion &Region) {89return json::Array({Region.LineStart, Region.ColumnStart, Region.LineEnd,90Region.ColumnEnd, clamp_uint64_to_int64(Region.ExecutionCount),91Region.FileID, Region.ExpandedFileID,92int64_t(Region.Kind)});93}9495json::Array renderBranch(const coverage::CountedRegion &Region) {96return json::Array(97{Region.LineStart, Region.ColumnStart, Region.LineEnd, Region.ColumnEnd,98clamp_uint64_to_int64(Region.ExecutionCount),99clamp_uint64_to_int64(Region.FalseExecutionCount), Region.FileID,100Region.ExpandedFileID, int64_t(Region.Kind)});101}102103json::Array gatherConditions(const coverage::MCDCRecord &Record) {104json::Array Conditions;105for (unsigned c = 0; c < Record.getNumConditions(); c++)106Conditions.push_back(Record.isConditionIndependencePairCovered(c));107return Conditions;108}109110json::Array renderMCDCRecord(const coverage::MCDCRecord &Record) {111const llvm::coverage::CounterMappingRegion &CMR = Record.getDecisionRegion();112return json::Array({CMR.LineStart, CMR.ColumnStart, CMR.LineEnd,113CMR.ColumnEnd, CMR.ExpandedFileID, int64_t(CMR.Kind),114gatherConditions(Record)});115}116117json::Array renderRegions(ArrayRef<coverage::CountedRegion> Regions) {118json::Array RegionArray;119for (const auto &Region : Regions)120RegionArray.push_back(renderRegion(Region));121return RegionArray;122}123124json::Array renderBranchRegions(ArrayRef<coverage::CountedRegion> Regions) {125json::Array RegionArray;126for (const auto &Region : Regions)127if (!Region.Folded)128RegionArray.push_back(renderBranch(Region));129return RegionArray;130}131132json::Array renderMCDCRecords(ArrayRef<coverage::MCDCRecord> Records) {133json::Array RecordArray;134for (auto &Record : Records)135RecordArray.push_back(renderMCDCRecord(Record));136return RecordArray;137}138139std::vector<llvm::coverage::CountedRegion>140collectNestedBranches(const coverage::CoverageMapping &Coverage,141ArrayRef<llvm::coverage::ExpansionRecord> Expansions) {142std::vector<llvm::coverage::CountedRegion> Branches;143for (const auto &Expansion : Expansions) {144auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion);145146// Recursively collect branches from nested expansions.147auto NestedExpansions = ExpansionCoverage.getExpansions();148auto NestedExBranches = collectNestedBranches(Coverage, NestedExpansions);149append_range(Branches, NestedExBranches);150151// Add branches from this level of expansion.152auto ExBranches = ExpansionCoverage.getBranches();153for (auto B : ExBranches)154if (B.FileID == Expansion.FileID)155Branches.push_back(B);156}157158return Branches;159}160161json::Object renderExpansion(const coverage::CoverageMapping &Coverage,162const coverage::ExpansionRecord &Expansion) {163std::vector<llvm::coverage::ExpansionRecord> Expansions = {Expansion};164return json::Object(165{{"filenames", json::Array(Expansion.Function.Filenames)},166// Mark the beginning and end of this expansion in the source file.167{"source_region", renderRegion(Expansion.Region)},168// Enumerate the coverage information for the expansion.169{"target_regions", renderRegions(Expansion.Function.CountedRegions)},170// Enumerate the branch coverage information for the expansion.171{"branches",172renderBranchRegions(collectNestedBranches(Coverage, Expansions))}});173}174175json::Object renderSummary(const FileCoverageSummary &Summary) {176return json::Object(177{{"lines",178json::Object({{"count", int64_t(Summary.LineCoverage.getNumLines())},179{"covered", int64_t(Summary.LineCoverage.getCovered())},180{"percent", Summary.LineCoverage.getPercentCovered()}})},181{"functions",182json::Object(183{{"count", int64_t(Summary.FunctionCoverage.getNumFunctions())},184{"covered", int64_t(Summary.FunctionCoverage.getExecuted())},185{"percent", Summary.FunctionCoverage.getPercentCovered()}})},186{"instantiations",187json::Object(188{{"count",189int64_t(Summary.InstantiationCoverage.getNumFunctions())},190{"covered", int64_t(Summary.InstantiationCoverage.getExecuted())},191{"percent", Summary.InstantiationCoverage.getPercentCovered()}})},192{"regions",193json::Object(194{{"count", int64_t(Summary.RegionCoverage.getNumRegions())},195{"covered", int64_t(Summary.RegionCoverage.getCovered())},196{"notcovered", int64_t(Summary.RegionCoverage.getNumRegions() -197Summary.RegionCoverage.getCovered())},198{"percent", Summary.RegionCoverage.getPercentCovered()}})},199{"branches",200json::Object(201{{"count", int64_t(Summary.BranchCoverage.getNumBranches())},202{"covered", int64_t(Summary.BranchCoverage.getCovered())},203{"notcovered", int64_t(Summary.BranchCoverage.getNumBranches() -204Summary.BranchCoverage.getCovered())},205{"percent", Summary.BranchCoverage.getPercentCovered()}})},206{"mcdc",207json::Object(208{{"count", int64_t(Summary.MCDCCoverage.getNumPairs())},209{"covered", int64_t(Summary.MCDCCoverage.getCoveredPairs())},210{"notcovered", int64_t(Summary.MCDCCoverage.getNumPairs() -211Summary.MCDCCoverage.getCoveredPairs())},212{"percent", Summary.MCDCCoverage.getPercentCovered()}})}});213}214215json::Array renderFileExpansions(const coverage::CoverageMapping &Coverage,216const coverage::CoverageData &FileCoverage,217const FileCoverageSummary &FileReport) {218json::Array ExpansionArray;219for (const auto &Expansion : FileCoverage.getExpansions())220ExpansionArray.push_back(renderExpansion(Coverage, Expansion));221return ExpansionArray;222}223224json::Array renderFileSegments(const coverage::CoverageData &FileCoverage,225const FileCoverageSummary &FileReport) {226json::Array SegmentArray;227for (const auto &Segment : FileCoverage)228SegmentArray.push_back(renderSegment(Segment));229return SegmentArray;230}231232json::Array renderFileBranches(const coverage::CoverageData &FileCoverage,233const FileCoverageSummary &FileReport) {234json::Array BranchArray;235for (const auto &Branch : FileCoverage.getBranches())236BranchArray.push_back(renderBranch(Branch));237return BranchArray;238}239240json::Array renderFileMCDC(const coverage::CoverageData &FileCoverage,241const FileCoverageSummary &FileReport) {242json::Array MCDCRecordArray;243for (const auto &Record : FileCoverage.getMCDCRecords())244MCDCRecordArray.push_back(renderMCDCRecord(Record));245return MCDCRecordArray;246}247248json::Object renderFile(const coverage::CoverageMapping &Coverage,249const std::string &Filename,250const FileCoverageSummary &FileReport,251const CoverageViewOptions &Options) {252json::Object File({{"filename", Filename}});253if (!Options.ExportSummaryOnly) {254// Calculate and render detailed coverage information for given file.255auto FileCoverage = Coverage.getCoverageForFile(Filename);256File["segments"] = renderFileSegments(FileCoverage, FileReport);257File["branches"] = renderFileBranches(FileCoverage, FileReport);258File["mcdc_records"] = renderFileMCDC(FileCoverage, FileReport);259if (!Options.SkipExpansions) {260File["expansions"] =261renderFileExpansions(Coverage, FileCoverage, FileReport);262}263}264File["summary"] = renderSummary(FileReport);265return File;266}267268json::Array renderFiles(const coverage::CoverageMapping &Coverage,269ArrayRef<std::string> SourceFiles,270ArrayRef<FileCoverageSummary> FileReports,271const CoverageViewOptions &Options) {272ThreadPoolStrategy S = hardware_concurrency(Options.NumThreads);273if (Options.NumThreads == 0) {274// If NumThreads is not specified, create one thread for each input, up to275// the number of hardware cores.276S = heavyweight_hardware_concurrency(SourceFiles.size());277S.Limit = true;278}279DefaultThreadPool Pool(S);280json::Array FileArray;281std::mutex FileArrayMutex;282283for (unsigned I = 0, E = SourceFiles.size(); I < E; ++I) {284auto &SourceFile = SourceFiles[I];285auto &FileReport = FileReports[I];286Pool.async([&] {287auto File = renderFile(Coverage, SourceFile, FileReport, Options);288{289std::lock_guard<std::mutex> Lock(FileArrayMutex);290FileArray.push_back(std::move(File));291}292});293}294Pool.wait();295return FileArray;296}297298json::Array renderFunctions(299const iterator_range<coverage::FunctionRecordIterator> &Functions) {300json::Array FunctionArray;301for (const auto &F : Functions)302FunctionArray.push_back(303json::Object({{"name", F.Name},304{"count", clamp_uint64_to_int64(F.ExecutionCount)},305{"regions", renderRegions(F.CountedRegions)},306{"branches", renderBranchRegions(F.CountedBranchRegions)},307{"mcdc_records", renderMCDCRecords(F.MCDCRecords)},308{"filenames", json::Array(F.Filenames)}}));309return FunctionArray;310}311312} // end anonymous namespace313314void CoverageExporterJson::renderRoot(const CoverageFilters &IgnoreFilters) {315std::vector<std::string> SourceFiles;316for (StringRef SF : Coverage.getUniqueSourceFiles()) {317if (!IgnoreFilters.matchesFilename(SF))318SourceFiles.emplace_back(SF);319}320renderRoot(SourceFiles);321}322323void CoverageExporterJson::renderRoot(ArrayRef<std::string> SourceFiles) {324FileCoverageSummary Totals = FileCoverageSummary("Totals");325auto FileReports = CoverageReport::prepareFileReports(Coverage, Totals,326SourceFiles, Options);327auto Files = renderFiles(Coverage, SourceFiles, FileReports, Options);328// Sort files in order of their names.329llvm::sort(Files, [](const json::Value &A, const json::Value &B) {330const json::Object *ObjA = A.getAsObject();331const json::Object *ObjB = B.getAsObject();332assert(ObjA != nullptr && "Value A was not an Object");333assert(ObjB != nullptr && "Value B was not an Object");334const StringRef FilenameA = *ObjA->getString("filename");335const StringRef FilenameB = *ObjB->getString("filename");336return FilenameA.compare(FilenameB) < 0;337});338auto Export = json::Object(339{{"files", std::move(Files)}, {"totals", renderSummary(Totals)}});340// Skip functions-level information if necessary.341if (!Options.ExportSummaryOnly && !Options.SkipFunctions)342Export["functions"] = renderFunctions(Coverage.getCoveredFunctions());343344auto ExportArray = json::Array({std::move(Export)});345346OS << json::Object({{"version", LLVM_COVERAGE_EXPORT_JSON_STR},347{"type", LLVM_COVERAGE_EXPORT_JSON_TYPE_STR},348{"data", std::move(ExportArray)}});349}350351352