1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // GCOV implements the interface to read and write coverage files that use
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ProfileData/GCOV.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/llvm-config.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
23 #include <system_error>
27 //===----------------------------------------------------------------------===//
28 // GCOVFile implementation.
30 /// readGCNO - Read GCNO buffer.
31 bool GCOVFile::readGCNO(GCOVBuffer
&Buffer
) {
32 if (!Buffer
.readGCNOFormat())
34 if (!Buffer
.readGCOVVersion(Version
))
37 if (!Buffer
.readInt(Checksum
))
40 if (!Buffer
.readFunctionTag())
42 auto GFun
= make_unique
<GCOVFunction
>(*this);
43 if (!GFun
->readGCNO(Buffer
, Version
))
45 Functions
.push_back(std::move(GFun
));
48 GCNOInitialized
= true;
52 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
53 /// called after readGCNO().
54 bool GCOVFile::readGCDA(GCOVBuffer
&Buffer
) {
55 assert(GCNOInitialized
&& "readGCDA() can only be called after readGCNO()");
56 if (!Buffer
.readGCDAFormat())
58 GCOV::GCOVVersion GCDAVersion
;
59 if (!Buffer
.readGCOVVersion(GCDAVersion
))
61 if (Version
!= GCDAVersion
) {
62 errs() << "GCOV versions do not match.\n";
66 uint32_t GCDAChecksum
;
67 if (!Buffer
.readInt(GCDAChecksum
))
69 if (Checksum
!= GCDAChecksum
) {
70 errs() << "File checksums do not match: " << Checksum
71 << " != " << GCDAChecksum
<< ".\n";
74 for (size_t i
= 0, e
= Functions
.size(); i
< e
; ++i
) {
75 if (!Buffer
.readFunctionTag()) {
76 errs() << "Unexpected number of functions.\n";
79 if (!Functions
[i
]->readGCDA(Buffer
, Version
))
82 if (Buffer
.readObjectTag()) {
85 if (!Buffer
.readInt(Length
))
87 if (!Buffer
.readInt(Dummy
))
88 return false; // checksum
89 if (!Buffer
.readInt(Dummy
))
91 if (!Buffer
.readInt(RunCount
))
93 Buffer
.advanceCursor(Length
- 3);
95 while (Buffer
.readProgramTag()) {
97 if (!Buffer
.readInt(Length
))
99 Buffer
.advanceCursor(Length
);
106 void GCOVFile::print(raw_ostream
&OS
) const {
107 for (const auto &FPtr
: Functions
)
111 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
112 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
113 LLVM_DUMP_METHOD
void GCOVFile::dump() const { print(dbgs()); }
116 /// collectLineCounts - Collect line counts. This must be used after
117 /// reading .gcno and .gcda files.
118 void GCOVFile::collectLineCounts(FileInfo
&FI
) {
119 for (const auto &FPtr
: Functions
)
120 FPtr
->collectLineCounts(FI
);
121 FI
.setRunCount(RunCount
);
122 FI
.setProgramCount(ProgramCount
);
125 //===----------------------------------------------------------------------===//
126 // GCOVFunction implementation.
128 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
130 bool GCOVFunction::readGCNO(GCOVBuffer
&Buff
, GCOV::GCOVVersion Version
) {
132 if (!Buff
.readInt(Dummy
))
133 return false; // Function header length
134 if (!Buff
.readInt(Ident
))
136 if (!Buff
.readInt(Checksum
))
138 if (Version
!= GCOV::V402
) {
139 uint32_t CfgChecksum
;
140 if (!Buff
.readInt(CfgChecksum
))
142 if (Parent
.getChecksum() != CfgChecksum
) {
143 errs() << "File checksums do not match: " << Parent
.getChecksum()
144 << " != " << CfgChecksum
<< " in (" << Name
<< ").\n";
148 if (!Buff
.readString(Name
))
150 if (!Buff
.readString(Filename
))
152 if (!Buff
.readInt(LineNumber
))
156 if (!Buff
.readBlockTag()) {
157 errs() << "Block tag not found.\n";
161 if (!Buff
.readInt(BlockCount
))
163 for (uint32_t i
= 0, e
= BlockCount
; i
!= e
; ++i
) {
164 if (!Buff
.readInt(Dummy
))
165 return false; // Block flags;
166 Blocks
.push_back(make_unique
<GCOVBlock
>(*this, i
));
170 while (Buff
.readEdgeTag()) {
172 if (!Buff
.readInt(EdgeCount
))
174 EdgeCount
= (EdgeCount
- 1) / 2;
176 if (!Buff
.readInt(BlockNo
))
178 if (BlockNo
>= BlockCount
) {
179 errs() << "Unexpected block number: " << BlockNo
<< " (in " << Name
183 for (uint32_t i
= 0, e
= EdgeCount
; i
!= e
; ++i
) {
185 if (!Buff
.readInt(Dst
))
187 Edges
.push_back(make_unique
<GCOVEdge
>(*Blocks
[BlockNo
], *Blocks
[Dst
]));
188 GCOVEdge
*Edge
= Edges
.back().get();
189 Blocks
[BlockNo
]->addDstEdge(Edge
);
190 Blocks
[Dst
]->addSrcEdge(Edge
);
191 if (!Buff
.readInt(Dummy
))
192 return false; // Edge flag
197 while (Buff
.readLineTag()) {
198 uint32_t LineTableLength
;
199 // Read the length of this line table.
200 if (!Buff
.readInt(LineTableLength
))
202 uint32_t EndPos
= Buff
.getCursor() + LineTableLength
* 4;
204 // Read the block number this table is associated with.
205 if (!Buff
.readInt(BlockNo
))
207 if (BlockNo
>= BlockCount
) {
208 errs() << "Unexpected block number: " << BlockNo
<< " (in " << Name
212 GCOVBlock
&Block
= *Blocks
[BlockNo
];
213 // Read the word that pads the beginning of the line table. This may be a
214 // flag of some sort, but seems to always be zero.
215 if (!Buff
.readInt(Dummy
))
218 // Line information starts here and continues up until the last word.
219 if (Buff
.getCursor() != (EndPos
- sizeof(uint32_t))) {
221 // Read the source file name.
222 if (!Buff
.readString(F
))
225 errs() << "Multiple sources for a single basic block: " << Filename
226 << " != " << F
<< " (in " << Name
<< ").\n";
229 // Read lines up to, but not including, the null terminator.
230 while (Buff
.getCursor() < (EndPos
- 2 * sizeof(uint32_t))) {
232 if (!Buff
.readInt(Line
))
234 // Line 0 means this instruction was injected by the compiler. Skip it.
239 // Read the null terminator.
240 if (!Buff
.readInt(Dummy
))
243 // The last word is either a flag or padding, it isn't clear which. Skip
245 if (!Buff
.readInt(Dummy
))
251 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
253 bool GCOVFunction::readGCDA(GCOVBuffer
&Buff
, GCOV::GCOVVersion Version
) {
254 uint32_t HeaderLength
;
255 if (!Buff
.readInt(HeaderLength
))
256 return false; // Function header length
258 uint64_t EndPos
= Buff
.getCursor() + HeaderLength
* sizeof(uint32_t);
261 if (!Buff
.readInt(GCDAIdent
))
263 if (Ident
!= GCDAIdent
) {
264 errs() << "Function identifiers do not match: " << Ident
265 << " != " << GCDAIdent
<< " (in " << Name
<< ").\n";
269 uint32_t GCDAChecksum
;
270 if (!Buff
.readInt(GCDAChecksum
))
272 if (Checksum
!= GCDAChecksum
) {
273 errs() << "Function checksums do not match: " << Checksum
274 << " != " << GCDAChecksum
<< " (in " << Name
<< ").\n";
278 uint32_t CfgChecksum
;
279 if (Version
!= GCOV::V402
) {
280 if (!Buff
.readInt(CfgChecksum
))
282 if (Parent
.getChecksum() != CfgChecksum
) {
283 errs() << "File checksums do not match: " << Parent
.getChecksum()
284 << " != " << CfgChecksum
<< " (in " << Name
<< ").\n";
289 if (Buff
.getCursor() < EndPos
) {
291 if (!Buff
.readString(GCDAName
))
293 if (Name
!= GCDAName
) {
294 errs() << "Function names do not match: " << Name
<< " != " << GCDAName
300 if (!Buff
.readArcTag()) {
301 errs() << "Arc tag not found (in " << Name
<< ").\n";
306 if (!Buff
.readInt(Count
))
310 // This for loop adds the counts for each block. A second nested loop is
311 // required to combine the edge counts that are contained in the GCDA file.
312 for (uint32_t BlockNo
= 0; Count
> 0; ++BlockNo
) {
313 // The last block is always reserved for exit block
314 if (BlockNo
>= Blocks
.size()) {
315 errs() << "Unexpected number of edges (in " << Name
<< ").\n";
318 if (BlockNo
== Blocks
.size() - 1)
319 errs() << "(" << Name
<< ") has arcs from exit block.\n";
320 GCOVBlock
&Block
= *Blocks
[BlockNo
];
321 for (size_t EdgeNo
= 0, End
= Block
.getNumDstEdges(); EdgeNo
< End
;
324 errs() << "Unexpected number of edges (in " << Name
<< ").\n";
328 if (!Buff
.readInt64(ArcCount
))
330 Block
.addCount(EdgeNo
, ArcCount
);
333 Block
.sortDstEdges();
338 /// getEntryCount - Get the number of times the function was called by
339 /// retrieving the entry block's count.
340 uint64_t GCOVFunction::getEntryCount() const {
341 return Blocks
.front()->getCount();
344 /// getExitCount - Get the number of times the function returned by retrieving
345 /// the exit block's count.
346 uint64_t GCOVFunction::getExitCount() const {
347 return Blocks
.back()->getCount();
350 void GCOVFunction::print(raw_ostream
&OS
) const {
351 OS
<< "===== " << Name
<< " (" << Ident
<< ") @ " << Filename
<< ":"
352 << LineNumber
<< "\n";
353 for (const auto &Block
: Blocks
)
357 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
358 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
359 LLVM_DUMP_METHOD
void GCOVFunction::dump() const { print(dbgs()); }
362 /// collectLineCounts - Collect line counts. This must be used after
363 /// reading .gcno and .gcda files.
364 void GCOVFunction::collectLineCounts(FileInfo
&FI
) {
365 // If the line number is zero, this is a function that doesn't actually appear
366 // in the source file, so there isn't anything we can do with it.
370 for (const auto &Block
: Blocks
)
371 Block
->collectLineCounts(FI
);
372 FI
.addFunctionLine(Filename
, LineNumber
, this);
375 //===----------------------------------------------------------------------===//
376 // GCOVBlock implementation.
378 /// ~GCOVBlock - Delete GCOVBlock and its content.
379 GCOVBlock::~GCOVBlock() {
385 /// addCount - Add to block counter while storing the edge count. If the
386 /// destination has no outgoing edges, also update that block's count too.
387 void GCOVBlock::addCount(size_t DstEdgeNo
, uint64_t N
) {
388 assert(DstEdgeNo
< DstEdges
.size()); // up to caller to ensure EdgeNo is valid
389 DstEdges
[DstEdgeNo
]->Count
= N
;
391 if (!DstEdges
[DstEdgeNo
]->Dst
.getNumDstEdges())
392 DstEdges
[DstEdgeNo
]->Dst
.Counter
+= N
;
395 /// sortDstEdges - Sort destination edges by block number, nop if already
396 /// sorted. This is required for printing branch info in the correct order.
397 void GCOVBlock::sortDstEdges() {
398 if (!DstEdgesAreSorted
) {
399 SortDstEdgesFunctor SortEdges
;
400 std::stable_sort(DstEdges
.begin(), DstEdges
.end(), SortEdges
);
404 /// collectLineCounts - Collect line counts. This must be used after
405 /// reading .gcno and .gcda files.
406 void GCOVBlock::collectLineCounts(FileInfo
&FI
) {
407 for (uint32_t N
: Lines
)
408 FI
.addBlockLine(Parent
.getFilename(), N
, this);
411 void GCOVBlock::print(raw_ostream
&OS
) const {
412 OS
<< "Block : " << Number
<< " Counter : " << Counter
<< "\n";
413 if (!SrcEdges
.empty()) {
414 OS
<< "\tSource Edges : ";
415 for (const GCOVEdge
*Edge
: SrcEdges
)
416 OS
<< Edge
->Src
.Number
<< " (" << Edge
->Count
<< "), ";
419 if (!DstEdges
.empty()) {
420 OS
<< "\tDestination Edges : ";
421 for (const GCOVEdge
*Edge
: DstEdges
)
422 OS
<< Edge
->Dst
.Number
<< " (" << Edge
->Count
<< "), ";
425 if (!Lines
.empty()) {
427 for (uint32_t N
: Lines
)
433 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
434 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
435 LLVM_DUMP_METHOD
void GCOVBlock::dump() const { print(dbgs()); }
438 //===----------------------------------------------------------------------===//
441 // The algorithm in GCC is based on the algorihtm by Hawick & James:
442 // "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
443 // http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf.
445 /// Get the count for the detected cycle.
446 uint64_t GCOVBlock::getCycleCount(const Edges
&Path
) {
447 uint64_t CycleCount
= std::numeric_limits
<uint64_t>::max();
448 for (auto E
: Path
) {
449 CycleCount
= std::min(E
->CyclesCount
, CycleCount
);
451 for (auto E
: Path
) {
452 E
->CyclesCount
-= CycleCount
;
457 /// Unblock a vertex previously marked as blocked.
458 void GCOVBlock::unblock(const GCOVBlock
*U
, BlockVector
&Blocked
,
459 BlockVectorLists
&BlockLists
) {
460 auto it
= find(Blocked
, U
);
461 if (it
== Blocked
.end()) {
465 const size_t index
= it
- Blocked
.begin();
468 const BlockVector
ToUnblock(BlockLists
[index
]);
469 BlockLists
.erase(BlockLists
.begin() + index
);
470 for (auto GB
: ToUnblock
) {
471 GCOVBlock::unblock(GB
, Blocked
, BlockLists
);
475 bool GCOVBlock::lookForCircuit(const GCOVBlock
*V
, const GCOVBlock
*Start
,
476 Edges
&Path
, BlockVector
&Blocked
,
477 BlockVectorLists
&BlockLists
,
478 const BlockVector
&Blocks
, uint64_t &Count
) {
479 Blocked
.push_back(V
);
480 BlockLists
.emplace_back(BlockVector());
481 bool FoundCircuit
= false;
483 for (auto E
: V
->dsts()) {
484 const GCOVBlock
*W
= &E
->Dst
;
485 if (W
< Start
|| find(Blocks
, W
) == Blocks
.end()) {
493 Count
+= GCOVBlock::getCycleCount(Path
);
495 } else if (find(Blocked
, W
) == Blocked
.end() && // W is not blocked.
496 GCOVBlock::lookForCircuit(W
, Start
, Path
, Blocked
, BlockLists
,
505 GCOVBlock::unblock(V
, Blocked
, BlockLists
);
507 for (auto E
: V
->dsts()) {
508 const GCOVBlock
*W
= &E
->Dst
;
509 if (W
< Start
|| find(Blocks
, W
) == Blocks
.end()) {
512 const size_t index
= find(Blocked
, W
) - Blocked
.begin();
513 BlockVector
&List
= BlockLists
[index
];
514 if (find(List
, V
) == List
.end()) {
523 /// Get the count for the list of blocks which lie on the same line.
524 void GCOVBlock::getCyclesCount(const BlockVector
&Blocks
, uint64_t &Count
) {
525 for (auto Block
: Blocks
) {
528 BlockVectorLists BlockLists
;
530 GCOVBlock::lookForCircuit(Block
, Block
, Path
, Blocked
, BlockLists
, Blocks
,
535 /// Get the count for the list of blocks which lie on the same line.
536 uint64_t GCOVBlock::getLineCount(const BlockVector
&Blocks
) {
539 for (auto Block
: Blocks
) {
540 if (Block
->getNumSrcEdges() == 0) {
541 // The block has no predecessors and a non-null counter
542 // (can be the case with entry block in functions).
543 Count
+= Block
->getCount();
545 // Add counts from predecessors that are not on the same line.
546 for (auto E
: Block
->srcs()) {
547 const GCOVBlock
*W
= &E
->Src
;
548 if (find(Blocks
, W
) == Blocks
.end()) {
553 for (auto E
: Block
->dsts()) {
554 E
->CyclesCount
= E
->Count
;
558 GCOVBlock::getCyclesCount(Blocks
, Count
);
563 //===----------------------------------------------------------------------===//
564 // FileInfo implementation.
566 // Safe integer division, returns 0 if numerator is 0.
567 static uint32_t safeDiv(uint64_t Numerator
, uint64_t Divisor
) {
570 return Numerator
/ Divisor
;
573 // This custom division function mimics gcov's branch ouputs:
574 // - Round to closest whole number
575 // - Only output 0% or 100% if it's exactly that value
576 static uint32_t branchDiv(uint64_t Numerator
, uint64_t Divisor
) {
579 if (Numerator
== Divisor
)
582 uint8_t Res
= (Numerator
* 100 + Divisor
/ 2) / Divisor
;
591 struct formatBranchInfo
{
592 formatBranchInfo(const GCOV::Options
&Options
, uint64_t Count
, uint64_t Total
)
593 : Options(Options
), Count(Count
), Total(Total
) {}
595 void print(raw_ostream
&OS
) const {
597 OS
<< "never executed";
598 else if (Options
.BranchCount
)
599 OS
<< "taken " << Count
;
601 OS
<< "taken " << branchDiv(Count
, Total
) << "%";
604 const GCOV::Options
&Options
;
609 static raw_ostream
&operator<<(raw_ostream
&OS
, const formatBranchInfo
&FBI
) {
615 std::unique_ptr
<MemoryBuffer
> Buffer
;
619 LineConsumer(StringRef Filename
) {
620 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
621 MemoryBuffer::getFileOrSTDIN(Filename
);
622 if (std::error_code EC
= BufferOrErr
.getError()) {
623 errs() << Filename
<< ": " << EC
.message() << "\n";
626 Buffer
= std::move(BufferOrErr
.get());
627 Remaining
= Buffer
->getBuffer();
630 bool empty() { return Remaining
.empty(); }
631 void printNext(raw_ostream
&OS
, uint32_t LineNum
) {
636 std::tie(Line
, Remaining
) = Remaining
.split("\n");
637 OS
<< format("%5u:", LineNum
) << Line
<< "\n";
640 } // end anonymous namespace
642 /// Convert a path to a gcov filename. If PreservePaths is true, this
643 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
644 static std::string
mangleCoveragePath(StringRef Filename
, bool PreservePaths
) {
646 return sys::path::filename(Filename
).str();
648 // This behaviour is defined by gcov in terms of text replacements, so it's
649 // not likely to do anything useful on filesystems with different textual
651 llvm::SmallString
<256> Result("");
652 StringRef::iterator I
, S
, E
;
653 for (I
= S
= Filename
.begin(), E
= Filename
.end(); I
!= E
; ++I
) {
657 if (I
- S
== 1 && *S
== '.') {
658 // ".", the current directory, is skipped.
659 } else if (I
- S
== 2 && *S
== '.' && *(S
+ 1) == '.') {
660 // "..", the parent directory, is replaced with "^".
664 // Leave other components intact,
666 // And separate with "#".
667 Result
.push_back('#');
677 std::string
FileInfo::getCoveragePath(StringRef Filename
,
678 StringRef MainFilename
) {
679 if (Options
.NoOutput
)
680 // This is probably a bug in gcov, but when -n is specified, paths aren't
681 // mangled at all, and the -l and -p options are ignored. Here, we do the
685 std::string CoveragePath
;
686 if (Options
.LongFileNames
&& !Filename
.equals(MainFilename
))
688 mangleCoveragePath(MainFilename
, Options
.PreservePaths
) + "##";
689 CoveragePath
+= mangleCoveragePath(Filename
, Options
.PreservePaths
) + ".gcov";
693 std::unique_ptr
<raw_ostream
>
694 FileInfo::openCoveragePath(StringRef CoveragePath
) {
695 if (Options
.NoOutput
)
696 return llvm::make_unique
<raw_null_ostream
>();
700 llvm::make_unique
<raw_fd_ostream
>(CoveragePath
, EC
, sys::fs::F_Text
);
702 errs() << EC
.message() << "\n";
703 return llvm::make_unique
<raw_null_ostream
>();
705 return std::move(OS
);
708 /// print - Print source files with collected line count information.
709 void FileInfo::print(raw_ostream
&InfoOS
, StringRef MainFilename
,
710 StringRef GCNOFile
, StringRef GCDAFile
) {
711 SmallVector
<StringRef
, 4> Filenames
;
712 for (const auto &LI
: LineInfo
)
713 Filenames
.push_back(LI
.first());
714 llvm::sort(Filenames
);
716 for (StringRef Filename
: Filenames
) {
717 auto AllLines
= LineConsumer(Filename
);
719 std::string CoveragePath
= getCoveragePath(Filename
, MainFilename
);
720 std::unique_ptr
<raw_ostream
> CovStream
= openCoveragePath(CoveragePath
);
721 raw_ostream
&CovOS
= *CovStream
;
723 CovOS
<< " -: 0:Source:" << Filename
<< "\n";
724 CovOS
<< " -: 0:Graph:" << GCNOFile
<< "\n";
725 CovOS
<< " -: 0:Data:" << GCDAFile
<< "\n";
726 CovOS
<< " -: 0:Runs:" << RunCount
<< "\n";
727 CovOS
<< " -: 0:Programs:" << ProgramCount
<< "\n";
729 const LineData
&Line
= LineInfo
[Filename
];
730 GCOVCoverage
FileCoverage(Filename
);
731 for (uint32_t LineIndex
= 0; LineIndex
< Line
.LastLine
|| !AllLines
.empty();
733 if (Options
.BranchInfo
) {
734 FunctionLines::const_iterator FuncsIt
= Line
.Functions
.find(LineIndex
);
735 if (FuncsIt
!= Line
.Functions
.end())
736 printFunctionSummary(CovOS
, FuncsIt
->second
);
739 BlockLines::const_iterator BlocksIt
= Line
.Blocks
.find(LineIndex
);
740 if (BlocksIt
== Line
.Blocks
.end()) {
741 // No basic blocks are on this line. Not an executable line of code.
743 AllLines
.printNext(CovOS
, LineIndex
+ 1);
745 const BlockVector
&Blocks
= BlocksIt
->second
;
747 // Add up the block counts to form line counts.
748 DenseMap
<const GCOVFunction
*, bool> LineExecs
;
749 for (const GCOVBlock
*Block
: Blocks
) {
750 if (Options
.FuncCoverage
) {
751 // This is a slightly convoluted way to most accurately gather line
752 // statistics for functions. Basically what is happening is that we
753 // don't want to count a single line with multiple blocks more than
754 // once. However, we also don't simply want to give the total line
755 // count to every function that starts on the line. Thus, what is
756 // happening here are two things:
757 // 1) Ensure that the number of logical lines is only incremented
758 // once per function.
759 // 2) If there are multiple blocks on the same line, ensure that the
760 // number of lines executed is incremented as long as at least
761 // one of the blocks are executed.
762 const GCOVFunction
*Function
= &Block
->getParent();
763 if (FuncCoverages
.find(Function
) == FuncCoverages
.end()) {
764 std::pair
<const GCOVFunction
*, GCOVCoverage
> KeyValue(
765 Function
, GCOVCoverage(Function
->getName()));
766 FuncCoverages
.insert(KeyValue
);
768 GCOVCoverage
&FuncCoverage
= FuncCoverages
.find(Function
)->second
;
770 if (LineExecs
.find(Function
) == LineExecs
.end()) {
771 if (Block
->getCount()) {
772 ++FuncCoverage
.LinesExec
;
773 LineExecs
[Function
] = true;
775 LineExecs
[Function
] = false;
777 ++FuncCoverage
.LogicalLines
;
778 } else if (!LineExecs
[Function
] && Block
->getCount()) {
779 ++FuncCoverage
.LinesExec
;
780 LineExecs
[Function
] = true;
785 const uint64_t LineCount
= GCOVBlock::getLineCount(Blocks
);
789 CovOS
<< format("%9" PRIu64
":", LineCount
);
790 ++FileCoverage
.LinesExec
;
792 ++FileCoverage
.LogicalLines
;
794 AllLines
.printNext(CovOS
, LineIndex
+ 1);
796 uint32_t BlockNo
= 0;
798 for (const GCOVBlock
*Block
: Blocks
) {
799 // Only print block and branch information at the end of the block.
800 if (Block
->getLastLine() != LineIndex
+ 1)
802 if (Options
.AllBlocks
)
803 printBlockInfo(CovOS
, *Block
, LineIndex
, BlockNo
);
804 if (Options
.BranchInfo
) {
805 size_t NumEdges
= Block
->getNumDstEdges();
807 printBranchInfo(CovOS
, *Block
, FileCoverage
, EdgeNo
);
808 else if (Options
.UncondBranch
&& NumEdges
== 1)
809 printUncondBranchInfo(CovOS
, EdgeNo
,
810 (*Block
->dst_begin())->Count
);
815 FileCoverages
.push_back(std::make_pair(CoveragePath
, FileCoverage
));
818 // FIXME: There is no way to detect calls given current instrumentation.
819 if (Options
.FuncCoverage
)
820 printFuncCoverage(InfoOS
);
821 printFileCoverage(InfoOS
);
824 /// printFunctionSummary - Print function and block summary.
825 void FileInfo::printFunctionSummary(raw_ostream
&OS
,
826 const FunctionVector
&Funcs
) const {
827 for (const GCOVFunction
*Func
: Funcs
) {
828 uint64_t EntryCount
= Func
->getEntryCount();
829 uint32_t BlocksExec
= 0;
830 for (const GCOVBlock
&Block
: Func
->blocks())
831 if (Block
.getNumDstEdges() && Block
.getCount())
834 OS
<< "function " << Func
->getName() << " called " << EntryCount
835 << " returned " << safeDiv(Func
->getExitCount() * 100, EntryCount
)
836 << "% blocks executed "
837 << safeDiv(BlocksExec
* 100, Func
->getNumBlocks() - 1) << "%\n";
841 /// printBlockInfo - Output counts for each block.
842 void FileInfo::printBlockInfo(raw_ostream
&OS
, const GCOVBlock
&Block
,
843 uint32_t LineIndex
, uint32_t &BlockNo
) const {
844 if (Block
.getCount() == 0)
847 OS
<< format("%9" PRIu64
":", Block
.getCount());
848 OS
<< format("%5u-block %2u\n", LineIndex
+ 1, BlockNo
++);
851 /// printBranchInfo - Print conditional branch probabilities.
852 void FileInfo::printBranchInfo(raw_ostream
&OS
, const GCOVBlock
&Block
,
853 GCOVCoverage
&Coverage
, uint32_t &EdgeNo
) {
854 SmallVector
<uint64_t, 16> BranchCounts
;
855 uint64_t TotalCounts
= 0;
856 for (const GCOVEdge
*Edge
: Block
.dsts()) {
857 BranchCounts
.push_back(Edge
->Count
);
858 TotalCounts
+= Edge
->Count
;
859 if (Block
.getCount())
860 ++Coverage
.BranchesExec
;
862 ++Coverage
.BranchesTaken
;
865 if (Options
.FuncCoverage
) {
866 const GCOVFunction
*Function
= &Block
.getParent();
867 GCOVCoverage
&FuncCoverage
= FuncCoverages
.find(Function
)->second
;
868 if (Block
.getCount())
869 ++FuncCoverage
.BranchesExec
;
871 ++FuncCoverage
.BranchesTaken
;
872 ++FuncCoverage
.Branches
;
876 for (uint64_t N
: BranchCounts
)
877 OS
<< format("branch %2u ", EdgeNo
++)
878 << formatBranchInfo(Options
, N
, TotalCounts
) << "\n";
881 /// printUncondBranchInfo - Print unconditional branch probabilities.
882 void FileInfo::printUncondBranchInfo(raw_ostream
&OS
, uint32_t &EdgeNo
,
883 uint64_t Count
) const {
884 OS
<< format("unconditional %2u ", EdgeNo
++)
885 << formatBranchInfo(Options
, Count
, Count
) << "\n";
888 // printCoverage - Print generic coverage info used by both printFuncCoverage
889 // and printFileCoverage.
890 void FileInfo::printCoverage(raw_ostream
&OS
,
891 const GCOVCoverage
&Coverage
) const {
892 OS
<< format("Lines executed:%.2f%% of %u\n",
893 double(Coverage
.LinesExec
) * 100 / Coverage
.LogicalLines
,
894 Coverage
.LogicalLines
);
895 if (Options
.BranchInfo
) {
896 if (Coverage
.Branches
) {
897 OS
<< format("Branches executed:%.2f%% of %u\n",
898 double(Coverage
.BranchesExec
) * 100 / Coverage
.Branches
,
900 OS
<< format("Taken at least once:%.2f%% of %u\n",
901 double(Coverage
.BranchesTaken
) * 100 / Coverage
.Branches
,
904 OS
<< "No branches\n";
906 OS
<< "No calls\n"; // to be consistent with gcov
910 // printFuncCoverage - Print per-function coverage info.
911 void FileInfo::printFuncCoverage(raw_ostream
&OS
) const {
912 for (const auto &FC
: FuncCoverages
) {
913 const GCOVCoverage
&Coverage
= FC
.second
;
914 OS
<< "Function '" << Coverage
.Name
<< "'\n";
915 printCoverage(OS
, Coverage
);
920 // printFileCoverage - Print per-file coverage info.
921 void FileInfo::printFileCoverage(raw_ostream
&OS
) const {
922 for (const auto &FC
: FileCoverages
) {
923 const std::string
&Filename
= FC
.first
;
924 const GCOVCoverage
&Coverage
= FC
.second
;
925 OS
<< "File '" << Coverage
.Name
<< "'\n";
926 printCoverage(OS
, Coverage
);
927 if (!Options
.NoOutput
)
928 OS
<< Coverage
.Name
<< ":creating '" << Filename
<< "'\n";