LLVM API Documentation

GCOV.cpp
Go to the documentation of this file.
00001 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // GCOV implements the interface to read and write coverage files that use
00011 // 'gcov' format.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Support/GCOV.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/Support/Debug.h"
00018 #include "llvm/Support/FileSystem.h"
00019 #include "llvm/Support/Format.h"
00020 #include "llvm/Support/MemoryObject.h"
00021 #include "llvm/Support/Path.h"
00022 #include <algorithm>
00023 #include <system_error>
00024 using namespace llvm;
00025 
00026 //===----------------------------------------------------------------------===//
00027 // GCOVFile implementation.
00028 
00029 /// readGCNO - Read GCNO buffer.
00030 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
00031   if (!Buffer.readGCNOFormat()) return false;
00032   if (!Buffer.readGCOVVersion(Version)) return false;
00033 
00034   if (!Buffer.readInt(Checksum)) return false;
00035   while (true) {
00036     if (!Buffer.readFunctionTag()) break;
00037     auto GFun = make_unique<GCOVFunction>(*this);
00038     if (!GFun->readGCNO(Buffer, Version))
00039       return false;
00040     Functions.push_back(std::move(GFun));
00041   }
00042 
00043   GCNOInitialized = true;
00044   return true;
00045 }
00046 
00047 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
00048 /// called after readGCNO().
00049 bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
00050   assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
00051   if (!Buffer.readGCDAFormat()) return false;
00052   GCOV::GCOVVersion GCDAVersion;
00053   if (!Buffer.readGCOVVersion(GCDAVersion)) return false;
00054   if (Version != GCDAVersion) {
00055     errs() << "GCOV versions do not match.\n";
00056     return false;
00057   }
00058 
00059   uint32_t GCDAChecksum;
00060   if (!Buffer.readInt(GCDAChecksum)) return false;
00061   if (Checksum != GCDAChecksum) {
00062     errs() << "File checksums do not match: " << Checksum << " != "
00063            << GCDAChecksum << ".\n";
00064     return false;
00065   }
00066   for (size_t i = 0, e = Functions.size(); i < e; ++i) {
00067     if (!Buffer.readFunctionTag()) {
00068       errs() << "Unexpected number of functions.\n";
00069       return false;
00070     }
00071     if (!Functions[i]->readGCDA(Buffer, Version))
00072       return false;
00073   }
00074   if (Buffer.readObjectTag()) {
00075     uint32_t Length;
00076     uint32_t Dummy;
00077     if (!Buffer.readInt(Length)) return false;
00078     if (!Buffer.readInt(Dummy)) return false; // checksum
00079     if (!Buffer.readInt(Dummy)) return false; // num
00080     if (!Buffer.readInt(RunCount)) return false;
00081     Buffer.advanceCursor(Length-3);
00082   }
00083   while (Buffer.readProgramTag()) {
00084     uint32_t Length;
00085     if (!Buffer.readInt(Length)) return false;
00086     Buffer.advanceCursor(Length);
00087     ++ProgramCount;
00088   }
00089 
00090   return true;
00091 }
00092 
00093 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
00094 void GCOVFile::dump() const {
00095   for (const auto &FPtr : Functions)
00096     FPtr->dump();
00097 }
00098 
00099 /// collectLineCounts - Collect line counts. This must be used after
00100 /// reading .gcno and .gcda files.
00101 void GCOVFile::collectLineCounts(FileInfo &FI) {
00102   for (const auto &FPtr : Functions)
00103     FPtr->collectLineCounts(FI);
00104   FI.setRunCount(RunCount);
00105   FI.setProgramCount(ProgramCount);
00106 }
00107 
00108 //===----------------------------------------------------------------------===//
00109 // GCOVFunction implementation.
00110 
00111 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
00112 /// occurs.
00113 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
00114   uint32_t Dummy;
00115   if (!Buff.readInt(Dummy)) return false; // Function header length
00116   if (!Buff.readInt(Ident)) return false;
00117   if (!Buff.readInt(Checksum)) return false;
00118   if (Version != GCOV::V402) {
00119     uint32_t CfgChecksum;
00120     if (!Buff.readInt(CfgChecksum)) return false;
00121     if (Parent.getChecksum() != CfgChecksum) {
00122       errs() << "File checksums do not match: " << Parent.getChecksum()
00123              << " != " << CfgChecksum << " in (" << Name << ").\n";
00124       return false;
00125     }
00126   }
00127   if (!Buff.readString(Name)) return false;
00128   if (!Buff.readString(Filename)) return false;
00129   if (!Buff.readInt(LineNumber)) return false;
00130 
00131   // read blocks.
00132   if (!Buff.readBlockTag()) {
00133     errs() << "Block tag not found.\n";
00134     return false;
00135   }
00136   uint32_t BlockCount;
00137   if (!Buff.readInt(BlockCount)) return false;
00138   for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
00139     if (!Buff.readInt(Dummy)) return false; // Block flags;
00140     Blocks.push_back(make_unique<GCOVBlock>(*this, i));
00141   }
00142 
00143   // read edges.
00144   while (Buff.readEdgeTag()) {
00145     uint32_t EdgeCount;
00146     if (!Buff.readInt(EdgeCount)) return false;
00147     EdgeCount = (EdgeCount - 1) / 2;
00148     uint32_t BlockNo;
00149     if (!Buff.readInt(BlockNo)) return false;
00150     if (BlockNo >= BlockCount) {
00151       errs() << "Unexpected block number: " << BlockNo << " (in " << Name
00152              << ").\n";
00153       return false;
00154     }
00155     for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
00156       uint32_t Dst;
00157       if (!Buff.readInt(Dst)) return false;
00158       Edges.push_back(make_unique<GCOVEdge>(*Blocks[BlockNo], *Blocks[Dst]));
00159       GCOVEdge *Edge = Edges.back().get();
00160       Blocks[BlockNo]->addDstEdge(Edge);
00161       Blocks[Dst]->addSrcEdge(Edge);
00162       if (!Buff.readInt(Dummy)) return false; // Edge flag
00163     }
00164   }
00165 
00166   // read line table.
00167   while (Buff.readLineTag()) {
00168     uint32_t LineTableLength;
00169     // Read the length of this line table.
00170     if (!Buff.readInt(LineTableLength)) return false;
00171     uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
00172     uint32_t BlockNo;
00173     // Read the block number this table is associated with.
00174     if (!Buff.readInt(BlockNo)) return false;
00175     if (BlockNo >= BlockCount) {
00176       errs() << "Unexpected block number: " << BlockNo << " (in " << Name
00177              << ").\n";
00178       return false;
00179     }
00180     GCOVBlock &Block = *Blocks[BlockNo];
00181     // Read the word that pads the beginning of the line table. This may be a
00182     // flag of some sort, but seems to always be zero.
00183     if (!Buff.readInt(Dummy)) return false;
00184 
00185     // Line information starts here and continues up until the last word.
00186     if (Buff.getCursor() != (EndPos - sizeof(uint32_t))) {
00187       StringRef F;
00188       // Read the source file name.
00189       if (!Buff.readString(F)) return false;
00190       if (Filename != F) {
00191         errs() << "Multiple sources for a single basic block: " << Filename
00192                << " != " << F << " (in " << Name << ").\n";
00193         return false;
00194       }
00195       // Read lines up to, but not including, the null terminator.
00196       while (Buff.getCursor() < (EndPos - 2 * sizeof(uint32_t))) {
00197         uint32_t Line;
00198         if (!Buff.readInt(Line)) return false;
00199         // Line 0 means this instruction was injected by the compiler. Skip it.
00200         if (!Line) continue;
00201         Block.addLine(Line);
00202       }
00203       // Read the null terminator.
00204       if (!Buff.readInt(Dummy)) return false;
00205     }
00206     // The last word is either a flag or padding, it isn't clear which. Skip
00207     // over it.
00208     if (!Buff.readInt(Dummy)) return false;
00209   }
00210   return true;
00211 }
00212 
00213 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
00214 /// occurs.
00215 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
00216   uint32_t Dummy;
00217   if (!Buff.readInt(Dummy)) return false; // Function header length
00218 
00219   uint32_t GCDAIdent;
00220   if (!Buff.readInt(GCDAIdent)) return false;
00221   if (Ident != GCDAIdent) {
00222     errs() << "Function identifiers do not match: " << Ident << " != "
00223            << GCDAIdent << " (in " << Name << ").\n";
00224     return false;
00225   }
00226 
00227   uint32_t GCDAChecksum;
00228   if (!Buff.readInt(GCDAChecksum)) return false;
00229   if (Checksum != GCDAChecksum) {
00230     errs() << "Function checksums do not match: " << Checksum << " != "
00231            << GCDAChecksum << " (in " << Name << ").\n";
00232     return false;
00233   }
00234 
00235   uint32_t CfgChecksum;
00236   if (Version != GCOV::V402) {
00237     if (!Buff.readInt(CfgChecksum)) return false;
00238     if (Parent.getChecksum() != CfgChecksum) {
00239       errs() << "File checksums do not match: " << Parent.getChecksum()
00240              << " != " << CfgChecksum << " (in " << Name << ").\n";
00241       return false;
00242     }
00243   }
00244 
00245   StringRef GCDAName;
00246   if (!Buff.readString(GCDAName)) return false;
00247   if (Name != GCDAName) {
00248     errs() << "Function names do not match: " << Name << " != " << GCDAName
00249            << ".\n";
00250     return false;
00251   }
00252 
00253   if (!Buff.readArcTag()) {
00254     errs() << "Arc tag not found (in " << Name << ").\n";
00255     return false;
00256   }
00257 
00258   uint32_t Count;
00259   if (!Buff.readInt(Count)) return false;
00260   Count /= 2;
00261 
00262   // This for loop adds the counts for each block. A second nested loop is
00263   // required to combine the edge counts that are contained in the GCDA file.
00264   for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
00265     // The last block is always reserved for exit block
00266     if (BlockNo >= Blocks.size()-1) {
00267       errs() << "Unexpected number of edges (in " << Name << ").\n";
00268       return false;
00269     }
00270     GCOVBlock &Block = *Blocks[BlockNo];
00271     for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
00272            ++EdgeNo) {
00273       if (Count == 0) {
00274         errs() << "Unexpected number of edges (in " << Name << ").\n";
00275         return false;
00276       }
00277       uint64_t ArcCount;
00278       if (!Buff.readInt64(ArcCount)) return false;
00279       Block.addCount(EdgeNo, ArcCount);
00280       --Count;
00281     }
00282     Block.sortDstEdges();
00283   }
00284   return true;
00285 }
00286 
00287 /// getEntryCount - Get the number of times the function was called by
00288 /// retrieving the entry block's count.
00289 uint64_t GCOVFunction::getEntryCount() const {
00290   return Blocks.front()->getCount();
00291 }
00292 
00293 /// getExitCount - Get the number of times the function returned by retrieving
00294 /// the exit block's count.
00295 uint64_t GCOVFunction::getExitCount() const {
00296   return Blocks.back()->getCount();
00297 }
00298 
00299 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
00300 void GCOVFunction::dump() const {
00301   dbgs() <<  "===== " << Name << " @ " << Filename << ":" << LineNumber << "\n";
00302   for (const auto &Block : Blocks)
00303     Block->dump();
00304 }
00305 
00306 /// collectLineCounts - Collect line counts. This must be used after
00307 /// reading .gcno and .gcda files.
00308 void GCOVFunction::collectLineCounts(FileInfo &FI) {
00309   // If the line number is zero, this is a function that doesn't actually appear
00310   // in the source file, so there isn't anything we can do with it.
00311   if (LineNumber == 0)
00312     return;
00313 
00314   for (const auto &Block : Blocks)
00315     Block->collectLineCounts(FI);
00316   FI.addFunctionLine(Filename, LineNumber, this);
00317 }
00318 
00319 //===----------------------------------------------------------------------===//
00320 // GCOVBlock implementation.
00321 
00322 /// ~GCOVBlock - Delete GCOVBlock and its content.
00323 GCOVBlock::~GCOVBlock() {
00324   SrcEdges.clear();
00325   DstEdges.clear();
00326   Lines.clear();
00327 }
00328 
00329 /// addCount - Add to block counter while storing the edge count. If the
00330 /// destination has no outgoing edges, also update that block's count too.
00331 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
00332   assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
00333   DstEdges[DstEdgeNo]->Count = N;
00334   Counter += N;
00335   if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
00336     DstEdges[DstEdgeNo]->Dst.Counter += N;
00337 }
00338 
00339 /// sortDstEdges - Sort destination edges by block number, nop if already
00340 /// sorted. This is required for printing branch info in the correct order.
00341 void GCOVBlock::sortDstEdges() {
00342   if (!DstEdgesAreSorted) {
00343     SortDstEdgesFunctor SortEdges;
00344     std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
00345   }
00346 }
00347 
00348 /// collectLineCounts - Collect line counts. This must be used after
00349 /// reading .gcno and .gcda files.
00350 void GCOVBlock::collectLineCounts(FileInfo &FI) {
00351   for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
00352          E = Lines.end(); I != E; ++I)
00353     FI.addBlockLine(Parent.getFilename(), *I, this);
00354 }
00355 
00356 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
00357 void GCOVBlock::dump() const {
00358   dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
00359   if (!SrcEdges.empty()) {
00360     dbgs() << "\tSource Edges : ";
00361     for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
00362       const GCOVEdge *Edge = *I;
00363       dbgs() << Edge->Src.Number << " (" << Edge->Count << "), ";
00364     }
00365     dbgs() << "\n";
00366   }
00367   if (!DstEdges.empty()) {
00368     dbgs() << "\tDestination Edges : ";
00369     for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
00370       const GCOVEdge *Edge = *I;
00371       dbgs() << Edge->Dst.Number << " (" << Edge->Count << "), ";
00372     }
00373     dbgs() << "\n";
00374   }
00375   if (!Lines.empty()) {
00376     dbgs() << "\tLines : ";
00377     for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
00378            E = Lines.end(); I != E; ++I)
00379       dbgs() << (*I) << ",";
00380     dbgs() << "\n";
00381   }
00382 }
00383 
00384 //===----------------------------------------------------------------------===//
00385 // FileInfo implementation.
00386 
00387 // Safe integer division, returns 0 if numerator is 0.
00388 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
00389   if (!Numerator)
00390     return 0;
00391   return Numerator/Divisor;
00392 }
00393 
00394 // This custom division function mimics gcov's branch ouputs:
00395 //   - Round to closest whole number
00396 //   - Only output 0% or 100% if it's exactly that value
00397 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
00398   if (!Numerator)
00399     return 0;
00400   if (Numerator == Divisor)
00401     return 100;
00402 
00403   uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
00404   if (Res == 0)
00405     return 1;
00406   if (Res == 100)
00407     return 99;
00408   return Res;
00409 }
00410 
00411 struct formatBranchInfo {
00412   formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
00413                    uint64_t Total) :
00414     Options(Options), Count(Count), Total(Total) {}
00415 
00416   void print(raw_ostream &OS) const {
00417     if (!Total)
00418       OS << "never executed";
00419     else if (Options.BranchCount)
00420       OS << "taken " << Count;
00421     else
00422       OS << "taken " << branchDiv(Count, Total) << "%";
00423   }
00424 
00425   const GCOVOptions &Options;
00426   uint64_t Count;
00427   uint64_t Total;
00428 };
00429 
00430 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
00431   FBI.print(OS);
00432   return OS;
00433 }
00434 
00435 namespace {
00436 class LineConsumer {
00437   std::unique_ptr<MemoryBuffer> Buffer;
00438   StringRef Remaining;
00439 public:
00440   LineConsumer(StringRef Filename) {
00441     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
00442         MemoryBuffer::getFileOrSTDIN(Filename);
00443     if (std::error_code EC = BufferOrErr.getError()) {
00444       errs() << Filename << ": " << EC.message() << "\n";
00445       Remaining = "";
00446     } else {
00447       Buffer = std::move(BufferOrErr.get());
00448       Remaining = Buffer->getBuffer();
00449     }
00450   }
00451   bool empty() { return Remaining.empty(); }
00452   void printNext(raw_ostream &OS, uint32_t LineNum) {
00453     StringRef Line;
00454     if (empty())
00455       Line = "/*EOF*/";
00456     else
00457       std::tie(Line, Remaining) = Remaining.split("\n");
00458     OS << format("%5u:", LineNum) << Line << "\n";
00459   }
00460 };
00461 }
00462 
00463 /// Convert a path to a gcov filename. If PreservePaths is true, this
00464 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
00465 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
00466   if (!PreservePaths)
00467     return sys::path::filename(Filename).str();
00468 
00469   // This behaviour is defined by gcov in terms of text replacements, so it's
00470   // not likely to do anything useful on filesystems with different textual
00471   // conventions.
00472   llvm::SmallString<256> Result("");
00473   StringRef::iterator I, S, E;
00474   for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
00475     if (*I != '/')
00476       continue;
00477 
00478     if (I - S == 1 && *S == '.') {
00479       // ".", the current directory, is skipped.
00480     } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
00481       // "..", the parent directory, is replaced with "^".
00482       Result.append("^#");
00483     } else {
00484       if (S < I)
00485         // Leave other components intact,
00486         Result.append(S, I);
00487       // And separate with "#".
00488       Result.push_back('#');
00489     }
00490     S = I + 1;
00491   }
00492 
00493   if (S < I)
00494     Result.append(S, I);
00495   return Result.str();
00496 }
00497 
00498 std::string FileInfo::getCoveragePath(StringRef Filename,
00499                                       StringRef MainFilename) {
00500   if (Options.NoOutput)
00501     // This is probably a bug in gcov, but when -n is specified, paths aren't
00502     // mangled at all, and the -l and -p options are ignored. Here, we do the
00503     // same.
00504     return Filename;
00505 
00506   std::string CoveragePath;
00507   if (Options.LongFileNames && !Filename.equals(MainFilename))
00508     CoveragePath =
00509         mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
00510   CoveragePath +=
00511       mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
00512   return CoveragePath;
00513 }
00514 
00515 std::unique_ptr<raw_ostream>
00516 FileInfo::openCoveragePath(StringRef CoveragePath) {
00517   if (Options.NoOutput)
00518     return llvm::make_unique<raw_null_ostream>();
00519 
00520   std::error_code EC;
00521   auto OS = llvm::make_unique<raw_fd_ostream>(CoveragePath.str(), EC,
00522                                               sys::fs::F_Text);
00523   if (EC) {
00524     errs() << EC.message() << "\n";
00525     return llvm::make_unique<raw_null_ostream>();
00526   }
00527   return std::move(OS);
00528 }
00529 
00530 /// print -  Print source files with collected line count information.
00531 void FileInfo::print(StringRef MainFilename, StringRef GCNOFile,
00532                      StringRef GCDAFile) {
00533   for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
00534          E = LineInfo.end(); I != E; ++I) {
00535     StringRef Filename = I->first();
00536     auto AllLines = LineConsumer(Filename);
00537 
00538     std::string CoveragePath = getCoveragePath(Filename, MainFilename);
00539     std::unique_ptr<raw_ostream> S = openCoveragePath(CoveragePath);
00540     raw_ostream &OS = *S;
00541 
00542     OS << "        -:    0:Source:" << Filename << "\n";
00543     OS << "        -:    0:Graph:" << GCNOFile << "\n";
00544     OS << "        -:    0:Data:" << GCDAFile << "\n";
00545     OS << "        -:    0:Runs:" << RunCount << "\n";
00546     OS << "        -:    0:Programs:" << ProgramCount << "\n";
00547 
00548     const LineData &Line = I->second;
00549     GCOVCoverage FileCoverage(Filename);
00550     for (uint32_t LineIndex = 0;
00551          LineIndex < Line.LastLine || !AllLines.empty(); ++LineIndex) {
00552       if (Options.BranchInfo) {
00553         FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
00554         if (FuncsIt != Line.Functions.end())
00555           printFunctionSummary(OS, FuncsIt->second);
00556       }
00557 
00558       BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
00559       if (BlocksIt == Line.Blocks.end()) {
00560         // No basic blocks are on this line. Not an executable line of code.
00561         OS << "        -:";
00562         AllLines.printNext(OS, LineIndex + 1);
00563       } else {
00564         const BlockVector &Blocks = BlocksIt->second;
00565 
00566         // Add up the block counts to form line counts.
00567         DenseMap<const GCOVFunction *, bool> LineExecs;
00568         uint64_t LineCount = 0;
00569         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
00570                I != E; ++I) {
00571           const GCOVBlock *Block = *I;
00572           if (Options.AllBlocks) {
00573             // Only take the highest block count for that line.
00574             uint64_t BlockCount = Block->getCount();
00575             LineCount = LineCount > BlockCount ? LineCount : BlockCount;
00576           } else {
00577             // Sum up all of the block counts.
00578             LineCount += Block->getCount();
00579           }
00580 
00581           if (Options.FuncCoverage) {
00582             // This is a slightly convoluted way to most accurately gather line
00583             // statistics for functions. Basically what is happening is that we
00584             // don't want to count a single line with multiple blocks more than
00585             // once. However, we also don't simply want to give the total line
00586             // count to every function that starts on the line. Thus, what is
00587             // happening here are two things:
00588             // 1) Ensure that the number of logical lines is only incremented
00589             //    once per function.
00590             // 2) If there are multiple blocks on the same line, ensure that the
00591             //    number of lines executed is incremented as long as at least
00592             //    one of the blocks are executed.
00593             const GCOVFunction *Function = &Block->getParent();
00594             if (FuncCoverages.find(Function) == FuncCoverages.end()) {
00595               std::pair<const GCOVFunction *, GCOVCoverage>
00596                 KeyValue(Function, GCOVCoverage(Function->getName()));
00597               FuncCoverages.insert(KeyValue);
00598             }
00599             GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
00600 
00601             if (LineExecs.find(Function) == LineExecs.end()) {
00602               if (Block->getCount()) {
00603                 ++FuncCoverage.LinesExec;
00604                 LineExecs[Function] = true;
00605               } else {
00606                 LineExecs[Function] = false;
00607               }
00608               ++FuncCoverage.LogicalLines;
00609             } else if (!LineExecs[Function] && Block->getCount()) {
00610               ++FuncCoverage.LinesExec;
00611               LineExecs[Function] = true;
00612             }
00613           }
00614         }
00615 
00616         if (LineCount == 0)
00617           OS << "    #####:";
00618         else {
00619           OS << format("%9" PRIu64 ":", LineCount);
00620           ++FileCoverage.LinesExec;
00621         }
00622         ++FileCoverage.LogicalLines;
00623 
00624         AllLines.printNext(OS, LineIndex + 1);
00625 
00626         uint32_t BlockNo = 0;
00627         uint32_t EdgeNo = 0;
00628         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
00629                I != E; ++I) {
00630           const GCOVBlock *Block = *I;
00631 
00632           // Only print block and branch information at the end of the block.
00633           if (Block->getLastLine() != LineIndex+1)
00634             continue;
00635           if (Options.AllBlocks)
00636             printBlockInfo(OS, *Block, LineIndex, BlockNo);
00637           if (Options.BranchInfo) {
00638             size_t NumEdges = Block->getNumDstEdges();
00639             if (NumEdges > 1)
00640               printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
00641             else if (Options.UncondBranch && NumEdges == 1)
00642               printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
00643           }
00644         }
00645       }
00646     }
00647     FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
00648   }
00649 
00650   // FIXME: There is no way to detect calls given current instrumentation.
00651   if (Options.FuncCoverage)
00652     printFuncCoverage();
00653   printFileCoverage();
00654   return;
00655 }
00656 
00657 /// printFunctionSummary - Print function and block summary.
00658 void FileInfo::printFunctionSummary(raw_ostream &OS,
00659                                     const FunctionVector &Funcs) const {
00660   for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
00661          I != E; ++I) {
00662     const GCOVFunction *Func = *I;
00663     uint64_t EntryCount = Func->getEntryCount();
00664     uint32_t BlocksExec = 0;
00665     for (GCOVFunction::BlockIterator I = Func->block_begin(),
00666            E = Func->block_end(); I != E; ++I) {
00667       const GCOVBlock &Block = **I;
00668       if (Block.getNumDstEdges() && Block.getCount())
00669           ++BlocksExec;
00670     }
00671 
00672     OS << "function " << Func->getName() << " called " << EntryCount
00673        << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
00674        << "% blocks executed "
00675        << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
00676   }
00677 }
00678 
00679 /// printBlockInfo - Output counts for each block.
00680 void FileInfo::printBlockInfo(raw_ostream &OS, const GCOVBlock &Block,
00681                               uint32_t LineIndex, uint32_t &BlockNo) const {
00682   if (Block.getCount() == 0)
00683     OS << "    $$$$$:";
00684   else
00685     OS << format("%9" PRIu64 ":", Block.getCount());
00686   OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
00687 }
00688 
00689 /// printBranchInfo - Print conditional branch probabilities.
00690 void FileInfo::printBranchInfo(raw_ostream &OS, const GCOVBlock &Block,
00691                                GCOVCoverage &Coverage, uint32_t &EdgeNo) {
00692   SmallVector<uint64_t, 16> BranchCounts;
00693   uint64_t TotalCounts = 0;
00694   for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
00695          I != E; ++I) {
00696     const GCOVEdge *Edge = *I;
00697     BranchCounts.push_back(Edge->Count);
00698     TotalCounts += Edge->Count;
00699     if (Block.getCount()) ++Coverage.BranchesExec;
00700     if (Edge->Count) ++Coverage.BranchesTaken;
00701     ++Coverage.Branches;
00702 
00703     if (Options.FuncCoverage) {
00704       const GCOVFunction *Function = &Block.getParent();
00705       GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
00706       if (Block.getCount()) ++FuncCoverage.BranchesExec;
00707       if (Edge->Count) ++FuncCoverage.BranchesTaken;
00708       ++FuncCoverage.Branches;
00709     }
00710   }
00711 
00712   for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
00713          E = BranchCounts.end(); I != E; ++I) {
00714     OS << format("branch %2u ", EdgeNo++)
00715        << formatBranchInfo(Options, *I, TotalCounts) << "\n";
00716   }
00717 }
00718 
00719 /// printUncondBranchInfo - Print unconditional branch probabilities.
00720 void FileInfo::printUncondBranchInfo(raw_ostream &OS, uint32_t &EdgeNo,
00721                                      uint64_t Count) const {
00722   OS << format("unconditional %2u ", EdgeNo++)
00723      << formatBranchInfo(Options, Count, Count) << "\n";
00724 }
00725 
00726 // printCoverage - Print generic coverage info used by both printFuncCoverage
00727 // and printFileCoverage.
00728 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
00729   outs() << format("Lines executed:%.2f%% of %u\n",
00730                    double(Coverage.LinesExec)*100/Coverage.LogicalLines,
00731                    Coverage.LogicalLines);
00732   if (Options.BranchInfo) {
00733     if (Coverage.Branches) {
00734       outs() << format("Branches executed:%.2f%% of %u\n",
00735                        double(Coverage.BranchesExec)*100/Coverage.Branches,
00736                        Coverage.Branches);
00737       outs() << format("Taken at least once:%.2f%% of %u\n",
00738                        double(Coverage.BranchesTaken)*100/Coverage.Branches,
00739                        Coverage.Branches);
00740     } else {
00741       outs() << "No branches\n";
00742     }
00743     outs() << "No calls\n"; // to be consistent with gcov
00744   }
00745 }
00746 
00747 // printFuncCoverage - Print per-function coverage info.
00748 void FileInfo::printFuncCoverage() const {
00749   for (FuncCoverageMap::const_iterator I = FuncCoverages.begin(),
00750                                        E = FuncCoverages.end(); I != E; ++I) {
00751     const GCOVCoverage &Coverage = I->second;
00752     outs() << "Function '" << Coverage.Name << "'\n";
00753     printCoverage(Coverage);
00754     outs() << "\n";
00755   }
00756 }
00757 
00758 // printFileCoverage - Print per-file coverage info.
00759 void FileInfo::printFileCoverage() const {
00760   for (FileCoverageList::const_iterator I = FileCoverages.begin(),
00761                                         E = FileCoverages.end(); I != E; ++I) {
00762     const std::string &Filename = I->first;
00763     const GCOVCoverage &Coverage = I->second;
00764     outs() << "File '" << Coverage.Name << "'\n";
00765     printCoverage(Coverage);
00766     if (!Options.NoOutput)
00767       outs() << Coverage.Name << ":creating '" << Filename << "'\n";
00768     outs() << "\n";
00769   }
00770 }