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