CoverageMappingGen.cpp 53 KB

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