CoverageMappingGen.cpp 64 KB

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