1e78d131aSEugene Zelenko //===- CoverageMappingWriter.cpp - Code coverage mapping writer -----------===//
2dc707122SEaswaran Raman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dc707122SEaswaran Raman //
7dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
8dc707122SEaswaran Raman //
9dc707122SEaswaran Raman // This file contains support for writing coverage mapping data for
10dc707122SEaswaran Raman // instrumentation based coverage.
11dc707122SEaswaran Raman //
12dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
13dc707122SEaswaran Raman 
146bda14b3SChandler Carruth #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
15e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
16e78d131aSEugene Zelenko #include "llvm/ADT/SmallVector.h"
17dc707122SEaswaran Raman #include "llvm/Support/LEB128.h"
18e78d131aSEugene Zelenko #include "llvm/Support/raw_ostream.h"
19e78d131aSEugene Zelenko #include <algorithm>
20e78d131aSEugene Zelenko #include <cassert>
21e78d131aSEugene Zelenko #include <limits>
22e78d131aSEugene Zelenko #include <vector>
23dc707122SEaswaran Raman 
24dc707122SEaswaran Raman using namespace llvm;
25dc707122SEaswaran Raman using namespace coverage;
26dc707122SEaswaran Raman 
27*95de2497SVedant Kumar CoverageFilenamesSectionWriter::CoverageFilenamesSectionWriter(
28*95de2497SVedant Kumar     ArrayRef<StringRef> Filenames)
29*95de2497SVedant Kumar     : Filenames(Filenames) {
30*95de2497SVedant Kumar #ifndef NDEBUG
31*95de2497SVedant Kumar   StringSet<> NameSet;
32*95de2497SVedant Kumar   for (StringRef Name : Filenames)
33*95de2497SVedant Kumar     assert(NameSet.insert(Name).second && "Duplicate filename");
34*95de2497SVedant Kumar #endif
35*95de2497SVedant Kumar }
36*95de2497SVedant Kumar 
3734e4e477SVedant Kumar void CoverageFilenamesSectionWriter::write(raw_ostream &OS) {
3834e4e477SVedant Kumar   encodeULEB128(Filenames.size(), OS);
3934e4e477SVedant Kumar   for (const auto &Filename : Filenames) {
4034e4e477SVedant Kumar     encodeULEB128(Filename.size(), OS);
4134e4e477SVedant Kumar     OS << Filename;
4234e4e477SVedant Kumar   }
4334e4e477SVedant Kumar }
4434e4e477SVedant Kumar 
45dc707122SEaswaran Raman namespace {
46e78d131aSEugene Zelenko 
475f8f34e4SAdrian Prantl /// Gather only the expressions that are used by the mapping
48dc707122SEaswaran Raman /// regions in this function.
49dc707122SEaswaran Raman class CounterExpressionsMinimizer {
50dc707122SEaswaran Raman   ArrayRef<CounterExpression> Expressions;
51e78d131aSEugene Zelenko   SmallVector<CounterExpression, 16> UsedExpressions;
52dc707122SEaswaran Raman   std::vector<unsigned> AdjustedExpressionIDs;
53dc707122SEaswaran Raman 
54dc707122SEaswaran Raman public:
55e78d131aSEugene Zelenko   CounterExpressionsMinimizer(ArrayRef<CounterExpression> Expressions,
56e78d131aSEugene Zelenko                               ArrayRef<CounterMappingRegion> MappingRegions)
57e78d131aSEugene Zelenko       : Expressions(Expressions) {
58e78d131aSEugene Zelenko     AdjustedExpressionIDs.resize(Expressions.size(), 0);
59e78d131aSEugene Zelenko     for (const auto &I : MappingRegions)
60e78d131aSEugene Zelenko       mark(I.Count);
61e78d131aSEugene Zelenko     for (const auto &I : MappingRegions)
62e78d131aSEugene Zelenko       gatherUsed(I.Count);
63e78d131aSEugene Zelenko   }
64e78d131aSEugene Zelenko 
65dc707122SEaswaran Raman   void mark(Counter C) {
66dc707122SEaswaran Raman     if (!C.isExpression())
67dc707122SEaswaran Raman       return;
68dc707122SEaswaran Raman     unsigned ID = C.getExpressionID();
69dc707122SEaswaran Raman     AdjustedExpressionIDs[ID] = 1;
70dc707122SEaswaran Raman     mark(Expressions[ID].LHS);
71dc707122SEaswaran Raman     mark(Expressions[ID].RHS);
72dc707122SEaswaran Raman   }
73dc707122SEaswaran Raman 
74dc707122SEaswaran Raman   void gatherUsed(Counter C) {
75dc707122SEaswaran Raman     if (!C.isExpression() || !AdjustedExpressionIDs[C.getExpressionID()])
76dc707122SEaswaran Raman       return;
77dc707122SEaswaran Raman     AdjustedExpressionIDs[C.getExpressionID()] = UsedExpressions.size();
78dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
79dc707122SEaswaran Raman     UsedExpressions.push_back(E);
80dc707122SEaswaran Raman     gatherUsed(E.LHS);
81dc707122SEaswaran Raman     gatherUsed(E.RHS);
82dc707122SEaswaran Raman   }
83dc707122SEaswaran Raman 
84dc707122SEaswaran Raman   ArrayRef<CounterExpression> getExpressions() const { return UsedExpressions; }
85dc707122SEaswaran Raman 
865f8f34e4SAdrian Prantl   /// Adjust the given counter to correctly transition from the old
87dc707122SEaswaran Raman   /// expression ids to the new expression ids.
88dc707122SEaswaran Raman   Counter adjust(Counter C) const {
89dc707122SEaswaran Raman     if (C.isExpression())
90dc707122SEaswaran Raman       C = Counter::getExpression(AdjustedExpressionIDs[C.getExpressionID()]);
91dc707122SEaswaran Raman     return C;
92dc707122SEaswaran Raman   }
93dc707122SEaswaran Raman };
94e78d131aSEugene Zelenko 
95e78d131aSEugene Zelenko } // end anonymous namespace
96dc707122SEaswaran Raman 
975f8f34e4SAdrian Prantl /// Encode the counter.
98dc707122SEaswaran Raman ///
99dc707122SEaswaran Raman /// The encoding uses the following format:
100dc707122SEaswaran Raman /// Low 2 bits - Tag:
101dc707122SEaswaran Raman ///   Counter::Zero(0) - A Counter with kind Counter::Zero
102dc707122SEaswaran Raman ///   Counter::CounterValueReference(1) - A counter with kind
103dc707122SEaswaran Raman ///     Counter::CounterValueReference
104dc707122SEaswaran Raman ///   Counter::Expression(2) + CounterExpression::Subtract(0) -
105dc707122SEaswaran Raman ///     A counter with kind Counter::Expression and an expression
106dc707122SEaswaran Raman ///     with kind CounterExpression::Subtract
107dc707122SEaswaran Raman ///   Counter::Expression(2) + CounterExpression::Add(1) -
108dc707122SEaswaran Raman ///     A counter with kind Counter::Expression and an expression
109dc707122SEaswaran Raman ///     with kind CounterExpression::Add
110dc707122SEaswaran Raman /// Remaining bits - Counter/Expression ID.
111dc707122SEaswaran Raman static unsigned encodeCounter(ArrayRef<CounterExpression> Expressions,
112dc707122SEaswaran Raman                               Counter C) {
113dc707122SEaswaran Raman   unsigned Tag = unsigned(C.getKind());
114dc707122SEaswaran Raman   if (C.isExpression())
115dc707122SEaswaran Raman     Tag += Expressions[C.getExpressionID()].Kind;
116dc707122SEaswaran Raman   unsigned ID = C.getCounterID();
117dc707122SEaswaran Raman   assert(ID <=
118dc707122SEaswaran Raman          (std::numeric_limits<unsigned>::max() >> Counter::EncodingTagBits));
119dc707122SEaswaran Raman   return Tag | (ID << Counter::EncodingTagBits);
120dc707122SEaswaran Raman }
121dc707122SEaswaran Raman 
122dc707122SEaswaran Raman static void writeCounter(ArrayRef<CounterExpression> Expressions, Counter C,
123dc707122SEaswaran Raman                          raw_ostream &OS) {
124dc707122SEaswaran Raman   encodeULEB128(encodeCounter(Expressions, C), OS);
125dc707122SEaswaran Raman }
126dc707122SEaswaran Raman 
127dc707122SEaswaran Raman void CoverageMappingWriter::write(raw_ostream &OS) {
128bae83970SVedant Kumar   // Check that we don't have any bogus regions.
129bae83970SVedant Kumar   assert(all_of(MappingRegions,
130bae83970SVedant Kumar                 [](const CounterMappingRegion &CMR) {
131bae83970SVedant Kumar                   return CMR.startLoc() <= CMR.endLoc();
132bae83970SVedant Kumar                 }) &&
133bae83970SVedant Kumar          "Source region does not begin before it ends");
134bae83970SVedant Kumar 
135dc707122SEaswaran Raman   // Sort the regions in an ascending order by the file id and the starting
136f3c8a9cfSIgor Kudrin   // location. Sort by region kinds to ensure stable order for tests.
137efd94c56SFangrui Song   llvm::stable_sort(MappingRegions, [](const CounterMappingRegion &LHS,
138efd94c56SFangrui Song                                        const CounterMappingRegion &RHS) {
139f3c8a9cfSIgor Kudrin     if (LHS.FileID != RHS.FileID)
140f3c8a9cfSIgor Kudrin       return LHS.FileID < RHS.FileID;
141f3c8a9cfSIgor Kudrin     if (LHS.startLoc() != RHS.startLoc())
142f3c8a9cfSIgor Kudrin       return LHS.startLoc() < RHS.startLoc();
143f3c8a9cfSIgor Kudrin     return LHS.Kind < RHS.Kind;
144f3c8a9cfSIgor Kudrin   });
145dc707122SEaswaran Raman 
146dc707122SEaswaran Raman   // Write out the fileid -> filename mapping.
147dc707122SEaswaran Raman   encodeULEB128(VirtualFileMapping.size(), OS);
148dc707122SEaswaran Raman   for (const auto &FileID : VirtualFileMapping)
149dc707122SEaswaran Raman     encodeULEB128(FileID, OS);
150dc707122SEaswaran Raman 
151dc707122SEaswaran Raman   // Write out the expressions.
152dc707122SEaswaran Raman   CounterExpressionsMinimizer Minimizer(Expressions, MappingRegions);
153dc707122SEaswaran Raman   auto MinExpressions = Minimizer.getExpressions();
154dc707122SEaswaran Raman   encodeULEB128(MinExpressions.size(), OS);
155dc707122SEaswaran Raman   for (const auto &E : MinExpressions) {
156dc707122SEaswaran Raman     writeCounter(MinExpressions, Minimizer.adjust(E.LHS), OS);
157dc707122SEaswaran Raman     writeCounter(MinExpressions, Minimizer.adjust(E.RHS), OS);
158dc707122SEaswaran Raman   }
159dc707122SEaswaran Raman 
160dc707122SEaswaran Raman   // Write out the mapping regions.
161dc707122SEaswaran Raman   // Split the regions into subarrays where each region in a
162dc707122SEaswaran Raman   // subarray has a fileID which is the index of that subarray.
163dc707122SEaswaran Raman   unsigned PrevLineStart = 0;
164dc707122SEaswaran Raman   unsigned CurrentFileID = ~0U;
165dc707122SEaswaran Raman   for (auto I = MappingRegions.begin(), E = MappingRegions.end(); I != E; ++I) {
166dc707122SEaswaran Raman     if (I->FileID != CurrentFileID) {
167dc707122SEaswaran Raman       // Ensure that all file ids have at least one mapping region.
168dc707122SEaswaran Raman       assert(I->FileID == (CurrentFileID + 1));
169dc707122SEaswaran Raman       // Find the number of regions with this file id.
170dc707122SEaswaran Raman       unsigned RegionCount = 1;
171dc707122SEaswaran Raman       for (auto J = I + 1; J != E && I->FileID == J->FileID; ++J)
172dc707122SEaswaran Raman         ++RegionCount;
173dc707122SEaswaran Raman       // Start a new region sub-array.
174dc707122SEaswaran Raman       encodeULEB128(RegionCount, OS);
175dc707122SEaswaran Raman 
176dc707122SEaswaran Raman       CurrentFileID = I->FileID;
177dc707122SEaswaran Raman       PrevLineStart = 0;
178dc707122SEaswaran Raman     }
179dc707122SEaswaran Raman     Counter Count = Minimizer.adjust(I->Count);
180dc707122SEaswaran Raman     switch (I->Kind) {
181dc707122SEaswaran Raman     case CounterMappingRegion::CodeRegion:
182ad8f637bSVedant Kumar     case CounterMappingRegion::GapRegion:
183dc707122SEaswaran Raman       writeCounter(MinExpressions, Count, OS);
184dc707122SEaswaran Raman       break;
185dc707122SEaswaran Raman     case CounterMappingRegion::ExpansionRegion: {
186dc707122SEaswaran Raman       assert(Count.isZero());
187dc707122SEaswaran Raman       assert(I->ExpandedFileID <=
188dc707122SEaswaran Raman              (std::numeric_limits<unsigned>::max() >>
189dc707122SEaswaran Raman               Counter::EncodingCounterTagAndExpansionRegionTagBits));
190dc707122SEaswaran Raman       // Mark an expansion region with a set bit that follows the counter tag,
191dc707122SEaswaran Raman       // and pack the expanded file id into the remaining bits.
192dc707122SEaswaran Raman       unsigned EncodedTagExpandedFileID =
193dc707122SEaswaran Raman           (1 << Counter::EncodingTagBits) |
194dc707122SEaswaran Raman           (I->ExpandedFileID
195dc707122SEaswaran Raman            << Counter::EncodingCounterTagAndExpansionRegionTagBits);
196dc707122SEaswaran Raman       encodeULEB128(EncodedTagExpandedFileID, OS);
197dc707122SEaswaran Raman       break;
198dc707122SEaswaran Raman     }
199dc707122SEaswaran Raman     case CounterMappingRegion::SkippedRegion:
200dc707122SEaswaran Raman       assert(Count.isZero());
201dc707122SEaswaran Raman       encodeULEB128(unsigned(I->Kind)
202dc707122SEaswaran Raman                         << Counter::EncodingCounterTagAndExpansionRegionTagBits,
203dc707122SEaswaran Raman                     OS);
204dc707122SEaswaran Raman       break;
205dc707122SEaswaran Raman     }
206dc707122SEaswaran Raman     assert(I->LineStart >= PrevLineStart);
207dc707122SEaswaran Raman     encodeULEB128(I->LineStart - PrevLineStart, OS);
208dc707122SEaswaran Raman     encodeULEB128(I->ColumnStart, OS);
209dc707122SEaswaran Raman     assert(I->LineEnd >= I->LineStart);
210dc707122SEaswaran Raman     encodeULEB128(I->LineEnd - I->LineStart, OS);
211dc707122SEaswaran Raman     encodeULEB128(I->ColumnEnd, OS);
212dc707122SEaswaran Raman     PrevLineStart = I->LineStart;
213dc707122SEaswaran Raman   }
214dc707122SEaswaran Raman   // Ensure that all file ids have at least one mapping region.
215dc707122SEaswaran Raman   assert(CurrentFileID == (VirtualFileMapping.size() - 1));
216dc707122SEaswaran Raman }
217