1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // GCOV implements the interface to read and write coverage files that use
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/Debug.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/GCOV.h"
20 #include "llvm/Support/MemoryObject.h"
21 #include "llvm/Support/system_error.h"
25 //===----------------------------------------------------------------------===//
26 // GCOVFile implementation.
28 /// ~GCOVFile - Delete GCOVFile and its content.
29 GCOVFile::~GCOVFile() {
30 DeleteContainerPointers(Functions);
33 /// readGCNO - Read GCNO buffer.
34 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
35 if (!Buffer.readGCNOFormat()) return false;
36 if (!Buffer.readGCOVVersion(Version)) return false;
38 if (!Buffer.readInt(Checksum)) return false;
40 if (!Buffer.readFunctionTag()) break;
41 GCOVFunction *GFun = new GCOVFunction(*this);
42 if (!GFun->readGCNO(Buffer, Version))
44 Functions.push_back(GFun);
47 GCNOInitialized = true;
51 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
52 /// called after readGCNO().
53 bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
54 assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
55 if (!Buffer.readGCDAFormat()) return false;
56 GCOV::GCOVVersion GCDAVersion;
57 if (!Buffer.readGCOVVersion(GCDAVersion)) return false;
58 if (Version != GCDAVersion) {
59 errs() << "GCOV versions do not match.\n";
63 uint32_t GCDAChecksum;
64 if (!Buffer.readInt(GCDAChecksum)) return false;
65 if (Checksum != GCDAChecksum) {
66 errs() << "File checksums do not match: " << Checksum << " != "
67 << GCDAChecksum << ".\n";
70 for (size_t i = 0, e = Functions.size(); i < e; ++i) {
71 if (!Buffer.readFunctionTag()) {
72 errs() << "Unexpected number of functions.\n";
75 if (!Functions[i]->readGCDA(Buffer, Version))
78 if (Buffer.readObjectTag()) {
81 if (!Buffer.readInt(Length)) return false;
82 if (!Buffer.readInt(Dummy)) return false; // checksum
83 if (!Buffer.readInt(Dummy)) return false; // num
84 if (!Buffer.readInt(RunCount)) return false;
85 Buffer.advanceCursor(Length-3);
87 while (Buffer.readProgramTag()) {
89 if (!Buffer.readInt(Length)) return false;
90 Buffer.advanceCursor(Length);
97 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
98 void GCOVFile::dump() const {
99 for (SmallVectorImpl<GCOVFunction *>::const_iterator I = Functions.begin(),
100 E = Functions.end(); I != E; ++I)
104 /// collectLineCounts - Collect line counts. This must be used after
105 /// reading .gcno and .gcda files.
106 void GCOVFile::collectLineCounts(FileInfo &FI) {
107 for (SmallVectorImpl<GCOVFunction *>::iterator I = Functions.begin(),
108 E = Functions.end(); I != E; ++I)
109 (*I)->collectLineCounts(FI);
110 FI.setRunCount(RunCount);
111 FI.setProgramCount(ProgramCount);
114 //===----------------------------------------------------------------------===//
115 // GCOVFunction implementation.
117 /// ~GCOVFunction - Delete GCOVFunction and its content.
118 GCOVFunction::~GCOVFunction() {
119 DeleteContainerPointers(Blocks);
120 DeleteContainerPointers(Edges);
123 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
125 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
127 if (!Buff.readInt(Dummy)) return false; // Function header length
128 if (!Buff.readInt(Ident)) return false;
129 if (!Buff.readInt(Checksum)) return false;
130 if (Version != GCOV::V402) {
131 uint32_t CfgChecksum;
132 if (!Buff.readInt(CfgChecksum)) return false;
133 if (Parent.getChecksum() != CfgChecksum) {
134 errs() << "File checksums do not match: " << Parent.getChecksum()
135 << " != " << CfgChecksum << " in (" << Name << ").\n";
139 if (!Buff.readString(Name)) return false;
140 if (!Buff.readString(Filename)) return false;
141 if (!Buff.readInt(LineNumber)) return false;
144 if (!Buff.readBlockTag()) {
145 errs() << "Block tag not found.\n";
149 if (!Buff.readInt(BlockCount)) return false;
150 for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
151 if (!Buff.readInt(Dummy)) return false; // Block flags;
152 Blocks.push_back(new GCOVBlock(*this, i));
156 while (Buff.readEdgeTag()) {
158 if (!Buff.readInt(EdgeCount)) return false;
159 EdgeCount = (EdgeCount - 1) / 2;
161 if (!Buff.readInt(BlockNo)) return false;
162 if (BlockNo >= BlockCount) {
163 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
167 for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
169 if (!Buff.readInt(Dst)) return false;
170 GCOVEdge *Edge = new GCOVEdge(Blocks[BlockNo], Blocks[Dst]);
171 Edges.push_back(Edge);
172 Blocks[BlockNo]->addDstEdge(Edge);
173 Blocks[Dst]->addSrcEdge(Edge);
174 if (!Buff.readInt(Dummy)) return false; // Edge flag
179 while (Buff.readLineTag()) {
180 uint32_t LineTableLength;
181 if (!Buff.readInt(LineTableLength)) return false;
182 uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
184 if (!Buff.readInt(BlockNo)) return false;
185 if (BlockNo >= BlockCount) {
186 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
190 GCOVBlock *Block = Blocks[BlockNo];
191 if (!Buff.readInt(Dummy)) return false; // flag
192 while (Buff.getCursor() != (EndPos - 4)) {
194 if (!Buff.readString(F)) return false;
196 errs() << "Multiple sources for a single basic block: " << Filename
197 << " != " << F << " (in " << Name << ").\n";
200 if (Buff.getCursor() == (EndPos - 4)) break;
203 if (!Buff.readInt(Line)) return false;
205 Block->addLine(Line);
208 if (!Buff.readInt(Dummy)) return false; // flag
213 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
215 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
217 if (!Buff.readInt(Dummy)) return false; // Function header length
220 if (!Buff.readInt(GCDAIdent)) return false;
221 if (Ident != GCDAIdent) {
222 errs() << "Function identifiers do not match: " << Ident << " != "
223 << GCDAIdent << " (in " << Name << ").\n";
227 uint32_t GCDAChecksum;
228 if (!Buff.readInt(GCDAChecksum)) return false;
229 if (Checksum != GCDAChecksum) {
230 errs() << "Function checksums do not match: " << Checksum << " != "
231 << GCDAChecksum << " (in " << Name << ").\n";
235 uint32_t CfgChecksum;
236 if (Version != GCOV::V402) {
237 if (!Buff.readInt(CfgChecksum)) return false;
238 if (Parent.getChecksum() != CfgChecksum) {
239 errs() << "File checksums do not match: " << Parent.getChecksum()
240 << " != " << CfgChecksum << " (in " << Name << ").\n";
246 if (!Buff.readString(GCDAName)) return false;
247 if (Name != GCDAName) {
248 errs() << "Function names do not match: " << Name << " != " << GCDAName
253 if (!Buff.readArcTag()) {
254 errs() << "Arc tag not found (in " << Name << ").\n";
259 if (!Buff.readInt(Count)) return false;
262 // This for loop adds the counts for each block. A second nested loop is
263 // required to combine the edge counts that are contained in the GCDA file.
264 for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
265 // The last block is always reserved for exit block
266 if (BlockNo >= Blocks.size()-1) {
267 errs() << "Unexpected number of edges (in " << Name << ").\n";
270 GCOVBlock &Block = *Blocks[BlockNo];
271 for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
274 errs() << "Unexpected number of edges (in " << Name << ").\n";
278 if (!Buff.readInt64(ArcCount)) return false;
279 Block.addCount(EdgeNo, ArcCount);
282 Block.sortDstEdges();
287 /// getEntryCount - Get the number of times the function was called by
288 /// retrieving the entry block's count.
289 uint64_t GCOVFunction::getEntryCount() const {
290 return Blocks.front()->getCount();
293 /// getExitCount - Get the number of times the function returned by retrieving
294 /// the exit block's count.
295 uint64_t GCOVFunction::getExitCount() const {
296 return Blocks.back()->getCount();
299 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
300 void GCOVFunction::dump() const {
301 dbgs() << "===== " << Name << " @ " << Filename << ":" << LineNumber << "\n";
302 for (SmallVectorImpl<GCOVBlock *>::const_iterator I = Blocks.begin(),
303 E = Blocks.end(); I != E; ++I)
307 /// collectLineCounts - Collect line counts. This must be used after
308 /// reading .gcno and .gcda files.
309 void GCOVFunction::collectLineCounts(FileInfo &FI) {
310 for (SmallVectorImpl<GCOVBlock *>::iterator I = Blocks.begin(),
311 E = Blocks.end(); I != E; ++I)
312 (*I)->collectLineCounts(FI);
313 FI.addFunctionLine(Filename, LineNumber, this);
316 //===----------------------------------------------------------------------===//
317 // GCOVBlock implementation.
319 /// ~GCOVBlock - Delete GCOVBlock and its content.
320 GCOVBlock::~GCOVBlock() {
326 /// addCount - Add to block counter while storing the edge count. If the
327 /// destination has no outgoing edges, also update that block's count too.
328 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
329 assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
330 DstEdges[DstEdgeNo]->Count = N;
332 if (!DstEdges[DstEdgeNo]->Dst->getNumDstEdges())
333 DstEdges[DstEdgeNo]->Dst->Counter += N;
336 /// sortDstEdges - Sort destination edges by block number, nop if already
337 /// sorted. This is required for printing branch info in the correct order.
338 void GCOVBlock::sortDstEdges() {
339 if (!DstEdgesAreSorted) {
340 SortDstEdgesFunctor SortEdges;
341 std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
345 /// collectLineCounts - Collect line counts. This must be used after
346 /// reading .gcno and .gcda files.
347 void GCOVBlock::collectLineCounts(FileInfo &FI) {
348 for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
349 E = Lines.end(); I != E; ++I)
350 FI.addBlockLine(Parent.getFilename(), *I, this);
353 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
354 void GCOVBlock::dump() const {
355 dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
356 if (!SrcEdges.empty()) {
357 dbgs() << "\tSource Edges : ";
358 for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
359 const GCOVEdge *Edge = *I;
360 dbgs() << Edge->Src->Number << " (" << Edge->Count << "), ";
364 if (!DstEdges.empty()) {
365 dbgs() << "\tDestination Edges : ";
366 for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
367 const GCOVEdge *Edge = *I;
368 dbgs() << Edge->Dst->Number << " (" << Edge->Count << "), ";
372 if (!Lines.empty()) {
373 dbgs() << "\tLines : ";
374 for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
375 E = Lines.end(); I != E; ++I)
376 dbgs() << (*I) << ",";
381 //===----------------------------------------------------------------------===//
382 // FileInfo implementation.
384 // Safe integer division, returns 0 if numerator is 0.
385 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
388 return Numerator/Divisor;
391 // This custom division function mimics gcov's branch ouputs:
392 // - Round to closest whole number
393 // - Only output 0% or 100% if it's exactly that value
394 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
397 if (Numerator == Divisor)
400 uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
408 struct formatBranchInfo {
409 formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
411 Options(Options), Count(Count), Total(Total) {}
413 void print(raw_ostream &OS) const {
415 OS << "never executed";
416 else if (Options.BranchCount)
417 OS << "taken " << Count;
419 OS << "taken " << branchDiv(Count, Total) << "%";
422 const GCOVOptions &Options;
427 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
432 /// print - Print source files with collected line count information.
433 void FileInfo::print(StringRef GCNOFile, StringRef GCDAFile) {
434 for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
435 E = LineInfo.end(); I != E; ++I) {
436 StringRef Filename = I->first();
437 OwningPtr<MemoryBuffer> Buff;
438 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
439 errs() << Filename << ": " << ec.message() << "\n";
442 StringRef AllLines = Buff->getBuffer();
444 std::string CovFilename = Filename.str() + ".gcov";
445 std::string ErrorInfo;
446 raw_fd_ostream OS(CovFilename.c_str(), ErrorInfo);
447 if (!ErrorInfo.empty())
448 errs() << ErrorInfo << "\n";
450 OS << " -: 0:Source:" << Filename << "\n";
451 OS << " -: 0:Graph:" << GCNOFile << "\n";
452 OS << " -: 0:Data:" << GCDAFile << "\n";
453 OS << " -: 0:Runs:" << RunCount << "\n";
454 OS << " -: 0:Programs:" << ProgramCount << "\n";
456 const LineData &Line = I->second;
457 GCOVCoverage FileCoverage(Filename);
458 for (uint32_t LineIndex = 0; !AllLines.empty(); ++LineIndex) {
459 if (Options.BranchInfo) {
460 FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
461 if (FuncsIt != Line.Functions.end())
462 printFunctionSummary(OS, FuncsIt->second);
465 BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
466 if (BlocksIt == Line.Blocks.end()) {
467 // No basic blocks are on this line. Not an executable line of code.
469 std::pair<StringRef, StringRef> P = AllLines.split('\n');
470 OS << format("%5u:", LineIndex+1) << P.first << "\n";
473 const BlockVector &Blocks = BlocksIt->second;
475 // Add up the block counts to form line counts.
476 DenseMap<const GCOVFunction *, bool> LineExecs;
477 uint64_t LineCount = 0;
478 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
480 const GCOVBlock *Block = *I;
481 if (Options.AllBlocks) {
482 // Only take the highest block count for that line.
483 uint64_t BlockCount = Block->getCount();
484 LineCount = LineCount > BlockCount ? LineCount : BlockCount;
486 // Sum up all of the block counts.
487 LineCount += Block->getCount();
490 if (Options.FuncCoverage) {
491 // This is a slightly convoluted way to most accurately gather line
492 // statistics for functions. Basically what is happening is that we
493 // don't want to count a single line with multiple blocks more than
494 // once. However, we also don't simply want to give the total line
495 // count to every function that starts on the line. Thus, what is
496 // happening here are two things:
497 // 1) Ensure that the number of logical lines is only incremented
498 // once per function.
499 // 2) If there are multiple blocks on the same line, ensure that the
500 // number of lines executed is incremented as long as at least
501 // one of the blocks are executed.
502 const GCOVFunction *Function = &Block->getParent();
503 if (FuncCoverages.find(Function) == FuncCoverages.end()) {
504 std::pair<const GCOVFunction *, GCOVCoverage>
505 KeyValue(Function, GCOVCoverage(Function->getName()));
506 FuncCoverages.insert(KeyValue);
508 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
510 if (LineExecs.find(Function) == LineExecs.end()) {
511 if (Block->getCount()) {
512 ++FuncCoverage.LinesExec;
513 LineExecs[Function] = true;
515 LineExecs[Function] = false;
517 ++FuncCoverage.LogicalLines;
518 } else if (!LineExecs[Function] && Block->getCount()) {
519 ++FuncCoverage.LinesExec;
520 LineExecs[Function] = true;
528 OS << format("%9" PRIu64 ":", LineCount);
529 ++FileCoverage.LinesExec;
531 ++FileCoverage.LogicalLines;
533 std::pair<StringRef, StringRef> P = AllLines.split('\n');
534 OS << format("%5u:", LineIndex+1) << P.first << "\n";
537 uint32_t BlockNo = 0;
539 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
541 const GCOVBlock *Block = *I;
543 // Only print block and branch information at the end of the block.
544 if (Block->getLastLine() != LineIndex+1)
546 if (Options.AllBlocks)
547 printBlockInfo(OS, *Block, LineIndex, BlockNo);
548 if (Options.BranchInfo) {
549 size_t NumEdges = Block->getNumDstEdges();
551 printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
552 else if (Options.UncondBranch && NumEdges == 1)
553 printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
558 FileCoverages.push_back(FileCoverage);
561 // FIXME: There is no way to detect calls given current instrumentation.
562 if (Options.FuncCoverage)
567 /// printFunctionSummary - Print function and block summary.
568 void FileInfo::printFunctionSummary(raw_fd_ostream &OS,
569 const FunctionVector &Funcs) const {
570 for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
572 const GCOVFunction *Func = *I;
573 uint64_t EntryCount = Func->getEntryCount();
574 uint32_t BlocksExec = 0;
575 for (GCOVFunction::BlockIterator I = Func->block_begin(),
576 E = Func->block_end(); I != E; ++I) {
577 const GCOVBlock *Block = *I;
578 if (Block->getNumDstEdges() && Block->getCount())
582 OS << "function " << Func->getName() << " called " << EntryCount
583 << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
584 << "% blocks executed "
585 << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
589 /// printBlockInfo - Output counts for each block.
590 void FileInfo::printBlockInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
591 uint32_t LineIndex, uint32_t &BlockNo) const {
592 if (Block.getCount() == 0)
595 OS << format("%9" PRIu64 ":", Block.getCount());
596 OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
599 /// printBranchInfo - Print conditional branch probabilities.
600 void FileInfo::printBranchInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
601 GCOVCoverage &Coverage, uint32_t &EdgeNo) {
602 SmallVector<uint64_t, 16> BranchCounts;
603 uint64_t TotalCounts = 0;
604 for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
606 const GCOVEdge *Edge = *I;
607 BranchCounts.push_back(Edge->Count);
608 TotalCounts += Edge->Count;
609 if (Block.getCount()) ++Coverage.BranchesExec;
610 if (Edge->Count) ++Coverage.BranchesTaken;
613 if (Options.FuncCoverage) {
614 const GCOVFunction *Function = &Block.getParent();
615 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
616 if (Block.getCount()) ++FuncCoverage.BranchesExec;
617 if (Edge->Count) ++FuncCoverage.BranchesTaken;
618 ++FuncCoverage.Branches;
622 for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
623 E = BranchCounts.end(); I != E; ++I) {
624 OS << format("branch %2u ", EdgeNo++)
625 << formatBranchInfo(Options, *I, TotalCounts) << "\n";
629 /// printUncondBranchInfo - Print unconditional branch probabilities.
630 void FileInfo::printUncondBranchInfo(raw_fd_ostream &OS, uint32_t &EdgeNo,
631 uint64_t Count) const {
632 OS << format("unconditional %2u ", EdgeNo++)
633 << formatBranchInfo(Options, Count, Count) << "\n";
636 // printCoverage - Print generic coverage info used by both printFuncCoverage
637 // and printFileCoverage.
638 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
639 outs() << format("Lines executed:%.2f%% of %u\n",
640 double(Coverage.LinesExec)*100/Coverage.LogicalLines,
641 Coverage.LogicalLines);
642 if (Options.BranchInfo) {
643 if (Coverage.Branches) {
644 outs() << format("Branches executed:%.2f%% of %u\n",
645 double(Coverage.BranchesExec)*100/Coverage.Branches,
647 outs() << format("Taken at least once:%.2f%% of %u\n",
648 double(Coverage.BranchesTaken)*100/Coverage.Branches,
651 outs() << "No branches\n";
653 outs() << "No calls\n"; // to be consistent with gcov
657 // printFuncCoverage - Print per-function coverage info.
658 void FileInfo::printFuncCoverage() const {
659 for (MapVector<const GCOVFunction *, GCOVCoverage>::const_iterator I =
660 FuncCoverages.begin(), E = FuncCoverages.end(); I != E; ++I) {
661 const GCOVCoverage &Coverage = I->second;
662 outs() << "Function '" << Coverage.Name << "'\n";
663 printCoverage(Coverage);
668 // printFileCoverage - Print per-file coverage info.
669 void FileInfo::printFileCoverage() const {
670 for (SmallVectorImpl<GCOVCoverage>::const_iterator I =
671 FileCoverages.begin(), E = FileCoverages.end(); I != E; ++I) {
672 const GCOVCoverage &Coverage = *I;
673 outs() << "File '" << Coverage.Name << "'\n";
674 printCoverage(Coverage);
675 outs() << Coverage.Name << ":creating '" << Coverage.Name