CoverageMappingGen.cpp 43 KB

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