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