CoverageMappingGen.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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/ProfileData/InstrProfReader.h"
  18. #include "llvm/ProfileData/CoverageMapping.h"
  19. #include "llvm/ProfileData/CoverageMappingWriter.h"
  20. #include "llvm/ProfileData/CoverageMappingReader.h"
  21. #include "llvm/Support/FileSystem.h"
  22. using namespace clang;
  23. using namespace CodeGen;
  24. using namespace llvm::coverage;
  25. void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
  26. SkippedRanges.push_back(Range);
  27. }
  28. namespace {
  29. /// \brief A region of source code that can be mapped to a counter.
  30. class SourceMappingRegion {
  31. public:
  32. enum RegionFlags {
  33. /// \brief This region won't be emitted if it wasn't extended.
  34. /// This is useful so that we won't emit source ranges for single tokens
  35. /// that we don't really care that much about, like:
  36. /// the '(' token in #define MACRO (
  37. IgnoreIfNotExtended = 0x0001,
  38. };
  39. private:
  40. FileID File, MacroArgumentFile;
  41. Counter Count;
  42. /// \brief A statement that initiated the count of Zero.
  43. ///
  44. /// This initiator statement is useful to prevent merging of unreachable
  45. /// regions with different statements that caused the counter to become
  46. /// unreachable.
  47. const Stmt *UnreachableInitiator;
  48. /// \brief A statement that separates certain mapping regions into groups.
  49. ///
  50. /// The group statement is sometimes useful when we are emitting the source
  51. /// regions not in their correct lexical order, e.g. the regions for the
  52. /// incrementation expression in the 'for' construct. By marking the regions
  53. /// in the incrementation expression with the group statement, we avoid the
  54. /// merging of the regions from the incrementation expression and the loop's
  55. /// body.
  56. const Stmt *Group;
  57. /// \brief The region's starting location.
  58. SourceLocation LocStart;
  59. /// \brief The region's ending location.
  60. SourceLocation LocEnd, AlternativeLocEnd;
  61. unsigned Flags;
  62. public:
  63. SourceMappingRegion(FileID File, FileID MacroArgumentFile, Counter Count,
  64. const Stmt *UnreachableInitiator, const Stmt *Group,
  65. SourceLocation LocStart, SourceLocation LocEnd,
  66. unsigned Flags = 0)
  67. : File(File), MacroArgumentFile(MacroArgumentFile), Count(Count),
  68. UnreachableInitiator(UnreachableInitiator), Group(Group),
  69. LocStart(LocStart), LocEnd(LocEnd), AlternativeLocEnd(LocStart),
  70. Flags(Flags) {}
  71. const FileID &getFile() const { return File; }
  72. const Counter &getCounter() const { return Count; }
  73. const SourceLocation &getStartLoc() const { return LocStart; }
  74. const SourceLocation &getEndLoc(const SourceManager &SM) const {
  75. if (SM.getFileID(LocEnd) != File)
  76. return AlternativeLocEnd;
  77. return LocEnd;
  78. }
  79. bool hasFlag(RegionFlags Flag) const { return (Flags & Flag) != 0; }
  80. void setFlag(RegionFlags Flag) { Flags |= Flag; }
  81. void clearFlag(RegionFlags Flag) { Flags &= ~Flag; }
  82. /// \brief Return true if two regions can be merged together.
  83. bool isMergeable(SourceMappingRegion &R) {
  84. // FIXME: We allow merging regions with a gap in between them. Should we?
  85. return File == R.File && MacroArgumentFile == R.MacroArgumentFile &&
  86. Count == R.Count && UnreachableInitiator == R.UnreachableInitiator &&
  87. Group == R.Group;
  88. }
  89. /// \brief A comparison that sorts such that mergeable regions are adjacent.
  90. friend bool operator<(const SourceMappingRegion &LHS,
  91. const SourceMappingRegion &RHS) {
  92. return std::tie(LHS.File, LHS.MacroArgumentFile, LHS.Count,
  93. LHS.UnreachableInitiator, LHS.Group) <
  94. std::tie(RHS.File, RHS.MacroArgumentFile, RHS.Count,
  95. RHS.UnreachableInitiator, RHS.Group);
  96. }
  97. };
  98. /// \brief The state of the coverage mapping builder.
  99. struct SourceMappingState {
  100. Counter CurrentRegionCount;
  101. const Stmt *CurrentSourceGroup;
  102. const Stmt *CurrentUnreachableRegionInitiator;
  103. SourceMappingState(Counter CurrentRegionCount, const Stmt *CurrentSourceGroup,
  104. const Stmt *CurrentUnreachableRegionInitiator)
  105. : CurrentRegionCount(CurrentRegionCount),
  106. CurrentSourceGroup(CurrentSourceGroup),
  107. CurrentUnreachableRegionInitiator(CurrentUnreachableRegionInitiator) {}
  108. };
  109. /// \brief Provides the common functionality for the different
  110. /// coverage mapping region builders.
  111. class CoverageMappingBuilder {
  112. public:
  113. CoverageMappingModuleGen &CVM;
  114. SourceManager &SM;
  115. const LangOptions &LangOpts;
  116. private:
  117. struct FileInfo {
  118. /// \brief The file id that will be used by the coverage mapping system.
  119. unsigned CovMappingFileID;
  120. const FileEntry *Entry;
  121. FileInfo(unsigned CovMappingFileID, const FileEntry *Entry)
  122. : CovMappingFileID(CovMappingFileID), Entry(Entry) {}
  123. };
  124. /// \brief This mapping maps clang's FileIDs to file ids used
  125. /// by the coverage mapping system and clang's file entries.
  126. llvm::SmallDenseMap<FileID, FileInfo, 8> FileIDMapping;
  127. public:
  128. /// \brief The statement that corresponds to the current source group.
  129. const Stmt *CurrentSourceGroup;
  130. /// \brief The statement the initiated the current unreachable region.
  131. const Stmt *CurrentUnreachableRegionInitiator;
  132. /// \brief The coverage mapping regions for this function
  133. llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
  134. /// \brief The source mapping regions for this function.
  135. std::vector<SourceMappingRegion> SourceRegions;
  136. CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  137. const LangOptions &LangOpts)
  138. : CVM(CVM), SM(SM), LangOpts(LangOpts),
  139. CurrentSourceGroup(nullptr),
  140. CurrentUnreachableRegionInitiator(nullptr) {}
  141. /// \brief Return the precise end location for the given token.
  142. SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
  143. return Lexer::getLocForEndOfToken(SM.getSpellingLoc(Loc), 0, SM, LangOpts);
  144. }
  145. /// \brief Create the mapping that maps from the function's file ids to
  146. /// the indices for the translation unit's filenames.
  147. void createFileIDMapping(SmallVectorImpl<unsigned> &Mapping) {
  148. Mapping.resize(FileIDMapping.size(), 0);
  149. for (const auto &I : FileIDMapping)
  150. Mapping[I.second.CovMappingFileID] = CVM.getFileID(I.second.Entry);
  151. }
  152. /// \brief Get the coverage mapping file id that corresponds to the given
  153. /// clang file id. If such file id doesn't exist, it gets added to the
  154. /// mapping that maps from clang's file ids to coverage mapping file ids.
  155. /// Return true if there was an error getting the coverage mapping file id.
  156. /// An example of an when this function fails is when the region tries
  157. /// to get a coverage file id for a location in a built-in macro.
  158. bool getCoverageFileID(SourceLocation LocStart, FileID File,
  159. FileID SpellingFile, unsigned &Result) {
  160. auto Mapping = FileIDMapping.find(File);
  161. if (Mapping != FileIDMapping.end()) {
  162. Result = Mapping->second.CovMappingFileID;
  163. return false;
  164. }
  165. auto Entry = SM.getFileEntryForID(SpellingFile);
  166. if (!Entry)
  167. return true;
  168. Result = FileIDMapping.size();
  169. FileIDMapping.insert(std::make_pair(File, FileInfo(Result, Entry)));
  170. createFileExpansionRegion(LocStart, File);
  171. return false;
  172. }
  173. /// \brief Get the coverage mapping file id that corresponds to the given
  174. /// clang file id.
  175. /// Return true if there was an error getting the coverage mapping file id.
  176. bool getExistingCoverageFileID(FileID File, unsigned &Result) {
  177. // Make sure that the file is valid.
  178. if (File.isInvalid())
  179. return true;
  180. auto Mapping = FileIDMapping.find(File);
  181. if (Mapping != FileIDMapping.end()) {
  182. Result = Mapping->second.CovMappingFileID;
  183. return false;
  184. }
  185. return true;
  186. }
  187. /// \brief Return true if the given clang's file id has a corresponding
  188. /// coverage file id.
  189. bool hasExistingCoverageFileID(FileID File) const {
  190. return FileIDMapping.count(File);
  191. }
  192. /// \brief Gather all the regions that were skipped by the preprocessor
  193. /// using the constructs like #if.
  194. void gatherSkippedRegions() {
  195. /// An array of the minimum lineStarts and the maximum lineEnds
  196. /// for mapping regions from the appropriate source files.
  197. llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
  198. FileLineRanges.resize(
  199. FileIDMapping.size(),
  200. std::make_pair(std::numeric_limits<unsigned>::max(), 0));
  201. for (const auto &R : MappingRegions) {
  202. FileLineRanges[R.FileID].first =
  203. std::min(FileLineRanges[R.FileID].first, R.LineStart);
  204. FileLineRanges[R.FileID].second =
  205. std::max(FileLineRanges[R.FileID].second, R.LineEnd);
  206. }
  207. auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
  208. for (const auto &I : SkippedRanges) {
  209. auto LocStart = I.getBegin();
  210. auto LocEnd = I.getEnd();
  211. auto FileStart = SM.getFileID(LocStart);
  212. if (!hasExistingCoverageFileID(FileStart))
  213. continue;
  214. auto ActualFileStart = SM.getDecomposedSpellingLoc(LocStart).first;
  215. if (ActualFileStart != SM.getDecomposedSpellingLoc(LocEnd).first)
  216. // Ignore regions that span across multiple files.
  217. continue;
  218. unsigned CovFileID;
  219. if (getCoverageFileID(LocStart, FileStart, ActualFileStart, CovFileID))
  220. continue;
  221. unsigned LineStart = SM.getSpellingLineNumber(LocStart);
  222. unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
  223. unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
  224. unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  225. CounterMappingRegion Region(Counter(), CovFileID, LineStart, ColumnStart,
  226. LineEnd, ColumnEnd, false,
  227. CounterMappingRegion::SkippedRegion);
  228. // Make sure that we only collect the regions that are inside
  229. // the souce code of this function.
  230. if (Region.LineStart >= FileLineRanges[CovFileID].first &&
  231. Region.LineEnd <= FileLineRanges[CovFileID].second)
  232. MappingRegions.push_back(Region);
  233. }
  234. }
  235. /// \brief Create a mapping region that correponds to an expansion of
  236. /// a macro or an embedded include.
  237. void createFileExpansionRegion(SourceLocation Loc, FileID ExpandedFile) {
  238. SourceLocation LocStart;
  239. if (Loc.isMacroID())
  240. LocStart = SM.getImmediateExpansionRange(Loc).first;
  241. else {
  242. LocStart = SM.getIncludeLoc(ExpandedFile);
  243. if (LocStart.isInvalid())
  244. return; // This file has no expansion region.
  245. }
  246. auto File = SM.getFileID(LocStart);
  247. auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
  248. unsigned CovFileID, ExpandedFileID;
  249. if (getExistingCoverageFileID(ExpandedFile, ExpandedFileID))
  250. return;
  251. if (getCoverageFileID(LocStart, File, SpellingFile, CovFileID))
  252. return;
  253. unsigned LineStart = SM.getSpellingLineNumber(LocStart);
  254. unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
  255. unsigned LineEnd = LineStart;
  256. // Compute the end column manually as Lexer::getLocForEndOfToken doesn't
  257. // give the correct result in all cases.
  258. unsigned ColumnEnd =
  259. ColumnStart +
  260. Lexer::MeasureTokenLength(SM.getSpellingLoc(LocStart), SM, LangOpts);
  261. MappingRegions.push_back(CounterMappingRegion(
  262. Counter(), CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd,
  263. false, CounterMappingRegion::ExpansionRegion));
  264. MappingRegions.back().ExpandedFileID = ExpandedFileID;
  265. }
  266. /// \brief Enter a source region group that is identified by the given
  267. /// statement.
  268. /// It's not possible to enter a group when there is already
  269. /// another group present.
  270. void beginSourceRegionGroup(const Stmt *Group) {
  271. assert(!CurrentSourceGroup);
  272. CurrentSourceGroup = Group;
  273. }
  274. /// \brief Exit the current source region group.
  275. void endSourceRegionGroup() { CurrentSourceGroup = nullptr; }
  276. /// \brief Associate a counter with a given source code range.
  277. void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
  278. Counter Count, const Stmt *UnreachableInitiator,
  279. const Stmt *SourceGroup, unsigned Flags = 0,
  280. FileID MacroArgumentFile = FileID()) {
  281. if (SM.isMacroArgExpansion(LocStart)) {
  282. // Map the code range with the macro argument's value.
  283. mapSourceCodeRange(SM.getImmediateSpellingLoc(LocStart),
  284. SM.getImmediateSpellingLoc(LocEnd), Count,
  285. UnreachableInitiator, SourceGroup, Flags,
  286. SM.getFileID(LocStart));
  287. // Map the code range where the macro argument is referenced.
  288. SourceLocation RefLocStart(SM.getImmediateExpansionRange(LocStart).first);
  289. SourceLocation RefLocEnd(RefLocStart);
  290. if (SM.isMacroArgExpansion(RefLocStart))
  291. mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
  292. SourceGroup, 0, SM.getFileID(RefLocStart));
  293. else
  294. mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
  295. SourceGroup);
  296. return;
  297. }
  298. auto File = SM.getFileID(LocStart);
  299. // Make sure that the file id is valid.
  300. if (File.isInvalid())
  301. return;
  302. SourceRegions.emplace_back(File, MacroArgumentFile, Count,
  303. UnreachableInitiator, SourceGroup, LocStart,
  304. LocEnd, Flags);
  305. }
  306. void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
  307. Counter Count, unsigned Flags = 0) {
  308. mapSourceCodeRange(LocStart, LocEnd, Count,
  309. CurrentUnreachableRegionInitiator, CurrentSourceGroup,
  310. Flags);
  311. }
  312. void mapSourceCodeRange(const SourceMappingState &State,
  313. SourceLocation LocStart, SourceLocation LocEnd,
  314. unsigned Flags = 0) {
  315. mapSourceCodeRange(LocStart, LocEnd, State.CurrentRegionCount,
  316. State.CurrentUnreachableRegionInitiator,
  317. State.CurrentSourceGroup, Flags);
  318. }
  319. /// \brief Generate the coverage counter mapping regions from collected
  320. /// source regions.
  321. void emitSourceRegions() {
  322. std::sort(SourceRegions.begin(), SourceRegions.end());
  323. for (auto I = SourceRegions.begin(), E = SourceRegions.end(); I != E; ++I) {
  324. // Keep the original start location of this region.
  325. SourceLocation LocStart = I->getStartLoc();
  326. SourceLocation LocEnd = I->getEndLoc(SM);
  327. bool Ignore = I->hasFlag(SourceMappingRegion::IgnoreIfNotExtended);
  328. // We need to handle mergeable regions together.
  329. for (auto Next = I + 1; Next != E && Next->isMergeable(*I); ++Next) {
  330. ++I;
  331. LocStart = std::min(LocStart, I->getStartLoc());
  332. LocEnd = std::max(LocEnd, I->getEndLoc(SM));
  333. // FIXME: Should we && together the Ignore flag of multiple regions?
  334. Ignore = false;
  335. }
  336. if (Ignore)
  337. continue;
  338. // Find the spilling locations for the mapping region.
  339. LocEnd = getPreciseTokenLocEnd(LocEnd);
  340. unsigned LineStart = SM.getSpellingLineNumber(LocStart);
  341. unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
  342. unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
  343. unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  344. auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
  345. unsigned CovFileID;
  346. if (getCoverageFileID(LocStart, I->getFile(), SpellingFile, CovFileID))
  347. continue;
  348. assert(LineStart <= LineEnd);
  349. MappingRegions.push_back(CounterMappingRegion(
  350. I->getCounter(), CovFileID, LineStart, ColumnStart, LineEnd,
  351. ColumnEnd, false, CounterMappingRegion::CodeRegion));
  352. }
  353. }
  354. };
  355. /// \brief Creates unreachable coverage regions for the functions that
  356. /// are not emitted.
  357. struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
  358. EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  359. const LangOptions &LangOpts)
  360. : CoverageMappingBuilder(CVM, SM, LangOpts) {}
  361. void VisitDecl(const Decl *D) {
  362. if (!D->hasBody())
  363. return;
  364. auto Body = D->getBody();
  365. mapSourceCodeRange(Body->getLocStart(), Body->getLocEnd(), Counter());
  366. }
  367. /// \brief Write the mapping data to the output stream
  368. void write(llvm::raw_ostream &OS) {
  369. emitSourceRegions();
  370. SmallVector<unsigned, 16> FileIDMapping;
  371. createFileIDMapping(FileIDMapping);
  372. CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
  373. Writer.write(OS);
  374. }
  375. };
  376. /// \brief A StmtVisitor that creates coverage mapping regions which map
  377. /// from the source code locations to the PGO counters.
  378. struct CounterCoverageMappingBuilder
  379. : public CoverageMappingBuilder,
  380. public ConstStmtVisitor<CounterCoverageMappingBuilder> {
  381. /// \brief The map of statements to count values.
  382. llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
  383. Counter CurrentRegionCount;
  384. CounterExpressionBuilder Builder;
  385. /// \brief Return a counter that represents the
  386. /// expression that subracts rhs from lhs.
  387. Counter subtractCounters(Counter LHS, Counter RHS) {
  388. return Builder.subtract(LHS, RHS);
  389. }
  390. /// \brief Return a counter that represents the
  391. /// the exression that adds lhs and rhs.
  392. Counter addCounters(Counter LHS, Counter RHS) {
  393. return Builder.add(LHS, RHS);
  394. }
  395. /// \brief Return the region counter for the given statement.
  396. /// This should only be called on statements that have a dedicated counter.
  397. unsigned getRegionCounter(const Stmt *S) { return CounterMap[S]; }
  398. /// \brief Return the region count for the counter at the given index.
  399. Counter getRegionCount(unsigned CounterId) {
  400. return Counter::getCounter(CounterId);
  401. }
  402. /// \brief Return the counter value of the current region.
  403. Counter getCurrentRegionCount() { return CurrentRegionCount; }
  404. /// \brief Set the counter value for the current region.
  405. /// This is used to keep track of changes to the most recent counter
  406. /// from control flow and non-local exits.
  407. void setCurrentRegionCount(Counter Count) {
  408. CurrentRegionCount = Count;
  409. CurrentUnreachableRegionInitiator = nullptr;
  410. }
  411. /// \brief Indicate that the current region is never reached,
  412. /// and thus should have a counter value of zero.
  413. /// This is important so that subsequent regions can correctly track
  414. /// their parent counts.
  415. void setCurrentRegionUnreachable(const Stmt *Initiator) {
  416. CurrentRegionCount = Counter::getZero();
  417. CurrentUnreachableRegionInitiator = Initiator;
  418. }
  419. /// \brief A counter for a particular region.
  420. /// This is the primary interface through
  421. /// which the coverage mapping builder manages counters and their values.
  422. class RegionMapper {
  423. CounterCoverageMappingBuilder &Mapping;
  424. Counter Count;
  425. Counter ParentCount;
  426. Counter RegionCount;
  427. Counter Adjust;
  428. public:
  429. RegionMapper(CounterCoverageMappingBuilder *Mapper, const Stmt *S)
  430. : Mapping(*Mapper),
  431. Count(Mapper->getRegionCount(Mapper->getRegionCounter(S))),
  432. ParentCount(Mapper->getCurrentRegionCount()) {}
  433. /// Get the value of the counter. In most cases this is the number of times
  434. /// the region of the counter was entered, but for switch labels it's the
  435. /// number of direct jumps to that label.
  436. Counter getCount() const { return Count; }
  437. /// Get the value of the counter with adjustments applied. Adjustments occur
  438. /// when control enters or leaves the region abnormally; i.e., if there is a
  439. /// jump to a label within the region, or if the function can return from
  440. /// within the region. The adjusted count, then, is the value of the counter
  441. /// at the end of the region.
  442. Counter getAdjustedCount() const {
  443. return Mapping.addCounters(Count, Adjust);
  444. }
  445. /// Get the value of the counter in this region's parent, i.e., the region
  446. /// that was active when this region began. This is useful for deriving
  447. /// counts in implicitly counted regions, like the false case of a condition
  448. /// or the normal exits of a loop.
  449. Counter getParentCount() const { return ParentCount; }
  450. /// Activate the counter by emitting an increment and starting to track
  451. /// adjustments. If AddIncomingFallThrough is true, the current region count
  452. /// will be added to the counter for the purposes of tracking the region.
  453. void beginRegion(bool AddIncomingFallThrough = false) {
  454. RegionCount = Count;
  455. if (AddIncomingFallThrough)
  456. RegionCount =
  457. Mapping.addCounters(RegionCount, Mapping.getCurrentRegionCount());
  458. Mapping.setCurrentRegionCount(RegionCount);
  459. }
  460. /// For counters on boolean branches, begins tracking adjustments for the
  461. /// uncounted path.
  462. void beginElseRegion() {
  463. RegionCount = Mapping.subtractCounters(ParentCount, Count);
  464. Mapping.setCurrentRegionCount(RegionCount);
  465. }
  466. /// Reset the current region count.
  467. void setCurrentRegionCount(Counter CurrentCount) {
  468. RegionCount = CurrentCount;
  469. Mapping.setCurrentRegionCount(RegionCount);
  470. }
  471. /// Adjust for non-local control flow after emitting a subexpression or
  472. /// substatement. This must be called to account for constructs such as
  473. /// gotos,
  474. /// labels, and returns, so that we can ensure that our region's count is
  475. /// correct in the code that follows.
  476. void adjustForControlFlow() {
  477. Adjust = Mapping.addCounters(
  478. Adjust, Mapping.subtractCounters(Mapping.getCurrentRegionCount(),
  479. RegionCount));
  480. // Reset the region count in case this is called again later.
  481. RegionCount = Mapping.getCurrentRegionCount();
  482. }
  483. /// Commit all adjustments to the current region. If the region is a loop,
  484. /// the LoopAdjust value should be the count of all the breaks and continues
  485. /// from the loop, to compensate for those counts being deducted from the
  486. /// adjustments for the body of the loop.
  487. void applyAdjustmentsToRegion() {
  488. Mapping.setCurrentRegionCount(Mapping.addCounters(ParentCount, Adjust));
  489. }
  490. void applyAdjustmentsToRegion(Counter LoopAdjust) {
  491. Mapping.setCurrentRegionCount(Mapping.addCounters(
  492. Mapping.addCounters(ParentCount, Adjust), LoopAdjust));
  493. }
  494. };
  495. /// \brief Keep counts of breaks and continues inside loops.
  496. struct BreakContinue {
  497. Counter BreakCount;
  498. Counter ContinueCount;
  499. };
  500. SmallVector<BreakContinue, 8> BreakContinueStack;
  501. CounterCoverageMappingBuilder(
  502. CoverageMappingModuleGen &CVM,
  503. llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
  504. const LangOptions &LangOpts)
  505. : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
  506. /// \brief Write the mapping data to the output stream
  507. void write(llvm::raw_ostream &OS) {
  508. emitSourceRegions();
  509. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  510. createFileIDMapping(VirtualFileMapping);
  511. gatherSkippedRegions();
  512. CoverageMappingWriter Writer(
  513. VirtualFileMapping, Builder.getExpressions(), MappingRegions);
  514. Writer.write(OS);
  515. }
  516. /// \brief Return the current source mapping state.
  517. SourceMappingState getCurrentState() const {
  518. return SourceMappingState(CurrentRegionCount, CurrentSourceGroup,
  519. CurrentUnreachableRegionInitiator);
  520. }
  521. /// \brief Associate the source code range with the current region count.
  522. void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
  523. unsigned Flags = 0) {
  524. CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocEnd,
  525. CurrentRegionCount, Flags);
  526. }
  527. void mapSourceCodeRange(SourceLocation LocStart) {
  528. CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocStart,
  529. CurrentRegionCount);
  530. }
  531. /// \brief Associate the source range of a token with the current region
  532. /// count.
  533. /// Ignore the source range for this token if it produces a distinct
  534. /// mapping region with no other source ranges.
  535. void mapToken(SourceLocation LocStart) {
  536. CoverageMappingBuilder::mapSourceCodeRange(
  537. LocStart, LocStart, CurrentRegionCount,
  538. SourceMappingRegion::IgnoreIfNotExtended);
  539. }
  540. void mapToken(const SourceMappingState &State, SourceLocation LocStart) {
  541. CoverageMappingBuilder::mapSourceCodeRange(
  542. State, LocStart, LocStart, SourceMappingRegion::IgnoreIfNotExtended);
  543. }
  544. void VisitStmt(const Stmt *S) {
  545. mapSourceCodeRange(S->getLocStart());
  546. for (Stmt::const_child_range I = S->children(); I; ++I) {
  547. if (*I)
  548. this->Visit(*I);
  549. }
  550. }
  551. /// \brief If the given statement is a compound statement,
  552. /// map '}' with the same count as '{'.
  553. void VisitSubStmtRBraceState(const Stmt *S) {
  554. if (!isa<CompoundStmt>(S))
  555. return Visit(S);
  556. const auto *CS = cast<CompoundStmt>(S);
  557. auto State = getCurrentState();
  558. mapSourceCodeRange(CS->getLBracLoc());
  559. for (Stmt::const_child_range I = S->children(); I; ++I) {
  560. if (*I)
  561. this->Visit(*I);
  562. }
  563. CoverageMappingBuilder::mapSourceCodeRange(State, CS->getRBracLoc(),
  564. CS->getRBracLoc());
  565. }
  566. void VisitDecl(const Decl *D) {
  567. if (!D->hasBody())
  568. return;
  569. // Counter tracks entry to the function body.
  570. auto Body = D->getBody();
  571. RegionMapper Cnt(this, Body);
  572. Cnt.beginRegion();
  573. VisitSubStmtRBraceState(Body);
  574. }
  575. void VisitDeclStmt(const DeclStmt *S) {
  576. mapSourceCodeRange(S->getLocStart());
  577. for (Stmt::const_child_range I = static_cast<const Stmt *>(S)->children();
  578. I; ++I) {
  579. if (*I)
  580. this->Visit(*I);
  581. }
  582. }
  583. void VisitCompoundStmt(const CompoundStmt *S) {
  584. mapSourceCodeRange(S->getLBracLoc());
  585. for (Stmt::const_child_range I = S->children(); I; ++I) {
  586. if (*I)
  587. this->Visit(*I);
  588. }
  589. mapSourceCodeRange(S->getRBracLoc(), S->getRBracLoc());
  590. }
  591. void VisitReturnStmt(const ReturnStmt *S) {
  592. mapSourceCodeRange(S->getLocStart());
  593. if (S->getRetValue())
  594. Visit(S->getRetValue());
  595. setCurrentRegionUnreachable(S);
  596. }
  597. void VisitGotoStmt(const GotoStmt *S) {
  598. mapSourceCodeRange(S->getLocStart());
  599. mapToken(S->getLabelLoc());
  600. setCurrentRegionUnreachable(S);
  601. }
  602. void VisitLabelStmt(const LabelStmt *S) {
  603. // Counter tracks the block following the label.
  604. RegionMapper Cnt(this, S);
  605. Cnt.beginRegion();
  606. mapSourceCodeRange(S->getLocStart());
  607. // Can't map the ':' token as its location isn't known.
  608. Visit(S->getSubStmt());
  609. }
  610. void VisitBreakStmt(const BreakStmt *S) {
  611. mapSourceCodeRange(S->getLocStart());
  612. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  613. BreakContinueStack.back().BreakCount = addCounters(
  614. BreakContinueStack.back().BreakCount, getCurrentRegionCount());
  615. setCurrentRegionUnreachable(S);
  616. }
  617. void VisitContinueStmt(const ContinueStmt *S) {
  618. mapSourceCodeRange(S->getLocStart());
  619. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  620. BreakContinueStack.back().ContinueCount = addCounters(
  621. BreakContinueStack.back().ContinueCount, getCurrentRegionCount());
  622. setCurrentRegionUnreachable(S);
  623. }
  624. void VisitWhileStmt(const WhileStmt *S) {
  625. mapSourceCodeRange(S->getLocStart());
  626. // Counter tracks the body of the loop.
  627. RegionMapper Cnt(this, S);
  628. BreakContinueStack.push_back(BreakContinue());
  629. // Visit the body region first so the break/continue adjustments can be
  630. // included when visiting the condition.
  631. Cnt.beginRegion();
  632. VisitSubStmtRBraceState(S->getBody());
  633. Cnt.adjustForControlFlow();
  634. // ...then go back and propagate counts through the condition. The count
  635. // at the start of the condition is the sum of the incoming edges,
  636. // the backedge from the end of the loop body, and the edges from
  637. // continue statements.
  638. BreakContinue BC = BreakContinueStack.pop_back_val();
  639. Cnt.setCurrentRegionCount(
  640. addCounters(Cnt.getParentCount(),
  641. addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
  642. beginSourceRegionGroup(S->getCond());
  643. Visit(S->getCond());
  644. endSourceRegionGroup();
  645. Cnt.adjustForControlFlow();
  646. Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
  647. }
  648. void VisitDoStmt(const DoStmt *S) {
  649. mapSourceCodeRange(S->getLocStart());
  650. // Counter tracks the body of the loop.
  651. RegionMapper Cnt(this, S);
  652. BreakContinueStack.push_back(BreakContinue());
  653. Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
  654. VisitSubStmtRBraceState(S->getBody());
  655. Cnt.adjustForControlFlow();
  656. BreakContinue BC = BreakContinueStack.pop_back_val();
  657. // The count at the start of the condition is equal to the count at the
  658. // end of the body. The adjusted count does not include either the
  659. // fall-through count coming into the loop or the continue count, so add
  660. // both of those separately. This is coincidentally the same equation as
  661. // with while loops but for different reasons.
  662. Cnt.setCurrentRegionCount(
  663. addCounters(Cnt.getParentCount(),
  664. addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
  665. Visit(S->getCond());
  666. Cnt.adjustForControlFlow();
  667. Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
  668. }
  669. void VisitForStmt(const ForStmt *S) {
  670. mapSourceCodeRange(S->getLocStart());
  671. if (S->getInit())
  672. Visit(S->getInit());
  673. // Counter tracks the body of the loop.
  674. RegionMapper Cnt(this, S);
  675. BreakContinueStack.push_back(BreakContinue());
  676. // Visit the body region first. (This is basically the same as a while
  677. // loop; see further comments in VisitWhileStmt.)
  678. Cnt.beginRegion();
  679. VisitSubStmtRBraceState(S->getBody());
  680. Cnt.adjustForControlFlow();
  681. // The increment is essentially part of the body but it needs to include
  682. // the count for all the continue statements.
  683. if (S->getInc()) {
  684. Cnt.setCurrentRegionCount(addCounters(
  685. getCurrentRegionCount(), BreakContinueStack.back().ContinueCount));
  686. beginSourceRegionGroup(S->getInc());
  687. Visit(S->getInc());
  688. endSourceRegionGroup();
  689. Cnt.adjustForControlFlow();
  690. }
  691. BreakContinue BC = BreakContinueStack.pop_back_val();
  692. // ...then go back and propagate counts through the condition.
  693. if (S->getCond()) {
  694. Cnt.setCurrentRegionCount(
  695. addCounters(addCounters(Cnt.getParentCount(), Cnt.getAdjustedCount()),
  696. BC.ContinueCount));
  697. beginSourceRegionGroup(S->getCond());
  698. Visit(S->getCond());
  699. endSourceRegionGroup();
  700. Cnt.adjustForControlFlow();
  701. }
  702. Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
  703. }
  704. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  705. mapSourceCodeRange(S->getLocStart());
  706. Visit(S->getRangeStmt());
  707. Visit(S->getBeginEndStmt());
  708. // Counter tracks the body of the loop.
  709. RegionMapper Cnt(this, S);
  710. BreakContinueStack.push_back(BreakContinue());
  711. // Visit the body region first. (This is basically the same as a while
  712. // loop; see further comments in VisitWhileStmt.)
  713. Cnt.beginRegion();
  714. VisitSubStmtRBraceState(S->getBody());
  715. Cnt.adjustForControlFlow();
  716. BreakContinue BC = BreakContinueStack.pop_back_val();
  717. Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
  718. }
  719. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  720. mapSourceCodeRange(S->getLocStart());
  721. Visit(S->getElement());
  722. // Counter tracks the body of the loop.
  723. RegionMapper Cnt(this, S);
  724. BreakContinueStack.push_back(BreakContinue());
  725. Cnt.beginRegion();
  726. VisitSubStmtRBraceState(S->getBody());
  727. BreakContinue BC = BreakContinueStack.pop_back_val();
  728. Cnt.adjustForControlFlow();
  729. Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
  730. }
  731. void VisitSwitchStmt(const SwitchStmt *S) {
  732. mapSourceCodeRange(S->getLocStart());
  733. Visit(S->getCond());
  734. BreakContinueStack.push_back(BreakContinue());
  735. // Map the '}' for the body to have the same count as the regions after
  736. // the switch.
  737. SourceLocation RBracLoc;
  738. if (const auto *CS = dyn_cast<CompoundStmt>(S->getBody())) {
  739. mapSourceCodeRange(CS->getLBracLoc());
  740. setCurrentRegionUnreachable(S);
  741. for (Stmt::const_child_range I = CS->children(); I; ++I) {
  742. if (*I)
  743. this->Visit(*I);
  744. }
  745. RBracLoc = CS->getRBracLoc();
  746. } else {
  747. setCurrentRegionUnreachable(S);
  748. Visit(S->getBody());
  749. }
  750. // If the switch is inside a loop, add the continue counts.
  751. BreakContinue BC = BreakContinueStack.pop_back_val();
  752. if (!BreakContinueStack.empty())
  753. BreakContinueStack.back().ContinueCount = addCounters(
  754. BreakContinueStack.back().ContinueCount, BC.ContinueCount);
  755. // Counter tracks the exit block of the switch.
  756. RegionMapper ExitCnt(this, S);
  757. ExitCnt.beginRegion();
  758. if (RBracLoc.isValid())
  759. mapSourceCodeRange(RBracLoc);
  760. }
  761. void VisitCaseStmt(const CaseStmt *S) {
  762. // Counter for this particular case. This counts only jumps from the
  763. // switch header and does not include fallthrough from the case before
  764. // this one.
  765. RegionMapper Cnt(this, S);
  766. Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
  767. mapSourceCodeRange(S->getLocStart());
  768. mapToken(S->getColonLoc());
  769. Visit(S->getSubStmt());
  770. }
  771. void VisitDefaultStmt(const DefaultStmt *S) {
  772. // Counter for this default case. This does not include fallthrough from
  773. // the previous case.
  774. RegionMapper Cnt(this, S);
  775. Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
  776. mapSourceCodeRange(S->getLocStart());
  777. mapToken(S->getColonLoc());
  778. Visit(S->getSubStmt());
  779. }
  780. void VisitIfStmt(const IfStmt *S) {
  781. mapSourceCodeRange(S->getLocStart());
  782. Visit(S->getCond());
  783. mapToken(S->getElseLoc());
  784. // Counter tracks the "then" part of an if statement. The count for
  785. // the "else" part, if it exists, will be calculated from this counter.
  786. RegionMapper Cnt(this, S);
  787. Cnt.beginRegion();
  788. VisitSubStmtRBraceState(S->getThen());
  789. Cnt.adjustForControlFlow();
  790. if (S->getElse()) {
  791. Cnt.beginElseRegion();
  792. VisitSubStmtRBraceState(S->getElse());
  793. Cnt.adjustForControlFlow();
  794. }
  795. Cnt.applyAdjustmentsToRegion();
  796. }
  797. void VisitCXXTryStmt(const CXXTryStmt *S) {
  798. mapSourceCodeRange(S->getLocStart());
  799. Visit(S->getTryBlock());
  800. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  801. Visit(S->getHandler(I));
  802. // Counter tracks the continuation block of the try statement.
  803. RegionMapper Cnt(this, S);
  804. Cnt.beginRegion();
  805. }
  806. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  807. mapSourceCodeRange(S->getLocStart());
  808. // Counter tracks the catch statement's handler block.
  809. RegionMapper Cnt(this, S);
  810. Cnt.beginRegion();
  811. VisitSubStmtRBraceState(S->getHandlerBlock());
  812. }
  813. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  814. Visit(E->getCond());
  815. mapToken(E->getQuestionLoc());
  816. auto State = getCurrentState();
  817. // Counter tracks the "true" part of a conditional operator. The
  818. // count in the "false" part will be calculated from this counter.
  819. RegionMapper Cnt(this, E);
  820. Cnt.beginRegion();
  821. Visit(E->getTrueExpr());
  822. Cnt.adjustForControlFlow();
  823. mapToken(State, E->getColonLoc());
  824. Cnt.beginElseRegion();
  825. Visit(E->getFalseExpr());
  826. Cnt.adjustForControlFlow();
  827. Cnt.applyAdjustmentsToRegion();
  828. }
  829. void VisitBinLAnd(const BinaryOperator *E) {
  830. Visit(E->getLHS());
  831. mapToken(E->getOperatorLoc());
  832. // Counter tracks the right hand side of a logical and operator.
  833. RegionMapper Cnt(this, E);
  834. Cnt.beginRegion();
  835. Visit(E->getRHS());
  836. Cnt.adjustForControlFlow();
  837. Cnt.applyAdjustmentsToRegion();
  838. }
  839. void VisitBinLOr(const BinaryOperator *E) {
  840. Visit(E->getLHS());
  841. mapToken(E->getOperatorLoc());
  842. // Counter tracks the right hand side of a logical or operator.
  843. RegionMapper Cnt(this, E);
  844. Cnt.beginRegion();
  845. Visit(E->getRHS());
  846. Cnt.adjustForControlFlow();
  847. Cnt.applyAdjustmentsToRegion();
  848. }
  849. void VisitParenExpr(const ParenExpr *E) {
  850. mapToken(E->getLParen());
  851. Visit(E->getSubExpr());
  852. mapToken(E->getRParen());
  853. }
  854. void VisitBinaryOperator(const BinaryOperator *E) {
  855. Visit(E->getLHS());
  856. mapToken(E->getOperatorLoc());
  857. Visit(E->getRHS());
  858. }
  859. void VisitUnaryOperator(const UnaryOperator *E) {
  860. bool Postfix = E->isPostfix();
  861. if (!Postfix)
  862. mapToken(E->getOperatorLoc());
  863. Visit(E->getSubExpr());
  864. if (Postfix)
  865. mapToken(E->getOperatorLoc());
  866. }
  867. void VisitMemberExpr(const MemberExpr *E) {
  868. Visit(E->getBase());
  869. mapToken(E->getMemberLoc());
  870. }
  871. void VisitCallExpr(const CallExpr *E) {
  872. Visit(E->getCallee());
  873. for (const auto &Arg : E->arguments())
  874. Visit(Arg);
  875. mapToken(E->getRParenLoc());
  876. }
  877. void VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  878. Visit(E->getLHS());
  879. Visit(E->getRHS());
  880. mapToken(E->getRBracketLoc());
  881. }
  882. void VisitCStyleCastExpr(const CStyleCastExpr *E) {
  883. mapToken(E->getLParenLoc());
  884. mapToken(E->getRParenLoc());
  885. Visit(E->getSubExpr());
  886. }
  887. // Map literals as tokens so that the macros like #define PI 3.14
  888. // won't generate coverage mapping regions.
  889. void VisitIntegerLiteral(const IntegerLiteral *E) {
  890. mapToken(E->getLocStart());
  891. }
  892. void VisitFloatingLiteral(const FloatingLiteral *E) {
  893. mapToken(E->getLocStart());
  894. }
  895. void VisitCharacterLiteral(const CharacterLiteral *E) {
  896. mapToken(E->getLocStart());
  897. }
  898. void VisitStringLiteral(const StringLiteral *E) {
  899. mapToken(E->getLocStart());
  900. }
  901. void VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  902. mapToken(E->getLocStart());
  903. }
  904. void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
  905. mapToken(E->getLeftLoc());
  906. for (Stmt::const_child_range I = static_cast<const Stmt*>(E)->children(); I;
  907. ++I) {
  908. if (*I)
  909. this->Visit(*I);
  910. }
  911. mapToken(E->getRightLoc());
  912. }
  913. };
  914. }
  915. static bool isMachO(const CodeGenModule &CGM) {
  916. return CGM.getTarget().getTriple().isOSBinFormatMachO();
  917. }
  918. static StringRef getCoverageSection(const CodeGenModule &CGM) {
  919. return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
  920. }
  921. static void dump(llvm::raw_ostream &OS, const CoverageMappingRecord &Function) {
  922. OS << Function.FunctionName << ":\n";
  923. CounterMappingContext Ctx(Function.Expressions);
  924. for (const auto &R : Function.MappingRegions) {
  925. OS.indent(2);
  926. switch (R.Kind) {
  927. case CounterMappingRegion::CodeRegion:
  928. break;
  929. case CounterMappingRegion::ExpansionRegion:
  930. OS << "Expansion,";
  931. break;
  932. case CounterMappingRegion::SkippedRegion:
  933. OS << "Skipped,";
  934. break;
  935. }
  936. OS << "File " << R.FileID << ", " << R.LineStart << ":"
  937. << R.ColumnStart << " -> " << R.LineEnd << ":" << R.ColumnEnd
  938. << " = ";
  939. Ctx.dump(R.Count);
  940. OS << " (HasCodeBefore = " << R.HasCodeBefore;
  941. if (R.Kind == CounterMappingRegion::ExpansionRegion)
  942. OS << ", Expanded file = " << R.ExpandedFileID;
  943. OS << ")\n";
  944. }
  945. }
  946. void CoverageMappingModuleGen::addFunctionMappingRecord(
  947. llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
  948. uint64_t FunctionHash, const std::string &CoverageMapping) {
  949. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  950. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  951. auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
  952. auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
  953. if (!FunctionRecordTy) {
  954. llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
  955. FunctionRecordTy =
  956. llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
  957. }
  958. llvm::Constant *FunctionRecordVals[] = {
  959. llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
  960. llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
  961. llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
  962. llvm::ConstantInt::get(Int64Ty, FunctionHash)};
  963. FunctionRecords.push_back(llvm::ConstantStruct::get(
  964. FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
  965. CoverageMappings += CoverageMapping;
  966. if (CGM.getCodeGenOpts().DumpCoverageMapping) {
  967. // Dump the coverage mapping data for this function by decoding the
  968. // encoded data. This allows us to dump the mapping regions which were
  969. // also processed by the CoverageMappingWriter which performs
  970. // additional minimization operations such as reducing the number of
  971. // expressions.
  972. std::vector<StringRef> Filenames;
  973. std::vector<CounterExpression> Expressions;
  974. std::vector<CounterMappingRegion> Regions;
  975. llvm::SmallVector<StringRef, 16> FilenameRefs;
  976. FilenameRefs.resize(FileEntries.size());
  977. for (const auto &Entry : FileEntries)
  978. FilenameRefs[Entry.second] = Entry.first->getName();
  979. RawCoverageMappingReader Reader(FunctionNameValue, CoverageMapping,
  980. FilenameRefs,
  981. Filenames, Expressions, Regions);
  982. CoverageMappingRecord FunctionRecord;
  983. if (Reader.read(FunctionRecord))
  984. return;
  985. dump(llvm::outs(), FunctionRecord);
  986. }
  987. }
  988. void CoverageMappingModuleGen::emit() {
  989. if (FunctionRecords.empty())
  990. return;
  991. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  992. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  993. // Create the filenames and merge them with coverage mappings
  994. llvm::SmallVector<std::string, 16> FilenameStrs;
  995. llvm::SmallVector<StringRef, 16> FilenameRefs;
  996. FilenameStrs.resize(FileEntries.size());
  997. FilenameRefs.resize(FileEntries.size());
  998. for (const auto &Entry : FileEntries) {
  999. llvm::SmallString<256> Path(Entry.first->getName());
  1000. llvm::sys::fs::make_absolute(Path);
  1001. auto I = Entry.second;
  1002. FilenameStrs[I] = std::move(std::string(Path.begin(), Path.end()));
  1003. FilenameRefs[I] = FilenameStrs[I];
  1004. }
  1005. std::string FilenamesAndCoverageMappings;
  1006. llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
  1007. CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
  1008. OS << CoverageMappings;
  1009. size_t CoverageMappingSize = CoverageMappings.size();
  1010. size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
  1011. // Append extra zeroes if necessary to ensure that the size of the filenames
  1012. // and coverage mappings is a multiple of 8.
  1013. if (size_t Rem = OS.str().size() % 8) {
  1014. CoverageMappingSize += 8 - Rem;
  1015. for (size_t I = 0, S = 8 - Rem; I < S; ++I)
  1016. OS << '\0';
  1017. }
  1018. auto *FilenamesAndMappingsVal =
  1019. llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
  1020. // Create the deferred function records array
  1021. auto RecordsTy =
  1022. llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
  1023. auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
  1024. // Create the coverage data record
  1025. llvm::Type *CovDataTypes[] = {Int32Ty, Int32Ty,
  1026. Int32Ty, Int32Ty,
  1027. RecordsTy, FilenamesAndMappingsVal->getType()};
  1028. auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
  1029. llvm::Constant *TUDataVals[] = {
  1030. llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
  1031. llvm::ConstantInt::get(Int32Ty, FilenamesSize),
  1032. llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
  1033. llvm::ConstantInt::get(Int32Ty,
  1034. /*Version=*/CoverageMappingVersion1),
  1035. RecordsVal, FilenamesAndMappingsVal};
  1036. auto CovDataVal =
  1037. llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
  1038. auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
  1039. llvm::GlobalValue::InternalLinkage,
  1040. CovDataVal,
  1041. "__llvm_coverage_mapping");
  1042. CovData->setSection(getCoverageSection(CGM));
  1043. CovData->setAlignment(8);
  1044. // Make sure the data doesn't get deleted.
  1045. CGM.addUsedGlobal(CovData);
  1046. }
  1047. unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
  1048. auto It = FileEntries.find(File);
  1049. if (It != FileEntries.end())
  1050. return It->second;
  1051. unsigned FileID = FileEntries.size();
  1052. FileEntries.insert(std::make_pair(File, FileID));
  1053. return FileID;
  1054. }
  1055. void CoverageMappingGen::emitCounterMapping(const Decl *D,
  1056. llvm::raw_ostream &OS) {
  1057. assert(CounterMap);
  1058. CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
  1059. Walker.VisitDecl(D);
  1060. Walker.write(OS);
  1061. }
  1062. void CoverageMappingGen::emitEmptyMapping(const Decl *D,
  1063. llvm::raw_ostream &OS) {
  1064. EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
  1065. Walker.VisitDecl(D);
  1066. Walker.write(OS);
  1067. }