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 #define DEBUG_TYPE "insert-gcov-profiling"
19 #include "llvm/Transforms/Instrumentation.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/UniqueVector.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/InstIterator.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 static cl::opt<std::string>
45 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
48 GCOVOptions GCOVOptions::getDefault() {
50 Options.EmitNotes = true;
51 Options.EmitData = true;
52 Options.UseCfgChecksum = false;
53 Options.NoRedZone = false;
54 Options.FunctionNamesInData = true;
56 if (DefaultGCOVVersion.size() != 4) {
57 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
60 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
65 class GCOVProfiler : public ModulePass {
68 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
69 ReversedVersion[0] = Options.Version[3];
70 ReversedVersion[1] = Options.Version[2];
71 ReversedVersion[2] = Options.Version[1];
72 ReversedVersion[3] = Options.Version[0];
73 ReversedVersion[4] = '\0';
74 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
76 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
77 assert((Options.EmitNotes || Options.EmitData) &&
78 "GCOVProfiler asked to do nothing?");
79 ReversedVersion[0] = Options.Version[3];
80 ReversedVersion[1] = Options.Version[2];
81 ReversedVersion[2] = Options.Version[1];
82 ReversedVersion[3] = Options.Version[0];
83 ReversedVersion[4] = '\0';
84 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
86 virtual const char *getPassName() const {
87 return "GCOV Profiler";
91 bool runOnModule(Module &M);
93 // Create the .gcno files for the Module based on DebugInfo.
94 void emitProfileNotes();
96 // Modify the program to track transitions along edges and call into the
97 // profiling runtime to emit .gcda files when run.
98 bool emitProfileArcs();
100 // Get pointers to the functions in the runtime library.
101 Constant *getStartFileFunc();
102 Constant *getIncrementIndirectCounterFunc();
103 Constant *getEmitFunctionFunc();
104 Constant *getEmitArcsFunc();
105 Constant *getDeleteWriteoutFunctionListFunc();
106 Constant *getDeleteFlushFunctionListFunc();
107 Constant *getEndFileFunc();
109 // Create or retrieve an i32 state value that is used to represent the
110 // pred block number for certain non-trivial edges.
111 GlobalVariable *getEdgeStateValue();
113 // Produce a table of pointers to counters, by predecessor and successor
115 GlobalVariable *buildEdgeLookupTable(Function *F,
116 GlobalVariable *Counter,
117 const UniqueVector<BasicBlock *>&Preds,
118 const UniqueVector<BasicBlock*>&Succs);
120 // Add the function to write out all our counters to the global destructor
122 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
124 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
125 void insertIndirectCounterIncrement();
127 std::string mangleName(DICompileUnit CU, const char *NewStem);
131 // Reversed, NUL-terminated copy of Options.Version.
132 char ReversedVersion[5];
139 char GCOVProfiler::ID = 0;
140 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
141 "Insert instrumentation for GCOV profiling", false, false)
143 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
144 return new GCOVProfiler(Options);
147 static std::string getFunctionName(DISubprogram SP) {
148 if (!SP.getLinkageName().empty())
149 return SP.getLinkageName();
156 static const char *const LinesTag;
157 static const char *const FunctionTag;
158 static const char *const BlockTag;
159 static const char *const EdgeTag;
163 void writeBytes(const char *Bytes, int Size) {
164 os->write(Bytes, Size);
167 void write(uint32_t i) {
168 writeBytes(reinterpret_cast<char*>(&i), 4);
171 // Returns the length measured in 4-byte blocks that will be used to
172 // represent this string in a GCOV file
173 static unsigned lengthOfGCOVString(StringRef s) {
174 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
175 // padding out to the next 4-byte word. The length is measured in 4-byte
176 // words including padding, not bytes of actual string.
177 return (s.size() / 4) + 1;
180 void writeGCOVString(StringRef s) {
181 uint32_t Len = lengthOfGCOVString(s);
183 writeBytes(s.data(), s.size());
185 // Write 1 to 4 bytes of NUL padding.
186 assert((unsigned)(4 - (s.size() % 4)) > 0);
187 assert((unsigned)(4 - (s.size() % 4)) <= 4);
188 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
193 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
194 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
195 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
196 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
201 // Constructed only by requesting it from a GCOVBlock, this object stores a
202 // list of line numbers and a single filename, representing lines that belong
204 class GCOVLines : public GCOVRecord {
206 void addLine(uint32_t Line) {
207 Lines.push_back(Line);
210 uint32_t length() const {
211 // Here 2 = 1 for string length + 1 for '0' id#.
212 return lengthOfGCOVString(Filename) + 2 + Lines.size();
217 writeGCOVString(Filename);
218 for (int i = 0, e = Lines.size(); i != e; ++i)
222 GCOVLines(StringRef F, raw_ostream *os)
229 SmallVector<uint32_t, 32> Lines;
233 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
234 struct StringKeySort {
235 bool operator()(StringMapEntry<GCOVLines *> *LHS,
236 StringMapEntry<GCOVLines *> *RHS) const {
237 return LHS->getKey() < RHS->getKey();
241 // Represent a basic block in GCOV. Each block has a unique number in the
242 // function, number of lines belonging to each block, and a set of edges to
244 class GCOVBlock : public GCOVRecord {
246 GCOVLines &getFile(StringRef Filename) {
247 GCOVLines *&Lines = LinesByFile[Filename];
249 Lines = new GCOVLines(Filename, os);
254 void addEdge(GCOVBlock &Successor) {
255 OutEdges.push_back(&Successor);
260 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
261 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
262 E = LinesByFile.end(); I != E; ++I) {
263 Len += I->second->length();
264 SortedLinesByFile.push_back(&*I);
267 writeBytes(LinesTag, 4);
271 StringKeySort Sorter;
272 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
273 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
274 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
276 (*I)->getValue()->writeOut();
282 DeleteContainerSeconds(LinesByFile);
286 friend class GCOVFunction;
288 GCOVBlock(uint32_t Number, raw_ostream *os)
294 StringMap<GCOVLines *> LinesByFile;
295 SmallVector<GCOVBlock *, 4> OutEdges;
298 // A function has a unique identifier, a checksum (we leave as zero) and a
299 // set of blocks and a map of edges between blocks. This is the only GCOV
300 // object users can construct, the blocks and lines will be rooted here.
301 class GCOVFunction : public GCOVRecord {
303 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
304 bool UseCfgChecksum) {
307 Function *F = SP.getFunction();
308 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
310 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
311 Blocks[BB] = new GCOVBlock(i++, os);
313 ReturnBlock = new GCOVBlock(i++, os);
315 writeBytes(FunctionTag, 4);
316 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
317 1 + lengthOfGCOVString(SP.getFilename()) + 1;
322 write(0); // lineno checksum
324 write(0); // cfg checksum
325 writeGCOVString(getFunctionName(SP));
326 writeGCOVString(SP.getFilename());
327 write(SP.getLineNumber());
331 DeleteContainerSeconds(Blocks);
335 GCOVBlock &getBlock(BasicBlock *BB) {
339 GCOVBlock &getReturnBlock() {
344 // Emit count of blocks.
345 writeBytes(BlockTag, 4);
346 write(Blocks.size() + 1);
347 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
348 write(0); // No flags on our blocks.
350 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
352 // Emit edges between blocks.
353 if (Blocks.empty()) return;
354 Function *F = Blocks.begin()->first->getParent();
355 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
356 GCOVBlock &Block = *Blocks[I];
357 if (Block.OutEdges.empty()) continue;
359 writeBytes(EdgeTag, 4);
360 write(Block.OutEdges.size() * 2 + 1);
362 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
363 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
365 write(Block.OutEdges[i]->Number);
366 write(0); // no flags
370 // Emit lines for each block.
371 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
372 Blocks[I]->writeOut();
377 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
378 GCOVBlock *ReturnBlock;
382 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
383 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
384 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
385 MDNode *N = GCov->getOperand(i);
386 if (N->getNumOperands() != 2) continue;
387 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
388 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
389 if (!GCovFile || !CompileUnit) continue;
390 if (CompileUnit == CU) {
391 SmallString<128> Filename = GCovFile->getString();
392 sys::path::replace_extension(Filename, NewStem);
393 return Filename.str();
398 SmallString<128> Filename = CU.getFilename();
399 sys::path::replace_extension(Filename, NewStem);
400 StringRef FName = sys::path::filename(Filename);
401 SmallString<128> CurPath;
402 if (sys::fs::current_path(CurPath)) return FName;
403 sys::path::append(CurPath, FName.str());
404 return CurPath.str();
407 bool GCOVProfiler::runOnModule(Module &M) {
409 Ctx = &M.getContext();
411 if (Options.EmitNotes) emitProfileNotes();
412 if (Options.EmitData) return emitProfileArcs();
416 void GCOVProfiler::emitProfileNotes() {
417 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
418 if (!CU_Nodes) return;
420 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
421 // Each compile unit gets its own .gcno file. This means that whether we run
422 // this pass over the original .o's as they're produced, or run it after
423 // LTO, we'll generate the same .gcno files.
425 DICompileUnit CU(CU_Nodes->getOperand(i));
426 std::string ErrorInfo;
427 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
429 out.write("oncg", 4);
430 out.write(ReversedVersion, 4);
431 out.write("MVLL", 4);
433 DIArray SPs = CU.getSubprograms();
434 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
435 DISubprogram SP(SPs.getElement(i));
436 assert((!SP || SP.isSubprogram()) &&
437 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
441 Function *F = SP.getFunction();
443 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
445 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
446 GCOVBlock &Block = Func.getBlock(BB);
447 TerminatorInst *TI = BB->getTerminator();
448 if (int successors = TI->getNumSuccessors()) {
449 for (int i = 0; i != successors; ++i) {
450 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
452 } else if (isa<ReturnInst>(TI)) {
453 Block.addEdge(Func.getReturnBlock());
457 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
459 const DebugLoc &Loc = I->getDebugLoc();
460 if (Loc.isUnknown()) continue;
461 if (Line == Loc.getLine()) continue;
462 Line = Loc.getLine();
463 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
465 GCOVLines &Lines = Block.getFile(SP.getFilename());
466 Lines.addLine(Loc.getLine());
471 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
476 bool GCOVProfiler::emitProfileArcs() {
477 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
478 if (!CU_Nodes) return false;
481 bool InsertIndCounterIncrCode = false;
482 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
483 DICompileUnit CU(CU_Nodes->getOperand(i));
484 DIArray SPs = CU.getSubprograms();
485 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
486 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
487 DISubprogram SP(SPs.getElement(i));
488 assert((!SP || SP.isSubprogram()) &&
489 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
492 Function *F = SP.getFunction();
494 if (!Result) Result = true;
496 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
497 TerminatorInst *TI = BB->getTerminator();
498 if (isa<ReturnInst>(TI))
501 Edges += TI->getNumSuccessors();
504 ArrayType *CounterTy =
505 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
506 GlobalVariable *Counters =
507 new GlobalVariable(*M, CounterTy, false,
508 GlobalValue::InternalLinkage,
509 Constant::getNullValue(CounterTy),
511 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
513 UniqueVector<BasicBlock *> ComplexEdgePreds;
514 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
517 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
518 TerminatorInst *TI = BB->getTerminator();
519 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
521 if (Successors == 1) {
522 IRBuilder<> Builder(BB->getFirstInsertionPt());
523 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
525 Value *Count = Builder.CreateLoad(Counter);
526 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
527 Builder.CreateStore(Count, Counter);
528 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
529 IRBuilder<> Builder(BI);
530 Value *Sel = Builder.CreateSelect(BI->getCondition(),
531 Builder.getInt64(Edge),
532 Builder.getInt64(Edge + 1));
533 SmallVector<Value *, 2> Idx;
534 Idx.push_back(Builder.getInt64(0));
536 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
537 Value *Count = Builder.CreateLoad(Counter);
538 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
539 Builder.CreateStore(Count, Counter);
541 ComplexEdgePreds.insert(BB);
542 for (int i = 0; i != Successors; ++i)
543 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
550 if (!ComplexEdgePreds.empty()) {
551 GlobalVariable *EdgeTable =
552 buildEdgeLookupTable(F, Counters,
553 ComplexEdgePreds, ComplexEdgeSuccs);
554 GlobalVariable *EdgeState = getEdgeStateValue();
556 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
557 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
558 Builder.CreateStore(Builder.getInt32(i), EdgeState);
561 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
562 // Call runtime to perform increment.
563 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
564 Value *CounterPtrArray =
565 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
566 i * ComplexEdgePreds.size());
568 // Build code to increment the counter.
569 InsertIndCounterIncrCode = true;
570 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
571 EdgeState, CounterPtrArray);
576 Function *WriteoutF = insertCounterWriteout(CountersBySP);
577 Function *FlushF = insertFlush(CountersBySP);
579 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
580 // be executed at exit and the "__llvm_gcov_flush" function to be executed
581 // when "__gcov_flush" is called.
582 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
583 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
584 "__llvm_gcov_init", M);
585 F->setUnnamedAddr(true);
586 F->setLinkage(GlobalValue::InternalLinkage);
587 F->addFnAttr(Attribute::NoInline);
588 if (Options.NoRedZone)
589 F->addFnAttr(Attribute::NoRedZone);
591 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
592 IRBuilder<> Builder(BB);
594 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
596 PointerType::get(FTy, 0),
597 PointerType::get(FTy, 0)
599 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
601 // Initialize the environment and register the local writeout and flush
603 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
604 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
605 Builder.CreateRetVoid();
607 appendToGlobalCtors(*M, F, 0);
610 if (InsertIndCounterIncrCode)
611 insertIndirectCounterIncrement();
616 // All edges with successors that aren't branches are "complex", because it
617 // requires complex logic to pick which counter to update.
618 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
620 GlobalVariable *Counters,
621 const UniqueVector<BasicBlock *> &Preds,
622 const UniqueVector<BasicBlock *> &Succs) {
623 // TODO: support invoke, threads. We rely on the fact that nothing can modify
624 // the whole-Module pred edge# between the time we set it and the time we next
625 // read it. Threads and invoke make this untrue.
627 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
628 size_t TableSize = Succs.size() * Preds.size();
629 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
630 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
632 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
633 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
634 for (size_t i = 0; i != TableSize; ++i)
635 EdgeTable[i] = NullValue;
638 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
639 TerminatorInst *TI = BB->getTerminator();
640 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
641 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
642 for (int i = 0; i != Successors; ++i) {
643 BasicBlock *Succ = TI->getSuccessor(i);
644 IRBuilder<> Builder(Succ);
645 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
647 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
648 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
654 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
655 GlobalVariable *EdgeTableGV =
657 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
658 ConstantArray::get(EdgeTableTy, V),
659 "__llvm_gcda_edge_table");
660 EdgeTableGV->setUnnamedAddr(true);
664 Constant *GCOVProfiler::getStartFileFunc() {
666 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
667 Type::getInt8PtrTy(*Ctx), // const char version[4]
669 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
670 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
673 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
674 Type *Int32Ty = Type::getInt32Ty(*Ctx);
675 Type *Int64Ty = Type::getInt64Ty(*Ctx);
677 Int32Ty->getPointerTo(), // uint32_t *predecessor
678 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
680 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
681 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
684 Constant *GCOVProfiler::getEmitFunctionFunc() {
686 Type::getInt32Ty(*Ctx), // uint32_t ident
687 Type::getInt8PtrTy(*Ctx), // const char *function_name
688 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
690 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
691 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
694 Constant *GCOVProfiler::getEmitArcsFunc() {
696 Type::getInt32Ty(*Ctx), // uint32_t num_counters
697 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
699 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
700 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
703 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
704 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
705 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
708 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
709 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
710 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
713 Constant *GCOVProfiler::getEndFileFunc() {
714 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
715 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
718 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
719 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
721 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
722 GlobalValue::InternalLinkage,
723 ConstantInt::get(Type::getInt32Ty(*Ctx),
725 "__llvm_gcov_global_state_pred");
726 GV->setUnnamedAddr(true);
731 Function *GCOVProfiler::insertCounterWriteout(
732 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
733 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
734 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
736 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
737 "__llvm_gcov_writeout", M);
738 WriteoutF->setUnnamedAddr(true);
739 WriteoutF->addFnAttr(Attribute::NoInline);
740 if (Options.NoRedZone)
741 WriteoutF->addFnAttr(Attribute::NoRedZone);
743 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
744 IRBuilder<> Builder(BB);
746 Constant *StartFile = getStartFileFunc();
747 Constant *EmitFunction = getEmitFunctionFunc();
748 Constant *EmitArcs = getEmitArcsFunc();
749 Constant *EndFile = getEndFileFunc();
751 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
753 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
754 DICompileUnit CU(CU_Nodes->getOperand(i));
755 std::string FilenameGcda = mangleName(CU, "gcda");
756 Builder.CreateCall2(StartFile,
757 Builder.CreateGlobalStringPtr(FilenameGcda),
758 Builder.CreateGlobalStringPtr(ReversedVersion));
759 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
760 DISubprogram SP(CountersBySP[j].second);
762 EmitFunction, Builder.getInt32(j),
763 Options.FunctionNamesInData ?
764 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
765 Constant::getNullValue(Builder.getInt8PtrTy()),
766 Builder.getInt8(Options.UseCfgChecksum));
768 GlobalVariable *GV = CountersBySP[j].first;
770 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
771 Builder.CreateCall2(EmitArcs,
772 Builder.getInt32(Arcs),
773 Builder.CreateConstGEP2_64(GV, 0, 0));
775 Builder.CreateCall(EndFile);
779 Builder.CreateRetVoid();
783 void GCOVProfiler::insertIndirectCounterIncrement() {
785 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
786 Fn->setUnnamedAddr(true);
787 Fn->setLinkage(GlobalValue::InternalLinkage);
788 Fn->addFnAttr(Attribute::NoInline);
789 if (Options.NoRedZone)
790 Fn->addFnAttr(Attribute::NoRedZone);
792 // Create basic blocks for function.
793 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
794 IRBuilder<> Builder(BB);
796 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
797 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
798 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
800 // uint32_t pred = *predecessor;
801 // if (pred == 0xffffffff) return;
802 Argument *Arg = Fn->arg_begin();
803 Arg->setName("predecessor");
804 Value *Pred = Builder.CreateLoad(Arg, "pred");
805 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
806 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
808 Builder.SetInsertPoint(PredNotNegOne);
810 // uint64_t *counter = counters[pred];
811 // if (!counter) return;
812 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
813 Arg = llvm::next(Fn->arg_begin());
814 Arg->setName("counters");
815 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
816 Value *Counter = Builder.CreateLoad(GEP, "counter");
817 Cond = Builder.CreateICmpEQ(Counter,
818 Constant::getNullValue(
819 Builder.getInt64Ty()->getPointerTo()));
820 Builder.CreateCondBr(Cond, Exit, CounterEnd);
823 Builder.SetInsertPoint(CounterEnd);
824 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
825 Builder.getInt64(1));
826 Builder.CreateStore(Add, Counter);
827 Builder.CreateBr(Exit);
829 // Fill in the exit block.
830 Builder.SetInsertPoint(Exit);
831 Builder.CreateRetVoid();
834 Function *GCOVProfiler::
835 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
836 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
837 Function *FlushF = M->getFunction("__llvm_gcov_flush");
839 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
840 "__llvm_gcov_flush", M);
842 FlushF->setLinkage(GlobalValue::InternalLinkage);
843 FlushF->setUnnamedAddr(true);
844 FlushF->addFnAttr(Attribute::NoInline);
845 if (Options.NoRedZone)
846 FlushF->addFnAttr(Attribute::NoRedZone);
848 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
850 // Write out the current counters.
851 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
852 assert(WriteoutF && "Need to create the writeout function first!");
854 IRBuilder<> Builder(Entry);
855 Builder.CreateCall(WriteoutF);
857 // Zero out the counters.
858 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
859 I = CountersBySP.begin(), E = CountersBySP.end();
861 GlobalVariable *GV = I->first;
862 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
863 Builder.CreateStore(Null, GV);
866 Type *RetTy = FlushF->getReturnType();
867 if (RetTy == Type::getVoidTy(*Ctx))
868 Builder.CreateRetVoid();
869 else if (RetTy->isIntegerTy())
870 // Used if __llvm_gcov_flush was implicitly declared.
871 Builder.CreateRet(ConstantInt::get(RetTy, 0));
873 report_fatal_error("invalid return type for __llvm_gcov_flush");