CoverageMappingGen.cpp 41 KB

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