1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
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
7 //===----------------------------------------------------------------------===//
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"
14 //===----------------------------------------------------------------------===//
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"
50 namespace endian = llvm::support::endian;
52 #define DEBUG_TYPE "insert-gcov-profiling"
55 GCOV_TAG_FUNCTION = 0x01000000,
56 GCOV_TAG_BLOCKS = 0x01410000,
57 GCOV_TAG_ARCS = 0x01430000,
58 GCOV_TAG_LINES = 0x01450000,
61 static cl::opt<std::string> DefaultGCOVVersion("default-gcov-version",
62 cl::init("408*"), cl::Hidden,
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;
71 GCOVOptions GCOVOptions::getDefault() {
73 Options.EmitNotes = true;
74 Options.EmitData = true;
75 Options.NoRedZone = false;
77 if (DefaultGCOVVersion.size() != 4) {
78 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
81 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
90 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
91 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {}
93 runOnModule(Module &M,
94 std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
96 void write(uint32_t i) {
98 endian::write32(Bytes, i, Endian);
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);
106 void writeBytes(const char *Bytes, int Size) { os->write(Bytes, Size); }
109 // Create the .gcno files for the Module based on DebugInfo.
110 void emitProfileNotes();
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();
116 bool isFunctionInstrumented(const Function &F);
117 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
118 static bool doesFilenameMatchARegex(StringRef Filename,
119 std::vector<Regex> &Regexes);
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();
128 // Add the function to write out all our counters to the global destructor
131 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
132 Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
133 Function *insertFlush(Function *ResetF);
135 bool AddFlushBeforeForkAndExec();
137 enum class GCovFileType { GCNO, GCDA };
138 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
141 support::endianness Endian;
144 // Checksum, produced by hash of EdgeDestinations
145 SmallVector<uint32_t, 4> FileChecksums;
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;
156 class GCOVProfilerLegacyPass : public ModulePass {
159 GCOVProfilerLegacyPass()
160 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
161 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
162 : ModulePass(ID), Profiler(Opts) {
163 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
165 StringRef getPassName() const override { return "GCOV Profiler"; }
167 bool runOnModule(Module &M) override {
168 return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
169 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
173 void getAnalysisUsage(AnalysisUsage &AU) const override {
174 AU.addRequired<TargetLibraryInfoWrapperPass>();
178 GCOVProfiler Profiler;
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)
188 GCOVProfilerLegacyPass, "insert-gcov-profiling",
189 "Insert instrumentation for GCOV profiling", false, false)
191 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
192 return new GCOVProfilerLegacyPass(Options);
195 static StringRef getFunctionName(const DISubprogram *SP) {
196 if (!SP->getLinkageName().empty())
197 return SP->getLinkageName();
198 return SP->getName();
201 /// Extract a filename for a DISubprogram.
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))
212 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
221 GCOVRecord(GCOVProfiler *P) : P(P) {}
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); }
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
234 class GCOVLines : public GCOVRecord {
236 void addLine(uint32_t Line) {
237 assert(Line != 0 && "Line zero is not a valid real line number.");
238 Lines.push_back(Line);
241 uint32_t length() const {
242 return 1 + wordsOfString(Filename) + Lines.size();
247 writeString(Filename);
248 for (int i = 0, e = Lines.size(); i != e; ++i)
252 GCOVLines(GCOVProfiler *P, StringRef F)
253 : GCOVRecord(P), Filename(std::string(F)) {}
256 std::string Filename;
257 SmallVector<uint32_t, 32> Lines;
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
264 class GCOVBlock : public GCOVRecord {
266 GCOVLines &getFile(StringRef Filename) {
267 return LinesByFile.try_emplace(Filename, P, Filename).first->second;
270 void addEdge(GCOVBlock &Successor) {
271 OutEdges.push_back(&Successor);
276 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
277 for (auto &I : LinesByFile) {
278 Len += I.second.length();
279 SortedLinesByFile.push_back(&I);
282 write(GCOV_TAG_LINES);
286 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
287 StringMapEntry<GCOVLines> *RHS) {
288 return LHS->getKey() < RHS->getKey();
290 for (auto &I : SortedLinesByFile)
291 I->getValue().writeOut();
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());
305 friend class GCOVFunction;
307 GCOVBlock(GCOVProfiler *P, uint32_t Number)
308 : GCOVRecord(P), Number(Number) {}
311 StringMap<GCOVLines> LinesByFile;
312 SmallVector<GCOVBlock *, 4> OutEdges;
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 {
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;
327 for (auto &BB : *F) {
328 // Skip index 1 if it's assigned to the ReturnBlock.
329 if (i == 1 && ExitBlockBeforeBody)
331 Blocks.insert(std::make_pair(&BB, GCOVBlock(P, i++)));
333 if (!ExitBlockBeforeBody)
334 ReturnBlock.Number = i;
336 std::string FunctionNameAndLine;
337 raw_string_ostream FNLOS(FunctionNameAndLine);
338 FNLOS << getFunctionName(SP) << SP->getLine();
340 FuncChecksum = hash_value(FunctionNameAndLine);
343 GCOVBlock &getBlock(BasicBlock *BB) {
344 return Blocks.find(BB)->second;
347 GCOVBlock &getReturnBlock() {
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;
360 return EdgeDestinations;
363 uint32_t getFuncChecksum() const {
367 void writeOut(uint32_t CfgChecksum) {
368 write(GCOV_TAG_FUNCTION);
369 SmallString<128> Filename = getFilename(SP);
371 2 + (Version >= 47) + wordsOfString(getFunctionName(SP));
373 BlockLen += wordsOfString(Filename) + 1;
375 BlockLen += 1 + wordsOfString(Filename) + 3 + (Version >= 90);
382 writeString(getFunctionName(SP));
384 writeString(Filename);
385 write(SP->getLine());
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,
395 write(0); // end_column
398 // Emit count of blocks.
399 write(GCOV_TAG_BLOCKS);
401 write(Blocks.size() + 1);
402 for (int i = Blocks.size() + 1; i; --i)
406 write(Blocks.size() + 1);
408 LLVM_DEBUG(dbgs() << (Blocks.size() + 1) << " blocks\n");
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;
416 write(GCOV_TAG_ARCS);
417 write(Block.OutEdges.size() * 2 + 1);
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
427 // Emit lines for each block.
428 for (BasicBlock &I : *F)
429 getBlock(&I).writeOut();
433 const DISubprogram *SP;
436 uint32_t FuncChecksum;
438 DenseMap<BasicBlock *, GCOVBlock> Blocks;
439 GCOVBlock ReturnBlock;
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);
452 if (!Re.isValid(Err)) {
453 Ctx->emitError(Twine("Regex ") + HeadTail.first +
454 " is not valid: " + Err);
456 Regexes.emplace_back(std::move(Re));
458 RegexesStr = HeadTail.second;
463 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
464 std::vector<Regex> &Regexes) {
465 for (Regex &Re : Regexes)
466 if (Re.match(Filename))
471 bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
472 if (FilterRe.empty() && ExcludeRe.empty()) {
475 SmallString<128> Filename = getFilename(F.getSubprogram());
476 auto It = InstrumentedFiles.find(Filename);
477 if (It != InstrumentedFiles.end()) {
481 SmallString<256> RealPath;
482 StringRef RealFilename;
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;
491 RealFilename = RealPath;
494 bool ShouldInstrument;
495 if (FilterRe.empty()) {
496 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
497 } else if (ExcludeRe.empty()) {
498 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
500 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
501 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
503 InstrumentedFiles[Filename] = ShouldInstrument;
504 return ShouldInstrument;
507 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
508 GCovFileType OutputType) {
509 bool Notes = OutputType == GCovFileType::GCNO;
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)
517 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
521 // These nodes have no mangling to apply, it's stored mangled in the
523 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
524 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
525 if (!NotesFile || !DataFile)
527 return std::string(Notes ? NotesFile->getString()
528 : DataFile->getString());
531 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
535 SmallString<128> Filename = GCovFile->getString();
536 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
537 return std::string(Filename.str());
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());
551 bool GCOVProfiler::runOnModule(
552 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
554 this->GetTLI = std::move(GetTLI);
555 Ctx = &M.getContext();
557 bool Modified = AddFlushBeforeForkAndExec();
559 FilterRe = createRegexesFromString(Options.Filter);
560 ExcludeRe = createRegexesFromString(Options.Exclude);
562 if (Options.EmitNotes) emitProfileNotes();
563 if (Options.EmitData)
564 Modified |= emitProfileArcs();
568 PreservedAnalyses GCOVProfilerPass::run(Module &M,
569 ModuleAnalysisManager &AM) {
571 GCOVProfiler Profiler(GCOVOpts);
572 FunctionAnalysisManager &FAM =
573 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
575 if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
576 return FAM.getResult<TargetLibraryAnalysis>(F);
578 return PreservedAnalyses::all();
580 return PreservedAnalyses::none();
583 static bool functionHasLines(const Function &F, unsigned &EndLine) {
584 // Check whether this function actually has any source lines. Not only
585 // do these waste space, they also can crash gcov.
589 // Debug intrinsic locations correspond to the location of the
590 // declaration, not necessarily any statements or expressions.
591 if (isa<DbgInfoIntrinsic>(&I)) continue;
593 const DebugLoc &Loc = I.getDebugLoc();
597 // Artificial lines such as calls to the global constructors.
598 if (Loc.getLine() == 0) continue;
599 EndLine = std::max(EndLine, Loc.getLine());
607 static bool isUsingScopeBasedEH(Function &F) {
608 if (!F.hasPersonalityFn()) return false;
610 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
611 return isScopedEHPersonality(Personality);
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;
624 bool GCOVProfiler::AddFlushBeforeForkAndExec() {
625 SmallVector<CallInst *, 2> Forks;
626 SmallVector<CallInst *, 2> Execs;
627 for (auto &F : M->functions()) {
628 auto *TLI = &GetTLI(F);
629 for (auto &I : instructions(F)) {
630 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
631 if (Function *Callee = CI->getCalledFunction()) {
633 if (TLI->getLibFunc(*Callee, LF)) {
634 if (LF == LibFunc_fork) {
638 } else if (LF == LibFunc_execl || LF == LibFunc_execle ||
639 LF == LibFunc_execlp || LF == LibFunc_execv ||
640 LF == LibFunc_execvp || LF == LibFunc_execve ||
641 LF == LibFunc_execvpe || LF == LibFunc_execvP) {
650 for (auto F : Forks) {
651 IRBuilder<> Builder(F);
652 BasicBlock *Parent = F->getParent();
653 auto NextInst = ++F->getIterator();
655 // We've a fork so just reset the counters in the child process
656 FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false);
657 FunctionCallee GCOVFork = M->getOrInsertFunction("__gcov_fork", FTy);
658 F->setCalledFunction(GCOVFork);
660 // We split just after the fork to have a counter for the lines after
661 // Anyway there's a bug:
662 // void foo() { fork(); }
663 // void bar() { foo(); blah(); }
664 // then "blah();" will be called 2 times but showed as 1
665 // because "blah()" belongs to the same block as "foo();"
666 Parent->splitBasicBlock(NextInst);
668 // back() is a br instruction with a debug location
669 // equals to the one from NextAfterFork
670 // So to avoid to have two debug locs on two blocks just change it
671 DebugLoc Loc = F->getDebugLoc();
672 Parent->back().setDebugLoc(Loc);
675 for (auto E : Execs) {
676 IRBuilder<> Builder(E);
677 BasicBlock *Parent = E->getParent();
678 auto NextInst = ++E->getIterator();
680 // Since the process is replaced by a new one we need to write out gcdas
681 // No need to reset the counters since they'll be lost after the exec**
682 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
683 FunctionCallee WriteoutF =
684 M->getOrInsertFunction("llvm_writeout_files", FTy);
685 Builder.CreateCall(WriteoutF);
687 DebugLoc Loc = E->getDebugLoc();
688 Builder.SetInsertPoint(&*NextInst);
689 // If the exec** fails we must reset the counters since they've been
691 FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy);
692 Builder.CreateCall(ResetF)->setDebugLoc(Loc);
693 Parent->splitBasicBlock(NextInst);
694 Parent->back().setDebugLoc(Loc);
697 return !Forks.empty() || !Execs.empty();
700 void GCOVProfiler::emitProfileNotes() {
701 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
702 if (!CU_Nodes) return;
706 uint8_t c3 = Options.Version[0];
707 uint8_t c2 = Options.Version[1];
708 uint8_t c1 = Options.Version[2];
709 Version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0'
710 : (c3 - '0') * 10 + c1 - '0';
713 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
714 // Each compile unit gets its own .gcno file. This means that whether we run
715 // this pass over the original .o's as they're produced, or run it after
716 // LTO, we'll generate the same .gcno files.
718 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
720 // Skip module skeleton (and module) CUs.
725 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
728 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
733 std::string EdgeDestinations;
735 Endian = M->getDataLayout().isLittleEndian() ? support::endianness::little
736 : support::endianness::big;
737 unsigned FunctionIdent = 0;
738 for (auto &F : M->functions()) {
739 DISubprogram *SP = F.getSubprogram();
742 if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F))
744 // TODO: Functions using scope-based EH are currently not supported.
745 if (isUsingScopeBasedEH(F)) continue;
747 // gcov expects every function to start with an entry block that has a
748 // single successor, so split the entry block to make sure of that.
749 BasicBlock &EntryBlock = F.getEntryBlock();
750 BasicBlock::iterator It = EntryBlock.begin();
751 while (shouldKeepInEntry(It))
753 EntryBlock.splitBasicBlock(It);
755 Funcs.push_back(std::make_unique<GCOVFunction>(this, &F, SP, EndLine,
756 FunctionIdent++, Version));
757 GCOVFunction &Func = *Funcs.back();
759 // Add the function line number to the lines of the entry block
760 // to have a counter for the function definition.
761 uint32_t Line = SP->getLine();
762 auto Filename = getFilename(SP);
764 // Artificial functions such as global initializers
765 if (!SP->isArtificial())
766 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
769 GCOVBlock &Block = Func.getBlock(&BB);
770 Instruction *TI = BB.getTerminator();
771 if (int successors = TI->getNumSuccessors()) {
772 for (int i = 0; i != successors; ++i) {
773 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
775 } else if (isa<ReturnInst>(TI)) {
776 Block.addEdge(Func.getReturnBlock());
780 // Debug intrinsic locations correspond to the location of the
781 // declaration, not necessarily any statements or expressions.
782 if (isa<DbgInfoIntrinsic>(&I)) continue;
784 const DebugLoc &Loc = I.getDebugLoc();
788 // Artificial lines such as calls to the global constructors.
789 if (Loc.getLine() == 0 || Loc.isImplicitCode())
792 if (Line == Loc.getLine()) continue;
793 Line = Loc.getLine();
794 if (SP != getDISubprogram(Loc.getScope()))
797 GCOVLines &Lines = Block.getFile(Filename);
798 Lines.addLine(Loc.getLine());
802 EdgeDestinations += Func.getEdgeDestinations();
807 auto Stamp = static_cast<uint32_t>(hash_value(EdgeDestinations));
808 FileChecksums.push_back(Stamp);
809 if (Endian == support::endianness::big) {
810 out.write("gcno", 4);
811 out.write(Options.Version, 4);
813 out.write("oncg", 4);
814 std::reverse_copy(Options.Version, Options.Version + 4, Tmp);
819 writeString(""); // unuseful current_working_directory
821 write(0); // unuseful has_unexecuted_blocks
823 for (auto &Func : Funcs)
824 Func->writeOut(Stamp);
832 bool GCOVProfiler::emitProfileArcs() {
833 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
834 if (!CU_Nodes) return false;
837 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
838 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
839 for (auto &F : M->functions()) {
840 DISubprogram *SP = F.getSubprogram();
843 if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F))
845 // TODO: Functions using scope-based EH are currently not supported.
846 if (isUsingScopeBasedEH(F)) continue;
848 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
851 Instruction *TI = BB.getTerminator();
852 if (isa<ReturnInst>(TI)) {
853 EdgeToCounter[{&BB, nullptr}] = Edges++;
855 for (BasicBlock *Succ : successors(TI)) {
856 EdgeToCounter[{&BB, Succ}] = Edges++;
861 ArrayType *CounterTy =
862 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
863 GlobalVariable *Counters =
864 new GlobalVariable(*M, CounterTy, false,
865 GlobalValue::InternalLinkage,
866 Constant::getNullValue(CounterTy),
868 CountersBySP.push_back(std::make_pair(Counters, SP));
870 // If a BB has several predecessors, use a PHINode to select
871 // the correct counter.
873 const unsigned EdgeCount =
874 std::distance(pred_begin(&BB), pred_end(&BB));
876 // The phi node must be at the begin of the BB.
877 IRBuilder<> BuilderForPhi(&*BB.begin());
878 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
879 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
880 for (BasicBlock *Pred : predecessors(&BB)) {
881 auto It = EdgeToCounter.find({Pred, &BB});
882 assert(It != EdgeToCounter.end());
883 const unsigned Edge = It->second;
884 Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
885 Counters->getValueType(), Counters, 0, Edge);
886 Phi->addIncoming(EdgeCounter, Pred);
889 // Skip phis, landingpads.
890 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
891 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
892 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
893 Builder.CreateStore(Count, Phi);
895 Instruction *TI = BB.getTerminator();
896 if (isa<ReturnInst>(TI)) {
897 auto It = EdgeToCounter.find({&BB, nullptr});
898 assert(It != EdgeToCounter.end());
899 const unsigned Edge = It->second;
900 Value *Counter = Builder.CreateConstInBoundsGEP2_64(
901 Counters->getValueType(), Counters, 0, Edge);
902 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
903 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
904 Builder.CreateStore(Count, Counter);
910 Function *WriteoutF = insertCounterWriteout(CountersBySP);
911 Function *ResetF = insertReset(CountersBySP);
912 Function *FlushF = insertFlush(ResetF);
914 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
915 // be executed at exit and the "__llvm_gcov_flush" function to be executed
916 // when "__gcov_flush" is called.
917 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
918 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
919 "__llvm_gcov_init", M);
920 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
921 F->setLinkage(GlobalValue::InternalLinkage);
922 F->addFnAttr(Attribute::NoInline);
923 if (Options.NoRedZone)
924 F->addFnAttr(Attribute::NoRedZone);
926 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
927 IRBuilder<> Builder(BB);
929 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
930 Type *Params[] = {PointerType::get(FTy, 0), PointerType::get(FTy, 0),
931 PointerType::get(FTy, 0)};
932 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
934 // Initialize the environment and register the local writeout, flush and
936 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
937 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF, ResetF});
938 Builder.CreateRetVoid();
940 appendToGlobalCtors(*M, F, 0);
947 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
949 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
950 Type::getInt32Ty(*Ctx), // uint32_t version
951 Type::getInt32Ty(*Ctx), // uint32_t checksum
953 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
955 if (auto AK = TLI->getExtAttrForI32Param(false))
956 AL = AL.addParamAttribute(*Ctx, 2, AK);
957 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
961 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
963 Type::getInt32Ty(*Ctx), // uint32_t ident
964 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
965 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
967 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
969 if (auto AK = TLI->getExtAttrForI32Param(false)) {
970 AL = AL.addParamAttribute(*Ctx, 0, AK);
971 AL = AL.addParamAttribute(*Ctx, 1, AK);
972 AL = AL.addParamAttribute(*Ctx, 2, AK);
974 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
977 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
979 Type::getInt32Ty(*Ctx), // uint32_t num_counters
980 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
982 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
984 if (auto AK = TLI->getExtAttrForI32Param(false))
985 AL = AL.addParamAttribute(*Ctx, 0, AK);
986 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
989 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
990 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
991 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
994 FunctionCallee GCOVProfiler::getEndFileFunc() {
995 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
996 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
999 Function *GCOVProfiler::insertCounterWriteout(
1000 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
1001 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1002 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1004 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
1005 "__llvm_gcov_writeout", M);
1006 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1007 WriteoutF->addFnAttr(Attribute::NoInline);
1008 if (Options.NoRedZone)
1009 WriteoutF->addFnAttr(Attribute::NoRedZone);
1011 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
1012 IRBuilder<> Builder(BB);
1014 auto *TLI = &GetTLI(*WriteoutF);
1016 FunctionCallee StartFile = getStartFileFunc(TLI);
1017 FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
1018 FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
1019 FunctionCallee SummaryInfo = getSummaryInfoFunc();
1020 FunctionCallee EndFile = getEndFileFunc();
1022 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
1024 Builder.CreateRetVoid();
1028 // Collect the relevant data into a large constant data structure that we can
1029 // walk to write out everything.
1030 StructType *StartFileCallArgsTy = StructType::create(
1031 {Builder.getInt8PtrTy(), Builder.getInt32Ty(), Builder.getInt32Ty()});
1032 StructType *EmitFunctionCallArgsTy = StructType::create(
1033 {Builder.getInt32Ty(), Builder.getInt32Ty(), Builder.getInt32Ty()});
1034 StructType *EmitArcsCallArgsTy = StructType::create(
1035 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
1036 StructType *FileInfoTy =
1037 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
1038 EmitFunctionCallArgsTy->getPointerTo(),
1039 EmitArcsCallArgsTy->getPointerTo()});
1041 Constant *Zero32 = Builder.getInt32(0);
1042 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
1043 Constant *TwoZero32s[] = {Zero32, Zero32};
1045 SmallVector<Constant *, 8> FileInfos;
1046 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
1047 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
1049 // Skip module skeleton (and module) CUs.
1053 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1054 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1055 auto *StartFileCallArgs = ConstantStruct::get(
1056 StartFileCallArgsTy,
1057 {Builder.CreateGlobalStringPtr(FilenameGcda),
1058 Builder.getInt32(endian::read32be(Options.Version)),
1059 Builder.getInt32(CfgChecksum)});
1061 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1062 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1063 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1064 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1065 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1066 EmitFunctionCallArgsTy,
1067 {Builder.getInt32(j),
1068 Builder.getInt32(FuncChecksum),
1069 Builder.getInt32(CfgChecksum)}));
1071 GlobalVariable *GV = CountersBySP[j].first;
1072 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1073 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1075 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1076 GV->getValueType(), GV, TwoZero32s)}));
1078 // Create global arrays for the two emit calls.
1079 int CountersSize = CountersBySP.size();
1080 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1081 "Mismatched array size!");
1082 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1083 "Mismatched array size!");
1084 auto *EmitFunctionCallArgsArrayTy =
1085 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1086 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1087 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1088 GlobalValue::InternalLinkage,
1089 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1090 EmitFunctionCallArgsArray),
1091 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1092 auto *EmitArcsCallArgsArrayTy =
1093 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1094 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1095 GlobalValue::UnnamedAddr::Global);
1096 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1097 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1098 GlobalValue::InternalLinkage,
1099 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1100 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1101 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1103 FileInfos.push_back(ConstantStruct::get(
1105 {StartFileCallArgs, Builder.getInt32(CountersSize),
1106 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1107 EmitFunctionCallArgsArrayGV,
1109 ConstantExpr::getInBoundsGetElementPtr(
1110 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1113 // If we didn't find anything to actually emit, bail on out.
1114 if (FileInfos.empty()) {
1115 Builder.CreateRetVoid();
1119 // To simplify code, we cap the number of file infos we write out to fit
1120 // easily in a 32-bit signed integer. This gives consistent behavior between
1121 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1122 // operations on 32-bit systems. It also seems unreasonable to try to handle
1123 // more than 2 billion files.
1124 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1125 FileInfos.resize(INT_MAX);
1127 // Create a global for the entire data structure so we can walk it more
1129 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1130 auto *FileInfoArrayGV = new GlobalVariable(
1131 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1132 ConstantArray::get(FileInfoArrayTy, FileInfos),
1133 "__llvm_internal_gcov_emit_file_info");
1134 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1136 // Create the CFG for walking this data structure.
1137 auto *FileLoopHeader =
1138 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1139 auto *CounterLoopHeader =
1140 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1141 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1142 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1144 // We always have at least one file, so just branch to the header.
1145 Builder.CreateBr(FileLoopHeader);
1147 // The index into the files structure is our loop induction variable.
1148 Builder.SetInsertPoint(FileLoopHeader);
1150 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1151 IV->addIncoming(Builder.getInt32(0), BB);
1152 auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1153 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1154 auto *StartFileCallArgsPtr =
1155 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1156 auto *StartFileCall = Builder.CreateCall(
1158 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1159 Builder.CreateStructGEP(StartFileCallArgsTy,
1160 StartFileCallArgsPtr, 0)),
1161 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1162 Builder.CreateStructGEP(StartFileCallArgsTy,
1163 StartFileCallArgsPtr, 1)),
1164 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1165 Builder.CreateStructGEP(StartFileCallArgsTy,
1166 StartFileCallArgsPtr, 2))});
1167 if (auto AK = TLI->getExtAttrForI32Param(false))
1168 StartFileCall->addParamAttr(2, AK);
1170 Builder.CreateLoad(FileInfoTy->getElementType(1),
1171 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1172 auto *EmitFunctionCallArgsArray =
1173 Builder.CreateLoad(FileInfoTy->getElementType(2),
1174 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1175 auto *EmitArcsCallArgsArray =
1176 Builder.CreateLoad(FileInfoTy->getElementType(3),
1177 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1178 auto *EnterCounterLoopCond =
1179 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1180 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1182 Builder.SetInsertPoint(CounterLoopHeader);
1183 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1184 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1185 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1186 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1187 auto *EmitFunctionCall = Builder.CreateCall(
1189 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1190 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1191 EmitFunctionCallArgsPtr, 0)),
1192 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1193 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1194 EmitFunctionCallArgsPtr, 1)),
1195 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1196 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1197 EmitFunctionCallArgsPtr,
1199 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1200 EmitFunctionCall->addParamAttr(0, AK);
1201 EmitFunctionCall->addParamAttr(1, AK);
1202 EmitFunctionCall->addParamAttr(2, AK);
1204 auto *EmitArcsCallArgsPtr =
1205 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1206 auto *EmitArcsCall = Builder.CreateCall(
1208 {Builder.CreateLoad(
1209 EmitArcsCallArgsTy->getElementType(0),
1210 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1211 Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1212 Builder.CreateStructGEP(EmitArcsCallArgsTy,
1213 EmitArcsCallArgsPtr, 1))});
1214 if (auto AK = TLI->getExtAttrForI32Param(false))
1215 EmitArcsCall->addParamAttr(0, AK);
1216 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1217 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1218 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1219 JV->addIncoming(NextJV, CounterLoopHeader);
1221 Builder.SetInsertPoint(FileLoopLatch);
1222 Builder.CreateCall(SummaryInfo, {});
1223 Builder.CreateCall(EndFile, {});
1224 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1225 auto *FileLoopCond =
1226 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1227 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1228 IV->addIncoming(NextIV, FileLoopLatch);
1230 Builder.SetInsertPoint(ExitBB);
1231 Builder.CreateRetVoid();
1236 Function *GCOVProfiler::insertReset(
1237 ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) {
1238 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1239 Function *ResetF = M->getFunction("__llvm_gcov_reset");
1241 ResetF = Function::Create(FTy, GlobalValue::InternalLinkage,
1242 "__llvm_gcov_reset", M);
1243 ResetF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1244 ResetF->addFnAttr(Attribute::NoInline);
1245 if (Options.NoRedZone)
1246 ResetF->addFnAttr(Attribute::NoRedZone);
1248 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF);
1249 IRBuilder<> Builder(Entry);
1251 // Zero out the counters.
1252 for (const auto &I : CountersBySP) {
1253 GlobalVariable *GV = I.first;
1254 Constant *Null = Constant::getNullValue(GV->getValueType());
1255 Builder.CreateStore(Null, GV);
1258 Type *RetTy = ResetF->getReturnType();
1259 if (RetTy->isVoidTy())
1260 Builder.CreateRetVoid();
1261 else if (RetTy->isIntegerTy())
1262 // Used if __llvm_gcov_reset was implicitly declared.
1263 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1265 report_fatal_error("invalid return type for __llvm_gcov_reset");
1270 Function *GCOVProfiler::insertFlush(Function *ResetF) {
1271 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1272 Function *FlushF = M->getFunction("__llvm_gcov_flush");
1274 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1275 "__llvm_gcov_flush", M);
1276 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1277 FlushF->addFnAttr(Attribute::NoInline);
1278 if (Options.NoRedZone)
1279 FlushF->addFnAttr(Attribute::NoRedZone);
1281 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1283 // Write out the current counters.
1284 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1285 assert(WriteoutF && "Need to create the writeout function first!");
1287 IRBuilder<> Builder(Entry);
1288 Builder.CreateCall(WriteoutF, {});
1289 Builder.CreateCall(ResetF, {});
1291 Type *RetTy = FlushF->getReturnType();
1292 if (RetTy->isVoidTy())
1293 Builder.CreateRetVoid();
1294 else if (RetTy->isIntegerTy())
1295 // Used if __llvm_gcov_flush was implicitly declared.
1296 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1298 report_fatal_error("invalid return type for __llvm_gcov_flush");