CoverageMappingGen.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
  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. // Instrumentation-based code coverage mapping generator
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CoverageMappingGen.h"
  13. #include "CodeGenFunction.h"
  14. #include "clang/AST/StmtVisitor.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Frontend/FrontendDiagnostic.h"
  18. #include "clang/Lex/Lexer.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  22. #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
  23. #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
  24. #include "llvm/ProfileData/InstrProfReader.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/Path.h"
  27. #include <optional>
  28. // This selects the coverage mapping format defined when `InstrProfData.inc`
  29. // is textually included.
  30. #define COVMAP_V3
  31. static llvm::cl::opt<bool> EmptyLineCommentCoverage(
  32. "emptyline-comment-coverage",
  33. llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
  34. "disable it on test)"),
  35. llvm::cl::init(true), llvm::cl::Hidden);
  36. using namespace clang;
  37. using namespace CodeGen;
  38. using namespace llvm::coverage;
  39. CoverageSourceInfo *
  40. CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
  41. CoverageSourceInfo *CoverageInfo =
  42. new CoverageSourceInfo(PP.getSourceManager());
  43. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
  44. if (EmptyLineCommentCoverage) {
  45. PP.addCommentHandler(CoverageInfo);
  46. PP.setEmptylineHandler(CoverageInfo);
  47. PP.setPreprocessToken(true);
  48. PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
  49. // Update previous token location.
  50. CoverageInfo->PrevTokLoc = Tok.getLocation();
  51. if (Tok.getKind() != clang::tok::eod)
  52. CoverageInfo->updateNextTokLoc(Tok.getLocation());
  53. });
  54. }
  55. return CoverageInfo;
  56. }
  57. void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
  58. SkippedRange::Kind RangeKind) {
  59. if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
  60. PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
  61. SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
  62. Range.getBegin()))
  63. SkippedRanges.back().Range.setEnd(Range.getEnd());
  64. else
  65. SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
  66. }
  67. void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
  68. AddSkippedRange(Range, SkippedRange::PPIfElse);
  69. }
  70. void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
  71. AddSkippedRange(Range, SkippedRange::EmptyLine);
  72. }
  73. bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
  74. AddSkippedRange(Range, SkippedRange::Comment);
  75. return false;
  76. }
  77. void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
  78. if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
  79. SkippedRanges.back().NextTokLoc = Loc;
  80. }
  81. namespace {
  82. /// A region of source code that can be mapped to a counter.
  83. class SourceMappingRegion {
  84. /// Primary Counter that is also used for Branch Regions for "True" branches.
  85. Counter Count;
  86. /// Secondary Counter used for Branch Regions for "False" branches.
  87. std::optional<Counter> FalseCount;
  88. /// The region's starting location.
  89. std::optional<SourceLocation> LocStart;
  90. /// The region's ending location.
  91. std::optional<SourceLocation> LocEnd;
  92. /// Whether this region is a gap region. The count from a gap region is set
  93. /// as the line execution count if there are no other regions on the line.
  94. bool GapRegion;
  95. public:
  96. SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
  97. std::optional<SourceLocation> LocEnd,
  98. bool GapRegion = false)
  99. : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
  100. }
  101. SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
  102. std::optional<SourceLocation> LocStart,
  103. std::optional<SourceLocation> LocEnd,
  104. bool GapRegion = false)
  105. : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
  106. LocEnd(LocEnd), GapRegion(GapRegion) {}
  107. const Counter &getCounter() const { return Count; }
  108. const Counter &getFalseCounter() const {
  109. assert(FalseCount && "Region has no alternate counter");
  110. return *FalseCount;
  111. }
  112. void setCounter(Counter C) { Count = C; }
  113. bool hasStartLoc() const { return LocStart.has_value(); }
  114. void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
  115. SourceLocation getBeginLoc() const {
  116. assert(LocStart && "Region has no start location");
  117. return *LocStart;
  118. }
  119. bool hasEndLoc() const { return LocEnd.has_value(); }
  120. void setEndLoc(SourceLocation Loc) {
  121. assert(Loc.isValid() && "Setting an invalid end location");
  122. LocEnd = Loc;
  123. }
  124. SourceLocation getEndLoc() const {
  125. assert(LocEnd && "Region has no end location");
  126. return *LocEnd;
  127. }
  128. bool isGap() const { return GapRegion; }
  129. void setGap(bool Gap) { GapRegion = Gap; }
  130. bool isBranch() const { return FalseCount.has_value(); }
  131. };
  132. /// Spelling locations for the start and end of a source region.
  133. struct SpellingRegion {
  134. /// The line where the region starts.
  135. unsigned LineStart;
  136. /// The column where the region starts.
  137. unsigned ColumnStart;
  138. /// The line where the region ends.
  139. unsigned LineEnd;
  140. /// The column where the region ends.
  141. unsigned ColumnEnd;
  142. SpellingRegion(SourceManager &SM, SourceLocation LocStart,
  143. SourceLocation LocEnd) {
  144. LineStart = SM.getSpellingLineNumber(LocStart);
  145. ColumnStart = SM.getSpellingColumnNumber(LocStart);
  146. LineEnd = SM.getSpellingLineNumber(LocEnd);
  147. ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  148. }
  149. SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
  150. : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
  151. /// Check if the start and end locations appear in source order, i.e
  152. /// top->bottom, left->right.
  153. bool isInSourceOrder() const {
  154. return (LineStart < LineEnd) ||
  155. (LineStart == LineEnd && ColumnStart <= ColumnEnd);
  156. }
  157. };
  158. /// Provides the common functionality for the different
  159. /// coverage mapping region builders.
  160. class CoverageMappingBuilder {
  161. public:
  162. CoverageMappingModuleGen &CVM;
  163. SourceManager &SM;
  164. const LangOptions &LangOpts;
  165. private:
  166. /// Map of clang's FileIDs to IDs used for coverage mapping.
  167. llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
  168. FileIDMapping;
  169. public:
  170. /// The coverage mapping regions for this function
  171. llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
  172. /// The source mapping regions for this function.
  173. std::vector<SourceMappingRegion> SourceRegions;
  174. /// A set of regions which can be used as a filter.
  175. ///
  176. /// It is produced by emitExpansionRegions() and is used in
  177. /// emitSourceRegions() to suppress producing code regions if
  178. /// the same area is covered by expansion regions.
  179. typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
  180. SourceRegionFilter;
  181. CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  182. const LangOptions &LangOpts)
  183. : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
  184. /// Return the precise end location for the given token.
  185. SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
  186. // We avoid getLocForEndOfToken here, because it doesn't do what we want for
  187. // macro locations, which we just treat as expanded files.
  188. unsigned TokLen =
  189. Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
  190. return Loc.getLocWithOffset(TokLen);
  191. }
  192. /// Return the start location of an included file or expanded macro.
  193. SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
  194. if (Loc.isMacroID())
  195. return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
  196. return SM.getLocForStartOfFile(SM.getFileID(Loc));
  197. }
  198. /// Return the end location of an included file or expanded macro.
  199. SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
  200. if (Loc.isMacroID())
  201. return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
  202. SM.getFileOffset(Loc));
  203. return SM.getLocForEndOfFile(SM.getFileID(Loc));
  204. }
  205. /// Find out where the current file is included or macro is expanded.
  206. SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
  207. return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
  208. : SM.getIncludeLoc(SM.getFileID(Loc));
  209. }
  210. /// Return true if \c Loc is a location in a built-in macro.
  211. bool isInBuiltin(SourceLocation Loc) {
  212. return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
  213. }
  214. /// Check whether \c Loc is included or expanded from \c Parent.
  215. bool isNestedIn(SourceLocation Loc, FileID Parent) {
  216. do {
  217. Loc = getIncludeOrExpansionLoc(Loc);
  218. if (Loc.isInvalid())
  219. return false;
  220. } while (!SM.isInFileID(Loc, Parent));
  221. return true;
  222. }
  223. /// Get the start of \c S ignoring macro arguments and builtin macros.
  224. SourceLocation getStart(const Stmt *S) {
  225. SourceLocation Loc = S->getBeginLoc();
  226. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  227. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  228. return Loc;
  229. }
  230. /// Get the end of \c S ignoring macro arguments and builtin macros.
  231. SourceLocation getEnd(const Stmt *S) {
  232. SourceLocation Loc = S->getEndLoc();
  233. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  234. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  235. return getPreciseTokenLocEnd(Loc);
  236. }
  237. /// Find the set of files we have regions for and assign IDs
  238. ///
  239. /// Fills \c Mapping with the virtual file mapping needed to write out
  240. /// coverage and collects the necessary file information to emit source and
  241. /// expansion regions.
  242. void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
  243. FileIDMapping.clear();
  244. llvm::SmallSet<FileID, 8> Visited;
  245. SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
  246. for (const auto &Region : SourceRegions) {
  247. SourceLocation Loc = Region.getBeginLoc();
  248. FileID File = SM.getFileID(Loc);
  249. if (!Visited.insert(File).second)
  250. continue;
  251. // Do not map FileID's associated with system headers.
  252. if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
  253. continue;
  254. unsigned Depth = 0;
  255. for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
  256. Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
  257. ++Depth;
  258. FileLocs.push_back(std::make_pair(Loc, Depth));
  259. }
  260. llvm::stable_sort(FileLocs, llvm::less_second());
  261. for (const auto &FL : FileLocs) {
  262. SourceLocation Loc = FL.first;
  263. FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
  264. auto Entry = SM.getFileEntryForID(SpellingFile);
  265. if (!Entry)
  266. continue;
  267. FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
  268. Mapping.push_back(CVM.getFileID(Entry));
  269. }
  270. }
  271. /// Get the coverage mapping file ID for \c Loc.
  272. ///
  273. /// If such file id doesn't exist, return std::nullopt.
  274. std::optional<unsigned> getCoverageFileID(SourceLocation Loc) {
  275. auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
  276. if (Mapping != FileIDMapping.end())
  277. return Mapping->second.first;
  278. return std::nullopt;
  279. }
  280. /// This shrinks the skipped range if it spans a line that contains a
  281. /// non-comment token. If shrinking the skipped range would make it empty,
  282. /// this returns std::nullopt.
  283. /// Note this function can potentially be expensive because
  284. /// getSpellingLineNumber uses getLineNumber, which is expensive.
  285. std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
  286. SourceLocation LocStart,
  287. SourceLocation LocEnd,
  288. SourceLocation PrevTokLoc,
  289. SourceLocation NextTokLoc) {
  290. SpellingRegion SR{SM, LocStart, LocEnd};
  291. SR.ColumnStart = 1;
  292. if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
  293. SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
  294. SR.LineStart++;
  295. if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
  296. SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
  297. SR.LineEnd--;
  298. SR.ColumnEnd++;
  299. }
  300. if (SR.isInSourceOrder())
  301. return SR;
  302. return std::nullopt;
  303. }
  304. /// Gather all the regions that were skipped by the preprocessor
  305. /// using the constructs like #if or comments.
  306. void gatherSkippedRegions() {
  307. /// An array of the minimum lineStarts and the maximum lineEnds
  308. /// for mapping regions from the appropriate source files.
  309. llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
  310. FileLineRanges.resize(
  311. FileIDMapping.size(),
  312. std::make_pair(std::numeric_limits<unsigned>::max(), 0));
  313. for (const auto &R : MappingRegions) {
  314. FileLineRanges[R.FileID].first =
  315. std::min(FileLineRanges[R.FileID].first, R.LineStart);
  316. FileLineRanges[R.FileID].second =
  317. std::max(FileLineRanges[R.FileID].second, R.LineEnd);
  318. }
  319. auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
  320. for (auto &I : SkippedRanges) {
  321. SourceRange Range = I.Range;
  322. auto LocStart = Range.getBegin();
  323. auto LocEnd = Range.getEnd();
  324. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  325. "region spans multiple files");
  326. auto CovFileID = getCoverageFileID(LocStart);
  327. if (!CovFileID)
  328. continue;
  329. std::optional<SpellingRegion> SR;
  330. if (I.isComment())
  331. SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
  332. I.NextTokLoc);
  333. else if (I.isPPIfElse() || I.isEmptyLine())
  334. SR = {SM, LocStart, LocEnd};
  335. if (!SR)
  336. continue;
  337. auto Region = CounterMappingRegion::makeSkipped(
  338. *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
  339. SR->ColumnEnd);
  340. // Make sure that we only collect the regions that are inside
  341. // the source code of this function.
  342. if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
  343. Region.LineEnd <= FileLineRanges[*CovFileID].second)
  344. MappingRegions.push_back(Region);
  345. }
  346. }
  347. /// Generate the coverage counter mapping regions from collected
  348. /// source regions.
  349. void emitSourceRegions(const SourceRegionFilter &Filter) {
  350. for (const auto &Region : SourceRegions) {
  351. assert(Region.hasEndLoc() && "incomplete region");
  352. SourceLocation LocStart = Region.getBeginLoc();
  353. assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
  354. // Ignore regions from system headers.
  355. if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
  356. continue;
  357. auto CovFileID = getCoverageFileID(LocStart);
  358. // Ignore regions that don't have a file, such as builtin macros.
  359. if (!CovFileID)
  360. continue;
  361. SourceLocation LocEnd = Region.getEndLoc();
  362. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  363. "region spans multiple files");
  364. // Don't add code regions for the area covered by expansion regions.
  365. // This not only suppresses redundant regions, but sometimes prevents
  366. // creating regions with wrong counters if, for example, a statement's
  367. // body ends at the end of a nested macro.
  368. if (Filter.count(std::make_pair(LocStart, LocEnd)))
  369. continue;
  370. // Find the spelling locations for the mapping region.
  371. SpellingRegion SR{SM, LocStart, LocEnd};
  372. assert(SR.isInSourceOrder() && "region start and end out of order");
  373. if (Region.isGap()) {
  374. MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
  375. Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
  376. SR.LineEnd, SR.ColumnEnd));
  377. } else if (Region.isBranch()) {
  378. MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
  379. Region.getCounter(), Region.getFalseCounter(), *CovFileID,
  380. SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
  381. } else {
  382. MappingRegions.push_back(CounterMappingRegion::makeRegion(
  383. Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
  384. SR.LineEnd, SR.ColumnEnd));
  385. }
  386. }
  387. }
  388. /// Generate expansion regions for each virtual file we've seen.
  389. SourceRegionFilter emitExpansionRegions() {
  390. SourceRegionFilter Filter;
  391. for (const auto &FM : FileIDMapping) {
  392. SourceLocation ExpandedLoc = FM.second.second;
  393. SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
  394. if (ParentLoc.isInvalid())
  395. continue;
  396. auto ParentFileID = getCoverageFileID(ParentLoc);
  397. if (!ParentFileID)
  398. continue;
  399. auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
  400. assert(ExpandedFileID && "expansion in uncovered file");
  401. SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
  402. assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
  403. "region spans multiple files");
  404. Filter.insert(std::make_pair(ParentLoc, LocEnd));
  405. SpellingRegion SR{SM, ParentLoc, LocEnd};
  406. assert(SR.isInSourceOrder() && "region start and end out of order");
  407. MappingRegions.push_back(CounterMappingRegion::makeExpansion(
  408. *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
  409. SR.LineEnd, SR.ColumnEnd));
  410. }
  411. return Filter;
  412. }
  413. };
  414. /// Creates unreachable coverage regions for the functions that
  415. /// are not emitted.
  416. struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
  417. EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  418. const LangOptions &LangOpts)
  419. : CoverageMappingBuilder(CVM, SM, LangOpts) {}
  420. void VisitDecl(const Decl *D) {
  421. if (!D->hasBody())
  422. return;
  423. auto Body = D->getBody();
  424. SourceLocation Start = getStart(Body);
  425. SourceLocation End = getEnd(Body);
  426. if (!SM.isWrittenInSameFile(Start, End)) {
  427. // Walk up to find the common ancestor.
  428. // Correct the locations accordingly.
  429. FileID StartFileID = SM.getFileID(Start);
  430. FileID EndFileID = SM.getFileID(End);
  431. while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
  432. Start = getIncludeOrExpansionLoc(Start);
  433. assert(Start.isValid() &&
  434. "Declaration start location not nested within a known region");
  435. StartFileID = SM.getFileID(Start);
  436. }
  437. while (StartFileID != EndFileID) {
  438. End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
  439. assert(End.isValid() &&
  440. "Declaration end location not nested within a known region");
  441. EndFileID = SM.getFileID(End);
  442. }
  443. }
  444. SourceRegions.emplace_back(Counter(), Start, End);
  445. }
  446. /// Write the mapping data to the output stream
  447. void write(llvm::raw_ostream &OS) {
  448. SmallVector<unsigned, 16> FileIDMapping;
  449. gatherFileIDs(FileIDMapping);
  450. emitSourceRegions(SourceRegionFilter());
  451. if (MappingRegions.empty())
  452. return;
  453. CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
  454. Writer.write(OS);
  455. }
  456. };
  457. /// A StmtVisitor that creates coverage mapping regions which map
  458. /// from the source code locations to the PGO counters.
  459. struct CounterCoverageMappingBuilder
  460. : public CoverageMappingBuilder,
  461. public ConstStmtVisitor<CounterCoverageMappingBuilder> {
  462. /// The map of statements to count values.
  463. llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
  464. /// A stack of currently live regions.
  465. std::vector<SourceMappingRegion> RegionStack;
  466. CounterExpressionBuilder Builder;
  467. /// A location in the most recently visited file or macro.
  468. ///
  469. /// This is used to adjust the active source regions appropriately when
  470. /// expressions cross file or macro boundaries.
  471. SourceLocation MostRecentLocation;
  472. /// Whether the visitor at a terminate statement.
  473. bool HasTerminateStmt = false;
  474. /// Gap region counter after terminate statement.
  475. Counter GapRegionCounter;
  476. /// Return a counter for the subtraction of \c RHS from \c LHS
  477. Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
  478. return Builder.subtract(LHS, RHS, Simplify);
  479. }
  480. /// Return a counter for the sum of \c LHS and \c RHS.
  481. Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
  482. return Builder.add(LHS, RHS, Simplify);
  483. }
  484. Counter addCounters(Counter C1, Counter C2, Counter C3,
  485. bool Simplify = true) {
  486. return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
  487. }
  488. /// Return the region counter for the given statement.
  489. ///
  490. /// This should only be called on statements that have a dedicated counter.
  491. Counter getRegionCounter(const Stmt *S) {
  492. return Counter::getCounter(CounterMap[S]);
  493. }
  494. /// Push a region onto the stack.
  495. ///
  496. /// Returns the index on the stack where the region was pushed. This can be
  497. /// used with popRegions to exit a "scope", ending the region that was pushed.
  498. size_t pushRegion(Counter Count,
  499. std::optional<SourceLocation> StartLoc = std::nullopt,
  500. std::optional<SourceLocation> EndLoc = std::nullopt,
  501. std::optional<Counter> FalseCount = std::nullopt) {
  502. if (StartLoc && !FalseCount) {
  503. MostRecentLocation = *StartLoc;
  504. }
  505. RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
  506. return RegionStack.size() - 1;
  507. }
  508. size_t locationDepth(SourceLocation Loc) {
  509. size_t Depth = 0;
  510. while (Loc.isValid()) {
  511. Loc = getIncludeOrExpansionLoc(Loc);
  512. Depth++;
  513. }
  514. return Depth;
  515. }
  516. /// Pop regions from the stack into the function's list of regions.
  517. ///
  518. /// Adds all regions from \c ParentIndex to the top of the stack to the
  519. /// function's \c SourceRegions.
  520. void popRegions(size_t ParentIndex) {
  521. assert(RegionStack.size() >= ParentIndex && "parent not in stack");
  522. while (RegionStack.size() > ParentIndex) {
  523. SourceMappingRegion &Region = RegionStack.back();
  524. if (Region.hasStartLoc()) {
  525. SourceLocation StartLoc = Region.getBeginLoc();
  526. SourceLocation EndLoc = Region.hasEndLoc()
  527. ? Region.getEndLoc()
  528. : RegionStack[ParentIndex].getEndLoc();
  529. bool isBranch = Region.isBranch();
  530. size_t StartDepth = locationDepth(StartLoc);
  531. size_t EndDepth = locationDepth(EndLoc);
  532. while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
  533. bool UnnestStart = StartDepth >= EndDepth;
  534. bool UnnestEnd = EndDepth >= StartDepth;
  535. if (UnnestEnd) {
  536. // The region ends in a nested file or macro expansion. If the
  537. // region is not a branch region, create a separate region for each
  538. // expansion, and for all regions, update the EndLoc. Branch
  539. // regions should not be split in order to keep a straightforward
  540. // correspondance between the region and its associated branch
  541. // condition, even if the condition spans multiple depths.
  542. SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
  543. assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
  544. if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
  545. SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
  546. EndLoc);
  547. EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
  548. if (EndLoc.isInvalid())
  549. llvm::report_fatal_error(
  550. "File exit not handled before popRegions");
  551. EndDepth--;
  552. }
  553. if (UnnestStart) {
  554. // The region ends in a nested file or macro expansion. If the
  555. // region is not a branch region, create a separate region for each
  556. // expansion, and for all regions, update the StartLoc. Branch
  557. // regions should not be split in order to keep a straightforward
  558. // correspondance between the region and its associated branch
  559. // condition, even if the condition spans multiple depths.
  560. SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
  561. assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
  562. if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
  563. SourceRegions.emplace_back(Region.getCounter(), StartLoc,
  564. NestedLoc);
  565. StartLoc = getIncludeOrExpansionLoc(StartLoc);
  566. if (StartLoc.isInvalid())
  567. llvm::report_fatal_error(
  568. "File exit not handled before popRegions");
  569. StartDepth--;
  570. }
  571. }
  572. Region.setStartLoc(StartLoc);
  573. Region.setEndLoc(EndLoc);
  574. if (!isBranch) {
  575. MostRecentLocation = EndLoc;
  576. // If this region happens to span an entire expansion, we need to
  577. // make sure we don't overlap the parent region with it.
  578. if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
  579. EndLoc == getEndOfFileOrMacro(EndLoc))
  580. MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
  581. }
  582. assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
  583. assert(SpellingRegion(SM, Region).isInSourceOrder());
  584. SourceRegions.push_back(Region);
  585. }
  586. RegionStack.pop_back();
  587. }
  588. }
  589. /// Return the currently active region.
  590. SourceMappingRegion &getRegion() {
  591. assert(!RegionStack.empty() && "statement has no region");
  592. return RegionStack.back();
  593. }
  594. /// Propagate counts through the children of \p S if \p VisitChildren is true.
  595. /// Otherwise, only emit a count for \p S itself.
  596. Counter propagateCounts(Counter TopCount, const Stmt *S,
  597. bool VisitChildren = true) {
  598. SourceLocation StartLoc = getStart(S);
  599. SourceLocation EndLoc = getEnd(S);
  600. size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
  601. if (VisitChildren)
  602. Visit(S);
  603. Counter ExitCount = getRegion().getCounter();
  604. popRegions(Index);
  605. // The statement may be spanned by an expansion. Make sure we handle a file
  606. // exit out of this expansion before moving to the next statement.
  607. if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
  608. MostRecentLocation = EndLoc;
  609. return ExitCount;
  610. }
  611. /// Determine whether the given condition can be constant folded.
  612. bool ConditionFoldsToBool(const Expr *Cond) {
  613. Expr::EvalResult Result;
  614. return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
  615. }
  616. /// Create a Branch Region around an instrumentable condition for coverage
  617. /// and add it to the function's SourceRegions. A branch region tracks a
  618. /// "True" counter and a "False" counter for boolean expressions that
  619. /// result in the generation of a branch.
  620. void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
  621. // Check for NULL conditions.
  622. if (!C)
  623. return;
  624. // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
  625. // region onto RegionStack but immediately pop it (which adds it to the
  626. // function's SourceRegions) because it doesn't apply to any other source
  627. // code other than the Condition.
  628. if (CodeGenFunction::isInstrumentedCondition(C)) {
  629. // If a condition can fold to true or false, the corresponding branch
  630. // will be removed. Create a region with both counters hard-coded to
  631. // zero. This allows us to visualize them in a special way.
  632. // Alternatively, we can prevent any optimization done via
  633. // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
  634. // CodeGenFunction.c always returns false, but that is very heavy-handed.
  635. if (ConditionFoldsToBool(C))
  636. popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
  637. Counter::getZero()));
  638. else
  639. // Otherwise, create a region with the True counter and False counter.
  640. popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
  641. }
  642. }
  643. /// Create a Branch Region around a SwitchCase for code coverage
  644. /// and add it to the function's SourceRegions.
  645. void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
  646. Counter FalseCnt) {
  647. // Push region onto RegionStack but immediately pop it (which adds it to
  648. // the function's SourceRegions) because it doesn't apply to any other
  649. // source other than the SwitchCase.
  650. popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
  651. }
  652. /// Check whether a region with bounds \c StartLoc and \c EndLoc
  653. /// is already added to \c SourceRegions.
  654. bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
  655. bool isBranch = false) {
  656. return llvm::any_of(
  657. llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
  658. return Region.getBeginLoc() == StartLoc &&
  659. Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
  660. });
  661. }
  662. /// Adjust the most recently visited location to \c EndLoc.
  663. ///
  664. /// This should be used after visiting any statements in non-source order.
  665. void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
  666. MostRecentLocation = EndLoc;
  667. // The code region for a whole macro is created in handleFileExit() when
  668. // it detects exiting of the virtual file of that macro. If we visited
  669. // statements in non-source order, we might already have such a region
  670. // added, for example, if a body of a loop is divided among multiple
  671. // macros. Avoid adding duplicate regions in such case.
  672. if (getRegion().hasEndLoc() &&
  673. MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
  674. isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
  675. MostRecentLocation, getRegion().isBranch()))
  676. MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
  677. }
  678. /// Adjust regions and state when \c NewLoc exits a file.
  679. ///
  680. /// If moving from our most recently tracked location to \c NewLoc exits any
  681. /// files, this adjusts our current region stack and creates the file regions
  682. /// for the exited file.
  683. void handleFileExit(SourceLocation NewLoc) {
  684. if (NewLoc.isInvalid() ||
  685. SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
  686. return;
  687. // If NewLoc is not in a file that contains MostRecentLocation, walk up to
  688. // find the common ancestor.
  689. SourceLocation LCA = NewLoc;
  690. FileID ParentFile = SM.getFileID(LCA);
  691. while (!isNestedIn(MostRecentLocation, ParentFile)) {
  692. LCA = getIncludeOrExpansionLoc(LCA);
  693. if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
  694. // Since there isn't a common ancestor, no file was exited. We just need
  695. // to adjust our location to the new file.
  696. MostRecentLocation = NewLoc;
  697. return;
  698. }
  699. ParentFile = SM.getFileID(LCA);
  700. }
  701. llvm::SmallSet<SourceLocation, 8> StartLocs;
  702. std::optional<Counter> ParentCounter;
  703. for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
  704. if (!I.hasStartLoc())
  705. continue;
  706. SourceLocation Loc = I.getBeginLoc();
  707. if (!isNestedIn(Loc, ParentFile)) {
  708. ParentCounter = I.getCounter();
  709. break;
  710. }
  711. while (!SM.isInFileID(Loc, ParentFile)) {
  712. // The most nested region for each start location is the one with the
  713. // correct count. We avoid creating redundant regions by stopping once
  714. // we've seen this region.
  715. if (StartLocs.insert(Loc).second) {
  716. if (I.isBranch())
  717. SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
  718. getEndOfFileOrMacro(Loc), I.isBranch());
  719. else
  720. SourceRegions.emplace_back(I.getCounter(), Loc,
  721. getEndOfFileOrMacro(Loc));
  722. }
  723. Loc = getIncludeOrExpansionLoc(Loc);
  724. }
  725. I.setStartLoc(getPreciseTokenLocEnd(Loc));
  726. }
  727. if (ParentCounter) {
  728. // If the file is contained completely by another region and doesn't
  729. // immediately start its own region, the whole file gets a region
  730. // corresponding to the parent.
  731. SourceLocation Loc = MostRecentLocation;
  732. while (isNestedIn(Loc, ParentFile)) {
  733. SourceLocation FileStart = getStartOfFileOrMacro(Loc);
  734. if (StartLocs.insert(FileStart).second) {
  735. SourceRegions.emplace_back(*ParentCounter, FileStart,
  736. getEndOfFileOrMacro(Loc));
  737. assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
  738. }
  739. Loc = getIncludeOrExpansionLoc(Loc);
  740. }
  741. }
  742. MostRecentLocation = NewLoc;
  743. }
  744. /// Ensure that \c S is included in the current region.
  745. void extendRegion(const Stmt *S) {
  746. SourceMappingRegion &Region = getRegion();
  747. SourceLocation StartLoc = getStart(S);
  748. handleFileExit(StartLoc);
  749. if (!Region.hasStartLoc())
  750. Region.setStartLoc(StartLoc);
  751. }
  752. /// Mark \c S as a terminator, starting a zero region.
  753. void terminateRegion(const Stmt *S) {
  754. extendRegion(S);
  755. SourceMappingRegion &Region = getRegion();
  756. SourceLocation EndLoc = getEnd(S);
  757. if (!Region.hasEndLoc())
  758. Region.setEndLoc(EndLoc);
  759. pushRegion(Counter::getZero());
  760. HasTerminateStmt = true;
  761. }
  762. /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
  763. std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
  764. SourceLocation BeforeLoc) {
  765. // If AfterLoc is in function-like macro, use the right parenthesis
  766. // location.
  767. if (AfterLoc.isMacroID()) {
  768. FileID FID = SM.getFileID(AfterLoc);
  769. const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
  770. if (EI->isFunctionMacroExpansion())
  771. AfterLoc = EI->getExpansionLocEnd();
  772. }
  773. size_t StartDepth = locationDepth(AfterLoc);
  774. size_t EndDepth = locationDepth(BeforeLoc);
  775. while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
  776. bool UnnestStart = StartDepth >= EndDepth;
  777. bool UnnestEnd = EndDepth >= StartDepth;
  778. if (UnnestEnd) {
  779. assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
  780. BeforeLoc));
  781. BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
  782. assert(BeforeLoc.isValid());
  783. EndDepth--;
  784. }
  785. if (UnnestStart) {
  786. assert(SM.isWrittenInSameFile(AfterLoc,
  787. getEndOfFileOrMacro(AfterLoc)));
  788. AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
  789. assert(AfterLoc.isValid());
  790. AfterLoc = getPreciseTokenLocEnd(AfterLoc);
  791. assert(AfterLoc.isValid());
  792. StartDepth--;
  793. }
  794. }
  795. AfterLoc = getPreciseTokenLocEnd(AfterLoc);
  796. // If the start and end locations of the gap are both within the same macro
  797. // file, the range may not be in source order.
  798. if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
  799. return std::nullopt;
  800. if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
  801. !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
  802. return std::nullopt;
  803. return {{AfterLoc, BeforeLoc}};
  804. }
  805. /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
  806. void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
  807. Counter Count) {
  808. if (StartLoc == EndLoc)
  809. return;
  810. assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
  811. handleFileExit(StartLoc);
  812. size_t Index = pushRegion(Count, StartLoc, EndLoc);
  813. getRegion().setGap(true);
  814. handleFileExit(EndLoc);
  815. popRegions(Index);
  816. }
  817. /// Keep counts of breaks and continues inside loops.
  818. struct BreakContinue {
  819. Counter BreakCount;
  820. Counter ContinueCount;
  821. };
  822. SmallVector<BreakContinue, 8> BreakContinueStack;
  823. CounterCoverageMappingBuilder(
  824. CoverageMappingModuleGen &CVM,
  825. llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
  826. const LangOptions &LangOpts)
  827. : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
  828. /// Write the mapping data to the output stream
  829. void write(llvm::raw_ostream &OS) {
  830. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  831. gatherFileIDs(VirtualFileMapping);
  832. SourceRegionFilter Filter = emitExpansionRegions();
  833. emitSourceRegions(Filter);
  834. gatherSkippedRegions();
  835. if (MappingRegions.empty())
  836. return;
  837. CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
  838. MappingRegions);
  839. Writer.write(OS);
  840. }
  841. void VisitStmt(const Stmt *S) {
  842. if (S->getBeginLoc().isValid())
  843. extendRegion(S);
  844. const Stmt *LastStmt = nullptr;
  845. bool SaveTerminateStmt = HasTerminateStmt;
  846. HasTerminateStmt = false;
  847. GapRegionCounter = Counter::getZero();
  848. for (const Stmt *Child : S->children())
  849. if (Child) {
  850. // If last statement contains terminate statements, add a gap area
  851. // between the two statements. Skipping attributed statements, because
  852. // they don't have valid start location.
  853. if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
  854. auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
  855. if (Gap)
  856. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
  857. GapRegionCounter);
  858. SaveTerminateStmt = true;
  859. HasTerminateStmt = false;
  860. }
  861. this->Visit(Child);
  862. LastStmt = Child;
  863. }
  864. if (SaveTerminateStmt)
  865. HasTerminateStmt = true;
  866. handleFileExit(getEnd(S));
  867. }
  868. void VisitDecl(const Decl *D) {
  869. Stmt *Body = D->getBody();
  870. // Do not propagate region counts into system headers.
  871. if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
  872. return;
  873. // Do not visit the artificial children nodes of defaulted methods. The
  874. // lexer may not be able to report back precise token end locations for
  875. // these children nodes (llvm.org/PR39822), and moreover users will not be
  876. // able to see coverage for them.
  877. bool Defaulted = false;
  878. if (auto *Method = dyn_cast<CXXMethodDecl>(D))
  879. Defaulted = Method->isDefaulted();
  880. propagateCounts(getRegionCounter(Body), Body,
  881. /*VisitChildren=*/!Defaulted);
  882. assert(RegionStack.empty() && "Regions entered but never exited");
  883. }
  884. void VisitReturnStmt(const ReturnStmt *S) {
  885. extendRegion(S);
  886. if (S->getRetValue())
  887. Visit(S->getRetValue());
  888. terminateRegion(S);
  889. }
  890. void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
  891. extendRegion(S);
  892. Visit(S->getBody());
  893. }
  894. void VisitCoreturnStmt(const CoreturnStmt *S) {
  895. extendRegion(S);
  896. if (S->getOperand())
  897. Visit(S->getOperand());
  898. terminateRegion(S);
  899. }
  900. void VisitCXXThrowExpr(const CXXThrowExpr *E) {
  901. extendRegion(E);
  902. if (E->getSubExpr())
  903. Visit(E->getSubExpr());
  904. terminateRegion(E);
  905. }
  906. void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
  907. void VisitLabelStmt(const LabelStmt *S) {
  908. Counter LabelCount = getRegionCounter(S);
  909. SourceLocation Start = getStart(S);
  910. // We can't extendRegion here or we risk overlapping with our new region.
  911. handleFileExit(Start);
  912. pushRegion(LabelCount, Start);
  913. Visit(S->getSubStmt());
  914. }
  915. void VisitBreakStmt(const BreakStmt *S) {
  916. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  917. BreakContinueStack.back().BreakCount = addCounters(
  918. BreakContinueStack.back().BreakCount, getRegion().getCounter());
  919. // FIXME: a break in a switch should terminate regions for all preceding
  920. // case statements, not just the most recent one.
  921. terminateRegion(S);
  922. }
  923. void VisitContinueStmt(const ContinueStmt *S) {
  924. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  925. BreakContinueStack.back().ContinueCount = addCounters(
  926. BreakContinueStack.back().ContinueCount, getRegion().getCounter());
  927. terminateRegion(S);
  928. }
  929. void VisitCallExpr(const CallExpr *E) {
  930. VisitStmt(E);
  931. // Terminate the region when we hit a noreturn function.
  932. // (This is helpful dealing with switch statements.)
  933. QualType CalleeType = E->getCallee()->getType();
  934. if (getFunctionExtInfo(*CalleeType).getNoReturn())
  935. terminateRegion(E);
  936. }
  937. void VisitWhileStmt(const WhileStmt *S) {
  938. extendRegion(S);
  939. Counter ParentCount = getRegion().getCounter();
  940. Counter BodyCount = getRegionCounter(S);
  941. // Handle the body first so that we can get the backedge count.
  942. BreakContinueStack.push_back(BreakContinue());
  943. extendRegion(S->getBody());
  944. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  945. BreakContinue BC = BreakContinueStack.pop_back_val();
  946. bool BodyHasTerminateStmt = HasTerminateStmt;
  947. HasTerminateStmt = false;
  948. // Go back to handle the condition.
  949. Counter CondCount =
  950. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  951. propagateCounts(CondCount, S->getCond());
  952. adjustForOutOfOrderTraversal(getEnd(S));
  953. // The body count applies to the area immediately after the increment.
  954. auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
  955. if (Gap)
  956. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  957. Counter OutCount =
  958. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  959. if (OutCount != ParentCount) {
  960. pushRegion(OutCount);
  961. GapRegionCounter = OutCount;
  962. if (BodyHasTerminateStmt)
  963. HasTerminateStmt = true;
  964. }
  965. // Create Branch Region around condition.
  966. createBranchRegion(S->getCond(), BodyCount,
  967. subtractCounters(CondCount, BodyCount));
  968. }
  969. void VisitDoStmt(const DoStmt *S) {
  970. extendRegion(S);
  971. Counter ParentCount = getRegion().getCounter();
  972. Counter BodyCount = getRegionCounter(S);
  973. BreakContinueStack.push_back(BreakContinue());
  974. extendRegion(S->getBody());
  975. Counter BackedgeCount =
  976. propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
  977. BreakContinue BC = BreakContinueStack.pop_back_val();
  978. bool BodyHasTerminateStmt = HasTerminateStmt;
  979. HasTerminateStmt = false;
  980. Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
  981. propagateCounts(CondCount, S->getCond());
  982. Counter OutCount =
  983. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  984. if (OutCount != ParentCount) {
  985. pushRegion(OutCount);
  986. GapRegionCounter = OutCount;
  987. }
  988. // Create Branch Region around condition.
  989. createBranchRegion(S->getCond(), BodyCount,
  990. subtractCounters(CondCount, BodyCount));
  991. if (BodyHasTerminateStmt)
  992. HasTerminateStmt = true;
  993. }
  994. void VisitForStmt(const ForStmt *S) {
  995. extendRegion(S);
  996. if (S->getInit())
  997. Visit(S->getInit());
  998. Counter ParentCount = getRegion().getCounter();
  999. Counter BodyCount = getRegionCounter(S);
  1000. // The loop increment may contain a break or continue.
  1001. if (S->getInc())
  1002. BreakContinueStack.emplace_back();
  1003. // Handle the body first so that we can get the backedge count.
  1004. BreakContinueStack.emplace_back();
  1005. extendRegion(S->getBody());
  1006. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  1007. BreakContinue BodyBC = BreakContinueStack.pop_back_val();
  1008. bool BodyHasTerminateStmt = HasTerminateStmt;
  1009. HasTerminateStmt = false;
  1010. // The increment is essentially part of the body but it needs to include
  1011. // the count for all the continue statements.
  1012. BreakContinue IncrementBC;
  1013. if (const Stmt *Inc = S->getInc()) {
  1014. propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
  1015. IncrementBC = BreakContinueStack.pop_back_val();
  1016. }
  1017. // Go back to handle the condition.
  1018. Counter CondCount = addCounters(
  1019. addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
  1020. IncrementBC.ContinueCount);
  1021. if (const Expr *Cond = S->getCond()) {
  1022. propagateCounts(CondCount, Cond);
  1023. adjustForOutOfOrderTraversal(getEnd(S));
  1024. }
  1025. // The body count applies to the area immediately after the increment.
  1026. auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
  1027. if (Gap)
  1028. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  1029. Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
  1030. subtractCounters(CondCount, BodyCount));
  1031. if (OutCount != ParentCount) {
  1032. pushRegion(OutCount);
  1033. GapRegionCounter = OutCount;
  1034. if (BodyHasTerminateStmt)
  1035. HasTerminateStmt = true;
  1036. }
  1037. // Create Branch Region around condition.
  1038. createBranchRegion(S->getCond(), BodyCount,
  1039. subtractCounters(CondCount, BodyCount));
  1040. }
  1041. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  1042. extendRegion(S);
  1043. if (S->getInit())
  1044. Visit(S->getInit());
  1045. Visit(S->getLoopVarStmt());
  1046. Visit(S->getRangeStmt());
  1047. Counter ParentCount = getRegion().getCounter();
  1048. Counter BodyCount = getRegionCounter(S);
  1049. BreakContinueStack.push_back(BreakContinue());
  1050. extendRegion(S->getBody());
  1051. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  1052. BreakContinue BC = BreakContinueStack.pop_back_val();
  1053. bool BodyHasTerminateStmt = HasTerminateStmt;
  1054. HasTerminateStmt = false;
  1055. // The body count applies to the area immediately after the range.
  1056. auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
  1057. if (Gap)
  1058. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  1059. Counter LoopCount =
  1060. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  1061. Counter OutCount =
  1062. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  1063. if (OutCount != ParentCount) {
  1064. pushRegion(OutCount);
  1065. GapRegionCounter = OutCount;
  1066. if (BodyHasTerminateStmt)
  1067. HasTerminateStmt = true;
  1068. }
  1069. // Create Branch Region around condition.
  1070. createBranchRegion(S->getCond(), BodyCount,
  1071. subtractCounters(LoopCount, BodyCount));
  1072. }
  1073. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  1074. extendRegion(S);
  1075. Visit(S->getElement());
  1076. Counter ParentCount = getRegion().getCounter();
  1077. Counter BodyCount = getRegionCounter(S);
  1078. BreakContinueStack.push_back(BreakContinue());
  1079. extendRegion(S->getBody());
  1080. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  1081. BreakContinue BC = BreakContinueStack.pop_back_val();
  1082. // The body count applies to the area immediately after the collection.
  1083. auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
  1084. if (Gap)
  1085. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  1086. Counter LoopCount =
  1087. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  1088. Counter OutCount =
  1089. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  1090. if (OutCount != ParentCount) {
  1091. pushRegion(OutCount);
  1092. GapRegionCounter = OutCount;
  1093. }
  1094. }
  1095. void VisitSwitchStmt(const SwitchStmt *S) {
  1096. extendRegion(S);
  1097. if (S->getInit())
  1098. Visit(S->getInit());
  1099. Visit(S->getCond());
  1100. BreakContinueStack.push_back(BreakContinue());
  1101. const Stmt *Body = S->getBody();
  1102. extendRegion(Body);
  1103. if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
  1104. if (!CS->body_empty()) {
  1105. // Make a region for the body of the switch. If the body starts with
  1106. // a case, that case will reuse this region; otherwise, this covers
  1107. // the unreachable code at the beginning of the switch body.
  1108. size_t Index = pushRegion(Counter::getZero(), getStart(CS));
  1109. getRegion().setGap(true);
  1110. Visit(Body);
  1111. // Set the end for the body of the switch, if it isn't already set.
  1112. for (size_t i = RegionStack.size(); i != Index; --i) {
  1113. if (!RegionStack[i - 1].hasEndLoc())
  1114. RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
  1115. }
  1116. popRegions(Index);
  1117. }
  1118. } else
  1119. propagateCounts(Counter::getZero(), Body);
  1120. BreakContinue BC = BreakContinueStack.pop_back_val();
  1121. if (!BreakContinueStack.empty())
  1122. BreakContinueStack.back().ContinueCount = addCounters(
  1123. BreakContinueStack.back().ContinueCount, BC.ContinueCount);
  1124. Counter ParentCount = getRegion().getCounter();
  1125. Counter ExitCount = getRegionCounter(S);
  1126. SourceLocation ExitLoc = getEnd(S);
  1127. pushRegion(ExitCount);
  1128. GapRegionCounter = ExitCount;
  1129. // Ensure that handleFileExit recognizes when the end location is located
  1130. // in a different file.
  1131. MostRecentLocation = getStart(S);
  1132. handleFileExit(ExitLoc);
  1133. // Create a Branch Region around each Case. Subtract the case's
  1134. // counter from the Parent counter to track the "False" branch count.
  1135. Counter CaseCountSum;
  1136. bool HasDefaultCase = false;
  1137. const SwitchCase *Case = S->getSwitchCaseList();
  1138. for (; Case; Case = Case->getNextSwitchCase()) {
  1139. HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
  1140. CaseCountSum =
  1141. addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false);
  1142. createSwitchCaseRegion(
  1143. Case, getRegionCounter(Case),
  1144. subtractCounters(ParentCount, getRegionCounter(Case)));
  1145. }
  1146. // Simplify is skipped while building the counters above: it can get really
  1147. // slow on top of switches with thousands of cases. Instead, trigger
  1148. // simplification by adding zero to the last counter.
  1149. CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
  1150. // If no explicit default case exists, create a branch region to represent
  1151. // the hidden branch, which will be added later by the CodeGen. This region
  1152. // will be associated with the switch statement's condition.
  1153. if (!HasDefaultCase) {
  1154. Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
  1155. Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
  1156. createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
  1157. }
  1158. }
  1159. void VisitSwitchCase(const SwitchCase *S) {
  1160. extendRegion(S);
  1161. SourceMappingRegion &Parent = getRegion();
  1162. Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
  1163. // Reuse the existing region if it starts at our label. This is typical of
  1164. // the first case in a switch.
  1165. if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
  1166. Parent.setCounter(Count);
  1167. else
  1168. pushRegion(Count, getStart(S));
  1169. GapRegionCounter = Count;
  1170. if (const auto *CS = dyn_cast<CaseStmt>(S)) {
  1171. Visit(CS->getLHS());
  1172. if (const Expr *RHS = CS->getRHS())
  1173. Visit(RHS);
  1174. }
  1175. Visit(S->getSubStmt());
  1176. }
  1177. void VisitIfStmt(const IfStmt *S) {
  1178. extendRegion(S);
  1179. if (S->getInit())
  1180. Visit(S->getInit());
  1181. // Extend into the condition before we propagate through it below - this is
  1182. // needed to handle macros that generate the "if" but not the condition.
  1183. if (!S->isConsteval())
  1184. extendRegion(S->getCond());
  1185. Counter ParentCount = getRegion().getCounter();
  1186. Counter ThenCount = getRegionCounter(S);
  1187. if (!S->isConsteval()) {
  1188. // Emitting a counter for the condition makes it easier to interpret the
  1189. // counter for the body when looking at the coverage.
  1190. propagateCounts(ParentCount, S->getCond());
  1191. // The 'then' count applies to the area immediately after the condition.
  1192. std::optional<SourceRange> Gap =
  1193. findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
  1194. if (Gap)
  1195. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
  1196. }
  1197. extendRegion(S->getThen());
  1198. Counter OutCount = propagateCounts(ThenCount, S->getThen());
  1199. Counter ElseCount = subtractCounters(ParentCount, ThenCount);
  1200. if (const Stmt *Else = S->getElse()) {
  1201. bool ThenHasTerminateStmt = HasTerminateStmt;
  1202. HasTerminateStmt = false;
  1203. // The 'else' count applies to the area immediately after the 'then'.
  1204. std::optional<SourceRange> Gap =
  1205. findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
  1206. if (Gap)
  1207. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
  1208. extendRegion(Else);
  1209. OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
  1210. if (ThenHasTerminateStmt)
  1211. HasTerminateStmt = true;
  1212. } else
  1213. OutCount = addCounters(OutCount, ElseCount);
  1214. if (OutCount != ParentCount) {
  1215. pushRegion(OutCount);
  1216. GapRegionCounter = OutCount;
  1217. }
  1218. if (!S->isConsteval()) {
  1219. // Create Branch Region around condition.
  1220. createBranchRegion(S->getCond(), ThenCount,
  1221. subtractCounters(ParentCount, ThenCount));
  1222. }
  1223. }
  1224. void VisitCXXTryStmt(const CXXTryStmt *S) {
  1225. extendRegion(S);
  1226. // Handle macros that generate the "try" but not the rest.
  1227. extendRegion(S->getTryBlock());
  1228. Counter ParentCount = getRegion().getCounter();
  1229. propagateCounts(ParentCount, S->getTryBlock());
  1230. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  1231. Visit(S->getHandler(I));
  1232. Counter ExitCount = getRegionCounter(S);
  1233. pushRegion(ExitCount);
  1234. }
  1235. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  1236. propagateCounts(getRegionCounter(S), S->getHandlerBlock());
  1237. }
  1238. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  1239. extendRegion(E);
  1240. Counter ParentCount = getRegion().getCounter();
  1241. Counter TrueCount = getRegionCounter(E);
  1242. propagateCounts(ParentCount, E->getCond());
  1243. if (!isa<BinaryConditionalOperator>(E)) {
  1244. // The 'then' count applies to the area immediately after the condition.
  1245. auto Gap =
  1246. findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
  1247. if (Gap)
  1248. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
  1249. extendRegion(E->getTrueExpr());
  1250. propagateCounts(TrueCount, E->getTrueExpr());
  1251. }
  1252. extendRegion(E->getFalseExpr());
  1253. propagateCounts(subtractCounters(ParentCount, TrueCount),
  1254. E->getFalseExpr());
  1255. // Create Branch Region around condition.
  1256. createBranchRegion(E->getCond(), TrueCount,
  1257. subtractCounters(ParentCount, TrueCount));
  1258. }
  1259. void VisitBinLAnd(const BinaryOperator *E) {
  1260. extendRegion(E->getLHS());
  1261. propagateCounts(getRegion().getCounter(), E->getLHS());
  1262. handleFileExit(getEnd(E->getLHS()));
  1263. // Counter tracks the right hand side of a logical and operator.
  1264. extendRegion(E->getRHS());
  1265. propagateCounts(getRegionCounter(E), E->getRHS());
  1266. // Extract the RHS's Execution Counter.
  1267. Counter RHSExecCnt = getRegionCounter(E);
  1268. // Extract the RHS's "True" Instance Counter.
  1269. Counter RHSTrueCnt = getRegionCounter(E->getRHS());
  1270. // Extract the Parent Region Counter.
  1271. Counter ParentCnt = getRegion().getCounter();
  1272. // Create Branch Region around LHS condition.
  1273. createBranchRegion(E->getLHS(), RHSExecCnt,
  1274. subtractCounters(ParentCnt, RHSExecCnt));
  1275. // Create Branch Region around RHS condition.
  1276. createBranchRegion(E->getRHS(), RHSTrueCnt,
  1277. subtractCounters(RHSExecCnt, RHSTrueCnt));
  1278. }
  1279. void VisitBinLOr(const BinaryOperator *E) {
  1280. extendRegion(E->getLHS());
  1281. propagateCounts(getRegion().getCounter(), E->getLHS());
  1282. handleFileExit(getEnd(E->getLHS()));
  1283. // Counter tracks the right hand side of a logical or operator.
  1284. extendRegion(E->getRHS());
  1285. propagateCounts(getRegionCounter(E), E->getRHS());
  1286. // Extract the RHS's Execution Counter.
  1287. Counter RHSExecCnt = getRegionCounter(E);
  1288. // Extract the RHS's "False" Instance Counter.
  1289. Counter RHSFalseCnt = getRegionCounter(E->getRHS());
  1290. // Extract the Parent Region Counter.
  1291. Counter ParentCnt = getRegion().getCounter();
  1292. // Create Branch Region around LHS condition.
  1293. createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
  1294. RHSExecCnt);
  1295. // Create Branch Region around RHS condition.
  1296. createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
  1297. RHSFalseCnt);
  1298. }
  1299. void VisitLambdaExpr(const LambdaExpr *LE) {
  1300. // Lambdas are treated as their own functions for now, so we shouldn't
  1301. // propagate counts into them.
  1302. }
  1303. };
  1304. } // end anonymous namespace
  1305. static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
  1306. ArrayRef<CounterExpression> Expressions,
  1307. ArrayRef<CounterMappingRegion> Regions) {
  1308. OS << FunctionName << ":\n";
  1309. CounterMappingContext Ctx(Expressions);
  1310. for (const auto &R : Regions) {
  1311. OS.indent(2);
  1312. switch (R.Kind) {
  1313. case CounterMappingRegion::CodeRegion:
  1314. break;
  1315. case CounterMappingRegion::ExpansionRegion:
  1316. OS << "Expansion,";
  1317. break;
  1318. case CounterMappingRegion::SkippedRegion:
  1319. OS << "Skipped,";
  1320. break;
  1321. case CounterMappingRegion::GapRegion:
  1322. OS << "Gap,";
  1323. break;
  1324. case CounterMappingRegion::BranchRegion:
  1325. OS << "Branch,";
  1326. break;
  1327. }
  1328. OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
  1329. << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
  1330. Ctx.dump(R.Count, OS);
  1331. if (R.Kind == CounterMappingRegion::BranchRegion) {
  1332. OS << ", ";
  1333. Ctx.dump(R.FalseCount, OS);
  1334. }
  1335. if (R.Kind == CounterMappingRegion::ExpansionRegion)
  1336. OS << " (Expanded file = " << R.ExpandedFileID << ")";
  1337. OS << "\n";
  1338. }
  1339. }
  1340. CoverageMappingModuleGen::CoverageMappingModuleGen(
  1341. CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
  1342. : CGM(CGM), SourceInfo(SourceInfo) {
  1343. CoveragePrefixMap = CGM.getCodeGenOpts().CoveragePrefixMap;
  1344. }
  1345. std::string CoverageMappingModuleGen::getCurrentDirname() {
  1346. if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
  1347. return CGM.getCodeGenOpts().CoverageCompilationDir;
  1348. SmallString<256> CWD;
  1349. llvm::sys::fs::current_path(CWD);
  1350. return CWD.str().str();
  1351. }
  1352. std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
  1353. llvm::SmallString<256> Path(Filename);
  1354. llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  1355. for (const auto &Entry : CoveragePrefixMap) {
  1356. if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
  1357. break;
  1358. }
  1359. return Path.str().str();
  1360. }
  1361. static std::string getInstrProfSection(const CodeGenModule &CGM,
  1362. llvm::InstrProfSectKind SK) {
  1363. return llvm::getInstrProfSectionName(
  1364. SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
  1365. }
  1366. void CoverageMappingModuleGen::emitFunctionMappingRecord(
  1367. const FunctionInfo &Info, uint64_t FilenamesRef) {
  1368. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1369. // Assign a name to the function record. This is used to merge duplicates.
  1370. std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
  1371. // A dummy description for a function included-but-not-used in a TU can be
  1372. // replaced by full description provided by a different TU. The two kinds of
  1373. // descriptions play distinct roles: therefore, assign them different names
  1374. // to prevent `linkonce_odr` merging.
  1375. if (Info.IsUsed)
  1376. FuncRecordName += "u";
  1377. // Create the function record type.
  1378. const uint64_t NameHash = Info.NameHash;
  1379. const uint64_t FuncHash = Info.FuncHash;
  1380. const std::string &CoverageMapping = Info.CoverageMapping;
  1381. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
  1382. llvm::Type *FunctionRecordTypes[] = {
  1383. #include "llvm/ProfileData/InstrProfData.inc"
  1384. };
  1385. auto *FunctionRecordTy =
  1386. llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes),
  1387. /*isPacked=*/true);
  1388. // Create the function record constant.
  1389. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
  1390. llvm::Constant *FunctionRecordVals[] = {
  1391. #include "llvm/ProfileData/InstrProfData.inc"
  1392. };
  1393. auto *FuncRecordConstant =
  1394. llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals));
  1395. // Create the function record global.
  1396. auto *FuncRecord = new llvm::GlobalVariable(
  1397. CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
  1398. llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
  1399. FuncRecordName);
  1400. FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1401. FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
  1402. FuncRecord->setAlignment(llvm::Align(8));
  1403. if (CGM.supportsCOMDAT())
  1404. FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
  1405. // Make sure the data doesn't get deleted.
  1406. CGM.addUsedGlobal(FuncRecord);
  1407. }
  1408. void CoverageMappingModuleGen::addFunctionMappingRecord(
  1409. llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
  1410. const std::string &CoverageMapping, bool IsUsed) {
  1411. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1412. const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
  1413. FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
  1414. if (!IsUsed)
  1415. FunctionNames.push_back(
  1416. llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
  1417. if (CGM.getCodeGenOpts().DumpCoverageMapping) {
  1418. // Dump the coverage mapping data for this function by decoding the
  1419. // encoded data. This allows us to dump the mapping regions which were
  1420. // also processed by the CoverageMappingWriter which performs
  1421. // additional minimization operations such as reducing the number of
  1422. // expressions.
  1423. llvm::SmallVector<std::string, 16> FilenameStrs;
  1424. std::vector<StringRef> Filenames;
  1425. std::vector<CounterExpression> Expressions;
  1426. std::vector<CounterMappingRegion> Regions;
  1427. FilenameStrs.resize(FileEntries.size() + 1);
  1428. FilenameStrs[0] = normalizeFilename(getCurrentDirname());
  1429. for (const auto &Entry : FileEntries) {
  1430. auto I = Entry.second;
  1431. FilenameStrs[I] = normalizeFilename(Entry.first->getName());
  1432. }
  1433. ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs);
  1434. RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
  1435. Expressions, Regions);
  1436. if (Reader.read())
  1437. return;
  1438. dump(llvm::outs(), NameValue, Expressions, Regions);
  1439. }
  1440. }
  1441. void CoverageMappingModuleGen::emit() {
  1442. if (FunctionRecords.empty())
  1443. return;
  1444. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1445. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  1446. // Create the filenames and merge them with coverage mappings
  1447. llvm::SmallVector<std::string, 16> FilenameStrs;
  1448. FilenameStrs.resize(FileEntries.size() + 1);
  1449. // The first filename is the current working directory.
  1450. FilenameStrs[0] = normalizeFilename(getCurrentDirname());
  1451. for (const auto &Entry : FileEntries) {
  1452. auto I = Entry.second;
  1453. FilenameStrs[I] = normalizeFilename(Entry.first->getName());
  1454. }
  1455. std::string Filenames;
  1456. {
  1457. llvm::raw_string_ostream OS(Filenames);
  1458. CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
  1459. }
  1460. auto *FilenamesVal =
  1461. llvm::ConstantDataArray::getString(Ctx, Filenames, false);
  1462. const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
  1463. // Emit the function records.
  1464. for (const FunctionInfo &Info : FunctionRecords)
  1465. emitFunctionMappingRecord(Info, FilenamesRef);
  1466. const unsigned NRecords = 0;
  1467. const size_t FilenamesSize = Filenames.size();
  1468. const unsigned CoverageMappingSize = 0;
  1469. llvm::Type *CovDataHeaderTypes[] = {
  1470. #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
  1471. #include "llvm/ProfileData/InstrProfData.inc"
  1472. };
  1473. auto CovDataHeaderTy =
  1474. llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes));
  1475. llvm::Constant *CovDataHeaderVals[] = {
  1476. #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
  1477. #include "llvm/ProfileData/InstrProfData.inc"
  1478. };
  1479. auto CovDataHeaderVal =
  1480. llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals));
  1481. // Create the coverage data record
  1482. llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
  1483. auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes));
  1484. llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
  1485. auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals));
  1486. auto CovData = new llvm::GlobalVariable(
  1487. CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
  1488. CovDataVal, llvm::getCoverageMappingVarName());
  1489. CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
  1490. CovData->setAlignment(llvm::Align(8));
  1491. // Make sure the data doesn't get deleted.
  1492. CGM.addUsedGlobal(CovData);
  1493. // Create the deferred function records array
  1494. if (!FunctionNames.empty()) {
  1495. auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
  1496. FunctionNames.size());
  1497. auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
  1498. // This variable will *NOT* be emitted to the object file. It is used
  1499. // to pass the list of names referenced to codegen.
  1500. new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
  1501. llvm::GlobalValue::InternalLinkage, NamesArrVal,
  1502. llvm::getCoverageUnusedNamesVarName());
  1503. }
  1504. }
  1505. unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
  1506. auto It = FileEntries.find(File);
  1507. if (It != FileEntries.end())
  1508. return It->second;
  1509. unsigned FileID = FileEntries.size() + 1;
  1510. FileEntries.insert(std::make_pair(File, FileID));
  1511. return FileID;
  1512. }
  1513. void CoverageMappingGen::emitCounterMapping(const Decl *D,
  1514. llvm::raw_ostream &OS) {
  1515. assert(CounterMap);
  1516. CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
  1517. Walker.VisitDecl(D);
  1518. Walker.write(OS);
  1519. }
  1520. void CoverageMappingGen::emitEmptyMapping(const Decl *D,
  1521. llvm::raw_ostream &OS) {
  1522. EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
  1523. Walker.VisitDecl(D);
  1524. Walker.write(OS);
  1525. }