1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/UniqueVector.h"
24 #include "llvm/Analysis/EHPersonalities.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/GCOVProfiler.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/ModuleUtils.h"
47 #define DEBUG_TYPE "insert-gcov-profiling"
49 static cl::opt<std::string>
50 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
52 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
53 cl::init(false), cl::Hidden);
55 GCOVOptions GCOVOptions::getDefault() {
57 Options.EmitNotes = true;
58 Options.EmitData = true;
59 Options.UseCfgChecksum = false;
60 Options.NoRedZone = false;
61 Options.FunctionNamesInData = true;
62 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
64 if (DefaultGCOVVersion.size() != 4) {
65 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
68 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
77 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
78 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
79 assert((Options.EmitNotes || Options.EmitData) &&
80 "GCOVProfiler asked to do nothing?");
81 ReversedVersion[0] = Options.Version[3];
82 ReversedVersion[1] = Options.Version[2];
83 ReversedVersion[2] = Options.Version[1];
84 ReversedVersion[3] = Options.Version[0];
85 ReversedVersion[4] = '\0';
87 bool runOnModule(Module &M);
90 // Create the .gcno files for the Module based on DebugInfo.
91 void emitProfileNotes();
93 // Modify the program to track transitions along edges and call into the
94 // profiling runtime to emit .gcda files when run.
95 bool emitProfileArcs();
97 // Get pointers to the functions in the runtime library.
98 Constant *getStartFileFunc();
99 Constant *getIncrementIndirectCounterFunc();
100 Constant *getEmitFunctionFunc();
101 Constant *getEmitArcsFunc();
102 Constant *getSummaryInfoFunc();
103 Constant *getEndFileFunc();
105 // Create or retrieve an i32 state value that is used to represent the
106 // pred block number for certain non-trivial edges.
107 GlobalVariable *getEdgeStateValue();
109 // Produce a table of pointers to counters, by predecessor and successor
111 GlobalVariable *buildEdgeLookupTable(Function *F, GlobalVariable *Counter,
112 const UniqueVector<BasicBlock *> &Preds,
113 const UniqueVector<BasicBlock *> &Succs);
115 // Add the function to write out all our counters to the global destructor
118 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
120 void insertIndirectCounterIncrement();
122 enum class GCovFileType { GCNO, GCDA };
123 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
127 // Reversed, NUL-terminated copy of Options.Version.
128 char ReversedVersion[5];
129 // Checksum, produced by hash of EdgeDestinations
130 SmallVector<uint32_t, 4> FileChecksums;
134 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
137 class GCOVProfilerLegacyPass : public ModulePass {
140 GCOVProfilerLegacyPass()
141 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
142 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
143 : ModulePass(ID), Profiler(Opts) {
144 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
146 StringRef getPassName() const override { return "GCOV Profiler"; }
148 bool runOnModule(Module &M) override { return Profiler.runOnModule(M); }
151 GCOVProfiler Profiler;
155 char GCOVProfilerLegacyPass::ID = 0;
156 INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling",
157 "Insert instrumentation for GCOV profiling", false, false)
159 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
160 return new GCOVProfilerLegacyPass(Options);
163 static StringRef getFunctionName(const DISubprogram *SP) {
164 if (!SP->getLinkageName().empty())
165 return SP->getLinkageName();
166 return SP->getName();
172 static const char *const LinesTag;
173 static const char *const FunctionTag;
174 static const char *const BlockTag;
175 static const char *const EdgeTag;
177 GCOVRecord() = default;
179 void writeBytes(const char *Bytes, int Size) {
180 os->write(Bytes, Size);
183 void write(uint32_t i) {
184 writeBytes(reinterpret_cast<char*>(&i), 4);
187 // Returns the length measured in 4-byte blocks that will be used to
188 // represent this string in a GCOV file
189 static unsigned lengthOfGCOVString(StringRef s) {
190 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
191 // padding out to the next 4-byte word. The length is measured in 4-byte
192 // words including padding, not bytes of actual string.
193 return (s.size() / 4) + 1;
196 void writeGCOVString(StringRef s) {
197 uint32_t Len = lengthOfGCOVString(s);
199 writeBytes(s.data(), s.size());
201 // Write 1 to 4 bytes of NUL padding.
202 assert((unsigned)(4 - (s.size() % 4)) > 0);
203 assert((unsigned)(4 - (s.size() % 4)) <= 4);
204 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
209 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
210 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
211 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
212 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
217 // Constructed only by requesting it from a GCOVBlock, this object stores a
218 // list of line numbers and a single filename, representing lines that belong
220 class GCOVLines : public GCOVRecord {
222 void addLine(uint32_t Line) {
223 assert(Line != 0 && "Line zero is not a valid real line number.");
224 Lines.push_back(Line);
227 uint32_t length() const {
228 // Here 2 = 1 for string length + 1 for '0' id#.
229 return lengthOfGCOVString(Filename) + 2 + Lines.size();
234 writeGCOVString(Filename);
235 for (int i = 0, e = Lines.size(); i != e; ++i)
239 GCOVLines(StringRef F, raw_ostream *os)
246 SmallVector<uint32_t, 32> Lines;
250 // Represent a basic block in GCOV. Each block has a unique number in the
251 // function, number of lines belonging to each block, and a set of edges to
253 class GCOVBlock : public GCOVRecord {
255 GCOVLines &getFile(StringRef Filename) {
256 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
259 void addEdge(GCOVBlock &Successor) {
260 OutEdges.push_back(&Successor);
265 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
266 for (auto &I : LinesByFile) {
267 Len += I.second.length();
268 SortedLinesByFile.push_back(&I);
271 writeBytes(LinesTag, 4);
276 SortedLinesByFile.begin(), SortedLinesByFile.end(),
277 [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
278 return LHS->getKey() < RHS->getKey();
280 for (auto &I : SortedLinesByFile)
281 I->getValue().writeOut();
286 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
287 // Only allow copy before edges and lines have been added. After that,
288 // there are inter-block pointers (eg: edges) that won't take kindly to
289 // blocks being copied or moved around.
290 assert(LinesByFile.empty());
291 assert(OutEdges.empty());
295 friend class GCOVFunction;
297 GCOVBlock(uint32_t Number, raw_ostream *os)
303 StringMap<GCOVLines> LinesByFile;
304 SmallVector<GCOVBlock *, 4> OutEdges;
307 // A function has a unique identifier, a checksum (we leave as zero) and a
308 // set of blocks and a map of edges between blocks. This is the only GCOV
309 // object users can construct, the blocks and lines will be rooted here.
310 class GCOVFunction : public GCOVRecord {
312 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
313 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
314 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
318 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
321 for (auto &BB : *F) {
322 // Skip index 1 if it's assigned to the ReturnBlock.
323 if (i == 1 && ExitBlockBeforeBody)
325 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
327 if (!ExitBlockBeforeBody)
328 ReturnBlock.Number = i;
330 std::string FunctionNameAndLine;
331 raw_string_ostream FNLOS(FunctionNameAndLine);
332 FNLOS << getFunctionName(SP) << SP->getLine();
334 FuncChecksum = hash_value(FunctionNameAndLine);
337 GCOVBlock &getBlock(BasicBlock *BB) {
338 return Blocks.find(BB)->second;
341 GCOVBlock &getReturnBlock() {
345 std::string getEdgeDestinations() {
346 std::string EdgeDestinations;
347 raw_string_ostream EDOS(EdgeDestinations);
348 Function *F = Blocks.begin()->first->getParent();
349 for (BasicBlock &I : *F) {
350 GCOVBlock &Block = getBlock(&I);
351 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
352 EDOS << Block.OutEdges[i]->Number;
354 return EdgeDestinations;
357 uint32_t getFuncChecksum() {
361 void setCfgChecksum(uint32_t Checksum) {
362 CfgChecksum = Checksum;
366 writeBytes(FunctionTag, 4);
367 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
368 1 + lengthOfGCOVString(SP->getFilename()) + 1;
376 writeGCOVString(getFunctionName(SP));
377 writeGCOVString(SP->getFilename());
378 write(SP->getLine());
380 // Emit count of blocks.
381 writeBytes(BlockTag, 4);
382 write(Blocks.size() + 1);
383 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
384 write(0); // No flags on our blocks.
386 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
388 // Emit edges between blocks.
389 if (Blocks.empty()) return;
390 Function *F = Blocks.begin()->first->getParent();
391 for (BasicBlock &I : *F) {
392 GCOVBlock &Block = getBlock(&I);
393 if (Block.OutEdges.empty()) continue;
395 writeBytes(EdgeTag, 4);
396 write(Block.OutEdges.size() * 2 + 1);
398 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
399 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
401 write(Block.OutEdges[i]->Number);
402 write(0); // no flags
406 // Emit lines for each block.
407 for (BasicBlock &I : *F)
408 getBlock(&I).writeOut();
412 const DISubprogram *SP;
414 uint32_t FuncChecksum;
416 uint32_t CfgChecksum;
417 DenseMap<BasicBlock *, GCOVBlock> Blocks;
418 GCOVBlock ReturnBlock;
422 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
423 GCovFileType OutputType) {
424 bool Notes = OutputType == GCovFileType::GCNO;
426 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
427 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
428 MDNode *N = GCov->getOperand(i);
429 bool ThreeElement = N->getNumOperands() == 3;
430 if (!ThreeElement && N->getNumOperands() != 2)
432 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
436 // These nodes have no mangling to apply, it's stored mangled in the
438 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
439 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
440 if (!NotesFile || !DataFile)
442 return Notes ? NotesFile->getString() : DataFile->getString();
445 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
449 SmallString<128> Filename = GCovFile->getString();
450 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
451 return Filename.str();
455 SmallString<128> Filename = CU->getFilename();
456 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
457 StringRef FName = sys::path::filename(Filename);
458 SmallString<128> CurPath;
459 if (sys::fs::current_path(CurPath)) return FName;
460 sys::path::append(CurPath, FName);
461 return CurPath.str();
464 bool GCOVProfiler::runOnModule(Module &M) {
466 Ctx = &M.getContext();
468 if (Options.EmitNotes) emitProfileNotes();
469 if (Options.EmitData) return emitProfileArcs();
473 PreservedAnalyses GCOVProfilerPass::run(Module &M,
474 ModuleAnalysisManager &AM) {
476 GCOVProfiler Profiler(GCOVOpts);
478 if (!Profiler.runOnModule(M))
479 return PreservedAnalyses::all();
481 return PreservedAnalyses::none();
484 static bool functionHasLines(Function &F) {
485 // Check whether this function actually has any source lines. Not only
486 // do these waste space, they also can crash gcov.
489 // Debug intrinsic locations correspond to the location of the
490 // declaration, not necessarily any statements or expressions.
491 if (isa<DbgInfoIntrinsic>(&I)) continue;
493 const DebugLoc &Loc = I.getDebugLoc();
497 // Artificial lines such as calls to the global constructors.
498 if (Loc.getLine() == 0) continue;
506 static bool isUsingFuncletBasedEH(Function &F) {
507 if (!F.hasPersonalityFn()) return false;
509 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
510 return isFuncletEHPersonality(Personality);
513 static bool shouldKeepInEntry(BasicBlock::iterator It) {
514 if (isa<AllocaInst>(*It)) return true;
515 if (isa<DbgInfoIntrinsic>(*It)) return true;
516 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
517 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
523 void GCOVProfiler::emitProfileNotes() {
524 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
525 if (!CU_Nodes) return;
527 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
528 // Each compile unit gets its own .gcno file. This means that whether we run
529 // this pass over the original .o's as they're produced, or run it after
530 // LTO, we'll generate the same .gcno files.
532 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
534 // Skip module skeleton (and module) CUs.
539 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
541 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
546 std::string EdgeDestinations;
548 unsigned FunctionIdent = 0;
549 for (auto &F : M->functions()) {
550 DISubprogram *SP = F.getSubprogram();
552 if (!functionHasLines(F)) continue;
553 // TODO: Functions using funclet-based EH are currently not supported.
554 if (isUsingFuncletBasedEH(F)) continue;
556 // gcov expects every function to start with an entry block that has a
557 // single successor, so split the entry block to make sure of that.
558 BasicBlock &EntryBlock = F.getEntryBlock();
559 BasicBlock::iterator It = EntryBlock.begin();
560 while (shouldKeepInEntry(It))
562 EntryBlock.splitBasicBlock(It);
564 Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
565 Options.UseCfgChecksum,
566 Options.ExitBlockBeforeBody));
567 GCOVFunction &Func = *Funcs.back();
570 GCOVBlock &Block = Func.getBlock(&BB);
571 TerminatorInst *TI = BB.getTerminator();
572 if (int successors = TI->getNumSuccessors()) {
573 for (int i = 0; i != successors; ++i) {
574 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
576 } else if (isa<ReturnInst>(TI)) {
577 Block.addEdge(Func.getReturnBlock());
582 // Debug intrinsic locations correspond to the location of the
583 // declaration, not necessarily any statements or expressions.
584 if (isa<DbgInfoIntrinsic>(&I)) continue;
586 const DebugLoc &Loc = I.getDebugLoc();
590 // Artificial lines such as calls to the global constructors.
591 if (Loc.getLine() == 0) continue;
593 if (Line == Loc.getLine()) continue;
594 Line = Loc.getLine();
595 if (SP != getDISubprogram(Loc.getScope()))
598 GCOVLines &Lines = Block.getFile(SP->getFilename());
599 Lines.addLine(Loc.getLine());
602 EdgeDestinations += Func.getEdgeDestinations();
605 FileChecksums.push_back(hash_value(EdgeDestinations));
606 out.write("oncg", 4);
607 out.write(ReversedVersion, 4);
608 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
610 for (auto &Func : Funcs) {
611 Func->setCfgChecksum(FileChecksums.back());
615 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
620 bool GCOVProfiler::emitProfileArcs() {
621 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
622 if (!CU_Nodes) return false;
625 bool InsertIndCounterIncrCode = false;
626 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
627 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
628 for (auto &F : M->functions()) {
629 DISubprogram *SP = F.getSubprogram();
631 if (!functionHasLines(F)) continue;
632 // TODO: Functions using funclet-based EH are currently not supported.
633 if (isUsingFuncletBasedEH(F)) continue;
634 if (!Result) Result = true;
638 TerminatorInst *TI = BB.getTerminator();
639 if (isa<ReturnInst>(TI))
642 Edges += TI->getNumSuccessors();
645 ArrayType *CounterTy =
646 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
647 GlobalVariable *Counters =
648 new GlobalVariable(*M, CounterTy, false,
649 GlobalValue::InternalLinkage,
650 Constant::getNullValue(CounterTy),
652 CountersBySP.push_back(std::make_pair(Counters, SP));
654 UniqueVector<BasicBlock *> ComplexEdgePreds;
655 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
659 TerminatorInst *TI = BB.getTerminator();
660 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
662 if (Successors == 1) {
663 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
664 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
666 Value *Count = Builder.CreateLoad(Counter);
667 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
668 Builder.CreateStore(Count, Counter);
669 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
670 IRBuilder<> Builder(BI);
671 Value *Sel = Builder.CreateSelect(BI->getCondition(),
672 Builder.getInt64(Edge),
673 Builder.getInt64(Edge + 1));
674 Value *Counter = Builder.CreateInBoundsGEP(
675 Counters->getValueType(), Counters, {Builder.getInt64(0), Sel});
676 Value *Count = Builder.CreateLoad(Counter);
677 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
678 Builder.CreateStore(Count, Counter);
680 ComplexEdgePreds.insert(&BB);
681 for (int i = 0; i != Successors; ++i)
682 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
689 if (!ComplexEdgePreds.empty()) {
690 GlobalVariable *EdgeTable =
691 buildEdgeLookupTable(&F, Counters,
692 ComplexEdgePreds, ComplexEdgeSuccs);
693 GlobalVariable *EdgeState = getEdgeStateValue();
695 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
696 IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
697 Builder.CreateStore(Builder.getInt32(i), EdgeState);
700 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
701 // Call runtime to perform increment.
702 IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
703 Value *CounterPtrArray =
704 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
705 i * ComplexEdgePreds.size());
707 // Build code to increment the counter.
708 InsertIndCounterIncrCode = true;
709 Builder.CreateCall(getIncrementIndirectCounterFunc(),
710 {EdgeState, CounterPtrArray});
715 Function *WriteoutF = insertCounterWriteout(CountersBySP);
716 Function *FlushF = insertFlush(CountersBySP);
718 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
719 // be executed at exit and the "__llvm_gcov_flush" function to be executed
720 // when "__gcov_flush" is called.
721 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
722 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
723 "__llvm_gcov_init", M);
724 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
725 F->setLinkage(GlobalValue::InternalLinkage);
726 F->addFnAttr(Attribute::NoInline);
727 if (Options.NoRedZone)
728 F->addFnAttr(Attribute::NoRedZone);
730 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
731 IRBuilder<> Builder(BB);
733 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
735 PointerType::get(FTy, 0),
736 PointerType::get(FTy, 0)
738 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
740 // Initialize the environment and register the local writeout and flush
742 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
743 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
744 Builder.CreateRetVoid();
746 appendToGlobalCtors(*M, F, 0);
749 if (InsertIndCounterIncrCode)
750 insertIndirectCounterIncrement();
755 // All edges with successors that aren't branches are "complex", because it
756 // requires complex logic to pick which counter to update.
757 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
759 GlobalVariable *Counters,
760 const UniqueVector<BasicBlock *> &Preds,
761 const UniqueVector<BasicBlock *> &Succs) {
762 // TODO: support invoke, threads. We rely on the fact that nothing can modify
763 // the whole-Module pred edge# between the time we set it and the time we next
764 // read it. Threads and invoke make this untrue.
766 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
767 size_t TableSize = Succs.size() * Preds.size();
768 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
769 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
771 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
772 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
773 for (size_t i = 0; i != TableSize; ++i)
774 EdgeTable[i] = NullValue;
777 for (BasicBlock &BB : *F) {
778 TerminatorInst *TI = BB.getTerminator();
779 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
780 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
781 for (int i = 0; i != Successors; ++i) {
782 BasicBlock *Succ = TI->getSuccessor(i);
783 IRBuilder<> Builder(Succ);
784 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
786 EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
787 (Preds.idFor(&BB) - 1)] = cast<Constant>(Counter);
793 GlobalVariable *EdgeTableGV =
795 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
796 ConstantArray::get(EdgeTableTy,
797 makeArrayRef(&EdgeTable[0],TableSize)),
798 "__llvm_gcda_edge_table");
799 EdgeTableGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
803 Constant *GCOVProfiler::getStartFileFunc() {
805 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
806 Type::getInt8PtrTy(*Ctx), // const char version[4]
807 Type::getInt32Ty(*Ctx), // uint32_t checksum
809 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
810 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
813 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
814 Type *Int32Ty = Type::getInt32Ty(*Ctx);
815 Type *Int64Ty = Type::getInt64Ty(*Ctx);
817 Int32Ty->getPointerTo(), // uint32_t *predecessor
818 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
820 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
821 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
824 Constant *GCOVProfiler::getEmitFunctionFunc() {
826 Type::getInt32Ty(*Ctx), // uint32_t ident
827 Type::getInt8PtrTy(*Ctx), // const char *function_name
828 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
829 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
830 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
832 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
833 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
836 Constant *GCOVProfiler::getEmitArcsFunc() {
838 Type::getInt32Ty(*Ctx), // uint32_t num_counters
839 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
841 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
842 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
845 Constant *GCOVProfiler::getSummaryInfoFunc() {
846 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
847 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
850 Constant *GCOVProfiler::getEndFileFunc() {
851 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
852 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
855 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
856 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
858 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
859 GlobalValue::InternalLinkage,
860 ConstantInt::get(Type::getInt32Ty(*Ctx),
862 "__llvm_gcov_global_state_pred");
863 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
868 Function *GCOVProfiler::insertCounterWriteout(
869 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
870 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
871 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
873 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
874 "__llvm_gcov_writeout", M);
875 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
876 WriteoutF->addFnAttr(Attribute::NoInline);
877 if (Options.NoRedZone)
878 WriteoutF->addFnAttr(Attribute::NoRedZone);
880 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
881 IRBuilder<> Builder(BB);
883 Constant *StartFile = getStartFileFunc();
884 Constant *EmitFunction = getEmitFunctionFunc();
885 Constant *EmitArcs = getEmitArcsFunc();
886 Constant *SummaryInfo = getSummaryInfoFunc();
887 Constant *EndFile = getEndFileFunc();
889 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
891 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
892 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
894 // Skip module skeleton (and module) CUs.
898 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
899 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
900 Builder.CreateCall(StartFile,
901 {Builder.CreateGlobalStringPtr(FilenameGcda),
902 Builder.CreateGlobalStringPtr(ReversedVersion),
903 Builder.getInt32(CfgChecksum)});
904 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
905 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
906 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
909 {Builder.getInt32(j),
910 Options.FunctionNamesInData
911 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
912 : Constant::getNullValue(Builder.getInt8PtrTy()),
913 Builder.getInt32(FuncChecksum),
914 Builder.getInt8(Options.UseCfgChecksum),
915 Builder.getInt32(CfgChecksum)});
917 GlobalVariable *GV = CountersBySP[j].first;
919 cast<ArrayType>(GV->getValueType())->getNumElements();
920 Builder.CreateCall(EmitArcs, {Builder.getInt32(Arcs),
921 Builder.CreateConstGEP2_64(GV, 0, 0)});
923 Builder.CreateCall(SummaryInfo, {});
924 Builder.CreateCall(EndFile, {});
928 Builder.CreateRetVoid();
932 void GCOVProfiler::insertIndirectCounterIncrement() {
934 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
935 Fn->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
936 Fn->setLinkage(GlobalValue::InternalLinkage);
937 Fn->addFnAttr(Attribute::NoInline);
938 if (Options.NoRedZone)
939 Fn->addFnAttr(Attribute::NoRedZone);
941 // Create basic blocks for function.
942 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
943 IRBuilder<> Builder(BB);
945 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
946 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
947 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
949 // uint32_t pred = *predecessor;
950 // if (pred == 0xffffffff) return;
951 Argument *Arg = &*Fn->arg_begin();
952 Arg->setName("predecessor");
953 Value *Pred = Builder.CreateLoad(Arg, "pred");
954 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
955 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
957 Builder.SetInsertPoint(PredNotNegOne);
959 // uint64_t *counter = counters[pred];
960 // if (!counter) return;
961 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
962 Arg = &*std::next(Fn->arg_begin());
963 Arg->setName("counters");
964 Value *GEP = Builder.CreateGEP(Type::getInt64PtrTy(*Ctx), Arg, ZExtPred);
965 Value *Counter = Builder.CreateLoad(GEP, "counter");
966 Cond = Builder.CreateICmpEQ(Counter,
967 Constant::getNullValue(
968 Builder.getInt64Ty()->getPointerTo()));
969 Builder.CreateCondBr(Cond, Exit, CounterEnd);
972 Builder.SetInsertPoint(CounterEnd);
973 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
974 Builder.getInt64(1));
975 Builder.CreateStore(Add, Counter);
976 Builder.CreateBr(Exit);
978 // Fill in the exit block.
979 Builder.SetInsertPoint(Exit);
980 Builder.CreateRetVoid();
983 Function *GCOVProfiler::
984 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
985 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
986 Function *FlushF = M->getFunction("__llvm_gcov_flush");
988 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
989 "__llvm_gcov_flush", M);
991 FlushF->setLinkage(GlobalValue::InternalLinkage);
992 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
993 FlushF->addFnAttr(Attribute::NoInline);
994 if (Options.NoRedZone)
995 FlushF->addFnAttr(Attribute::NoRedZone);
997 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
999 // Write out the current counters.
1000 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1001 assert(WriteoutF && "Need to create the writeout function first!");
1003 IRBuilder<> Builder(Entry);
1004 Builder.CreateCall(WriteoutF, {});
1006 // Zero out the counters.
1007 for (const auto &I : CountersBySP) {
1008 GlobalVariable *GV = I.first;
1009 Constant *Null = Constant::getNullValue(GV->getValueType());
1010 Builder.CreateStore(Null, GV);
1013 Type *RetTy = FlushF->getReturnType();
1014 if (RetTy == Type::getVoidTy(*Ctx))
1015 Builder.CreateRetVoid();
1016 else if (RetTy->isIntegerTy())
1017 // Used if __llvm_gcov_flush was implicitly declared.
1018 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1020 report_fatal_error("invalid return type for __llvm_gcov_flush");