CoverageMappingGen.cpp 52 KB

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