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/Transforms/Instrumentation.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/UniqueVector.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/Utils/ModuleUtils.h"
45 #define DEBUG_TYPE "insert-gcov-profiling"
47 static cl::opt<std::string>
48 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
51 GCOVOptions GCOVOptions::getDefault() {
53 Options.EmitNotes = true;
54 Options.EmitData = true;
55 Options.UseCfgChecksum = false;
56 Options.NoRedZone = false;
57 Options.FunctionNamesInData = true;
59 if (DefaultGCOVVersion.size() != 4) {
60 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
63 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
70 class GCOVProfiler : public ModulePass {
73 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
74 GCOVProfiler(const GCOVOptions &Opts) : ModulePass(ID), Options(Opts) {
75 assert((Options.EmitNotes || Options.EmitData) &&
76 "GCOVProfiler asked to do nothing?");
77 ReversedVersion[0] = Options.Version[3];
78 ReversedVersion[1] = Options.Version[2];
79 ReversedVersion[2] = Options.Version[1];
80 ReversedVersion[3] = Options.Version[0];
81 ReversedVersion[4] = '\0';
82 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
84 const char *getPassName() const override {
85 return "GCOV Profiler";
89 bool runOnModule(Module &M) override;
91 // Create the .gcno files for the Module based on DebugInfo.
92 void emitProfileNotes();
94 // Modify the program to track transitions along edges and call into the
95 // profiling runtime to emit .gcda files when run.
96 bool emitProfileArcs();
98 // Get pointers to the functions in the runtime library.
99 Constant *getStartFileFunc();
100 Constant *getIncrementIndirectCounterFunc();
101 Constant *getEmitFunctionFunc();
102 Constant *getEmitArcsFunc();
103 Constant *getSummaryInfoFunc();
104 Constant *getDeleteWriteoutFunctionListFunc();
105 Constant *getDeleteFlushFunctionListFunc();
106 Constant *getEndFileFunc();
108 // Create or retrieve an i32 state value that is used to represent the
109 // pred block number for certain non-trivial edges.
110 GlobalVariable *getEdgeStateValue();
112 // Produce a table of pointers to counters, by predecessor and successor
114 GlobalVariable *buildEdgeLookupTable(Function *F,
115 GlobalVariable *Counter,
116 const UniqueVector<BasicBlock *>&Preds,
117 const UniqueVector<BasicBlock*>&Succs);
119 // Add the function to write out all our counters to the global destructor
121 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
123 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
124 void insertIndirectCounterIncrement();
126 std::string mangleName(DICompileUnit CU, const char *NewStem);
130 // Reversed, NUL-terminated copy of Options.Version.
131 char ReversedVersion[5];
132 // Checksum, produced by hash of EdgeDestinations
133 SmallVector<uint32_t, 4> FileChecksums;
137 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
141 char GCOVProfiler::ID = 0;
142 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
143 "Insert instrumentation for GCOV profiling", false, false)
145 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
146 return new GCOVProfiler(Options);
149 static StringRef getFunctionName(DISubprogram SP) {
150 if (!SP.getLinkageName().empty())
151 return SP.getLinkageName();
158 static const char *const LinesTag;
159 static const char *const FunctionTag;
160 static const char *const BlockTag;
161 static const char *const EdgeTag;
165 void writeBytes(const char *Bytes, int Size) {
166 os->write(Bytes, Size);
169 void write(uint32_t i) {
170 writeBytes(reinterpret_cast<char*>(&i), 4);
173 // Returns the length measured in 4-byte blocks that will be used to
174 // represent this string in a GCOV file
175 static unsigned lengthOfGCOVString(StringRef s) {
176 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
177 // padding out to the next 4-byte word. The length is measured in 4-byte
178 // words including padding, not bytes of actual string.
179 return (s.size() / 4) + 1;
182 void writeGCOVString(StringRef s) {
183 uint32_t Len = lengthOfGCOVString(s);
185 writeBytes(s.data(), s.size());
187 // Write 1 to 4 bytes of NUL padding.
188 assert((unsigned)(4 - (s.size() % 4)) > 0);
189 assert((unsigned)(4 - (s.size() % 4)) <= 4);
190 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
195 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
196 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
197 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
198 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
203 // Constructed only by requesting it from a GCOVBlock, this object stores a
204 // list of line numbers and a single filename, representing lines that belong
206 class GCOVLines : public GCOVRecord {
208 void addLine(uint32_t Line) {
209 assert(Line != 0 && "Line zero is not a valid real line number.");
210 Lines.push_back(Line);
213 uint32_t length() const {
214 // Here 2 = 1 for string length + 1 for '0' id#.
215 return lengthOfGCOVString(Filename) + 2 + Lines.size();
220 writeGCOVString(Filename);
221 for (int i = 0, e = Lines.size(); i != e; ++i)
225 GCOVLines(StringRef F, raw_ostream *os)
232 SmallVector<uint32_t, 32> Lines;
236 // Represent a basic block in GCOV. Each block has a unique number in the
237 // function, number of lines belonging to each block, and a set of edges to
239 class GCOVBlock : public GCOVRecord {
241 GCOVLines &getFile(StringRef Filename) {
242 GCOVLines *&Lines = LinesByFile[Filename];
244 Lines = new GCOVLines(Filename, os);
249 void addEdge(GCOVBlock &Successor) {
250 OutEdges.push_back(&Successor);
255 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
256 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
257 E = LinesByFile.end(); I != E; ++I) {
258 Len += I->second->length();
259 SortedLinesByFile.push_back(&*I);
262 writeBytes(LinesTag, 4);
266 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(),
267 [](StringMapEntry<GCOVLines *> *LHS,
268 StringMapEntry<GCOVLines *> *RHS) {
269 return LHS->getKey() < RHS->getKey();
271 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
272 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
274 (*I)->getValue()->writeOut();
280 DeleteContainerSeconds(LinesByFile);
283 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
284 // Only allow copy before edges and lines have been added. After that,
285 // there are inter-block pointers (eg: edges) that won't take kindly to
286 // blocks being copied or moved around.
287 assert(LinesByFile.empty());
288 assert(OutEdges.empty());
292 friend class GCOVFunction;
294 GCOVBlock(uint32_t Number, raw_ostream *os)
300 StringMap<GCOVLines *> LinesByFile;
301 SmallVector<GCOVBlock *, 4> OutEdges;
304 // A function has a unique identifier, a checksum (we leave as zero) and a
305 // set of blocks and a map of edges between blocks. This is the only GCOV
306 // object users can construct, the blocks and lines will be rooted here.
307 class GCOVFunction : public GCOVRecord {
309 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
311 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
315 Function *F = SP.getFunction();
316 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
319 for (auto &BB : *F) {
320 // Skip index 1 (0, 2, 3, 4, ...) because that's assigned to the
323 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++ + !first, os)));
326 std::string FunctionNameAndLine;
327 raw_string_ostream FNLOS(FunctionNameAndLine);
328 FNLOS << getFunctionName(SP) << SP.getLineNumber();
330 FuncChecksum = hash_value(FunctionNameAndLine);
333 GCOVBlock &getBlock(BasicBlock *BB) {
334 return Blocks.find(BB)->second;
337 GCOVBlock &getReturnBlock() {
341 std::string getEdgeDestinations() {
342 std::string EdgeDestinations;
343 raw_string_ostream EDOS(EdgeDestinations);
344 Function *F = Blocks.begin()->first->getParent();
345 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
346 GCOVBlock &Block = getBlock(I);
347 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
348 EDOS << Block.OutEdges[i]->Number;
350 return EdgeDestinations;
353 uint32_t getFuncChecksum() {
357 void setCfgChecksum(uint32_t Checksum) {
358 CfgChecksum = Checksum;
362 writeBytes(FunctionTag, 4);
363 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
364 1 + lengthOfGCOVString(SP.getFilename()) + 1;
372 writeGCOVString(getFunctionName(SP));
373 writeGCOVString(SP.getFilename());
374 write(SP.getLineNumber());
376 // Emit count of blocks.
377 writeBytes(BlockTag, 4);
378 write(Blocks.size() + 1);
379 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
380 write(0); // No flags on our blocks.
382 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
384 // Emit edges between blocks.
385 if (Blocks.empty()) return;
386 Function *F = Blocks.begin()->first->getParent();
387 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
388 GCOVBlock &Block = getBlock(I);
389 if (Block.OutEdges.empty()) continue;
391 writeBytes(EdgeTag, 4);
392 write(Block.OutEdges.size() * 2 + 1);
394 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
395 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
397 write(Block.OutEdges[i]->Number);
398 write(0); // no flags
402 // Emit lines for each block.
403 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
404 getBlock(I).writeOut();
411 uint32_t FuncChecksum;
413 uint32_t CfgChecksum;
414 DenseMap<BasicBlock *, GCOVBlock> Blocks;
415 GCOVBlock ReturnBlock;
419 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
420 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
421 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
422 MDNode *N = GCov->getOperand(i);
423 if (N->getNumOperands() != 2) continue;
424 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
425 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
426 if (!GCovFile || !CompileUnit) continue;
427 if (CompileUnit == CU) {
428 SmallString<128> Filename = GCovFile->getString();
429 sys::path::replace_extension(Filename, NewStem);
430 return Filename.str();
435 SmallString<128> Filename = CU.getFilename();
436 sys::path::replace_extension(Filename, NewStem);
437 StringRef FName = sys::path::filename(Filename);
438 SmallString<128> CurPath;
439 if (sys::fs::current_path(CurPath)) return FName;
440 sys::path::append(CurPath, FName.str());
441 return CurPath.str();
444 bool GCOVProfiler::runOnModule(Module &M) {
446 Ctx = &M.getContext();
448 if (Options.EmitNotes) emitProfileNotes();
449 if (Options.EmitData) return emitProfileArcs();
453 static bool functionHasLines(Function *F) {
454 // Check whether this function actually has any source lines. Not only
455 // do these waste space, they also can crash gcov.
456 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
457 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
459 // Debug intrinsic locations correspond to the location of the
460 // declaration, not necessarily any statements or expressions.
461 if (isa<DbgInfoIntrinsic>(I)) continue;
463 const DebugLoc &Loc = I->getDebugLoc();
464 if (Loc.isUnknown()) continue;
466 // Artificial lines such as calls to the global constructors.
467 if (Loc.getLine() == 0) continue;
475 void GCOVProfiler::emitProfileNotes() {
476 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
477 if (!CU_Nodes) return;
479 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
480 // Each compile unit gets its own .gcno file. This means that whether we run
481 // this pass over the original .o's as they're produced, or run it after
482 // LTO, we'll generate the same .gcno files.
484 DICompileUnit CU(CU_Nodes->getOperand(i));
486 raw_fd_ostream out(mangleName(CU, "gcno"), EC, sys::fs::F_None);
487 std::string EdgeDestinations;
489 DIArray SPs = CU.getSubprograms();
490 unsigned FunctionIdent = 0;
491 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
492 DISubprogram SP(SPs.getElement(i));
493 assert((!SP || SP.isSubprogram()) &&
494 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
498 Function *F = SP.getFunction();
500 if (!functionHasLines(F)) continue;
502 // gcov expects every function to start with an entry block that has a
503 // single successor, so split the entry block to make sure of that.
504 BasicBlock &EntryBlock = F->getEntryBlock();
505 BasicBlock::iterator It = EntryBlock.begin();
506 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
508 EntryBlock.splitBasicBlock(It);
510 Funcs.push_back(make_unique<GCOVFunction>(SP, &out, FunctionIdent++,
511 Options.UseCfgChecksum));
512 GCOVFunction &Func = *Funcs.back();
514 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
515 GCOVBlock &Block = Func.getBlock(BB);
516 TerminatorInst *TI = BB->getTerminator();
517 if (int successors = TI->getNumSuccessors()) {
518 for (int i = 0; i != successors; ++i) {
519 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
521 } else if (isa<ReturnInst>(TI)) {
522 Block.addEdge(Func.getReturnBlock());
526 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
528 // Debug intrinsic locations correspond to the location of the
529 // declaration, not necessarily any statements or expressions.
530 if (isa<DbgInfoIntrinsic>(I)) continue;
532 const DebugLoc &Loc = I->getDebugLoc();
533 if (Loc.isUnknown()) continue;
535 // Artificial lines such as calls to the global constructors.
536 if (Loc.getLine() == 0) continue;
538 if (Line == Loc.getLine()) continue;
539 Line = Loc.getLine();
540 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
542 GCOVLines &Lines = Block.getFile(SP.getFilename());
543 Lines.addLine(Loc.getLine());
546 EdgeDestinations += Func.getEdgeDestinations();
549 FileChecksums.push_back(hash_value(EdgeDestinations));
550 out.write("oncg", 4);
551 out.write(ReversedVersion, 4);
552 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
554 for (auto &Func : Funcs) {
555 Func->setCfgChecksum(FileChecksums.back());
559 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
564 bool GCOVProfiler::emitProfileArcs() {
565 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
566 if (!CU_Nodes) return false;
569 bool InsertIndCounterIncrCode = false;
570 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
571 DICompileUnit CU(CU_Nodes->getOperand(i));
572 DIArray SPs = CU.getSubprograms();
573 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
574 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
575 DISubprogram SP(SPs.getElement(i));
576 assert((!SP || SP.isSubprogram()) &&
577 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
580 Function *F = SP.getFunction();
582 if (!functionHasLines(F)) continue;
583 if (!Result) Result = true;
585 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
586 TerminatorInst *TI = BB->getTerminator();
587 if (isa<ReturnInst>(TI))
590 Edges += TI->getNumSuccessors();
593 ArrayType *CounterTy =
594 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
595 GlobalVariable *Counters =
596 new GlobalVariable(*M, CounterTy, false,
597 GlobalValue::InternalLinkage,
598 Constant::getNullValue(CounterTy),
600 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
602 UniqueVector<BasicBlock *> ComplexEdgePreds;
603 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
606 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
607 TerminatorInst *TI = BB->getTerminator();
608 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
610 if (Successors == 1) {
611 IRBuilder<> Builder(BB->getFirstInsertionPt());
612 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
614 Value *Count = Builder.CreateLoad(Counter);
615 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
616 Builder.CreateStore(Count, Counter);
617 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
618 IRBuilder<> Builder(BI);
619 Value *Sel = Builder.CreateSelect(BI->getCondition(),
620 Builder.getInt64(Edge),
621 Builder.getInt64(Edge + 1));
622 SmallVector<Value *, 2> Idx;
623 Idx.push_back(Builder.getInt64(0));
625 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
626 Value *Count = Builder.CreateLoad(Counter);
627 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
628 Builder.CreateStore(Count, Counter);
630 ComplexEdgePreds.insert(BB);
631 for (int i = 0; i != Successors; ++i)
632 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
639 if (!ComplexEdgePreds.empty()) {
640 GlobalVariable *EdgeTable =
641 buildEdgeLookupTable(F, Counters,
642 ComplexEdgePreds, ComplexEdgeSuccs);
643 GlobalVariable *EdgeState = getEdgeStateValue();
645 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
646 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
647 Builder.CreateStore(Builder.getInt32(i), EdgeState);
650 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
651 // Call runtime to perform increment.
652 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
653 Value *CounterPtrArray =
654 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
655 i * ComplexEdgePreds.size());
657 // Build code to increment the counter.
658 InsertIndCounterIncrCode = true;
659 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
660 EdgeState, CounterPtrArray);
665 Function *WriteoutF = insertCounterWriteout(CountersBySP);
666 Function *FlushF = insertFlush(CountersBySP);
668 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
669 // be executed at exit and the "__llvm_gcov_flush" function to be executed
670 // when "__gcov_flush" is called.
671 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
672 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
673 "__llvm_gcov_init", M);
674 F->setUnnamedAddr(true);
675 F->setLinkage(GlobalValue::InternalLinkage);
676 F->addFnAttr(Attribute::NoInline);
677 if (Options.NoRedZone)
678 F->addFnAttr(Attribute::NoRedZone);
680 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
681 IRBuilder<> Builder(BB);
683 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
685 PointerType::get(FTy, 0),
686 PointerType::get(FTy, 0)
688 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
690 // Initialize the environment and register the local writeout and flush
692 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
693 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
694 Builder.CreateRetVoid();
696 appendToGlobalCtors(*M, F, 0);
699 if (InsertIndCounterIncrCode)
700 insertIndirectCounterIncrement();
705 // All edges with successors that aren't branches are "complex", because it
706 // requires complex logic to pick which counter to update.
707 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
709 GlobalVariable *Counters,
710 const UniqueVector<BasicBlock *> &Preds,
711 const UniqueVector<BasicBlock *> &Succs) {
712 // TODO: support invoke, threads. We rely on the fact that nothing can modify
713 // the whole-Module pred edge# between the time we set it and the time we next
714 // read it. Threads and invoke make this untrue.
716 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
717 size_t TableSize = Succs.size() * Preds.size();
718 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
719 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
721 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
722 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
723 for (size_t i = 0; i != TableSize; ++i)
724 EdgeTable[i] = NullValue;
727 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
728 TerminatorInst *TI = BB->getTerminator();
729 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
730 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
731 for (int i = 0; i != Successors; ++i) {
732 BasicBlock *Succ = TI->getSuccessor(i);
733 IRBuilder<> Builder(Succ);
734 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
736 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
737 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
743 GlobalVariable *EdgeTableGV =
745 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
746 ConstantArray::get(EdgeTableTy,
747 makeArrayRef(&EdgeTable[0],TableSize)),
748 "__llvm_gcda_edge_table");
749 EdgeTableGV->setUnnamedAddr(true);
753 Constant *GCOVProfiler::getStartFileFunc() {
755 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
756 Type::getInt8PtrTy(*Ctx), // const char version[4]
757 Type::getInt32Ty(*Ctx), // uint32_t checksum
759 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
760 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
763 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
764 Type *Int32Ty = Type::getInt32Ty(*Ctx);
765 Type *Int64Ty = Type::getInt64Ty(*Ctx);
767 Int32Ty->getPointerTo(), // uint32_t *predecessor
768 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
770 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
771 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
774 Constant *GCOVProfiler::getEmitFunctionFunc() {
776 Type::getInt32Ty(*Ctx), // uint32_t ident
777 Type::getInt8PtrTy(*Ctx), // const char *function_name
778 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
779 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
780 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
782 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
783 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
786 Constant *GCOVProfiler::getEmitArcsFunc() {
788 Type::getInt32Ty(*Ctx), // uint32_t num_counters
789 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
791 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
792 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
795 Constant *GCOVProfiler::getSummaryInfoFunc() {
796 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
797 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
800 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
801 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
802 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
805 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
806 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
807 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
810 Constant *GCOVProfiler::getEndFileFunc() {
811 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
812 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
815 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
816 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
818 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
819 GlobalValue::InternalLinkage,
820 ConstantInt::get(Type::getInt32Ty(*Ctx),
822 "__llvm_gcov_global_state_pred");
823 GV->setUnnamedAddr(true);
828 Function *GCOVProfiler::insertCounterWriteout(
829 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
830 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
831 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
833 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
834 "__llvm_gcov_writeout", M);
835 WriteoutF->setUnnamedAddr(true);
836 WriteoutF->addFnAttr(Attribute::NoInline);
837 if (Options.NoRedZone)
838 WriteoutF->addFnAttr(Attribute::NoRedZone);
840 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
841 IRBuilder<> Builder(BB);
843 Constant *StartFile = getStartFileFunc();
844 Constant *EmitFunction = getEmitFunctionFunc();
845 Constant *EmitArcs = getEmitArcsFunc();
846 Constant *SummaryInfo = getSummaryInfoFunc();
847 Constant *EndFile = getEndFileFunc();
849 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
851 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
852 DICompileUnit CU(CU_Nodes->getOperand(i));
853 std::string FilenameGcda = mangleName(CU, "gcda");
854 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
855 Builder.CreateCall3(StartFile,
856 Builder.CreateGlobalStringPtr(FilenameGcda),
857 Builder.CreateGlobalStringPtr(ReversedVersion),
858 Builder.getInt32(CfgChecksum));
859 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
860 DISubprogram SP(CountersBySP[j].second);
861 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
863 EmitFunction, Builder.getInt32(j),
864 Options.FunctionNamesInData ?
865 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
866 Constant::getNullValue(Builder.getInt8PtrTy()),
867 Builder.getInt32(FuncChecksum),
868 Builder.getInt8(Options.UseCfgChecksum),
869 Builder.getInt32(CfgChecksum));
871 GlobalVariable *GV = CountersBySP[j].first;
873 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
874 Builder.CreateCall2(EmitArcs,
875 Builder.getInt32(Arcs),
876 Builder.CreateConstGEP2_64(GV, 0, 0));
878 Builder.CreateCall(SummaryInfo);
879 Builder.CreateCall(EndFile);
883 Builder.CreateRetVoid();
887 void GCOVProfiler::insertIndirectCounterIncrement() {
889 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
890 Fn->setUnnamedAddr(true);
891 Fn->setLinkage(GlobalValue::InternalLinkage);
892 Fn->addFnAttr(Attribute::NoInline);
893 if (Options.NoRedZone)
894 Fn->addFnAttr(Attribute::NoRedZone);
896 // Create basic blocks for function.
897 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
898 IRBuilder<> Builder(BB);
900 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
901 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
902 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
904 // uint32_t pred = *predecessor;
905 // if (pred == 0xffffffff) return;
906 Argument *Arg = Fn->arg_begin();
907 Arg->setName("predecessor");
908 Value *Pred = Builder.CreateLoad(Arg, "pred");
909 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
910 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
912 Builder.SetInsertPoint(PredNotNegOne);
914 // uint64_t *counter = counters[pred];
915 // if (!counter) return;
916 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
917 Arg = std::next(Fn->arg_begin());
918 Arg->setName("counters");
919 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
920 Value *Counter = Builder.CreateLoad(GEP, "counter");
921 Cond = Builder.CreateICmpEQ(Counter,
922 Constant::getNullValue(
923 Builder.getInt64Ty()->getPointerTo()));
924 Builder.CreateCondBr(Cond, Exit, CounterEnd);
927 Builder.SetInsertPoint(CounterEnd);
928 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
929 Builder.getInt64(1));
930 Builder.CreateStore(Add, Counter);
931 Builder.CreateBr(Exit);
933 // Fill in the exit block.
934 Builder.SetInsertPoint(Exit);
935 Builder.CreateRetVoid();
938 Function *GCOVProfiler::
939 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
940 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
941 Function *FlushF = M->getFunction("__llvm_gcov_flush");
943 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
944 "__llvm_gcov_flush", M);
946 FlushF->setLinkage(GlobalValue::InternalLinkage);
947 FlushF->setUnnamedAddr(true);
948 FlushF->addFnAttr(Attribute::NoInline);
949 if (Options.NoRedZone)
950 FlushF->addFnAttr(Attribute::NoRedZone);
952 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
954 // Write out the current counters.
955 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
956 assert(WriteoutF && "Need to create the writeout function first!");
958 IRBuilder<> Builder(Entry);
959 Builder.CreateCall(WriteoutF);
961 // Zero out the counters.
962 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
963 I = CountersBySP.begin(), E = CountersBySP.end();
965 GlobalVariable *GV = I->first;
966 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
967 Builder.CreateStore(Null, GV);
970 Type *RetTy = FlushF->getReturnType();
971 if (RetTy == Type::getVoidTy(*Ctx))
972 Builder.CreateRetVoid();
973 else if (RetTy->isIntegerTy())
974 // Used if __llvm_gcov_flush was implicitly declared.
975 Builder.CreateRet(ConstantInt::get(RetTy, 0));
977 report_fatal_error("invalid return type for __llvm_gcov_flush");