CoverageMappingGen.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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/Lex/Lexer.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  20. #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
  21. #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
  22. #include "llvm/ProfileData/InstrProfReader.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/Path.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. using namespace llvm::coverage;
  28. void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
  29. SkippedRanges.push_back(Range);
  30. }
  31. namespace {
  32. /// A region of source code that can be mapped to a counter.
  33. class SourceMappingRegion {
  34. Counter Count;
  35. /// The region's starting location.
  36. Optional<SourceLocation> LocStart;
  37. /// The region's ending location.
  38. Optional<SourceLocation> LocEnd;
  39. /// Whether this region should be emitted after its parent is emitted.
  40. bool DeferRegion;
  41. /// Whether this region is a gap region. The count from a gap region is set
  42. /// as the line execution count if there are no other regions on the line.
  43. bool GapRegion;
  44. public:
  45. SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
  46. Optional<SourceLocation> LocEnd, bool DeferRegion = false,
  47. bool GapRegion = false)
  48. : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
  49. DeferRegion(DeferRegion), GapRegion(GapRegion) {}
  50. const Counter &getCounter() const { return Count; }
  51. void setCounter(Counter C) { Count = C; }
  52. bool hasStartLoc() const { return LocStart.hasValue(); }
  53. void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
  54. SourceLocation getBeginLoc() const {
  55. assert(LocStart && "Region has no start location");
  56. return *LocStart;
  57. }
  58. bool hasEndLoc() const { return LocEnd.hasValue(); }
  59. void setEndLoc(SourceLocation Loc) {
  60. assert(Loc.isValid() && "Setting an invalid end location");
  61. LocEnd = Loc;
  62. }
  63. SourceLocation getEndLoc() const {
  64. assert(LocEnd && "Region has no end location");
  65. return *LocEnd;
  66. }
  67. bool isDeferred() const { return DeferRegion; }
  68. void setDeferred(bool Deferred) { DeferRegion = Deferred; }
  69. bool isGap() const { return GapRegion; }
  70. void setGap(bool Gap) { GapRegion = Gap; }
  71. };
  72. /// Spelling locations for the start and end of a source region.
  73. struct SpellingRegion {
  74. /// The line where the region starts.
  75. unsigned LineStart;
  76. /// The column where the region starts.
  77. unsigned ColumnStart;
  78. /// The line where the region ends.
  79. unsigned LineEnd;
  80. /// The column where the region ends.
  81. unsigned ColumnEnd;
  82. SpellingRegion(SourceManager &SM, SourceLocation LocStart,
  83. SourceLocation LocEnd) {
  84. LineStart = SM.getSpellingLineNumber(LocStart);
  85. ColumnStart = SM.getSpellingColumnNumber(LocStart);
  86. LineEnd = SM.getSpellingLineNumber(LocEnd);
  87. ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  88. }
  89. SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
  90. : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
  91. /// Check if the start and end locations appear in source order, i.e
  92. /// top->bottom, left->right.
  93. bool isInSourceOrder() const {
  94. return (LineStart < LineEnd) ||
  95. (LineStart == LineEnd && ColumnStart <= ColumnEnd);
  96. }
  97. };
  98. /// Provides the common functionality for the different
  99. /// coverage mapping region builders.
  100. class CoverageMappingBuilder {
  101. public:
  102. CoverageMappingModuleGen &CVM;
  103. SourceManager &SM;
  104. const LangOptions &LangOpts;
  105. private:
  106. /// Map of clang's FileIDs to IDs used for coverage mapping.
  107. llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
  108. FileIDMapping;
  109. public:
  110. /// The coverage mapping regions for this function
  111. llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
  112. /// The source mapping regions for this function.
  113. std::vector<SourceMappingRegion> SourceRegions;
  114. /// A set of regions which can be used as a filter.
  115. ///
  116. /// It is produced by emitExpansionRegions() and is used in
  117. /// emitSourceRegions() to suppress producing code regions if
  118. /// the same area is covered by expansion regions.
  119. typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
  120. SourceRegionFilter;
  121. CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  122. const LangOptions &LangOpts)
  123. : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
  124. /// Return the precise end location for the given token.
  125. SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
  126. // We avoid getLocForEndOfToken here, because it doesn't do what we want for
  127. // macro locations, which we just treat as expanded files.
  128. unsigned TokLen =
  129. Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
  130. return Loc.getLocWithOffset(TokLen);
  131. }
  132. /// Return the start location of an included file or expanded macro.
  133. SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
  134. if (Loc.isMacroID())
  135. return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
  136. return SM.getLocForStartOfFile(SM.getFileID(Loc));
  137. }
  138. /// Return the end location of an included file or expanded macro.
  139. SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
  140. if (Loc.isMacroID())
  141. return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
  142. SM.getFileOffset(Loc));
  143. return SM.getLocForEndOfFile(SM.getFileID(Loc));
  144. }
  145. /// Find out where the current file is included or macro is expanded.
  146. SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
  147. return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
  148. : SM.getIncludeLoc(SM.getFileID(Loc));
  149. }
  150. /// Return true if \c Loc is a location in a built-in macro.
  151. bool isInBuiltin(SourceLocation Loc) {
  152. return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
  153. }
  154. /// Check whether \c Loc is included or expanded from \c Parent.
  155. bool isNestedIn(SourceLocation Loc, FileID Parent) {
  156. do {
  157. Loc = getIncludeOrExpansionLoc(Loc);
  158. if (Loc.isInvalid())
  159. return false;
  160. } while (!SM.isInFileID(Loc, Parent));
  161. return true;
  162. }
  163. /// Get the start of \c S ignoring macro arguments and builtin macros.
  164. SourceLocation getStart(const Stmt *S) {
  165. SourceLocation Loc = S->getBeginLoc();
  166. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  167. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  168. return Loc;
  169. }
  170. /// Get the end of \c S ignoring macro arguments and builtin macros.
  171. SourceLocation getEnd(const Stmt *S) {
  172. SourceLocation Loc = S->getEndLoc();
  173. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  174. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  175. return getPreciseTokenLocEnd(Loc);
  176. }
  177. /// Find the set of files we have regions for and assign IDs
  178. ///
  179. /// Fills \c Mapping with the virtual file mapping needed to write out
  180. /// coverage and collects the necessary file information to emit source and
  181. /// expansion regions.
  182. void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
  183. FileIDMapping.clear();
  184. llvm::SmallSet<FileID, 8> Visited;
  185. SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
  186. for (const auto &Region : SourceRegions) {
  187. SourceLocation Loc = Region.getBeginLoc();
  188. FileID File = SM.getFileID(Loc);
  189. if (!Visited.insert(File).second)
  190. continue;
  191. // Do not map FileID's associated with system headers.
  192. if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
  193. continue;
  194. unsigned Depth = 0;
  195. for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
  196. Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
  197. ++Depth;
  198. FileLocs.push_back(std::make_pair(Loc, Depth));
  199. }
  200. llvm::stable_sort(FileLocs, llvm::less_second());
  201. for (const auto &FL : FileLocs) {
  202. SourceLocation Loc = FL.first;
  203. FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
  204. auto Entry = SM.getFileEntryForID(SpellingFile);
  205. if (!Entry)
  206. continue;
  207. FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
  208. Mapping.push_back(CVM.getFileID(Entry));
  209. }
  210. }
  211. /// Get the coverage mapping file ID for \c Loc.
  212. ///
  213. /// If such file id doesn't exist, return None.
  214. Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
  215. auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
  216. if (Mapping != FileIDMapping.end())
  217. return Mapping->second.first;
  218. return None;
  219. }
  220. /// Gather all the regions that were skipped by the preprocessor
  221. /// using the constructs like #if.
  222. void gatherSkippedRegions() {
  223. /// An array of the minimum lineStarts and the maximum lineEnds
  224. /// for mapping regions from the appropriate source files.
  225. llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
  226. FileLineRanges.resize(
  227. FileIDMapping.size(),
  228. std::make_pair(std::numeric_limits<unsigned>::max(), 0));
  229. for (const auto &R : MappingRegions) {
  230. FileLineRanges[R.FileID].first =
  231. std::min(FileLineRanges[R.FileID].first, R.LineStart);
  232. FileLineRanges[R.FileID].second =
  233. std::max(FileLineRanges[R.FileID].second, R.LineEnd);
  234. }
  235. auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
  236. for (const auto &I : SkippedRanges) {
  237. auto LocStart = I.getBegin();
  238. auto LocEnd = I.getEnd();
  239. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  240. "region spans multiple files");
  241. auto CovFileID = getCoverageFileID(LocStart);
  242. if (!CovFileID)
  243. continue;
  244. SpellingRegion SR{SM, LocStart, LocEnd};
  245. auto Region = CounterMappingRegion::makeSkipped(
  246. *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
  247. // Make sure that we only collect the regions that are inside
  248. // the source code of this function.
  249. if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
  250. Region.LineEnd <= FileLineRanges[*CovFileID].second)
  251. MappingRegions.push_back(Region);
  252. }
  253. }
  254. /// Generate the coverage counter mapping regions from collected
  255. /// source regions.
  256. void emitSourceRegions(const SourceRegionFilter &Filter) {
  257. for (const auto &Region : SourceRegions) {
  258. assert(Region.hasEndLoc() && "incomplete region");
  259. SourceLocation LocStart = Region.getBeginLoc();
  260. assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
  261. // Ignore regions from system headers.
  262. if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
  263. continue;
  264. auto CovFileID = getCoverageFileID(LocStart);
  265. // Ignore regions that don't have a file, such as builtin macros.
  266. if (!CovFileID)
  267. continue;
  268. SourceLocation LocEnd = Region.getEndLoc();
  269. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  270. "region spans multiple files");
  271. // Don't add code regions for the area covered by expansion regions.
  272. // This not only suppresses redundant regions, but sometimes prevents
  273. // creating regions with wrong counters if, for example, a statement's
  274. // body ends at the end of a nested macro.
  275. if (Filter.count(std::make_pair(LocStart, LocEnd)))
  276. continue;
  277. // Find the spelling locations for the mapping region.
  278. SpellingRegion SR{SM, LocStart, LocEnd};
  279. assert(SR.isInSourceOrder() && "region start and end out of order");
  280. if (Region.isGap()) {
  281. MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
  282. Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
  283. SR.LineEnd, SR.ColumnEnd));
  284. } else {
  285. MappingRegions.push_back(CounterMappingRegion::makeRegion(
  286. Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
  287. SR.LineEnd, SR.ColumnEnd));
  288. }
  289. }
  290. }
  291. /// Generate expansion regions for each virtual file we've seen.
  292. SourceRegionFilter emitExpansionRegions() {
  293. SourceRegionFilter Filter;
  294. for (const auto &FM : FileIDMapping) {
  295. SourceLocation ExpandedLoc = FM.second.second;
  296. SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
  297. if (ParentLoc.isInvalid())
  298. continue;
  299. auto ParentFileID = getCoverageFileID(ParentLoc);
  300. if (!ParentFileID)
  301. continue;
  302. auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
  303. assert(ExpandedFileID && "expansion in uncovered file");
  304. SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
  305. assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
  306. "region spans multiple files");
  307. Filter.insert(std::make_pair(ParentLoc, LocEnd));
  308. SpellingRegion SR{SM, ParentLoc, LocEnd};
  309. assert(SR.isInSourceOrder() && "region start and end out of order");
  310. MappingRegions.push_back(CounterMappingRegion::makeExpansion(
  311. *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
  312. SR.LineEnd, SR.ColumnEnd));
  313. }
  314. return Filter;
  315. }
  316. };
  317. /// Creates unreachable coverage regions for the functions that
  318. /// are not emitted.
  319. struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
  320. EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  321. const LangOptions &LangOpts)
  322. : CoverageMappingBuilder(CVM, SM, LangOpts) {}
  323. void VisitDecl(const Decl *D) {
  324. if (!D->hasBody())
  325. return;
  326. auto Body = D->getBody();
  327. SourceLocation Start = getStart(Body);
  328. SourceLocation End = getEnd(Body);
  329. if (!SM.isWrittenInSameFile(Start, End)) {
  330. // Walk up to find the common ancestor.
  331. // Correct the locations accordingly.
  332. FileID StartFileID = SM.getFileID(Start);
  333. FileID EndFileID = SM.getFileID(End);
  334. while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
  335. Start = getIncludeOrExpansionLoc(Start);
  336. assert(Start.isValid() &&
  337. "Declaration start location not nested within a known region");
  338. StartFileID = SM.getFileID(Start);
  339. }
  340. while (StartFileID != EndFileID) {
  341. End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
  342. assert(End.isValid() &&
  343. "Declaration end location not nested within a known region");
  344. EndFileID = SM.getFileID(End);
  345. }
  346. }
  347. SourceRegions.emplace_back(Counter(), Start, End);
  348. }
  349. /// Write the mapping data to the output stream
  350. void write(llvm::raw_ostream &OS) {
  351. SmallVector<unsigned, 16> FileIDMapping;
  352. gatherFileIDs(FileIDMapping);
  353. emitSourceRegions(SourceRegionFilter());
  354. if (MappingRegions.empty())
  355. return;
  356. CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
  357. Writer.write(OS);
  358. }
  359. };
  360. /// A StmtVisitor that creates coverage mapping regions which map
  361. /// from the source code locations to the PGO counters.
  362. struct CounterCoverageMappingBuilder
  363. : public CoverageMappingBuilder,
  364. public ConstStmtVisitor<CounterCoverageMappingBuilder> {
  365. /// The map of statements to count values.
  366. llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
  367. /// A stack of currently live regions.
  368. std::vector<SourceMappingRegion> RegionStack;
  369. /// The currently deferred region: its end location and count can be set once
  370. /// its parent has been popped from the region stack.
  371. Optional<SourceMappingRegion> DeferredRegion;
  372. CounterExpressionBuilder Builder;
  373. /// A location in the most recently visited file or macro.
  374. ///
  375. /// This is used to adjust the active source regions appropriately when
  376. /// expressions cross file or macro boundaries.
  377. SourceLocation MostRecentLocation;
  378. /// Location of the last terminated region.
  379. Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
  380. /// Return a counter for the subtraction of \c RHS from \c LHS
  381. Counter subtractCounters(Counter LHS, Counter RHS) {
  382. return Builder.subtract(LHS, RHS);
  383. }
  384. /// Return a counter for the sum of \c LHS and \c RHS.
  385. Counter addCounters(Counter LHS, Counter RHS) {
  386. return Builder.add(LHS, RHS);
  387. }
  388. Counter addCounters(Counter C1, Counter C2, Counter C3) {
  389. return addCounters(addCounters(C1, C2), C3);
  390. }
  391. /// Return the region counter for the given statement.
  392. ///
  393. /// This should only be called on statements that have a dedicated counter.
  394. Counter getRegionCounter(const Stmt *S) {
  395. return Counter::getCounter(CounterMap[S]);
  396. }
  397. /// Push a region onto the stack.
  398. ///
  399. /// Returns the index on the stack where the region was pushed. This can be
  400. /// used with popRegions to exit a "scope", ending the region that was pushed.
  401. size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
  402. Optional<SourceLocation> EndLoc = None) {
  403. if (StartLoc) {
  404. MostRecentLocation = *StartLoc;
  405. completeDeferred(Count, MostRecentLocation);
  406. }
  407. RegionStack.emplace_back(Count, StartLoc, EndLoc);
  408. return RegionStack.size() - 1;
  409. }
  410. /// Complete any pending deferred region by setting its end location and
  411. /// count, and then pushing it onto the region stack.
  412. size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
  413. size_t Index = RegionStack.size();
  414. if (!DeferredRegion)
  415. return Index;
  416. // Consume the pending region.
  417. SourceMappingRegion DR = DeferredRegion.getValue();
  418. DeferredRegion = None;
  419. // If the region ends in an expansion, find the expansion site.
  420. FileID StartFile = SM.getFileID(DR.getBeginLoc());
  421. if (SM.getFileID(DeferredEndLoc) != StartFile) {
  422. if (isNestedIn(DeferredEndLoc, StartFile)) {
  423. do {
  424. DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
  425. } while (StartFile != SM.getFileID(DeferredEndLoc));
  426. } else {
  427. return Index;
  428. }
  429. }
  430. // The parent of this deferred region ends where the containing decl ends,
  431. // so the region isn't useful.
  432. if (DR.getBeginLoc() == DeferredEndLoc)
  433. return Index;
  434. // If we're visiting statements in non-source order (e.g switch cases or
  435. // a loop condition) we can't construct a sensible deferred region.
  436. if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
  437. return Index;
  438. DR.setGap(true);
  439. DR.setCounter(Count);
  440. DR.setEndLoc(DeferredEndLoc);
  441. handleFileExit(DeferredEndLoc);
  442. RegionStack.push_back(DR);
  443. return Index;
  444. }
  445. /// Complete a deferred region created after a terminated region at the
  446. /// top-level.
  447. void completeTopLevelDeferredRegion(Counter Count,
  448. SourceLocation DeferredEndLoc) {
  449. if (DeferredRegion || !LastTerminatedRegion)
  450. return;
  451. if (LastTerminatedRegion->second != RegionStack.size())
  452. return;
  453. SourceLocation Start = LastTerminatedRegion->first;
  454. if (SM.getFileID(Start) != SM.getMainFileID())
  455. return;
  456. SourceMappingRegion DR = RegionStack.back();
  457. DR.setStartLoc(Start);
  458. DR.setDeferred(false);
  459. DeferredRegion = DR;
  460. completeDeferred(Count, DeferredEndLoc);
  461. }
  462. size_t locationDepth(SourceLocation Loc) {
  463. size_t Depth = 0;
  464. while (Loc.isValid()) {
  465. Loc = getIncludeOrExpansionLoc(Loc);
  466. Depth++;
  467. }
  468. return Depth;
  469. }
  470. /// Pop regions from the stack into the function's list of regions.
  471. ///
  472. /// Adds all regions from \c ParentIndex to the top of the stack to the
  473. /// function's \c SourceRegions.
  474. void popRegions(size_t ParentIndex) {
  475. assert(RegionStack.size() >= ParentIndex && "parent not in stack");
  476. bool ParentOfDeferredRegion = false;
  477. while (RegionStack.size() > ParentIndex) {
  478. SourceMappingRegion &Region = RegionStack.back();
  479. if (Region.hasStartLoc()) {
  480. SourceLocation StartLoc = Region.getBeginLoc();
  481. SourceLocation EndLoc = Region.hasEndLoc()
  482. ? Region.getEndLoc()
  483. : RegionStack[ParentIndex].getEndLoc();
  484. size_t StartDepth = locationDepth(StartLoc);
  485. size_t EndDepth = locationDepth(EndLoc);
  486. while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
  487. bool UnnestStart = StartDepth >= EndDepth;
  488. bool UnnestEnd = EndDepth >= StartDepth;
  489. if (UnnestEnd) {
  490. // The region ends in a nested file or macro expansion. Create a
  491. // separate region for each expansion.
  492. SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
  493. assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
  494. if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
  495. SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
  496. EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
  497. if (EndLoc.isInvalid())
  498. llvm::report_fatal_error("File exit not handled before popRegions");
  499. EndDepth--;
  500. }
  501. if (UnnestStart) {
  502. // The region begins in a nested file or macro expansion. Create a
  503. // separate region for each expansion.
  504. SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
  505. assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
  506. if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
  507. SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
  508. StartLoc = getIncludeOrExpansionLoc(StartLoc);
  509. if (StartLoc.isInvalid())
  510. llvm::report_fatal_error("File exit not handled before popRegions");
  511. StartDepth--;
  512. }
  513. }
  514. Region.setStartLoc(StartLoc);
  515. Region.setEndLoc(EndLoc);
  516. MostRecentLocation = EndLoc;
  517. // If this region happens to span an entire expansion, we need to make
  518. // sure we don't overlap the parent region with it.
  519. if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
  520. EndLoc == getEndOfFileOrMacro(EndLoc))
  521. MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
  522. assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
  523. assert(SpellingRegion(SM, Region).isInSourceOrder());
  524. SourceRegions.push_back(Region);
  525. if (ParentOfDeferredRegion) {
  526. ParentOfDeferredRegion = false;
  527. // If there's an existing deferred region, keep the old one, because
  528. // it means there are two consecutive returns (or a similar pattern).
  529. if (!DeferredRegion.hasValue() &&
  530. // File IDs aren't gathered within macro expansions, so it isn't
  531. // useful to try and create a deferred region inside of one.
  532. !EndLoc.isMacroID())
  533. DeferredRegion =
  534. SourceMappingRegion(Counter::getZero(), EndLoc, None);
  535. }
  536. } else if (Region.isDeferred()) {
  537. assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
  538. ParentOfDeferredRegion = true;
  539. }
  540. RegionStack.pop_back();
  541. // If the zero region pushed after the last terminated region no longer
  542. // exists, clear its cached information.
  543. if (LastTerminatedRegion &&
  544. RegionStack.size() < LastTerminatedRegion->second)
  545. LastTerminatedRegion = None;
  546. }
  547. assert(!ParentOfDeferredRegion && "Deferred region with no parent");
  548. }
  549. /// Return the currently active region.
  550. SourceMappingRegion &getRegion() {
  551. assert(!RegionStack.empty() && "statement has no region");
  552. return RegionStack.back();
  553. }
  554. /// Propagate counts through the children of \p S if \p VisitChildren is true.
  555. /// Otherwise, only emit a count for \p S itself.
  556. Counter propagateCounts(Counter TopCount, const Stmt *S,
  557. bool VisitChildren = true) {
  558. SourceLocation StartLoc = getStart(S);
  559. SourceLocation EndLoc = getEnd(S);
  560. size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
  561. if (VisitChildren)
  562. Visit(S);
  563. Counter ExitCount = getRegion().getCounter();
  564. popRegions(Index);
  565. // The statement may be spanned by an expansion. Make sure we handle a file
  566. // exit out of this expansion before moving to the next statement.
  567. if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
  568. MostRecentLocation = EndLoc;
  569. return ExitCount;
  570. }
  571. /// Check whether a region with bounds \c StartLoc and \c EndLoc
  572. /// is already added to \c SourceRegions.
  573. bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
  574. return SourceRegions.rend() !=
  575. std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
  576. [&](const SourceMappingRegion &Region) {
  577. return Region.getBeginLoc() == StartLoc &&
  578. Region.getEndLoc() == EndLoc;
  579. });
  580. }
  581. /// Adjust the most recently visited location to \c EndLoc.
  582. ///
  583. /// This should be used after visiting any statements in non-source order.
  584. void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
  585. MostRecentLocation = EndLoc;
  586. // The code region for a whole macro is created in handleFileExit() when
  587. // it detects exiting of the virtual file of that macro. If we visited
  588. // statements in non-source order, we might already have such a region
  589. // added, for example, if a body of a loop is divided among multiple
  590. // macros. Avoid adding duplicate regions in such case.
  591. if (getRegion().hasEndLoc() &&
  592. MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
  593. isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
  594. MostRecentLocation))
  595. MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
  596. }
  597. /// Adjust regions and state when \c NewLoc exits a file.
  598. ///
  599. /// If moving from our most recently tracked location to \c NewLoc exits any
  600. /// files, this adjusts our current region stack and creates the file regions
  601. /// for the exited file.
  602. void handleFileExit(SourceLocation NewLoc) {
  603. if (NewLoc.isInvalid() ||
  604. SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
  605. return;
  606. // If NewLoc is not in a file that contains MostRecentLocation, walk up to
  607. // find the common ancestor.
  608. SourceLocation LCA = NewLoc;
  609. FileID ParentFile = SM.getFileID(LCA);
  610. while (!isNestedIn(MostRecentLocation, ParentFile)) {
  611. LCA = getIncludeOrExpansionLoc(LCA);
  612. if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
  613. // Since there isn't a common ancestor, no file was exited. We just need
  614. // to adjust our location to the new file.
  615. MostRecentLocation = NewLoc;
  616. return;
  617. }
  618. ParentFile = SM.getFileID(LCA);
  619. }
  620. llvm::SmallSet<SourceLocation, 8> StartLocs;
  621. Optional<Counter> ParentCounter;
  622. for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
  623. if (!I.hasStartLoc())
  624. continue;
  625. SourceLocation Loc = I.getBeginLoc();
  626. if (!isNestedIn(Loc, ParentFile)) {
  627. ParentCounter = I.getCounter();
  628. break;
  629. }
  630. while (!SM.isInFileID(Loc, ParentFile)) {
  631. // The most nested region for each start location is the one with the
  632. // correct count. We avoid creating redundant regions by stopping once
  633. // we've seen this region.
  634. if (StartLocs.insert(Loc).second)
  635. SourceRegions.emplace_back(I.getCounter(), Loc,
  636. getEndOfFileOrMacro(Loc));
  637. Loc = getIncludeOrExpansionLoc(Loc);
  638. }
  639. I.setStartLoc(getPreciseTokenLocEnd(Loc));
  640. }
  641. if (ParentCounter) {
  642. // If the file is contained completely by another region and doesn't
  643. // immediately start its own region, the whole file gets a region
  644. // corresponding to the parent.
  645. SourceLocation Loc = MostRecentLocation;
  646. while (isNestedIn(Loc, ParentFile)) {
  647. SourceLocation FileStart = getStartOfFileOrMacro(Loc);
  648. if (StartLocs.insert(FileStart).second) {
  649. SourceRegions.emplace_back(*ParentCounter, FileStart,
  650. getEndOfFileOrMacro(Loc));
  651. assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
  652. }
  653. Loc = getIncludeOrExpansionLoc(Loc);
  654. }
  655. }
  656. MostRecentLocation = NewLoc;
  657. }
  658. /// Ensure that \c S is included in the current region.
  659. void extendRegion(const Stmt *S) {
  660. SourceMappingRegion &Region = getRegion();
  661. SourceLocation StartLoc = getStart(S);
  662. handleFileExit(StartLoc);
  663. if (!Region.hasStartLoc())
  664. Region.setStartLoc(StartLoc);
  665. completeDeferred(Region.getCounter(), StartLoc);
  666. }
  667. /// Mark \c S as a terminator, starting a zero region.
  668. void terminateRegion(const Stmt *S) {
  669. extendRegion(S);
  670. SourceMappingRegion &Region = getRegion();
  671. SourceLocation EndLoc = getEnd(S);
  672. if (!Region.hasEndLoc())
  673. Region.setEndLoc(EndLoc);
  674. pushRegion(Counter::getZero());
  675. auto &ZeroRegion = getRegion();
  676. ZeroRegion.setDeferred(true);
  677. LastTerminatedRegion = {EndLoc, RegionStack.size()};
  678. }
  679. /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
  680. Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
  681. SourceLocation BeforeLoc) {
  682. // If the start and end locations of the gap are both within the same macro
  683. // file, the range may not be in source order.
  684. if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
  685. return None;
  686. if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
  687. return None;
  688. return {{AfterLoc, BeforeLoc}};
  689. }
  690. /// Find the source range after \p AfterStmt and before \p BeforeStmt.
  691. Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
  692. const Stmt *BeforeStmt) {
  693. return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
  694. getStart(BeforeStmt));
  695. }
  696. /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
  697. void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
  698. Counter Count) {
  699. if (StartLoc == EndLoc)
  700. return;
  701. assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
  702. handleFileExit(StartLoc);
  703. size_t Index = pushRegion(Count, StartLoc, EndLoc);
  704. getRegion().setGap(true);
  705. handleFileExit(EndLoc);
  706. popRegions(Index);
  707. }
  708. /// Keep counts of breaks and continues inside loops.
  709. struct BreakContinue {
  710. Counter BreakCount;
  711. Counter ContinueCount;
  712. };
  713. SmallVector<BreakContinue, 8> BreakContinueStack;
  714. CounterCoverageMappingBuilder(
  715. CoverageMappingModuleGen &CVM,
  716. llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
  717. const LangOptions &LangOpts)
  718. : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
  719. DeferredRegion(None) {}
  720. /// Write the mapping data to the output stream
  721. void write(llvm::raw_ostream &OS) {
  722. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  723. gatherFileIDs(VirtualFileMapping);
  724. SourceRegionFilter Filter = emitExpansionRegions();
  725. assert(!DeferredRegion && "Deferred region never completed");
  726. emitSourceRegions(Filter);
  727. gatherSkippedRegions();
  728. if (MappingRegions.empty())
  729. return;
  730. CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
  731. MappingRegions);
  732. Writer.write(OS);
  733. }
  734. void VisitStmt(const Stmt *S) {
  735. if (S->getBeginLoc().isValid())
  736. extendRegion(S);
  737. for (const Stmt *Child : S->children())
  738. if (Child)
  739. this->Visit(Child);
  740. handleFileExit(getEnd(S));
  741. }
  742. void VisitDecl(const Decl *D) {
  743. assert(!DeferredRegion && "Deferred region never completed");
  744. Stmt *Body = D->getBody();
  745. // Do not propagate region counts into system headers.
  746. if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
  747. return;
  748. // Do not visit the artificial children nodes of defaulted methods. The
  749. // lexer may not be able to report back precise token end locations for
  750. // these children nodes (llvm.org/PR39822), and moreover users will not be
  751. // able to see coverage for them.
  752. bool Defaulted = false;
  753. if (auto *Method = dyn_cast<CXXMethodDecl>(D))
  754. Defaulted = Method->isDefaulted();
  755. propagateCounts(getRegionCounter(Body), Body,
  756. /*VisitChildren=*/!Defaulted);
  757. assert(RegionStack.empty() && "Regions entered but never exited");
  758. // Discard the last uncompleted deferred region in a decl, if one exists.
  759. // This prevents lines at the end of a function containing only whitespace
  760. // or closing braces from being marked as uncovered.
  761. DeferredRegion = None;
  762. }
  763. void VisitReturnStmt(const ReturnStmt *S) {
  764. extendRegion(S);
  765. if (S->getRetValue())
  766. Visit(S->getRetValue());
  767. terminateRegion(S);
  768. }
  769. void VisitCXXThrowExpr(const CXXThrowExpr *E) {
  770. extendRegion(E);
  771. if (E->getSubExpr())
  772. Visit(E->getSubExpr());
  773. terminateRegion(E);
  774. }
  775. void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
  776. void VisitLabelStmt(const LabelStmt *S) {
  777. Counter LabelCount = getRegionCounter(S);
  778. SourceLocation Start = getStart(S);
  779. completeTopLevelDeferredRegion(LabelCount, Start);
  780. completeDeferred(LabelCount, Start);
  781. // We can't extendRegion here or we risk overlapping with our new region.
  782. handleFileExit(Start);
  783. pushRegion(LabelCount, Start);
  784. Visit(S->getSubStmt());
  785. }
  786. void VisitBreakStmt(const BreakStmt *S) {
  787. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  788. BreakContinueStack.back().BreakCount = addCounters(
  789. BreakContinueStack.back().BreakCount, getRegion().getCounter());
  790. // FIXME: a break in a switch should terminate regions for all preceding
  791. // case statements, not just the most recent one.
  792. terminateRegion(S);
  793. }
  794. void VisitContinueStmt(const ContinueStmt *S) {
  795. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  796. BreakContinueStack.back().ContinueCount = addCounters(
  797. BreakContinueStack.back().ContinueCount, getRegion().getCounter());
  798. terminateRegion(S);
  799. }
  800. void VisitCallExpr(const CallExpr *E) {
  801. VisitStmt(E);
  802. // Terminate the region when we hit a noreturn function.
  803. // (This is helpful dealing with switch statements.)
  804. QualType CalleeType = E->getCallee()->getType();
  805. if (getFunctionExtInfo(*CalleeType).getNoReturn())
  806. terminateRegion(E);
  807. }
  808. void VisitWhileStmt(const WhileStmt *S) {
  809. extendRegion(S);
  810. Counter ParentCount = getRegion().getCounter();
  811. Counter BodyCount = getRegionCounter(S);
  812. // Handle the body first so that we can get the backedge count.
  813. BreakContinueStack.push_back(BreakContinue());
  814. extendRegion(S->getBody());
  815. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  816. BreakContinue BC = BreakContinueStack.pop_back_val();
  817. // Go back to handle the condition.
  818. Counter CondCount =
  819. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  820. propagateCounts(CondCount, S->getCond());
  821. adjustForOutOfOrderTraversal(getEnd(S));
  822. // The body count applies to the area immediately after the increment.
  823. auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
  824. if (Gap)
  825. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  826. Counter OutCount =
  827. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  828. if (OutCount != ParentCount)
  829. pushRegion(OutCount);
  830. }
  831. void VisitDoStmt(const DoStmt *S) {
  832. extendRegion(S);
  833. Counter ParentCount = getRegion().getCounter();
  834. Counter BodyCount = getRegionCounter(S);
  835. BreakContinueStack.push_back(BreakContinue());
  836. extendRegion(S->getBody());
  837. Counter BackedgeCount =
  838. propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
  839. BreakContinue BC = BreakContinueStack.pop_back_val();
  840. Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
  841. propagateCounts(CondCount, S->getCond());
  842. Counter OutCount =
  843. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  844. if (OutCount != ParentCount)
  845. pushRegion(OutCount);
  846. }
  847. void VisitForStmt(const ForStmt *S) {
  848. extendRegion(S);
  849. if (S->getInit())
  850. Visit(S->getInit());
  851. Counter ParentCount = getRegion().getCounter();
  852. Counter BodyCount = getRegionCounter(S);
  853. // The loop increment may contain a break or continue.
  854. if (S->getInc())
  855. BreakContinueStack.emplace_back();
  856. // Handle the body first so that we can get the backedge count.
  857. BreakContinueStack.emplace_back();
  858. extendRegion(S->getBody());
  859. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  860. BreakContinue BodyBC = BreakContinueStack.pop_back_val();
  861. // The increment is essentially part of the body but it needs to include
  862. // the count for all the continue statements.
  863. BreakContinue IncrementBC;
  864. if (const Stmt *Inc = S->getInc()) {
  865. propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
  866. IncrementBC = BreakContinueStack.pop_back_val();
  867. }
  868. // Go back to handle the condition.
  869. Counter CondCount = addCounters(
  870. addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
  871. IncrementBC.ContinueCount);
  872. if (const Expr *Cond = S->getCond()) {
  873. propagateCounts(CondCount, Cond);
  874. adjustForOutOfOrderTraversal(getEnd(S));
  875. }
  876. // The body count applies to the area immediately after the increment.
  877. auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
  878. getStart(S->getBody()));
  879. if (Gap)
  880. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  881. Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
  882. subtractCounters(CondCount, BodyCount));
  883. if (OutCount != ParentCount)
  884. pushRegion(OutCount);
  885. }
  886. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  887. extendRegion(S);
  888. if (S->getInit())
  889. Visit(S->getInit());
  890. Visit(S->getLoopVarStmt());
  891. Visit(S->getRangeStmt());
  892. Counter ParentCount = getRegion().getCounter();
  893. Counter BodyCount = getRegionCounter(S);
  894. BreakContinueStack.push_back(BreakContinue());
  895. extendRegion(S->getBody());
  896. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  897. BreakContinue BC = BreakContinueStack.pop_back_val();
  898. // The body count applies to the area immediately after the range.
  899. auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
  900. getStart(S->getBody()));
  901. if (Gap)
  902. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  903. Counter LoopCount =
  904. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  905. Counter OutCount =
  906. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  907. if (OutCount != ParentCount)
  908. pushRegion(OutCount);
  909. }
  910. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  911. extendRegion(S);
  912. Visit(S->getElement());
  913. Counter ParentCount = getRegion().getCounter();
  914. Counter BodyCount = getRegionCounter(S);
  915. BreakContinueStack.push_back(BreakContinue());
  916. extendRegion(S->getBody());
  917. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  918. BreakContinue BC = BreakContinueStack.pop_back_val();
  919. // The body count applies to the area immediately after the collection.
  920. auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
  921. getStart(S->getBody()));
  922. if (Gap)
  923. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
  924. Counter LoopCount =
  925. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  926. Counter OutCount =
  927. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  928. if (OutCount != ParentCount)
  929. pushRegion(OutCount);
  930. }
  931. void VisitSwitchStmt(const SwitchStmt *S) {
  932. extendRegion(S);
  933. if (S->getInit())
  934. Visit(S->getInit());
  935. Visit(S->getCond());
  936. BreakContinueStack.push_back(BreakContinue());
  937. const Stmt *Body = S->getBody();
  938. extendRegion(Body);
  939. if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
  940. if (!CS->body_empty()) {
  941. // Make a region for the body of the switch. If the body starts with
  942. // a case, that case will reuse this region; otherwise, this covers
  943. // the unreachable code at the beginning of the switch body.
  944. size_t Index =
  945. pushRegion(Counter::getZero(), getStart(CS->body_front()));
  946. for (const auto *Child : CS->children())
  947. Visit(Child);
  948. // Set the end for the body of the switch, if it isn't already set.
  949. for (size_t i = RegionStack.size(); i != Index; --i) {
  950. if (!RegionStack[i - 1].hasEndLoc())
  951. RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
  952. }
  953. popRegions(Index);
  954. }
  955. } else
  956. propagateCounts(Counter::getZero(), Body);
  957. BreakContinue BC = BreakContinueStack.pop_back_val();
  958. if (!BreakContinueStack.empty())
  959. BreakContinueStack.back().ContinueCount = addCounters(
  960. BreakContinueStack.back().ContinueCount, BC.ContinueCount);
  961. Counter ExitCount = getRegionCounter(S);
  962. SourceLocation ExitLoc = getEnd(S);
  963. pushRegion(ExitCount);
  964. // Ensure that handleFileExit recognizes when the end location is located
  965. // in a different file.
  966. MostRecentLocation = getStart(S);
  967. handleFileExit(ExitLoc);
  968. }
  969. void VisitSwitchCase(const SwitchCase *S) {
  970. extendRegion(S);
  971. SourceMappingRegion &Parent = getRegion();
  972. Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
  973. // Reuse the existing region if it starts at our label. This is typical of
  974. // the first case in a switch.
  975. if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
  976. Parent.setCounter(Count);
  977. else
  978. pushRegion(Count, getStart(S));
  979. if (const auto *CS = dyn_cast<CaseStmt>(S)) {
  980. Visit(CS->getLHS());
  981. if (const Expr *RHS = CS->getRHS())
  982. Visit(RHS);
  983. }
  984. Visit(S->getSubStmt());
  985. }
  986. void VisitIfStmt(const IfStmt *S) {
  987. extendRegion(S);
  988. if (S->getInit())
  989. Visit(S->getInit());
  990. // Extend into the condition before we propagate through it below - this is
  991. // needed to handle macros that generate the "if" but not the condition.
  992. extendRegion(S->getCond());
  993. Counter ParentCount = getRegion().getCounter();
  994. Counter ThenCount = getRegionCounter(S);
  995. // Emitting a counter for the condition makes it easier to interpret the
  996. // counter for the body when looking at the coverage.
  997. propagateCounts(ParentCount, S->getCond());
  998. // The 'then' count applies to the area immediately after the condition.
  999. auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
  1000. if (Gap)
  1001. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
  1002. extendRegion(S->getThen());
  1003. Counter OutCount = propagateCounts(ThenCount, S->getThen());
  1004. Counter ElseCount = subtractCounters(ParentCount, ThenCount);
  1005. if (const Stmt *Else = S->getElse()) {
  1006. // The 'else' count applies to the area immediately after the 'then'.
  1007. Gap = findGapAreaBetween(S->getThen(), Else);
  1008. if (Gap)
  1009. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
  1010. extendRegion(Else);
  1011. OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
  1012. } else
  1013. OutCount = addCounters(OutCount, ElseCount);
  1014. if (OutCount != ParentCount)
  1015. pushRegion(OutCount);
  1016. }
  1017. void VisitCXXTryStmt(const CXXTryStmt *S) {
  1018. extendRegion(S);
  1019. // Handle macros that generate the "try" but not the rest.
  1020. extendRegion(S->getTryBlock());
  1021. Counter ParentCount = getRegion().getCounter();
  1022. propagateCounts(ParentCount, S->getTryBlock());
  1023. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  1024. Visit(S->getHandler(I));
  1025. Counter ExitCount = getRegionCounter(S);
  1026. pushRegion(ExitCount);
  1027. }
  1028. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  1029. propagateCounts(getRegionCounter(S), S->getHandlerBlock());
  1030. }
  1031. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  1032. extendRegion(E);
  1033. Counter ParentCount = getRegion().getCounter();
  1034. Counter TrueCount = getRegionCounter(E);
  1035. Visit(E->getCond());
  1036. if (!isa<BinaryConditionalOperator>(E)) {
  1037. // The 'then' count applies to the area immediately after the condition.
  1038. auto Gap =
  1039. findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
  1040. if (Gap)
  1041. fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
  1042. extendRegion(E->getTrueExpr());
  1043. propagateCounts(TrueCount, E->getTrueExpr());
  1044. }
  1045. extendRegion(E->getFalseExpr());
  1046. propagateCounts(subtractCounters(ParentCount, TrueCount),
  1047. E->getFalseExpr());
  1048. }
  1049. void VisitBinLAnd(const BinaryOperator *E) {
  1050. extendRegion(E->getLHS());
  1051. propagateCounts(getRegion().getCounter(), E->getLHS());
  1052. handleFileExit(getEnd(E->getLHS()));
  1053. extendRegion(E->getRHS());
  1054. propagateCounts(getRegionCounter(E), E->getRHS());
  1055. }
  1056. void VisitBinLOr(const BinaryOperator *E) {
  1057. extendRegion(E->getLHS());
  1058. propagateCounts(getRegion().getCounter(), E->getLHS());
  1059. handleFileExit(getEnd(E->getLHS()));
  1060. extendRegion(E->getRHS());
  1061. propagateCounts(getRegionCounter(E), E->getRHS());
  1062. }
  1063. void VisitLambdaExpr(const LambdaExpr *LE) {
  1064. // Lambdas are treated as their own functions for now, so we shouldn't
  1065. // propagate counts into them.
  1066. }
  1067. };
  1068. std::string getCoverageSection(const CodeGenModule &CGM) {
  1069. return llvm::getInstrProfSectionName(
  1070. llvm::IPSK_covmap,
  1071. CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
  1072. }
  1073. } // end anonymous namespace
  1074. static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
  1075. ArrayRef<CounterExpression> Expressions,
  1076. ArrayRef<CounterMappingRegion> Regions) {
  1077. OS << FunctionName << ":\n";
  1078. CounterMappingContext Ctx(Expressions);
  1079. for (const auto &R : Regions) {
  1080. OS.indent(2);
  1081. switch (R.Kind) {
  1082. case CounterMappingRegion::CodeRegion:
  1083. break;
  1084. case CounterMappingRegion::ExpansionRegion:
  1085. OS << "Expansion,";
  1086. break;
  1087. case CounterMappingRegion::SkippedRegion:
  1088. OS << "Skipped,";
  1089. break;
  1090. case CounterMappingRegion::GapRegion:
  1091. OS << "Gap,";
  1092. break;
  1093. }
  1094. OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
  1095. << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
  1096. Ctx.dump(R.Count, OS);
  1097. if (R.Kind == CounterMappingRegion::ExpansionRegion)
  1098. OS << " (Expanded file = " << R.ExpandedFileID << ")";
  1099. OS << "\n";
  1100. }
  1101. }
  1102. CoverageMappingModuleGen::CoverageMappingModuleGen(
  1103. CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
  1104. : CGM(CGM), SourceInfo(SourceInfo), FunctionRecordTy(nullptr) {
  1105. // Honor -fdebug-compilation-dir in paths in coverage data. Otherwise, use the
  1106. // regular working directory when normalizing paths.
  1107. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  1108. CWD = CGM.getCodeGenOpts().DebugCompilationDir;
  1109. else
  1110. llvm::sys::fs::current_path(CWD);
  1111. }
  1112. std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
  1113. llvm::SmallString<256> Path(Filename);
  1114. llvm::sys::fs::make_absolute(CWD, Path);
  1115. llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  1116. return Path.str().str();
  1117. }
  1118. void CoverageMappingModuleGen::addFunctionMappingRecord(
  1119. llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
  1120. const std::string &CoverageMapping, bool IsUsed) {
  1121. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1122. if (!FunctionRecordTy) {
  1123. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
  1124. llvm::Type *FunctionRecordTypes[] = {
  1125. #include "llvm/ProfileData/InstrProfData.inc"
  1126. };
  1127. FunctionRecordTy =
  1128. llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
  1129. /*isPacked=*/true);
  1130. }
  1131. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
  1132. llvm::Constant *FunctionRecordVals[] = {
  1133. #include "llvm/ProfileData/InstrProfData.inc"
  1134. };
  1135. FunctionRecords.push_back(llvm::ConstantStruct::get(
  1136. FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
  1137. if (!IsUsed)
  1138. FunctionNames.push_back(
  1139. llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
  1140. CoverageMappings.push_back(CoverageMapping);
  1141. if (CGM.getCodeGenOpts().DumpCoverageMapping) {
  1142. // Dump the coverage mapping data for this function by decoding the
  1143. // encoded data. This allows us to dump the mapping regions which were
  1144. // also processed by the CoverageMappingWriter which performs
  1145. // additional minimization operations such as reducing the number of
  1146. // expressions.
  1147. std::vector<StringRef> Filenames;
  1148. std::vector<CounterExpression> Expressions;
  1149. std::vector<CounterMappingRegion> Regions;
  1150. llvm::SmallVector<std::string, 16> FilenameStrs;
  1151. llvm::SmallVector<StringRef, 16> FilenameRefs;
  1152. FilenameStrs.resize(FileEntries.size());
  1153. FilenameRefs.resize(FileEntries.size());
  1154. for (const auto &Entry : FileEntries) {
  1155. auto I = Entry.second;
  1156. FilenameStrs[I] = normalizeFilename(Entry.first->getName());
  1157. FilenameRefs[I] = FilenameStrs[I];
  1158. }
  1159. RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
  1160. Expressions, Regions);
  1161. if (Reader.read())
  1162. return;
  1163. dump(llvm::outs(), NameValue, Expressions, Regions);
  1164. }
  1165. }
  1166. void CoverageMappingModuleGen::emit() {
  1167. if (FunctionRecords.empty())
  1168. return;
  1169. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1170. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  1171. // Create the filenames and merge them with coverage mappings
  1172. llvm::SmallVector<std::string, 16> FilenameStrs;
  1173. llvm::SmallVector<StringRef, 16> FilenameRefs;
  1174. FilenameStrs.resize(FileEntries.size());
  1175. FilenameRefs.resize(FileEntries.size());
  1176. for (const auto &Entry : FileEntries) {
  1177. auto I = Entry.second;
  1178. FilenameStrs[I] = normalizeFilename(Entry.first->getName());
  1179. FilenameRefs[I] = FilenameStrs[I];
  1180. }
  1181. std::string FilenamesAndCoverageMappings;
  1182. llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
  1183. CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
  1184. // Stream the content of CoverageMappings to OS while keeping
  1185. // memory consumption under control.
  1186. size_t CoverageMappingSize = 0;
  1187. for (auto &S : CoverageMappings) {
  1188. CoverageMappingSize += S.size();
  1189. OS << S;
  1190. S.clear();
  1191. S.shrink_to_fit();
  1192. }
  1193. CoverageMappings.clear();
  1194. CoverageMappings.shrink_to_fit();
  1195. size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
  1196. // Append extra zeroes if necessary to ensure that the size of the filenames
  1197. // and coverage mappings is a multiple of 8.
  1198. if (size_t Rem = OS.str().size() % 8) {
  1199. CoverageMappingSize += 8 - Rem;
  1200. OS.write_zeros(8 - Rem);
  1201. }
  1202. auto *FilenamesAndMappingsVal =
  1203. llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
  1204. // Create the deferred function records array
  1205. auto RecordsTy =
  1206. llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
  1207. auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
  1208. llvm::Type *CovDataHeaderTypes[] = {
  1209. #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
  1210. #include "llvm/ProfileData/InstrProfData.inc"
  1211. };
  1212. auto CovDataHeaderTy =
  1213. llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
  1214. llvm::Constant *CovDataHeaderVals[] = {
  1215. #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
  1216. #include "llvm/ProfileData/InstrProfData.inc"
  1217. };
  1218. auto CovDataHeaderVal = llvm::ConstantStruct::get(
  1219. CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
  1220. // Create the coverage data record
  1221. llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
  1222. FilenamesAndMappingsVal->getType()};
  1223. auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
  1224. llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
  1225. FilenamesAndMappingsVal};
  1226. auto CovDataVal =
  1227. llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
  1228. auto CovData = new llvm::GlobalVariable(
  1229. CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
  1230. CovDataVal, llvm::getCoverageMappingVarName());
  1231. CovData->setSection(getCoverageSection(CGM));
  1232. CovData->setAlignment(llvm::Align(8));
  1233. // Make sure the data doesn't get deleted.
  1234. CGM.addUsedGlobal(CovData);
  1235. // Create the deferred function records array
  1236. if (!FunctionNames.empty()) {
  1237. auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
  1238. FunctionNames.size());
  1239. auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
  1240. // This variable will *NOT* be emitted to the object file. It is used
  1241. // to pass the list of names referenced to codegen.
  1242. new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
  1243. llvm::GlobalValue::InternalLinkage, NamesArrVal,
  1244. llvm::getCoverageUnusedNamesVarName());
  1245. }
  1246. }
  1247. unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
  1248. auto It = FileEntries.find(File);
  1249. if (It != FileEntries.end())
  1250. return It->second;
  1251. unsigned FileID = FileEntries.size();
  1252. FileEntries.insert(std::make_pair(File, FileID));
  1253. return FileID;
  1254. }
  1255. void CoverageMappingGen::emitCounterMapping(const Decl *D,
  1256. llvm::raw_ostream &OS) {
  1257. assert(CounterMap);
  1258. CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
  1259. Walker.VisitDecl(D);
  1260. Walker.write(OS);
  1261. }
  1262. void CoverageMappingGen::emitEmptyMapping(const Decl *D,
  1263. llvm::raw_ostream &OS) {
  1264. EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
  1265. Walker.VisitDecl(D);
  1266. Walker.write(OS);
  1267. }