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