1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass implements GCOV-style profiling. When this pass is run it emits 10 // "gcno" files next to the existing source, and instruments the code that runs 11 // to records the edges between blocks that run and emit a complementary "gcda" 12 // file on exit. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/Hashing.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/Sequence.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringMap.h" 23 #include "llvm/Analysis/EHPersonalities.h" 24 #include "llvm/Analysis/TargetLibraryInfo.h" 25 #include "llvm/IR/CFG.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/InstIterator.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/InitializePasses.h" 34 #include "llvm/Pass.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/Regex.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Transforms/Instrumentation.h" 42 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 43 #include "llvm/Transforms/Utils/ModuleUtils.h" 44 #include <algorithm> 45 #include <memory> 46 #include <string> 47 #include <utility> 48 49 using namespace llvm; 50 namespace endian = llvm::support::endian; 51 52 #define DEBUG_TYPE "insert-gcov-profiling" 53 54 enum : uint32_t { 55 GCOV_TAG_FUNCTION = 0x01000000, 56 GCOV_TAG_BLOCKS = 0x01410000, 57 GCOV_TAG_ARCS = 0x01430000, 58 GCOV_TAG_LINES = 0x01450000, 59 }; 60 61 static cl::opt<std::string> DefaultGCOVVersion("default-gcov-version", 62 cl::init("408*"), cl::Hidden, 63 cl::ValueRequired); 64 65 // Returns the number of words which will be used to represent this string. 66 static unsigned wordsOfString(StringRef s) { 67 // Length + NUL-terminated string + 0~3 padding NULs. 68 return (s.size() / 4) + 2; 69 } 70 71 GCOVOptions GCOVOptions::getDefault() { 72 GCOVOptions Options; 73 Options.EmitNotes = true; 74 Options.EmitData = true; 75 Options.NoRedZone = false; 76 77 if (DefaultGCOVVersion.size() != 4) { 78 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") + 79 DefaultGCOVVersion); 80 } 81 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4); 82 return Options; 83 } 84 85 namespace { 86 class GCOVFunction; 87 88 class GCOVProfiler { 89 public: 90 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {} 91 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {} 92 bool 93 runOnModule(Module &M, 94 std::function<const TargetLibraryInfo &(Function &F)> GetTLI); 95 96 void write(uint32_t i) { 97 char Bytes[4]; 98 endian::write32(Bytes, i, Endian); 99 os->write(Bytes, 4); 100 } 101 void writeString(StringRef s) { 102 write(wordsOfString(s) - 1); 103 os->write(s.data(), s.size()); 104 os->write_zeros(4 - s.size() % 4); 105 } 106 void writeBytes(const char *Bytes, int Size) { os->write(Bytes, Size); } 107 108 private: 109 // Create the .gcno files for the Module based on DebugInfo. 110 void emitProfileNotes(); 111 112 // Modify the program to track transitions along edges and call into the 113 // profiling runtime to emit .gcda files when run. 114 bool emitProfileArcs(); 115 116 bool isFunctionInstrumented(const Function &F); 117 std::vector<Regex> createRegexesFromString(StringRef RegexesStr); 118 static bool doesFilenameMatchARegex(StringRef Filename, 119 std::vector<Regex> &Regexes); 120 121 // Get pointers to the functions in the runtime library. 122 FunctionCallee getStartFileFunc(const TargetLibraryInfo *TLI); 123 FunctionCallee getEmitFunctionFunc(const TargetLibraryInfo *TLI); 124 FunctionCallee getEmitArcsFunc(const TargetLibraryInfo *TLI); 125 FunctionCallee getSummaryInfoFunc(); 126 FunctionCallee getEndFileFunc(); 127 128 // Add the function to write out all our counters to the global destructor 129 // list. 130 Function * 131 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>); 132 Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>); 133 Function *insertFlush(Function *ResetF); 134 135 void AddFlushBeforeForkAndExec(); 136 137 enum class GCovFileType { GCNO, GCDA }; 138 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType); 139 140 GCOVOptions Options; 141 support::endianness Endian; 142 raw_ostream *os; 143 144 // Checksum, produced by hash of EdgeDestinations 145 SmallVector<uint32_t, 4> FileChecksums; 146 147 Module *M = nullptr; 148 std::function<const TargetLibraryInfo &(Function &F)> GetTLI; 149 LLVMContext *Ctx = nullptr; 150 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs; 151 std::vector<Regex> FilterRe; 152 std::vector<Regex> ExcludeRe; 153 StringMap<bool> InstrumentedFiles; 154 }; 155 156 class GCOVProfilerLegacyPass : public ModulePass { 157 public: 158 static char ID; 159 GCOVProfilerLegacyPass() 160 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {} 161 GCOVProfilerLegacyPass(const GCOVOptions &Opts) 162 : ModulePass(ID), Profiler(Opts) { 163 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry()); 164 } 165 StringRef getPassName() const override { return "GCOV Profiler"; } 166 167 bool runOnModule(Module &M) override { 168 return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & { 169 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 170 }); 171 } 172 173 void getAnalysisUsage(AnalysisUsage &AU) const override { 174 AU.addRequired<TargetLibraryInfoWrapperPass>(); 175 } 176 177 private: 178 GCOVProfiler Profiler; 179 }; 180 } 181 182 char GCOVProfilerLegacyPass::ID = 0; 183 INITIALIZE_PASS_BEGIN( 184 GCOVProfilerLegacyPass, "insert-gcov-profiling", 185 "Insert instrumentation for GCOV profiling", false, false) 186 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 187 INITIALIZE_PASS_END( 188 GCOVProfilerLegacyPass, "insert-gcov-profiling", 189 "Insert instrumentation for GCOV profiling", false, false) 190 191 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) { 192 return new GCOVProfilerLegacyPass(Options); 193 } 194 195 static StringRef getFunctionName(const DISubprogram *SP) { 196 if (!SP->getLinkageName().empty()) 197 return SP->getLinkageName(); 198 return SP->getName(); 199 } 200 201 /// Extract a filename for a DISubprogram. 202 /// 203 /// Prefer relative paths in the coverage notes. Clang also may split 204 /// up absolute paths into a directory and filename component. When 205 /// the relative path doesn't exist, reconstruct the absolute path. 206 static SmallString<128> getFilename(const DISubprogram *SP) { 207 SmallString<128> Path; 208 StringRef RelPath = SP->getFilename(); 209 if (sys::fs::exists(RelPath)) 210 Path = RelPath; 211 else 212 sys::path::append(Path, SP->getDirectory(), SP->getFilename()); 213 return Path; 214 } 215 216 namespace { 217 class GCOVRecord { 218 protected: 219 GCOVProfiler *P; 220 221 GCOVRecord(GCOVProfiler *P) : P(P) {} 222 223 void write(uint32_t i) { P->write(i); } 224 void writeString(StringRef s) { P->writeString(s); } 225 void writeBytes(const char *Bytes, int Size) { P->writeBytes(Bytes, Size); } 226 }; 227 228 class GCOVFunction; 229 class GCOVBlock; 230 231 // Constructed only by requesting it from a GCOVBlock, this object stores a 232 // list of line numbers and a single filename, representing lines that belong 233 // to the block. 234 class GCOVLines : public GCOVRecord { 235 public: 236 void addLine(uint32_t Line) { 237 assert(Line != 0 && "Line zero is not a valid real line number."); 238 Lines.push_back(Line); 239 } 240 241 uint32_t length() const { 242 return 1 + wordsOfString(Filename) + Lines.size(); 243 } 244 245 void writeOut() { 246 write(0); 247 writeString(Filename); 248 for (int i = 0, e = Lines.size(); i != e; ++i) 249 write(Lines[i]); 250 } 251 252 GCOVLines(GCOVProfiler *P, StringRef F) 253 : GCOVRecord(P), Filename(std::string(F)) {} 254 255 private: 256 std::string Filename; 257 SmallVector<uint32_t, 32> Lines; 258 }; 259 260 261 // Represent a basic block in GCOV. Each block has a unique number in the 262 // function, number of lines belonging to each block, and a set of edges to 263 // other blocks. 264 class GCOVBlock : public GCOVRecord { 265 public: 266 GCOVLines &getFile(StringRef Filename) { 267 return LinesByFile.try_emplace(Filename, P, Filename).first->second; 268 } 269 270 void addEdge(GCOVBlock &Successor) { 271 OutEdges.push_back(&Successor); 272 } 273 274 void writeOut() { 275 uint32_t Len = 3; 276 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile; 277 for (auto &I : LinesByFile) { 278 Len += I.second.length(); 279 SortedLinesByFile.push_back(&I); 280 } 281 282 write(GCOV_TAG_LINES); 283 write(Len); 284 write(Number); 285 286 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS, 287 StringMapEntry<GCOVLines> *RHS) { 288 return LHS->getKey() < RHS->getKey(); 289 }); 290 for (auto &I : SortedLinesByFile) 291 I->getValue().writeOut(); 292 write(0); 293 write(0); 294 } 295 296 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) { 297 // Only allow copy before edges and lines have been added. After that, 298 // there are inter-block pointers (eg: edges) that won't take kindly to 299 // blocks being copied or moved around. 300 assert(LinesByFile.empty()); 301 assert(OutEdges.empty()); 302 } 303 304 private: 305 friend class GCOVFunction; 306 307 GCOVBlock(GCOVProfiler *P, uint32_t Number) 308 : GCOVRecord(P), Number(Number) {} 309 310 uint32_t Number; 311 StringMap<GCOVLines> LinesByFile; 312 SmallVector<GCOVBlock *, 4> OutEdges; 313 }; 314 315 // A function has a unique identifier, a checksum (we leave as zero) and a 316 // set of blocks and a map of edges between blocks. This is the only GCOV 317 // object users can construct, the blocks and lines will be rooted here. 318 class GCOVFunction : public GCOVRecord { 319 public: 320 GCOVFunction(GCOVProfiler *P, Function *F, const DISubprogram *SP, 321 unsigned EndLine, uint32_t Ident, int Version) 322 : GCOVRecord(P), SP(SP), EndLine(EndLine), Ident(Ident), 323 Version(Version), ReturnBlock(P, 1) { 324 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n"); 325 bool ExitBlockBeforeBody = Version >= 48; 326 uint32_t i = 0; 327 for (auto &BB : *F) { 328 // Skip index 1 if it's assigned to the ReturnBlock. 329 if (i == 1 && ExitBlockBeforeBody) 330 ++i; 331 Blocks.insert(std::make_pair(&BB, GCOVBlock(P, i++))); 332 } 333 if (!ExitBlockBeforeBody) 334 ReturnBlock.Number = i; 335 336 std::string FunctionNameAndLine; 337 raw_string_ostream FNLOS(FunctionNameAndLine); 338 FNLOS << getFunctionName(SP) << SP->getLine(); 339 FNLOS.flush(); 340 FuncChecksum = hash_value(FunctionNameAndLine); 341 } 342 343 GCOVBlock &getBlock(BasicBlock *BB) { 344 return Blocks.find(BB)->second; 345 } 346 347 GCOVBlock &getReturnBlock() { 348 return ReturnBlock; 349 } 350 351 std::string getEdgeDestinations() { 352 std::string EdgeDestinations; 353 raw_string_ostream EDOS(EdgeDestinations); 354 Function *F = Blocks.begin()->first->getParent(); 355 for (BasicBlock &I : *F) { 356 GCOVBlock &Block = getBlock(&I); 357 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) 358 EDOS << Block.OutEdges[i]->Number; 359 } 360 return EdgeDestinations; 361 } 362 363 uint32_t getFuncChecksum() const { 364 return FuncChecksum; 365 } 366 367 void writeOut(uint32_t CfgChecksum) { 368 write(GCOV_TAG_FUNCTION); 369 SmallString<128> Filename = getFilename(SP); 370 uint32_t BlockLen = 371 2 + (Version >= 47) + wordsOfString(getFunctionName(SP)); 372 if (Version < 80) 373 BlockLen += wordsOfString(Filename) + 1; 374 else 375 BlockLen += 1 + wordsOfString(Filename) + 3 + (Version >= 90); 376 377 write(BlockLen); 378 write(Ident); 379 write(FuncChecksum); 380 if (Version >= 47) 381 write(CfgChecksum); 382 writeString(getFunctionName(SP)); 383 if (Version < 80) { 384 writeString(Filename); 385 write(SP->getLine()); 386 } else { 387 write(SP->isArtificial()); // artificial 388 writeString(Filename); 389 write(SP->getLine()); // start_line 390 write(0); // start_column 391 // EndLine is the last line with !dbg. It is not the } line as in GCC, 392 // but good enough. 393 write(EndLine); 394 if (Version >= 90) 395 write(0); // end_column 396 } 397 398 // Emit count of blocks. 399 write(GCOV_TAG_BLOCKS); 400 if (Version < 80) { 401 write(Blocks.size() + 1); 402 for (int i = Blocks.size() + 1; i; --i) 403 write(0); 404 } else { 405 write(1); 406 write(Blocks.size() + 1); 407 } 408 LLVM_DEBUG(dbgs() << (Blocks.size() + 1) << " blocks\n"); 409 410 // Emit edges between blocks. 411 Function *F = Blocks.begin()->first->getParent(); 412 for (BasicBlock &I : *F) { 413 GCOVBlock &Block = getBlock(&I); 414 if (Block.OutEdges.empty()) continue; 415 416 write(GCOV_TAG_ARCS); 417 write(Block.OutEdges.size() * 2 + 1); 418 write(Block.Number); 419 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) { 420 LLVM_DEBUG(dbgs() << Block.Number << " -> " 421 << Block.OutEdges[i]->Number << "\n"); 422 write(Block.OutEdges[i]->Number); 423 write(0); // no flags 424 } 425 } 426 427 // Emit lines for each block. 428 for (BasicBlock &I : *F) 429 getBlock(&I).writeOut(); 430 } 431 432 private: 433 const DISubprogram *SP; 434 unsigned EndLine; 435 uint32_t Ident; 436 uint32_t FuncChecksum; 437 int Version; 438 DenseMap<BasicBlock *, GCOVBlock> Blocks; 439 GCOVBlock ReturnBlock; 440 }; 441 } 442 443 // RegexesStr is a string containing differents regex separated by a semi-colon. 444 // For example "foo\..*$;bar\..*$". 445 std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) { 446 std::vector<Regex> Regexes; 447 while (!RegexesStr.empty()) { 448 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';'); 449 if (!HeadTail.first.empty()) { 450 Regex Re(HeadTail.first); 451 std::string Err; 452 if (!Re.isValid(Err)) { 453 Ctx->emitError(Twine("Regex ") + HeadTail.first + 454 " is not valid: " + Err); 455 } 456 Regexes.emplace_back(std::move(Re)); 457 } 458 RegexesStr = HeadTail.second; 459 } 460 return Regexes; 461 } 462 463 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename, 464 std::vector<Regex> &Regexes) { 465 for (Regex &Re : Regexes) 466 if (Re.match(Filename)) 467 return true; 468 return false; 469 } 470 471 bool GCOVProfiler::isFunctionInstrumented(const Function &F) { 472 if (FilterRe.empty() && ExcludeRe.empty()) { 473 return true; 474 } 475 SmallString<128> Filename = getFilename(F.getSubprogram()); 476 auto It = InstrumentedFiles.find(Filename); 477 if (It != InstrumentedFiles.end()) { 478 return It->second; 479 } 480 481 SmallString<256> RealPath; 482 StringRef RealFilename; 483 484 // Path can be 485 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for 486 // such a case we must get the real_path. 487 if (sys::fs::real_path(Filename, RealPath)) { 488 // real_path can fail with path like "foo.c". 489 RealFilename = Filename; 490 } else { 491 RealFilename = RealPath; 492 } 493 494 bool ShouldInstrument; 495 if (FilterRe.empty()) { 496 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe); 497 } else if (ExcludeRe.empty()) { 498 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe); 499 } else { 500 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) && 501 !doesFilenameMatchARegex(RealFilename, ExcludeRe); 502 } 503 InstrumentedFiles[Filename] = ShouldInstrument; 504 return ShouldInstrument; 505 } 506 507 std::string GCOVProfiler::mangleName(const DICompileUnit *CU, 508 GCovFileType OutputType) { 509 bool Notes = OutputType == GCovFileType::GCNO; 510 511 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) { 512 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) { 513 MDNode *N = GCov->getOperand(i); 514 bool ThreeElement = N->getNumOperands() == 3; 515 if (!ThreeElement && N->getNumOperands() != 2) 516 continue; 517 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU) 518 continue; 519 520 if (ThreeElement) { 521 // These nodes have no mangling to apply, it's stored mangled in the 522 // bitcode. 523 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0)); 524 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1)); 525 if (!NotesFile || !DataFile) 526 continue; 527 return std::string(Notes ? NotesFile->getString() 528 : DataFile->getString()); 529 } 530 531 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0)); 532 if (!GCovFile) 533 continue; 534 535 SmallString<128> Filename = GCovFile->getString(); 536 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda"); 537 return std::string(Filename.str()); 538 } 539 } 540 541 SmallString<128> Filename = CU->getFilename(); 542 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda"); 543 StringRef FName = sys::path::filename(Filename); 544 SmallString<128> CurPath; 545 if (sys::fs::current_path(CurPath)) 546 return std::string(FName); 547 sys::path::append(CurPath, FName); 548 return std::string(CurPath.str()); 549 } 550 551 bool GCOVProfiler::runOnModule( 552 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) { 553 this->M = &M; 554 this->GetTLI = std::move(GetTLI); 555 Ctx = &M.getContext(); 556 557 AddFlushBeforeForkAndExec(); 558 559 FilterRe = createRegexesFromString(Options.Filter); 560 ExcludeRe = createRegexesFromString(Options.Exclude); 561 562 if (Options.EmitNotes) emitProfileNotes(); 563 if (Options.EmitData) return emitProfileArcs(); 564 return false; 565 } 566 567 PreservedAnalyses GCOVProfilerPass::run(Module &M, 568 ModuleAnalysisManager &AM) { 569 570 GCOVProfiler Profiler(GCOVOpts); 571 FunctionAnalysisManager &FAM = 572 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 573 574 if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & { 575 return FAM.getResult<TargetLibraryAnalysis>(F); 576 })) 577 return PreservedAnalyses::all(); 578 579 return PreservedAnalyses::none(); 580 } 581 582 static bool functionHasLines(const Function &F, unsigned &EndLine) { 583 // Check whether this function actually has any source lines. Not only 584 // do these waste space, they also can crash gcov. 585 EndLine = 0; 586 for (auto &BB : F) { 587 for (auto &I : BB) { 588 // Debug intrinsic locations correspond to the location of the 589 // declaration, not necessarily any statements or expressions. 590 if (isa<DbgInfoIntrinsic>(&I)) continue; 591 592 const DebugLoc &Loc = I.getDebugLoc(); 593 if (!Loc) 594 continue; 595 596 // Artificial lines such as calls to the global constructors. 597 if (Loc.getLine() == 0) continue; 598 EndLine = std::max(EndLine, Loc.getLine()); 599 600 return true; 601 } 602 } 603 return false; 604 } 605 606 static bool isUsingScopeBasedEH(Function &F) { 607 if (!F.hasPersonalityFn()) return false; 608 609 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn()); 610 return isScopedEHPersonality(Personality); 611 } 612 613 static bool shouldKeepInEntry(BasicBlock::iterator It) { 614 if (isa<AllocaInst>(*It)) return true; 615 if (isa<DbgInfoIntrinsic>(*It)) return true; 616 if (auto *II = dyn_cast<IntrinsicInst>(It)) { 617 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true; 618 } 619 620 return false; 621 } 622 623 void GCOVProfiler::AddFlushBeforeForkAndExec() { 624 SmallVector<CallInst *, 2> Forks; 625 SmallVector<CallInst *, 2> Execs; 626 for (auto &F : M->functions()) { 627 auto *TLI = &GetTLI(F); 628 for (auto &I : instructions(F)) { 629 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 630 if (Function *Callee = CI->getCalledFunction()) { 631 LibFunc LF; 632 if (TLI->getLibFunc(*Callee, LF)) { 633 if (LF == LibFunc_fork) { 634 #if !defined(_WIN32) 635 Forks.push_back(CI); 636 #endif 637 } else if (LF == LibFunc_execl || LF == LibFunc_execle || 638 LF == LibFunc_execlp || LF == LibFunc_execv || 639 LF == LibFunc_execvp || LF == LibFunc_execve || 640 LF == LibFunc_execvpe || LF == LibFunc_execvP) { 641 Execs.push_back(CI); 642 } 643 } 644 } 645 } 646 } 647 } 648 649 for (auto F : Forks) { 650 IRBuilder<> Builder(F); 651 BasicBlock *Parent = F->getParent(); 652 auto NextInst = ++F->getIterator(); 653 654 // We've a fork so just reset the counters in the child process 655 FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false); 656 FunctionCallee GCOVFork = M->getOrInsertFunction("__gcov_fork", FTy); 657 F->setCalledFunction(GCOVFork); 658 659 // We split just after the fork to have a counter for the lines after 660 // Anyway there's a bug: 661 // void foo() { fork(); } 662 // void bar() { foo(); blah(); } 663 // then "blah();" will be called 2 times but showed as 1 664 // because "blah()" belongs to the same block as "foo();" 665 Parent->splitBasicBlock(NextInst); 666 667 // back() is a br instruction with a debug location 668 // equals to the one from NextAfterFork 669 // So to avoid to have two debug locs on two blocks just change it 670 DebugLoc Loc = F->getDebugLoc(); 671 Parent->back().setDebugLoc(Loc); 672 } 673 674 for (auto E : Execs) { 675 IRBuilder<> Builder(E); 676 BasicBlock *Parent = E->getParent(); 677 auto NextInst = ++E->getIterator(); 678 679 // Since the process is replaced by a new one we need to write out gcdas 680 // No need to reset the counters since they'll be lost after the exec** 681 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false); 682 FunctionCallee WriteoutF = 683 M->getOrInsertFunction("llvm_writeout_files", FTy); 684 Builder.CreateCall(WriteoutF); 685 686 DebugLoc Loc = E->getDebugLoc(); 687 Builder.SetInsertPoint(&*NextInst); 688 // If the exec** fails we must reset the counters since they've been 689 // dumped 690 FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy); 691 Builder.CreateCall(ResetF)->setDebugLoc(Loc); 692 Parent->splitBasicBlock(NextInst); 693 Parent->back().setDebugLoc(Loc); 694 } 695 } 696 697 void GCOVProfiler::emitProfileNotes() { 698 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 699 if (!CU_Nodes) return; 700 701 int Version; 702 { 703 uint8_t c3 = Options.Version[0]; 704 uint8_t c2 = Options.Version[1]; 705 uint8_t c1 = Options.Version[2]; 706 Version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0' 707 : (c3 - '0') * 10 + c1 - '0'; 708 } 709 710 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) { 711 // Each compile unit gets its own .gcno file. This means that whether we run 712 // this pass over the original .o's as they're produced, or run it after 713 // LTO, we'll generate the same .gcno files. 714 715 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i)); 716 717 // Skip module skeleton (and module) CUs. 718 if (CU->getDWOId()) 719 continue; 720 721 std::error_code EC; 722 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, 723 sys::fs::OF_None); 724 if (EC) { 725 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") + 726 EC.message()); 727 continue; 728 } 729 730 std::string EdgeDestinations; 731 732 Endian = M->getDataLayout().isLittleEndian() ? support::endianness::little 733 : support::endianness::big; 734 unsigned FunctionIdent = 0; 735 for (auto &F : M->functions()) { 736 DISubprogram *SP = F.getSubprogram(); 737 unsigned EndLine; 738 if (!SP) continue; 739 if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F)) 740 continue; 741 // TODO: Functions using scope-based EH are currently not supported. 742 if (isUsingScopeBasedEH(F)) continue; 743 744 // gcov expects every function to start with an entry block that has a 745 // single successor, so split the entry block to make sure of that. 746 BasicBlock &EntryBlock = F.getEntryBlock(); 747 BasicBlock::iterator It = EntryBlock.begin(); 748 while (shouldKeepInEntry(It)) 749 ++It; 750 EntryBlock.splitBasicBlock(It); 751 752 Funcs.push_back(std::make_unique<GCOVFunction>(this, &F, SP, EndLine, 753 FunctionIdent++, Version)); 754 GCOVFunction &Func = *Funcs.back(); 755 756 // Add the function line number to the lines of the entry block 757 // to have a counter for the function definition. 758 uint32_t Line = SP->getLine(); 759 auto Filename = getFilename(SP); 760 761 // Artificial functions such as global initializers 762 if (!SP->isArtificial()) 763 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line); 764 765 for (auto &BB : F) { 766 GCOVBlock &Block = Func.getBlock(&BB); 767 Instruction *TI = BB.getTerminator(); 768 if (int successors = TI->getNumSuccessors()) { 769 for (int i = 0; i != successors; ++i) { 770 Block.addEdge(Func.getBlock(TI->getSuccessor(i))); 771 } 772 } else if (isa<ReturnInst>(TI)) { 773 Block.addEdge(Func.getReturnBlock()); 774 } 775 776 for (auto &I : BB) { 777 // Debug intrinsic locations correspond to the location of the 778 // declaration, not necessarily any statements or expressions. 779 if (isa<DbgInfoIntrinsic>(&I)) continue; 780 781 const DebugLoc &Loc = I.getDebugLoc(); 782 if (!Loc) 783 continue; 784 785 // Artificial lines such as calls to the global constructors. 786 if (Loc.getLine() == 0 || Loc.isImplicitCode()) 787 continue; 788 789 if (Line == Loc.getLine()) continue; 790 Line = Loc.getLine(); 791 if (SP != getDISubprogram(Loc.getScope())) 792 continue; 793 794 GCOVLines &Lines = Block.getFile(Filename); 795 Lines.addLine(Loc.getLine()); 796 } 797 Line = 0; 798 } 799 EdgeDestinations += Func.getEdgeDestinations(); 800 } 801 802 char Tmp[4]; 803 os = &out; 804 auto Stamp = static_cast<uint32_t>(hash_value(EdgeDestinations)); 805 FileChecksums.push_back(Stamp); 806 if (Endian == support::endianness::big) { 807 out.write("gcno", 4); 808 out.write(Options.Version, 4); 809 } else { 810 out.write("oncg", 4); 811 std::reverse_copy(Options.Version, Options.Version + 4, Tmp); 812 out.write(Tmp, 4); 813 } 814 write(Stamp); 815 if (Version >= 90) 816 writeString(""); // unuseful current_working_directory 817 if (Version >= 80) 818 write(0); // unuseful has_unexecuted_blocks 819 820 for (auto &Func : Funcs) 821 Func->writeOut(Stamp); 822 823 write(0); 824 write(0); 825 out.close(); 826 } 827 } 828 829 bool GCOVProfiler::emitProfileArcs() { 830 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 831 if (!CU_Nodes) return false; 832 833 bool Result = false; 834 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) { 835 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP; 836 for (auto &F : M->functions()) { 837 DISubprogram *SP = F.getSubprogram(); 838 unsigned EndLine; 839 if (!SP) continue; 840 if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F)) 841 continue; 842 // TODO: Functions using scope-based EH are currently not supported. 843 if (isUsingScopeBasedEH(F)) continue; 844 if (!Result) Result = true; 845 846 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter; 847 unsigned Edges = 0; 848 for (auto &BB : F) { 849 Instruction *TI = BB.getTerminator(); 850 if (isa<ReturnInst>(TI)) { 851 EdgeToCounter[{&BB, nullptr}] = Edges++; 852 } else { 853 for (BasicBlock *Succ : successors(TI)) { 854 EdgeToCounter[{&BB, Succ}] = Edges++; 855 } 856 } 857 } 858 859 ArrayType *CounterTy = 860 ArrayType::get(Type::getInt64Ty(*Ctx), Edges); 861 GlobalVariable *Counters = 862 new GlobalVariable(*M, CounterTy, false, 863 GlobalValue::InternalLinkage, 864 Constant::getNullValue(CounterTy), 865 "__llvm_gcov_ctr"); 866 CountersBySP.push_back(std::make_pair(Counters, SP)); 867 868 // If a BB has several predecessors, use a PHINode to select 869 // the correct counter. 870 for (auto &BB : F) { 871 const unsigned EdgeCount = 872 std::distance(pred_begin(&BB), pred_end(&BB)); 873 if (EdgeCount) { 874 // The phi node must be at the begin of the BB. 875 IRBuilder<> BuilderForPhi(&*BB.begin()); 876 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx); 877 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount); 878 for (BasicBlock *Pred : predecessors(&BB)) { 879 auto It = EdgeToCounter.find({Pred, &BB}); 880 assert(It != EdgeToCounter.end()); 881 const unsigned Edge = It->second; 882 Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64( 883 Counters->getValueType(), Counters, 0, Edge); 884 Phi->addIncoming(EdgeCounter, Pred); 885 } 886 887 // Skip phis, landingpads. 888 IRBuilder<> Builder(&*BB.getFirstInsertionPt()); 889 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi); 890 Count = Builder.CreateAdd(Count, Builder.getInt64(1)); 891 Builder.CreateStore(Count, Phi); 892 893 Instruction *TI = BB.getTerminator(); 894 if (isa<ReturnInst>(TI)) { 895 auto It = EdgeToCounter.find({&BB, nullptr}); 896 assert(It != EdgeToCounter.end()); 897 const unsigned Edge = It->second; 898 Value *Counter = Builder.CreateConstInBoundsGEP2_64( 899 Counters->getValueType(), Counters, 0, Edge); 900 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter); 901 Count = Builder.CreateAdd(Count, Builder.getInt64(1)); 902 Builder.CreateStore(Count, Counter); 903 } 904 } 905 } 906 } 907 908 Function *WriteoutF = insertCounterWriteout(CountersBySP); 909 Function *ResetF = insertReset(CountersBySP); 910 Function *FlushF = insertFlush(ResetF); 911 912 // Create a small bit of code that registers the "__llvm_gcov_writeout" to 913 // be executed at exit and the "__llvm_gcov_flush" function to be executed 914 // when "__gcov_flush" is called. 915 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 916 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage, 917 "__llvm_gcov_init", M); 918 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 919 F->setLinkage(GlobalValue::InternalLinkage); 920 F->addFnAttr(Attribute::NoInline); 921 if (Options.NoRedZone) 922 F->addFnAttr(Attribute::NoRedZone); 923 924 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F); 925 IRBuilder<> Builder(BB); 926 927 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 928 Type *Params[] = {PointerType::get(FTy, 0), PointerType::get(FTy, 0), 929 PointerType::get(FTy, 0)}; 930 FTy = FunctionType::get(Builder.getVoidTy(), Params, false); 931 932 // Initialize the environment and register the local writeout, flush and 933 // reset functions. 934 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy); 935 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF, ResetF}); 936 Builder.CreateRetVoid(); 937 938 appendToGlobalCtors(*M, F, 0); 939 } 940 941 return Result; 942 } 943 944 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) { 945 Type *Args[] = { 946 Type::getInt8PtrTy(*Ctx), // const char *orig_filename 947 Type::getInt32Ty(*Ctx), // uint32_t version 948 Type::getInt32Ty(*Ctx), // uint32_t checksum 949 }; 950 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false); 951 AttributeList AL; 952 if (auto AK = TLI->getExtAttrForI32Param(false)) 953 AL = AL.addParamAttribute(*Ctx, 2, AK); 954 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL); 955 return Res; 956 } 957 958 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) { 959 Type *Args[] = { 960 Type::getInt32Ty(*Ctx), // uint32_t ident 961 Type::getInt32Ty(*Ctx), // uint32_t func_checksum 962 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum 963 }; 964 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false); 965 AttributeList AL; 966 if (auto AK = TLI->getExtAttrForI32Param(false)) { 967 AL = AL.addParamAttribute(*Ctx, 0, AK); 968 AL = AL.addParamAttribute(*Ctx, 1, AK); 969 AL = AL.addParamAttribute(*Ctx, 2, AK); 970 } 971 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy); 972 } 973 974 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) { 975 Type *Args[] = { 976 Type::getInt32Ty(*Ctx), // uint32_t num_counters 977 Type::getInt64PtrTy(*Ctx), // uint64_t *counters 978 }; 979 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false); 980 AttributeList AL; 981 if (auto AK = TLI->getExtAttrForI32Param(false)) 982 AL = AL.addParamAttribute(*Ctx, 0, AK); 983 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL); 984 } 985 986 FunctionCallee GCOVProfiler::getSummaryInfoFunc() { 987 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 988 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy); 989 } 990 991 FunctionCallee GCOVProfiler::getEndFileFunc() { 992 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 993 return M->getOrInsertFunction("llvm_gcda_end_file", FTy); 994 } 995 996 Function *GCOVProfiler::insertCounterWriteout( 997 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) { 998 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 999 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout"); 1000 if (!WriteoutF) 1001 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage, 1002 "__llvm_gcov_writeout", M); 1003 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1004 WriteoutF->addFnAttr(Attribute::NoInline); 1005 if (Options.NoRedZone) 1006 WriteoutF->addFnAttr(Attribute::NoRedZone); 1007 1008 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF); 1009 IRBuilder<> Builder(BB); 1010 1011 auto *TLI = &GetTLI(*WriteoutF); 1012 1013 FunctionCallee StartFile = getStartFileFunc(TLI); 1014 FunctionCallee EmitFunction = getEmitFunctionFunc(TLI); 1015 FunctionCallee EmitArcs = getEmitArcsFunc(TLI); 1016 FunctionCallee SummaryInfo = getSummaryInfoFunc(); 1017 FunctionCallee EndFile = getEndFileFunc(); 1018 1019 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu"); 1020 if (!CUNodes) { 1021 Builder.CreateRetVoid(); 1022 return WriteoutF; 1023 } 1024 1025 // Collect the relevant data into a large constant data structure that we can 1026 // walk to write out everything. 1027 StructType *StartFileCallArgsTy = StructType::create( 1028 {Builder.getInt8PtrTy(), Builder.getInt32Ty(), Builder.getInt32Ty()}); 1029 StructType *EmitFunctionCallArgsTy = StructType::create( 1030 {Builder.getInt32Ty(), Builder.getInt32Ty(), Builder.getInt32Ty()}); 1031 StructType *EmitArcsCallArgsTy = StructType::create( 1032 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()}); 1033 StructType *FileInfoTy = 1034 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(), 1035 EmitFunctionCallArgsTy->getPointerTo(), 1036 EmitArcsCallArgsTy->getPointerTo()}); 1037 1038 Constant *Zero32 = Builder.getInt32(0); 1039 // Build an explicit array of two zeros for use in ConstantExpr GEP building. 1040 Constant *TwoZero32s[] = {Zero32, Zero32}; 1041 1042 SmallVector<Constant *, 8> FileInfos; 1043 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) { 1044 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i)); 1045 1046 // Skip module skeleton (and module) CUs. 1047 if (CU->getDWOId()) 1048 continue; 1049 1050 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA); 1051 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i]; 1052 auto *StartFileCallArgs = ConstantStruct::get( 1053 StartFileCallArgsTy, 1054 {Builder.CreateGlobalStringPtr(FilenameGcda), 1055 Builder.getInt32(endian::read32be(Options.Version)), 1056 Builder.getInt32(CfgChecksum)}); 1057 1058 SmallVector<Constant *, 8> EmitFunctionCallArgsArray; 1059 SmallVector<Constant *, 8> EmitArcsCallArgsArray; 1060 for (int j : llvm::seq<int>(0, CountersBySP.size())) { 1061 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum(); 1062 EmitFunctionCallArgsArray.push_back(ConstantStruct::get( 1063 EmitFunctionCallArgsTy, 1064 {Builder.getInt32(j), 1065 Builder.getInt32(FuncChecksum), 1066 Builder.getInt32(CfgChecksum)})); 1067 1068 GlobalVariable *GV = CountersBySP[j].first; 1069 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements(); 1070 EmitArcsCallArgsArray.push_back(ConstantStruct::get( 1071 EmitArcsCallArgsTy, 1072 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr( 1073 GV->getValueType(), GV, TwoZero32s)})); 1074 } 1075 // Create global arrays for the two emit calls. 1076 int CountersSize = CountersBySP.size(); 1077 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() && 1078 "Mismatched array size!"); 1079 assert(CountersSize == (int)EmitArcsCallArgsArray.size() && 1080 "Mismatched array size!"); 1081 auto *EmitFunctionCallArgsArrayTy = 1082 ArrayType::get(EmitFunctionCallArgsTy, CountersSize); 1083 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable( 1084 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true, 1085 GlobalValue::InternalLinkage, 1086 ConstantArray::get(EmitFunctionCallArgsArrayTy, 1087 EmitFunctionCallArgsArray), 1088 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i)); 1089 auto *EmitArcsCallArgsArrayTy = 1090 ArrayType::get(EmitArcsCallArgsTy, CountersSize); 1091 EmitFunctionCallArgsArrayGV->setUnnamedAddr( 1092 GlobalValue::UnnamedAddr::Global); 1093 auto *EmitArcsCallArgsArrayGV = new GlobalVariable( 1094 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true, 1095 GlobalValue::InternalLinkage, 1096 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray), 1097 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i)); 1098 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1099 1100 FileInfos.push_back(ConstantStruct::get( 1101 FileInfoTy, 1102 {StartFileCallArgs, Builder.getInt32(CountersSize), 1103 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy, 1104 EmitFunctionCallArgsArrayGV, 1105 TwoZero32s), 1106 ConstantExpr::getInBoundsGetElementPtr( 1107 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)})); 1108 } 1109 1110 // If we didn't find anything to actually emit, bail on out. 1111 if (FileInfos.empty()) { 1112 Builder.CreateRetVoid(); 1113 return WriteoutF; 1114 } 1115 1116 // To simplify code, we cap the number of file infos we write out to fit 1117 // easily in a 32-bit signed integer. This gives consistent behavior between 1118 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit 1119 // operations on 32-bit systems. It also seems unreasonable to try to handle 1120 // more than 2 billion files. 1121 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX) 1122 FileInfos.resize(INT_MAX); 1123 1124 // Create a global for the entire data structure so we can walk it more 1125 // easily. 1126 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size()); 1127 auto *FileInfoArrayGV = new GlobalVariable( 1128 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage, 1129 ConstantArray::get(FileInfoArrayTy, FileInfos), 1130 "__llvm_internal_gcov_emit_file_info"); 1131 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1132 1133 // Create the CFG for walking this data structure. 1134 auto *FileLoopHeader = 1135 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF); 1136 auto *CounterLoopHeader = 1137 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF); 1138 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF); 1139 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF); 1140 1141 // We always have at least one file, so just branch to the header. 1142 Builder.CreateBr(FileLoopHeader); 1143 1144 // The index into the files structure is our loop induction variable. 1145 Builder.SetInsertPoint(FileLoopHeader); 1146 PHINode *IV = 1147 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2); 1148 IV->addIncoming(Builder.getInt32(0), BB); 1149 auto *FileInfoPtr = Builder.CreateInBoundsGEP( 1150 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV}); 1151 auto *StartFileCallArgsPtr = 1152 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0); 1153 auto *StartFileCall = Builder.CreateCall( 1154 StartFile, 1155 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0), 1156 Builder.CreateStructGEP(StartFileCallArgsTy, 1157 StartFileCallArgsPtr, 0)), 1158 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1), 1159 Builder.CreateStructGEP(StartFileCallArgsTy, 1160 StartFileCallArgsPtr, 1)), 1161 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2), 1162 Builder.CreateStructGEP(StartFileCallArgsTy, 1163 StartFileCallArgsPtr, 2))}); 1164 if (auto AK = TLI->getExtAttrForI32Param(false)) 1165 StartFileCall->addParamAttr(2, AK); 1166 auto *NumCounters = 1167 Builder.CreateLoad(FileInfoTy->getElementType(1), 1168 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1)); 1169 auto *EmitFunctionCallArgsArray = 1170 Builder.CreateLoad(FileInfoTy->getElementType(2), 1171 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2)); 1172 auto *EmitArcsCallArgsArray = 1173 Builder.CreateLoad(FileInfoTy->getElementType(3), 1174 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3)); 1175 auto *EnterCounterLoopCond = 1176 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters); 1177 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch); 1178 1179 Builder.SetInsertPoint(CounterLoopHeader); 1180 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2); 1181 JV->addIncoming(Builder.getInt32(0), FileLoopHeader); 1182 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP( 1183 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV); 1184 auto *EmitFunctionCall = Builder.CreateCall( 1185 EmitFunction, 1186 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0), 1187 Builder.CreateStructGEP(EmitFunctionCallArgsTy, 1188 EmitFunctionCallArgsPtr, 0)), 1189 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1), 1190 Builder.CreateStructGEP(EmitFunctionCallArgsTy, 1191 EmitFunctionCallArgsPtr, 1)), 1192 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2), 1193 Builder.CreateStructGEP(EmitFunctionCallArgsTy, 1194 EmitFunctionCallArgsPtr, 1195 2))}); 1196 if (auto AK = TLI->getExtAttrForI32Param(false)) { 1197 EmitFunctionCall->addParamAttr(0, AK); 1198 EmitFunctionCall->addParamAttr(1, AK); 1199 EmitFunctionCall->addParamAttr(2, AK); 1200 } 1201 auto *EmitArcsCallArgsPtr = 1202 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV); 1203 auto *EmitArcsCall = Builder.CreateCall( 1204 EmitArcs, 1205 {Builder.CreateLoad( 1206 EmitArcsCallArgsTy->getElementType(0), 1207 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)), 1208 Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1), 1209 Builder.CreateStructGEP(EmitArcsCallArgsTy, 1210 EmitArcsCallArgsPtr, 1))}); 1211 if (auto AK = TLI->getExtAttrForI32Param(false)) 1212 EmitArcsCall->addParamAttr(0, AK); 1213 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1)); 1214 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters); 1215 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch); 1216 JV->addIncoming(NextJV, CounterLoopHeader); 1217 1218 Builder.SetInsertPoint(FileLoopLatch); 1219 Builder.CreateCall(SummaryInfo, {}); 1220 Builder.CreateCall(EndFile, {}); 1221 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1)); 1222 auto *FileLoopCond = 1223 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size())); 1224 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB); 1225 IV->addIncoming(NextIV, FileLoopLatch); 1226 1227 Builder.SetInsertPoint(ExitBB); 1228 Builder.CreateRetVoid(); 1229 1230 return WriteoutF; 1231 } 1232 1233 Function *GCOVProfiler::insertReset( 1234 ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) { 1235 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 1236 Function *ResetF = M->getFunction("__llvm_gcov_reset"); 1237 if (!ResetF) 1238 ResetF = Function::Create(FTy, GlobalValue::InternalLinkage, 1239 "__llvm_gcov_reset", M); 1240 ResetF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1241 ResetF->addFnAttr(Attribute::NoInline); 1242 if (Options.NoRedZone) 1243 ResetF->addFnAttr(Attribute::NoRedZone); 1244 1245 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF); 1246 IRBuilder<> Builder(Entry); 1247 1248 // Zero out the counters. 1249 for (const auto &I : CountersBySP) { 1250 GlobalVariable *GV = I.first; 1251 Constant *Null = Constant::getNullValue(GV->getValueType()); 1252 Builder.CreateStore(Null, GV); 1253 } 1254 1255 Type *RetTy = ResetF->getReturnType(); 1256 if (RetTy->isVoidTy()) 1257 Builder.CreateRetVoid(); 1258 else if (RetTy->isIntegerTy()) 1259 // Used if __llvm_gcov_reset was implicitly declared. 1260 Builder.CreateRet(ConstantInt::get(RetTy, 0)); 1261 else 1262 report_fatal_error("invalid return type for __llvm_gcov_reset"); 1263 1264 return ResetF; 1265 } 1266 1267 Function *GCOVProfiler::insertFlush(Function *ResetF) { 1268 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false); 1269 Function *FlushF = M->getFunction("__llvm_gcov_flush"); 1270 if (!FlushF) 1271 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage, 1272 "__llvm_gcov_flush", M); 1273 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1274 FlushF->addFnAttr(Attribute::NoInline); 1275 if (Options.NoRedZone) 1276 FlushF->addFnAttr(Attribute::NoRedZone); 1277 1278 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF); 1279 1280 // Write out the current counters. 1281 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout"); 1282 assert(WriteoutF && "Need to create the writeout function first!"); 1283 1284 IRBuilder<> Builder(Entry); 1285 Builder.CreateCall(WriteoutF, {}); 1286 Builder.CreateCall(ResetF, {}); 1287 1288 Type *RetTy = FlushF->getReturnType(); 1289 if (RetTy->isVoidTy()) 1290 Builder.CreateRetVoid(); 1291 else if (RetTy->isIntegerTy()) 1292 // Used if __llvm_gcov_flush was implicitly declared. 1293 Builder.CreateRet(ConstantInt::get(RetTy, 0)); 1294 else 1295 report_fatal_error("invalid return type for __llvm_gcov_flush"); 1296 1297 return FlushF; 1298 } 1299