GCOV.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // GCOV implements the interface to read and write coverage files that use
  10. // 'gcov' format.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/GCOV.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/Config/llvm-config.h"
  16. #include "llvm/Demangle/Demangle.h"
  17. #include "llvm/Support/Debug.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/Format.h"
  20. #include "llvm/Support/MD5.h"
  21. #include "llvm/Support/Path.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include <algorithm>
  24. #include <system_error>
  25. #include <unordered_map>
  26. using namespace llvm;
  27. enum : uint32_t {
  28. GCOV_ARC_ON_TREE = 1 << 0,
  29. GCOV_ARC_FALLTHROUGH = 1 << 2,
  30. GCOV_TAG_FUNCTION = 0x01000000,
  31. GCOV_TAG_BLOCKS = 0x01410000,
  32. GCOV_TAG_ARCS = 0x01430000,
  33. GCOV_TAG_LINES = 0x01450000,
  34. GCOV_TAG_COUNTER_ARCS = 0x01a10000,
  35. // GCOV_TAG_OBJECT_SUMMARY superseded GCOV_TAG_PROGRAM_SUMMARY in GCC 9.
  36. GCOV_TAG_OBJECT_SUMMARY = 0xa1000000,
  37. GCOV_TAG_PROGRAM_SUMMARY = 0xa3000000,
  38. };
  39. namespace {
  40. struct Summary {
  41. Summary(StringRef Name) : Name(Name) {}
  42. StringRef Name;
  43. uint64_t lines = 0;
  44. uint64_t linesExec = 0;
  45. uint64_t branches = 0;
  46. uint64_t branchesExec = 0;
  47. uint64_t branchesTaken = 0;
  48. };
  49. struct LineInfo {
  50. SmallVector<const GCOVBlock *, 1> blocks;
  51. uint64_t count = 0;
  52. bool exists = false;
  53. };
  54. struct SourceInfo {
  55. StringRef filename;
  56. SmallString<0> displayName;
  57. std::vector<std::vector<const GCOVFunction *>> startLineToFunctions;
  58. std::vector<LineInfo> lines;
  59. bool ignored = false;
  60. SourceInfo(StringRef filename) : filename(filename) {}
  61. };
  62. class Context {
  63. public:
  64. Context(const GCOV::Options &Options) : options(Options) {}
  65. void print(StringRef filename, StringRef gcno, StringRef gcda,
  66. GCOVFile &file);
  67. private:
  68. std::string getCoveragePath(StringRef filename, StringRef mainFilename) const;
  69. void printFunctionDetails(const GCOVFunction &f, raw_ostream &os) const;
  70. void printBranchInfo(const GCOVBlock &Block, uint32_t &edgeIdx,
  71. raw_ostream &OS) const;
  72. void printSummary(const Summary &summary, raw_ostream &os) const;
  73. void collectFunction(GCOVFunction &f, Summary &summary);
  74. void collectSourceLine(SourceInfo &si, Summary *summary, LineInfo &line,
  75. size_t lineNum) const;
  76. void collectSource(SourceInfo &si, Summary &summary) const;
  77. void annotateSource(SourceInfo &si, const GCOVFile &file, StringRef gcno,
  78. StringRef gcda, raw_ostream &os) const;
  79. void printSourceToIntermediate(const SourceInfo &si, raw_ostream &os) const;
  80. const GCOV::Options &options;
  81. std::vector<SourceInfo> sources;
  82. };
  83. } // namespace
  84. //===----------------------------------------------------------------------===//
  85. // GCOVFile implementation.
  86. /// readGCNO - Read GCNO buffer.
  87. bool GCOVFile::readGCNO(GCOVBuffer &buf) {
  88. if (!buf.readGCNOFormat())
  89. return false;
  90. if (!buf.readGCOVVersion(version))
  91. return false;
  92. checksum = buf.getWord();
  93. if (version >= GCOV::V900 && !buf.readString(cwd))
  94. return false;
  95. if (version >= GCOV::V800)
  96. buf.getWord(); // hasUnexecutedBlocks
  97. uint32_t tag, length;
  98. GCOVFunction *fn = nullptr;
  99. while ((tag = buf.getWord())) {
  100. if (!buf.readInt(length))
  101. return false;
  102. uint32_t pos = buf.cursor.tell();
  103. if (tag == GCOV_TAG_FUNCTION) {
  104. functions.push_back(std::make_unique<GCOVFunction>(*this));
  105. fn = functions.back().get();
  106. fn->ident = buf.getWord();
  107. fn->linenoChecksum = buf.getWord();
  108. if (version >= GCOV::V407)
  109. fn->cfgChecksum = buf.getWord();
  110. buf.readString(fn->Name);
  111. StringRef filename;
  112. if (version < GCOV::V800) {
  113. if (!buf.readString(filename))
  114. return false;
  115. fn->startLine = buf.getWord();
  116. } else {
  117. fn->artificial = buf.getWord();
  118. if (!buf.readString(filename))
  119. return false;
  120. fn->startLine = buf.getWord();
  121. fn->startColumn = buf.getWord();
  122. fn->endLine = buf.getWord();
  123. if (version >= GCOV::V900)
  124. fn->endColumn = buf.getWord();
  125. }
  126. auto r = filenameToIdx.try_emplace(filename, filenameToIdx.size());
  127. if (r.second)
  128. filenames.emplace_back(filename);
  129. fn->srcIdx = r.first->second;
  130. identToFunction[fn->ident] = fn;
  131. } else if (tag == GCOV_TAG_BLOCKS && fn) {
  132. if (version < GCOV::V800) {
  133. for (uint32_t i = 0; i != length; ++i) {
  134. buf.getWord(); // Ignored block flags
  135. fn->blocks.push_back(std::make_unique<GCOVBlock>(i));
  136. }
  137. } else {
  138. uint32_t num = buf.getWord();
  139. for (uint32_t i = 0; i != num; ++i)
  140. fn->blocks.push_back(std::make_unique<GCOVBlock>(i));
  141. }
  142. } else if (tag == GCOV_TAG_ARCS && fn) {
  143. uint32_t srcNo = buf.getWord();
  144. if (srcNo >= fn->blocks.size()) {
  145. errs() << "unexpected block number: " << srcNo << " (in "
  146. << fn->blocks.size() << ")\n";
  147. return false;
  148. }
  149. GCOVBlock *src = fn->blocks[srcNo].get();
  150. const uint32_t e =
  151. version >= GCOV::V1200 ? (length / 4 - 1) / 2 : (length - 1) / 2;
  152. for (uint32_t i = 0; i != e; ++i) {
  153. uint32_t dstNo = buf.getWord(), flags = buf.getWord();
  154. GCOVBlock *dst = fn->blocks[dstNo].get();
  155. auto arc = std::make_unique<GCOVArc>(*src, *dst, flags);
  156. src->addDstEdge(arc.get());
  157. dst->addSrcEdge(arc.get());
  158. if (arc->onTree())
  159. fn->treeArcs.push_back(std::move(arc));
  160. else
  161. fn->arcs.push_back(std::move(arc));
  162. }
  163. } else if (tag == GCOV_TAG_LINES && fn) {
  164. uint32_t srcNo = buf.getWord();
  165. if (srcNo >= fn->blocks.size()) {
  166. errs() << "unexpected block number: " << srcNo << " (in "
  167. << fn->blocks.size() << ")\n";
  168. return false;
  169. }
  170. GCOVBlock &Block = *fn->blocks[srcNo];
  171. for (;;) {
  172. uint32_t line = buf.getWord();
  173. if (line)
  174. Block.addLine(line);
  175. else {
  176. StringRef filename;
  177. buf.readString(filename);
  178. if (filename.empty())
  179. break;
  180. // TODO Unhandled
  181. }
  182. }
  183. }
  184. pos += version >= GCOV::V1200 ? length : 4 * length;
  185. if (pos < buf.cursor.tell())
  186. return false;
  187. buf.de.skip(buf.cursor, pos - buf.cursor.tell());
  188. }
  189. GCNOInitialized = true;
  190. return true;
  191. }
  192. /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
  193. /// called after readGCNO().
  194. bool GCOVFile::readGCDA(GCOVBuffer &buf) {
  195. assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
  196. if (!buf.readGCDAFormat())
  197. return false;
  198. GCOV::GCOVVersion GCDAVersion;
  199. if (!buf.readGCOVVersion(GCDAVersion))
  200. return false;
  201. if (version != GCDAVersion) {
  202. errs() << "GCOV versions do not match.\n";
  203. return false;
  204. }
  205. uint32_t GCDAChecksum;
  206. if (!buf.readInt(GCDAChecksum))
  207. return false;
  208. if (checksum != GCDAChecksum) {
  209. errs() << "file checksums do not match: " << checksum
  210. << " != " << GCDAChecksum << "\n";
  211. return false;
  212. }
  213. uint32_t dummy, tag, length;
  214. uint32_t ident;
  215. GCOVFunction *fn = nullptr;
  216. while ((tag = buf.getWord())) {
  217. if (!buf.readInt(length))
  218. return false;
  219. uint32_t pos = buf.cursor.tell();
  220. if (tag == GCOV_TAG_OBJECT_SUMMARY) {
  221. buf.readInt(runCount);
  222. buf.readInt(dummy);
  223. // clang<11 uses a fake 4.2 format which sets length to 9.
  224. if (length == 9)
  225. buf.readInt(runCount);
  226. } else if (tag == GCOV_TAG_PROGRAM_SUMMARY) {
  227. // clang<11 uses a fake 4.2 format which sets length to 0.
  228. if (length > 0) {
  229. buf.readInt(dummy);
  230. buf.readInt(dummy);
  231. buf.readInt(runCount);
  232. }
  233. ++programCount;
  234. } else if (tag == GCOV_TAG_FUNCTION) {
  235. if (length == 0) // Placeholder
  236. continue;
  237. // As of GCC 10, GCOV_TAG_FUNCTION_LENGTH has never been larger than 3.
  238. // However, clang<11 uses a fake 4.2 format which may set length larger
  239. // than 3.
  240. if (length < 2 || !buf.readInt(ident))
  241. return false;
  242. auto It = identToFunction.find(ident);
  243. uint32_t linenoChecksum, cfgChecksum = 0;
  244. buf.readInt(linenoChecksum);
  245. if (version >= GCOV::V407)
  246. buf.readInt(cfgChecksum);
  247. if (It != identToFunction.end()) {
  248. fn = It->second;
  249. if (linenoChecksum != fn->linenoChecksum ||
  250. cfgChecksum != fn->cfgChecksum) {
  251. errs() << fn->Name
  252. << format(": checksum mismatch, (%u, %u) != (%u, %u)\n",
  253. linenoChecksum, cfgChecksum, fn->linenoChecksum,
  254. fn->cfgChecksum);
  255. return false;
  256. }
  257. }
  258. } else if (tag == GCOV_TAG_COUNTER_ARCS && fn) {
  259. uint32_t expected = 2 * fn->arcs.size();
  260. if (version >= GCOV::V1200)
  261. expected *= 4;
  262. if (length != expected) {
  263. errs() << fn->Name
  264. << format(
  265. ": GCOV_TAG_COUNTER_ARCS mismatch, got %u, expected %u\n",
  266. length, expected);
  267. return false;
  268. }
  269. for (std::unique_ptr<GCOVArc> &arc : fn->arcs) {
  270. if (!buf.readInt64(arc->count))
  271. return false;
  272. arc->src.count += arc->count;
  273. }
  274. if (fn->blocks.size() >= 2) {
  275. GCOVBlock &src = *fn->blocks[0];
  276. GCOVBlock &sink =
  277. version < GCOV::V408 ? *fn->blocks.back() : *fn->blocks[1];
  278. auto arc = std::make_unique<GCOVArc>(sink, src, GCOV_ARC_ON_TREE);
  279. sink.addDstEdge(arc.get());
  280. src.addSrcEdge(arc.get());
  281. fn->treeArcs.push_back(std::move(arc));
  282. for (GCOVBlock &block : fn->blocksRange())
  283. fn->propagateCounts(block, nullptr);
  284. for (size_t i = fn->treeArcs.size() - 1; i; --i)
  285. fn->treeArcs[i - 1]->src.count += fn->treeArcs[i - 1]->count;
  286. }
  287. }
  288. pos += version >= GCOV::V1200 ? length : 4 * length;
  289. if (pos < buf.cursor.tell())
  290. return false;
  291. buf.de.skip(buf.cursor, pos - buf.cursor.tell());
  292. }
  293. return true;
  294. }
  295. void GCOVFile::print(raw_ostream &OS) const {
  296. for (const GCOVFunction &f : *this)
  297. f.print(OS);
  298. }
  299. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  300. /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
  301. LLVM_DUMP_METHOD void GCOVFile::dump() const { print(dbgs()); }
  302. #endif
  303. bool GCOVArc::onTree() const { return flags & GCOV_ARC_ON_TREE; }
  304. //===----------------------------------------------------------------------===//
  305. // GCOVFunction implementation.
  306. StringRef GCOVFunction::getName(bool demangle) const {
  307. if (!demangle)
  308. return Name;
  309. if (demangled.empty()) {
  310. do {
  311. if (Name.startswith("_Z")) {
  312. int status = 0;
  313. // Name is guaranteed to be NUL-terminated.
  314. char *res = itaniumDemangle(Name.data(), nullptr, nullptr, &status);
  315. if (status == 0) {
  316. demangled = res;
  317. free(res);
  318. break;
  319. }
  320. }
  321. demangled = Name;
  322. } while (false);
  323. }
  324. return demangled;
  325. }
  326. StringRef GCOVFunction::getFilename() const { return file.filenames[srcIdx]; }
  327. /// getEntryCount - Get the number of times the function was called by
  328. /// retrieving the entry block's count.
  329. uint64_t GCOVFunction::getEntryCount() const {
  330. return blocks.front()->getCount();
  331. }
  332. GCOVBlock &GCOVFunction::getExitBlock() const {
  333. return file.getVersion() < GCOV::V408 ? *blocks.back() : *blocks[1];
  334. }
  335. // For each basic block, the sum of incoming edge counts equals the sum of
  336. // outgoing edge counts by Kirchoff's circuit law. If the unmeasured arcs form a
  337. // spanning tree, the count for each unmeasured arc (GCOV_ARC_ON_TREE) can be
  338. // uniquely identified.
  339. uint64_t GCOVFunction::propagateCounts(const GCOVBlock &v, GCOVArc *pred) {
  340. // If GCOV_ARC_ON_TREE edges do form a tree, visited is not needed; otherwise
  341. // this prevents infinite recursion.
  342. if (!visited.insert(&v).second)
  343. return 0;
  344. uint64_t excess = 0;
  345. for (GCOVArc *e : v.srcs())
  346. if (e != pred)
  347. excess += e->onTree() ? propagateCounts(e->src, e) : e->count;
  348. for (GCOVArc *e : v.dsts())
  349. if (e != pred)
  350. excess -= e->onTree() ? propagateCounts(e->dst, e) : e->count;
  351. if (int64_t(excess) < 0)
  352. excess = -excess;
  353. if (pred)
  354. pred->count = excess;
  355. return excess;
  356. }
  357. void GCOVFunction::print(raw_ostream &OS) const {
  358. OS << "===== " << Name << " (" << ident << ") @ " << getFilename() << ":"
  359. << startLine << "\n";
  360. for (const auto &Block : blocks)
  361. Block->print(OS);
  362. }
  363. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  364. /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
  365. LLVM_DUMP_METHOD void GCOVFunction::dump() const { print(dbgs()); }
  366. #endif
  367. /// collectLineCounts - Collect line counts. This must be used after
  368. /// reading .gcno and .gcda files.
  369. //===----------------------------------------------------------------------===//
  370. // GCOVBlock implementation.
  371. void GCOVBlock::print(raw_ostream &OS) const {
  372. OS << "Block : " << number << " Counter : " << count << "\n";
  373. if (!pred.empty()) {
  374. OS << "\tSource Edges : ";
  375. for (const GCOVArc *Edge : pred)
  376. OS << Edge->src.number << " (" << Edge->count << "), ";
  377. OS << "\n";
  378. }
  379. if (!succ.empty()) {
  380. OS << "\tDestination Edges : ";
  381. for (const GCOVArc *Edge : succ) {
  382. if (Edge->flags & GCOV_ARC_ON_TREE)
  383. OS << '*';
  384. OS << Edge->dst.number << " (" << Edge->count << "), ";
  385. }
  386. OS << "\n";
  387. }
  388. if (!lines.empty()) {
  389. OS << "\tLines : ";
  390. for (uint32_t N : lines)
  391. OS << (N) << ",";
  392. OS << "\n";
  393. }
  394. }
  395. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  396. /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
  397. LLVM_DUMP_METHOD void GCOVBlock::dump() const { print(dbgs()); }
  398. #endif
  399. uint64_t
  400. GCOVBlock::augmentOneCycle(GCOVBlock *src,
  401. std::vector<std::pair<GCOVBlock *, size_t>> &stack) {
  402. GCOVBlock *u;
  403. size_t i;
  404. stack.clear();
  405. stack.emplace_back(src, 0);
  406. src->incoming = (GCOVArc *)1; // Mark u available for cycle detection
  407. for (;;) {
  408. std::tie(u, i) = stack.back();
  409. if (i == u->succ.size()) {
  410. u->traversable = false;
  411. stack.pop_back();
  412. if (stack.empty())
  413. break;
  414. continue;
  415. }
  416. ++stack.back().second;
  417. GCOVArc *succ = u->succ[i];
  418. // Ignore saturated arcs (cycleCount has been reduced to 0) and visited
  419. // blocks. Ignore self arcs to guard against bad input (.gcno has no
  420. // self arcs).
  421. if (succ->cycleCount == 0 || !succ->dst.traversable || &succ->dst == u)
  422. continue;
  423. if (succ->dst.incoming == nullptr) {
  424. succ->dst.incoming = succ;
  425. stack.emplace_back(&succ->dst, 0);
  426. continue;
  427. }
  428. uint64_t minCount = succ->cycleCount;
  429. for (GCOVBlock *v = u;;) {
  430. minCount = std::min(minCount, v->incoming->cycleCount);
  431. v = &v->incoming->src;
  432. if (v == &succ->dst)
  433. break;
  434. }
  435. succ->cycleCount -= minCount;
  436. for (GCOVBlock *v = u;;) {
  437. v->incoming->cycleCount -= minCount;
  438. v = &v->incoming->src;
  439. if (v == &succ->dst)
  440. break;
  441. }
  442. return minCount;
  443. }
  444. return 0;
  445. }
  446. // Get the total execution count of loops among blocks on the same line.
  447. // Assuming a reducible flow graph, the count is the sum of back edge counts.
  448. // Identifying loops is complex, so we simply find cycles and perform cycle
  449. // cancelling iteratively.
  450. uint64_t GCOVBlock::getCyclesCount(const BlockVector &blocks) {
  451. std::vector<std::pair<GCOVBlock *, size_t>> stack;
  452. uint64_t count = 0, d;
  453. for (;;) {
  454. // Make blocks on the line traversable and try finding a cycle.
  455. for (auto b : blocks) {
  456. const_cast<GCOVBlock *>(b)->traversable = true;
  457. const_cast<GCOVBlock *>(b)->incoming = nullptr;
  458. }
  459. d = 0;
  460. for (auto block : blocks) {
  461. auto *b = const_cast<GCOVBlock *>(block);
  462. if (b->traversable && (d = augmentOneCycle(b, stack)) > 0)
  463. break;
  464. }
  465. if (d == 0)
  466. break;
  467. count += d;
  468. }
  469. // If there is no more loop, all traversable bits should have been cleared.
  470. // This property is needed by subsequent calls.
  471. for (auto b : blocks) {
  472. assert(!b->traversable);
  473. (void)b;
  474. }
  475. return count;
  476. }
  477. //===----------------------------------------------------------------------===//
  478. // FileInfo implementation.
  479. // Format dividend/divisor as a percentage. Return 1 if the result is greater
  480. // than 0% and less than 1%.
  481. static uint32_t formatPercentage(uint64_t dividend, uint64_t divisor) {
  482. if (!dividend || !divisor)
  483. return 0;
  484. dividend *= 100;
  485. return dividend < divisor ? 1 : dividend / divisor;
  486. }
  487. // This custom division function mimics gcov's branch ouputs:
  488. // - Round to closest whole number
  489. // - Only output 0% or 100% if it's exactly that value
  490. static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
  491. if (!Numerator)
  492. return 0;
  493. if (Numerator == Divisor)
  494. return 100;
  495. uint8_t Res = (Numerator * 100 + Divisor / 2) / Divisor;
  496. if (Res == 0)
  497. return 1;
  498. if (Res == 100)
  499. return 99;
  500. return Res;
  501. }
  502. namespace {
  503. struct formatBranchInfo {
  504. formatBranchInfo(const GCOV::Options &Options, uint64_t Count, uint64_t Total)
  505. : Options(Options), Count(Count), Total(Total) {}
  506. void print(raw_ostream &OS) const {
  507. if (!Total)
  508. OS << "never executed";
  509. else if (Options.BranchCount)
  510. OS << "taken " << Count;
  511. else
  512. OS << "taken " << branchDiv(Count, Total) << "%";
  513. }
  514. const GCOV::Options &Options;
  515. uint64_t Count;
  516. uint64_t Total;
  517. };
  518. static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
  519. FBI.print(OS);
  520. return OS;
  521. }
  522. class LineConsumer {
  523. std::unique_ptr<MemoryBuffer> Buffer;
  524. StringRef Remaining;
  525. public:
  526. LineConsumer() = default;
  527. LineConsumer(StringRef Filename) {
  528. // Open source files without requiring a NUL terminator. The concurrent
  529. // modification may nullify the NUL terminator condition.
  530. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  531. MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/false,
  532. /*RequiresNullTerminator=*/false);
  533. if (std::error_code EC = BufferOrErr.getError()) {
  534. errs() << Filename << ": " << EC.message() << "\n";
  535. Remaining = "";
  536. } else {
  537. Buffer = std::move(BufferOrErr.get());
  538. Remaining = Buffer->getBuffer();
  539. }
  540. }
  541. bool empty() { return Remaining.empty(); }
  542. void printNext(raw_ostream &OS, uint32_t LineNum) {
  543. StringRef Line;
  544. if (empty())
  545. Line = "/*EOF*/";
  546. else
  547. std::tie(Line, Remaining) = Remaining.split("\n");
  548. OS << format("%5u:", LineNum) << Line << "\n";
  549. }
  550. };
  551. } // end anonymous namespace
  552. /// Convert a path to a gcov filename. If PreservePaths is true, this
  553. /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
  554. static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
  555. if (!PreservePaths)
  556. return sys::path::filename(Filename).str();
  557. // This behaviour is defined by gcov in terms of text replacements, so it's
  558. // not likely to do anything useful on filesystems with different textual
  559. // conventions.
  560. llvm::SmallString<256> Result("");
  561. StringRef::iterator I, S, E;
  562. for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
  563. if (*I != '/')
  564. continue;
  565. if (I - S == 1 && *S == '.') {
  566. // ".", the current directory, is skipped.
  567. } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
  568. // "..", the parent directory, is replaced with "^".
  569. Result.append("^#");
  570. } else {
  571. if (S < I)
  572. // Leave other components intact,
  573. Result.append(S, I);
  574. // And separate with "#".
  575. Result.push_back('#');
  576. }
  577. S = I + 1;
  578. }
  579. if (S < I)
  580. Result.append(S, I);
  581. return std::string(Result.str());
  582. }
  583. std::string Context::getCoveragePath(StringRef filename,
  584. StringRef mainFilename) const {
  585. if (options.NoOutput)
  586. // This is probably a bug in gcov, but when -n is specified, paths aren't
  587. // mangled at all, and the -l and -p options are ignored. Here, we do the
  588. // same.
  589. return std::string(filename);
  590. std::string CoveragePath;
  591. if (options.LongFileNames && !filename.equals(mainFilename))
  592. CoveragePath =
  593. mangleCoveragePath(mainFilename, options.PreservePaths) + "##";
  594. CoveragePath += mangleCoveragePath(filename, options.PreservePaths);
  595. if (options.HashFilenames) {
  596. MD5 Hasher;
  597. MD5::MD5Result Result;
  598. Hasher.update(filename.str());
  599. Hasher.final(Result);
  600. CoveragePath += "##" + std::string(Result.digest());
  601. }
  602. CoveragePath += ".gcov";
  603. return CoveragePath;
  604. }
  605. void Context::collectFunction(GCOVFunction &f, Summary &summary) {
  606. SourceInfo &si = sources[f.srcIdx];
  607. if (f.startLine >= si.startLineToFunctions.size())
  608. si.startLineToFunctions.resize(f.startLine + 1);
  609. si.startLineToFunctions[f.startLine].push_back(&f);
  610. for (const GCOVBlock &b : f.blocksRange()) {
  611. if (b.lines.empty())
  612. continue;
  613. uint32_t maxLineNum = *std::max_element(b.lines.begin(), b.lines.end());
  614. if (maxLineNum >= si.lines.size())
  615. si.lines.resize(maxLineNum + 1);
  616. for (uint32_t lineNum : b.lines) {
  617. LineInfo &line = si.lines[lineNum];
  618. if (!line.exists)
  619. ++summary.lines;
  620. if (line.count == 0 && b.count)
  621. ++summary.linesExec;
  622. line.exists = true;
  623. line.count += b.count;
  624. line.blocks.push_back(&b);
  625. }
  626. }
  627. }
  628. void Context::collectSourceLine(SourceInfo &si, Summary *summary,
  629. LineInfo &line, size_t lineNum) const {
  630. uint64_t count = 0;
  631. for (const GCOVBlock *b : line.blocks) {
  632. if (b->number == 0) {
  633. // For nonstandard control flows, arcs into the exit block may be
  634. // duplicately counted (fork) or not be counted (abnormal exit), and thus
  635. // the (exit,entry) counter may be inaccurate. Count the entry block with
  636. // the outgoing arcs.
  637. for (const GCOVArc *arc : b->succ)
  638. count += arc->count;
  639. } else {
  640. // Add counts from predecessors that are not on the same line.
  641. for (const GCOVArc *arc : b->pred)
  642. if (!llvm::is_contained(line.blocks, &arc->src))
  643. count += arc->count;
  644. }
  645. for (GCOVArc *arc : b->succ)
  646. arc->cycleCount = arc->count;
  647. }
  648. count += GCOVBlock::getCyclesCount(line.blocks);
  649. line.count = count;
  650. if (line.exists) {
  651. ++summary->lines;
  652. if (line.count != 0)
  653. ++summary->linesExec;
  654. }
  655. if (options.BranchInfo)
  656. for (const GCOVBlock *b : line.blocks) {
  657. if (b->getLastLine() != lineNum)
  658. continue;
  659. int branches = 0, execBranches = 0, takenBranches = 0;
  660. for (const GCOVArc *arc : b->succ) {
  661. ++branches;
  662. if (count != 0)
  663. ++execBranches;
  664. if (arc->count != 0)
  665. ++takenBranches;
  666. }
  667. if (branches > 1) {
  668. summary->branches += branches;
  669. summary->branchesExec += execBranches;
  670. summary->branchesTaken += takenBranches;
  671. }
  672. }
  673. }
  674. void Context::collectSource(SourceInfo &si, Summary &summary) const {
  675. size_t lineNum = 0;
  676. for (LineInfo &line : si.lines) {
  677. collectSourceLine(si, &summary, line, lineNum);
  678. ++lineNum;
  679. }
  680. }
  681. void Context::annotateSource(SourceInfo &si, const GCOVFile &file,
  682. StringRef gcno, StringRef gcda,
  683. raw_ostream &os) const {
  684. auto source =
  685. options.Intermediate ? LineConsumer() : LineConsumer(si.filename);
  686. os << " -: 0:Source:" << si.displayName << '\n';
  687. os << " -: 0:Graph:" << gcno << '\n';
  688. os << " -: 0:Data:" << gcda << '\n';
  689. os << " -: 0:Runs:" << file.runCount << '\n';
  690. if (file.version < GCOV::V900)
  691. os << " -: 0:Programs:" << file.programCount << '\n';
  692. for (size_t lineNum = 1; !source.empty(); ++lineNum) {
  693. if (lineNum >= si.lines.size()) {
  694. os << " -:";
  695. source.printNext(os, lineNum);
  696. continue;
  697. }
  698. const LineInfo &line = si.lines[lineNum];
  699. if (options.BranchInfo && lineNum < si.startLineToFunctions.size())
  700. for (const auto *f : si.startLineToFunctions[lineNum])
  701. printFunctionDetails(*f, os);
  702. if (!line.exists)
  703. os << " -:";
  704. else if (line.count == 0)
  705. os << " #####:";
  706. else
  707. os << format("%9" PRIu64 ":", line.count);
  708. source.printNext(os, lineNum);
  709. uint32_t blockIdx = 0, edgeIdx = 0;
  710. for (const GCOVBlock *b : line.blocks) {
  711. if (b->getLastLine() != lineNum)
  712. continue;
  713. if (options.AllBlocks) {
  714. if (b->getCount() == 0)
  715. os << " $$$$$:";
  716. else
  717. os << format("%9" PRIu64 ":", b->count);
  718. os << format("%5u-block %2u\n", lineNum, blockIdx++);
  719. }
  720. if (options.BranchInfo) {
  721. size_t NumEdges = b->succ.size();
  722. if (NumEdges > 1)
  723. printBranchInfo(*b, edgeIdx, os);
  724. else if (options.UncondBranch && NumEdges == 1) {
  725. uint64_t count = b->succ[0]->count;
  726. os << format("unconditional %2u ", edgeIdx++)
  727. << formatBranchInfo(options, count, count) << '\n';
  728. }
  729. }
  730. }
  731. }
  732. }
  733. void Context::printSourceToIntermediate(const SourceInfo &si,
  734. raw_ostream &os) const {
  735. os << "file:" << si.filename << '\n';
  736. for (const auto &fs : si.startLineToFunctions)
  737. for (const GCOVFunction *f : fs)
  738. os << "function:" << f->startLine << ',' << f->getEntryCount() << ','
  739. << f->getName(options.Demangle) << '\n';
  740. for (size_t lineNum = 1, size = si.lines.size(); lineNum < size; ++lineNum) {
  741. const LineInfo &line = si.lines[lineNum];
  742. if (line.blocks.empty())
  743. continue;
  744. // GCC 8 (r254259) added third third field for Ada:
  745. // lcount:<line>,<count>,<has_unexecuted_blocks>
  746. // We don't need the third field.
  747. os << "lcount:" << lineNum << ',' << line.count << '\n';
  748. if (!options.BranchInfo)
  749. continue;
  750. for (const GCOVBlock *b : line.blocks) {
  751. if (b->succ.size() < 2 || b->getLastLine() != lineNum)
  752. continue;
  753. for (const GCOVArc *arc : b->succ) {
  754. const char *type =
  755. b->getCount() ? arc->count ? "taken" : "nottaken" : "notexec";
  756. os << "branch:" << lineNum << ',' << type << '\n';
  757. }
  758. }
  759. }
  760. }
  761. void Context::print(StringRef filename, StringRef gcno, StringRef gcda,
  762. GCOVFile &file) {
  763. for (StringRef filename : file.filenames) {
  764. sources.emplace_back(filename);
  765. SourceInfo &si = sources.back();
  766. si.displayName = si.filename;
  767. if (!options.SourcePrefix.empty() &&
  768. sys::path::replace_path_prefix(si.displayName, options.SourcePrefix,
  769. "") &&
  770. !si.displayName.empty()) {
  771. // TODO replace_path_prefix may strip the prefix even if the remaining
  772. // part does not start with a separator.
  773. if (sys::path::is_separator(si.displayName[0]))
  774. si.displayName.erase(si.displayName.begin());
  775. else
  776. si.displayName = si.filename;
  777. }
  778. if (options.RelativeOnly && sys::path::is_absolute(si.displayName))
  779. si.ignored = true;
  780. }
  781. raw_ostream &os = llvm::outs();
  782. for (GCOVFunction &f : make_pointee_range(file.functions)) {
  783. Summary summary(f.getName(options.Demangle));
  784. collectFunction(f, summary);
  785. if (options.FuncCoverage && !options.UseStdout) {
  786. os << "Function '" << summary.Name << "'\n";
  787. printSummary(summary, os);
  788. os << '\n';
  789. }
  790. }
  791. for (SourceInfo &si : sources) {
  792. if (si.ignored)
  793. continue;
  794. Summary summary(si.displayName);
  795. collectSource(si, summary);
  796. // Print file summary unless -t is specified.
  797. std::string gcovName = getCoveragePath(si.filename, filename);
  798. if (!options.UseStdout) {
  799. os << "File '" << summary.Name << "'\n";
  800. printSummary(summary, os);
  801. if (!options.NoOutput && !options.Intermediate)
  802. os << "Creating '" << gcovName << "'\n";
  803. os << '\n';
  804. }
  805. if (options.NoOutput || options.Intermediate)
  806. continue;
  807. Optional<raw_fd_ostream> os;
  808. if (!options.UseStdout) {
  809. std::error_code ec;
  810. os.emplace(gcovName, ec, sys::fs::OF_TextWithCRLF);
  811. if (ec) {
  812. errs() << ec.message() << '\n';
  813. continue;
  814. }
  815. }
  816. annotateSource(si, file, gcno, gcda,
  817. options.UseStdout ? llvm::outs() : *os);
  818. }
  819. if (options.Intermediate && !options.NoOutput) {
  820. // gcov 7.* unexpectedly create multiple .gcov files, which was fixed in 8.0
  821. // (PR GCC/82702). We create just one file.
  822. std::string outputPath(sys::path::filename(filename));
  823. std::error_code ec;
  824. raw_fd_ostream os(outputPath + ".gcov", ec, sys::fs::OF_TextWithCRLF);
  825. if (ec) {
  826. errs() << ec.message() << '\n';
  827. return;
  828. }
  829. for (const SourceInfo &si : sources)
  830. printSourceToIntermediate(si, os);
  831. }
  832. }
  833. void Context::printFunctionDetails(const GCOVFunction &f,
  834. raw_ostream &os) const {
  835. const uint64_t entryCount = f.getEntryCount();
  836. uint32_t blocksExec = 0;
  837. const GCOVBlock &exitBlock = f.getExitBlock();
  838. uint64_t exitCount = 0;
  839. for (const GCOVArc *arc : exitBlock.pred)
  840. exitCount += arc->count;
  841. for (const GCOVBlock &b : f.blocksRange())
  842. if (b.number != 0 && &b != &exitBlock && b.getCount())
  843. ++blocksExec;
  844. os << "function " << f.getName(options.Demangle) << " called " << entryCount
  845. << " returned " << formatPercentage(exitCount, entryCount)
  846. << "% blocks executed "
  847. << formatPercentage(blocksExec, f.blocks.size() - 2) << "%\n";
  848. }
  849. /// printBranchInfo - Print conditional branch probabilities.
  850. void Context::printBranchInfo(const GCOVBlock &Block, uint32_t &edgeIdx,
  851. raw_ostream &os) const {
  852. uint64_t total = 0;
  853. for (const GCOVArc *arc : Block.dsts())
  854. total += arc->count;
  855. for (const GCOVArc *arc : Block.dsts())
  856. os << format("branch %2u ", edgeIdx++)
  857. << formatBranchInfo(options, arc->count, total) << '\n';
  858. }
  859. void Context::printSummary(const Summary &summary, raw_ostream &os) const {
  860. os << format("Lines executed:%.2f%% of %" PRIu64 "\n",
  861. double(summary.linesExec) * 100 / summary.lines, summary.lines);
  862. if (options.BranchInfo) {
  863. if (summary.branches == 0) {
  864. os << "No branches\n";
  865. } else {
  866. os << format("Branches executed:%.2f%% of %" PRIu64 "\n",
  867. double(summary.branchesExec) * 100 / summary.branches,
  868. summary.branches);
  869. os << format("Taken at least once:%.2f%% of %" PRIu64 "\n",
  870. double(summary.branchesTaken) * 100 / summary.branches,
  871. summary.branches);
  872. }
  873. os << "No calls\n";
  874. }
  875. }
  876. void llvm::gcovOneInput(const GCOV::Options &options, StringRef filename,
  877. StringRef gcno, StringRef gcda, GCOVFile &file) {
  878. Context fi(options);
  879. fi.print(filename, gcno, gcda, file);
  880. }