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/Hashing.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/UniqueVector.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/DebugLoc.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/InstIterator.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
45 static cl::opt<std::string>
46 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
49 GCOVOptions GCOVOptions::getDefault() {
51 Options.EmitNotes = true;
52 Options.EmitData = true;
53 Options.UseCfgChecksum = false;
54 Options.NoRedZone = false;
55 Options.FunctionNamesInData = true;
57 if (DefaultGCOVVersion.size() != 4) {
58 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
61 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
68 class GCOVProfiler : public ModulePass {
71 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
74 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
75 assert((Options.EmitNotes || Options.EmitData) &&
76 "GCOVProfiler asked to do nothing?");
80 DeleteContainerPointers(Funcs);
82 virtual const char *getPassName() const {
83 return "GCOV Profiler";
88 ReversedVersion[0] = Options.Version[3];
89 ReversedVersion[1] = Options.Version[2];
90 ReversedVersion[2] = Options.Version[1];
91 ReversedVersion[3] = Options.Version[0];
92 ReversedVersion[4] = '\0';
93 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
95 bool runOnModule(Module &M);
97 // Create the .gcno files for the Module based on DebugInfo.
98 void emitProfileNotes();
100 // Modify the program to track transitions along edges and call into the
101 // profiling runtime to emit .gcda files when run.
102 bool emitProfileArcs();
104 // Get pointers to the functions in the runtime library.
105 Constant *getStartFileFunc();
106 Constant *getIncrementIndirectCounterFunc();
107 Constant *getEmitFunctionFunc();
108 Constant *getEmitArcsFunc();
109 Constant *getSummaryInfoFunc();
110 Constant *getDeleteWriteoutFunctionListFunc();
111 Constant *getDeleteFlushFunctionListFunc();
112 Constant *getEndFileFunc();
114 // Create or retrieve an i32 state value that is used to represent the
115 // pred block number for certain non-trivial edges.
116 GlobalVariable *getEdgeStateValue();
118 // Produce a table of pointers to counters, by predecessor and successor
120 GlobalVariable *buildEdgeLookupTable(Function *F,
121 GlobalVariable *Counter,
122 const UniqueVector<BasicBlock *>&Preds,
123 const UniqueVector<BasicBlock*>&Succs);
125 // Add the function to write out all our counters to the global destructor
127 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
129 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
130 void insertIndirectCounterIncrement();
132 std::string mangleName(DICompileUnit CU, const char *NewStem);
136 // Reversed, NUL-terminated copy of Options.Version.
137 char ReversedVersion[5];
138 // Checksum, produced by hash of EdgeDestinations
139 SmallVector<uint32_t, 4> FileChecksums;
143 SmallVector<GCOVFunction *, 16> Funcs;
147 char GCOVProfiler::ID = 0;
148 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
149 "Insert instrumentation for GCOV profiling", false, false)
151 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
152 return new GCOVProfiler(Options);
155 static StringRef getFunctionName(DISubprogram SP) {
156 if (!SP.getLinkageName().empty())
157 return SP.getLinkageName();
164 static const char *const LinesTag;
165 static const char *const FunctionTag;
166 static const char *const BlockTag;
167 static const char *const EdgeTag;
171 void writeBytes(const char *Bytes, int Size) {
172 os->write(Bytes, Size);
175 void write(uint32_t i) {
176 writeBytes(reinterpret_cast<char*>(&i), 4);
179 // Returns the length measured in 4-byte blocks that will be used to
180 // represent this string in a GCOV file
181 static unsigned lengthOfGCOVString(StringRef s) {
182 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
183 // padding out to the next 4-byte word. The length is measured in 4-byte
184 // words including padding, not bytes of actual string.
185 return (s.size() / 4) + 1;
188 void writeGCOVString(StringRef s) {
189 uint32_t Len = lengthOfGCOVString(s);
191 writeBytes(s.data(), s.size());
193 // Write 1 to 4 bytes of NUL padding.
194 assert((unsigned)(4 - (s.size() % 4)) > 0);
195 assert((unsigned)(4 - (s.size() % 4)) <= 4);
196 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
201 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
202 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
203 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
204 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
209 // Constructed only by requesting it from a GCOVBlock, this object stores a
210 // list of line numbers and a single filename, representing lines that belong
212 class GCOVLines : public GCOVRecord {
214 void addLine(uint32_t Line) {
215 Lines.push_back(Line);
218 uint32_t length() const {
219 // Here 2 = 1 for string length + 1 for '0' id#.
220 return lengthOfGCOVString(Filename) + 2 + Lines.size();
225 writeGCOVString(Filename);
226 for (int i = 0, e = Lines.size(); i != e; ++i)
230 GCOVLines(StringRef F, raw_ostream *os)
237 SmallVector<uint32_t, 32> Lines;
241 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
242 struct StringKeySort {
243 bool operator()(StringMapEntry<GCOVLines *> *LHS,
244 StringMapEntry<GCOVLines *> *RHS) const {
245 return LHS->getKey() < RHS->getKey();
249 // Represent a basic block in GCOV. Each block has a unique number in the
250 // function, number of lines belonging to each block, and a set of edges to
252 class GCOVBlock : public GCOVRecord {
254 GCOVLines &getFile(StringRef Filename) {
255 GCOVLines *&Lines = LinesByFile[Filename];
257 Lines = new GCOVLines(Filename, os);
262 void addEdge(GCOVBlock &Successor) {
263 OutEdges.push_back(&Successor);
268 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
269 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
270 E = LinesByFile.end(); I != E; ++I) {
271 Len += I->second->length();
272 SortedLinesByFile.push_back(&*I);
275 writeBytes(LinesTag, 4);
279 StringKeySort Sorter;
280 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
281 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
282 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
284 (*I)->getValue()->writeOut();
290 DeleteContainerSeconds(LinesByFile);
294 friend class GCOVFunction;
296 GCOVBlock(uint32_t Number, raw_ostream *os)
302 StringMap<GCOVLines *> LinesByFile;
303 SmallVector<GCOVBlock *, 4> OutEdges;
306 // A function has a unique identifier, a checksum (we leave as zero) and a
307 // set of blocks and a map of edges between blocks. This is the only GCOV
308 // object users can construct, the blocks and lines will be rooted here.
309 class GCOVFunction : public GCOVRecord {
311 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
312 bool UseCfgChecksum) :
313 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
316 Function *F = SP.getFunction();
317 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
319 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
320 Blocks[BB] = new GCOVBlock(i++, os);
322 ReturnBlock = new GCOVBlock(i++, os);
324 std::string FunctionNameAndLine;
325 raw_string_ostream FNLOS(FunctionNameAndLine);
326 FNLOS << getFunctionName(SP) << SP.getLineNumber();
328 FuncChecksum = hash_value(FunctionNameAndLine);
332 DeleteContainerSeconds(Blocks);
336 GCOVBlock &getBlock(BasicBlock *BB) {
340 GCOVBlock &getReturnBlock() {
344 std::string getEdgeDestinations() {
345 std::string EdgeDestinations;
346 raw_string_ostream EDOS(EdgeDestinations);
347 Function *F = Blocks.begin()->first->getParent();
348 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
349 GCOVBlock &Block = *Blocks[I];
350 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
351 EDOS << Block.OutEdges[i]->Number;
353 return EdgeDestinations;
356 uint32_t getFuncChecksum() {
360 void setCfgChecksum(uint32_t Checksum) {
361 CfgChecksum = Checksum;
365 writeBytes(FunctionTag, 4);
366 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
367 1 + lengthOfGCOVString(SP.getFilename()) + 1;
375 writeGCOVString(getFunctionName(SP));
376 writeGCOVString(SP.getFilename());
377 write(SP.getLineNumber());
379 // Emit count of blocks.
380 writeBytes(BlockTag, 4);
381 write(Blocks.size() + 1);
382 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
383 write(0); // No flags on our blocks.
385 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
387 // Emit edges between blocks.
388 if (Blocks.empty()) return;
389 Function *F = Blocks.begin()->first->getParent();
390 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
391 GCOVBlock &Block = *Blocks[I];
392 if (Block.OutEdges.empty()) continue;
394 writeBytes(EdgeTag, 4);
395 write(Block.OutEdges.size() * 2 + 1);
397 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
398 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
400 write(Block.OutEdges[i]->Number);
401 write(0); // no flags
405 // Emit lines for each block.
406 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
407 Blocks[I]->writeOut();
414 uint32_t FuncChecksum;
416 uint32_t CfgChecksum;
417 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
418 GCOVBlock *ReturnBlock;
422 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
423 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
424 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
425 MDNode *N = GCov->getOperand(i);
426 if (N->getNumOperands() != 2) continue;
427 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
428 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
429 if (!GCovFile || !CompileUnit) continue;
430 if (CompileUnit == CU) {
431 SmallString<128> Filename = GCovFile->getString();
432 sys::path::replace_extension(Filename, NewStem);
433 return Filename.str();
438 SmallString<128> Filename = CU.getFilename();
439 sys::path::replace_extension(Filename, NewStem);
440 StringRef FName = sys::path::filename(Filename);
441 SmallString<128> CurPath;
442 if (sys::fs::current_path(CurPath)) return FName;
443 sys::path::append(CurPath, FName.str());
444 return CurPath.str();
447 bool GCOVProfiler::runOnModule(Module &M) {
449 Ctx = &M.getContext();
451 if (Options.EmitNotes) emitProfileNotes();
452 if (Options.EmitData) return emitProfileArcs();
456 void GCOVProfiler::emitProfileNotes() {
457 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
458 if (!CU_Nodes) return;
460 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
461 // Each compile unit gets its own .gcno file. This means that whether we run
462 // this pass over the original .o's as they're produced, or run it after
463 // LTO, we'll generate the same .gcno files.
465 DICompileUnit CU(CU_Nodes->getOperand(i));
466 std::string ErrorInfo;
467 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
469 std::string EdgeDestinations;
471 DIArray SPs = CU.getSubprograms();
472 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
473 DISubprogram SP(SPs.getElement(i));
474 assert((!SP || SP.isSubprogram()) &&
475 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
479 Function *F = SP.getFunction();
481 BasicBlock &EntryBlock = F->getEntryBlock();
482 EntryBlock.splitBasicBlock(EntryBlock.begin());
485 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
486 Funcs.push_back(Func);
488 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
489 GCOVBlock &Block = Func->getBlock(BB);
490 TerminatorInst *TI = BB->getTerminator();
491 if (int successors = TI->getNumSuccessors()) {
492 for (int i = 0; i != successors; ++i) {
493 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
495 } else if (isa<ReturnInst>(TI)) {
496 Block.addEdge(Func->getReturnBlock());
500 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
502 const DebugLoc &Loc = I->getDebugLoc();
503 if (Loc.isUnknown()) continue;
504 if (Line == Loc.getLine()) continue;
505 Line = Loc.getLine();
506 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
508 GCOVLines &Lines = Block.getFile(SP.getFilename());
509 Lines.addLine(Loc.getLine());
512 EdgeDestinations += Func->getEdgeDestinations();
515 FileChecksums.push_back(hash_value(EdgeDestinations));
516 out.write("oncg", 4);
517 out.write(ReversedVersion, 4);
518 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
520 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
521 E = Funcs.end(); I != E; ++I) {
522 GCOVFunction *Func = *I;
523 Func->setCfgChecksum(FileChecksums.back());
527 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
532 bool GCOVProfiler::emitProfileArcs() {
533 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
534 if (!CU_Nodes) return false;
537 bool InsertIndCounterIncrCode = false;
538 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
539 DICompileUnit CU(CU_Nodes->getOperand(i));
540 DIArray SPs = CU.getSubprograms();
541 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
542 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
543 DISubprogram SP(SPs.getElement(i));
544 assert((!SP || SP.isSubprogram()) &&
545 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
548 Function *F = SP.getFunction();
550 if (!Result) Result = true;
552 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
553 TerminatorInst *TI = BB->getTerminator();
554 if (isa<ReturnInst>(TI))
557 Edges += TI->getNumSuccessors();
560 ArrayType *CounterTy =
561 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
562 GlobalVariable *Counters =
563 new GlobalVariable(*M, CounterTy, false,
564 GlobalValue::InternalLinkage,
565 Constant::getNullValue(CounterTy),
567 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
569 UniqueVector<BasicBlock *> ComplexEdgePreds;
570 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
573 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
574 TerminatorInst *TI = BB->getTerminator();
575 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
577 if (Successors == 1) {
578 IRBuilder<> Builder(BB->getFirstInsertionPt());
579 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
581 Value *Count = Builder.CreateLoad(Counter);
582 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
583 Builder.CreateStore(Count, Counter);
584 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
585 IRBuilder<> Builder(BI);
586 Value *Sel = Builder.CreateSelect(BI->getCondition(),
587 Builder.getInt64(Edge),
588 Builder.getInt64(Edge + 1));
589 SmallVector<Value *, 2> Idx;
590 Idx.push_back(Builder.getInt64(0));
592 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
593 Value *Count = Builder.CreateLoad(Counter);
594 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
595 Builder.CreateStore(Count, Counter);
597 ComplexEdgePreds.insert(BB);
598 for (int i = 0; i != Successors; ++i)
599 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
606 if (!ComplexEdgePreds.empty()) {
607 GlobalVariable *EdgeTable =
608 buildEdgeLookupTable(F, Counters,
609 ComplexEdgePreds, ComplexEdgeSuccs);
610 GlobalVariable *EdgeState = getEdgeStateValue();
612 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
613 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
614 Builder.CreateStore(Builder.getInt32(i), EdgeState);
617 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
618 // Call runtime to perform increment.
619 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
620 Value *CounterPtrArray =
621 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
622 i * ComplexEdgePreds.size());
624 // Build code to increment the counter.
625 InsertIndCounterIncrCode = true;
626 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
627 EdgeState, CounterPtrArray);
632 Function *WriteoutF = insertCounterWriteout(CountersBySP);
633 Function *FlushF = insertFlush(CountersBySP);
635 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
636 // be executed at exit and the "__llvm_gcov_flush" function to be executed
637 // when "__gcov_flush" is called.
638 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
639 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
640 "__llvm_gcov_init", M);
641 F->setUnnamedAddr(true);
642 F->setLinkage(GlobalValue::InternalLinkage);
643 F->addFnAttr(Attribute::NoInline);
644 if (Options.NoRedZone)
645 F->addFnAttr(Attribute::NoRedZone);
647 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
648 IRBuilder<> Builder(BB);
650 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
652 PointerType::get(FTy, 0),
653 PointerType::get(FTy, 0)
655 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
657 // Initialize the environment and register the local writeout and flush
659 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
660 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
661 Builder.CreateRetVoid();
663 appendToGlobalCtors(*M, F, 0);
666 if (InsertIndCounterIncrCode)
667 insertIndirectCounterIncrement();
672 // All edges with successors that aren't branches are "complex", because it
673 // requires complex logic to pick which counter to update.
674 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
676 GlobalVariable *Counters,
677 const UniqueVector<BasicBlock *> &Preds,
678 const UniqueVector<BasicBlock *> &Succs) {
679 // TODO: support invoke, threads. We rely on the fact that nothing can modify
680 // the whole-Module pred edge# between the time we set it and the time we next
681 // read it. Threads and invoke make this untrue.
683 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
684 size_t TableSize = Succs.size() * Preds.size();
685 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
686 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
688 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
689 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
690 for (size_t i = 0; i != TableSize; ++i)
691 EdgeTable[i] = NullValue;
694 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
695 TerminatorInst *TI = BB->getTerminator();
696 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
697 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
698 for (int i = 0; i != Successors; ++i) {
699 BasicBlock *Succ = TI->getSuccessor(i);
700 IRBuilder<> Builder(Succ);
701 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
703 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
704 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
710 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
711 GlobalVariable *EdgeTableGV =
713 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
714 ConstantArray::get(EdgeTableTy, V),
715 "__llvm_gcda_edge_table");
716 EdgeTableGV->setUnnamedAddr(true);
720 Constant *GCOVProfiler::getStartFileFunc() {
722 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
723 Type::getInt8PtrTy(*Ctx), // const char version[4]
724 Type::getInt32Ty(*Ctx), // uint32_t checksum
726 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
727 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
730 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
731 Type *Int32Ty = Type::getInt32Ty(*Ctx);
732 Type *Int64Ty = Type::getInt64Ty(*Ctx);
734 Int32Ty->getPointerTo(), // uint32_t *predecessor
735 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
737 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
738 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
741 Constant *GCOVProfiler::getEmitFunctionFunc() {
743 Type::getInt32Ty(*Ctx), // uint32_t ident
744 Type::getInt8PtrTy(*Ctx), // const char *function_name
745 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
746 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
747 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
749 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
750 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
753 Constant *GCOVProfiler::getEmitArcsFunc() {
755 Type::getInt32Ty(*Ctx), // uint32_t num_counters
756 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
758 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
759 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
762 Constant *GCOVProfiler::getSummaryInfoFunc() {
763 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
764 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
767 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
768 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
769 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
772 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
773 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
774 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
777 Constant *GCOVProfiler::getEndFileFunc() {
778 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
779 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
782 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
783 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
785 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
786 GlobalValue::InternalLinkage,
787 ConstantInt::get(Type::getInt32Ty(*Ctx),
789 "__llvm_gcov_global_state_pred");
790 GV->setUnnamedAddr(true);
795 Function *GCOVProfiler::insertCounterWriteout(
796 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
797 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
798 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
800 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
801 "__llvm_gcov_writeout", M);
802 WriteoutF->setUnnamedAddr(true);
803 WriteoutF->addFnAttr(Attribute::NoInline);
804 if (Options.NoRedZone)
805 WriteoutF->addFnAttr(Attribute::NoRedZone);
807 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
808 IRBuilder<> Builder(BB);
810 Constant *StartFile = getStartFileFunc();
811 Constant *EmitFunction = getEmitFunctionFunc();
812 Constant *EmitArcs = getEmitArcsFunc();
813 Constant *SummaryInfo = getSummaryInfoFunc();
814 Constant *EndFile = getEndFileFunc();
816 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
818 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
819 DICompileUnit CU(CU_Nodes->getOperand(i));
820 std::string FilenameGcda = mangleName(CU, "gcda");
821 uint32_t CfgChecksum = FileChecksums.size() ? FileChecksums[i] : 0;
822 Builder.CreateCall3(StartFile,
823 Builder.CreateGlobalStringPtr(FilenameGcda),
824 Builder.CreateGlobalStringPtr(ReversedVersion),
825 Builder.getInt32(CfgChecksum));
826 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
827 DISubprogram SP(CountersBySP[j].second);
829 EmitFunction, Builder.getInt32(j),
830 Options.FunctionNamesInData ?
831 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
832 Constant::getNullValue(Builder.getInt8PtrTy()),
833 Builder.getInt32(Funcs[j]->getFuncChecksum()),
834 Builder.getInt8(Options.UseCfgChecksum),
835 Builder.getInt32(CfgChecksum));
837 GlobalVariable *GV = CountersBySP[j].first;
839 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
840 Builder.CreateCall2(EmitArcs,
841 Builder.getInt32(Arcs),
842 Builder.CreateConstGEP2_64(GV, 0, 0));
844 Builder.CreateCall(SummaryInfo);
845 Builder.CreateCall(EndFile);
849 Builder.CreateRetVoid();
853 void GCOVProfiler::insertIndirectCounterIncrement() {
855 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
856 Fn->setUnnamedAddr(true);
857 Fn->setLinkage(GlobalValue::InternalLinkage);
858 Fn->addFnAttr(Attribute::NoInline);
859 if (Options.NoRedZone)
860 Fn->addFnAttr(Attribute::NoRedZone);
862 // Create basic blocks for function.
863 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
864 IRBuilder<> Builder(BB);
866 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
867 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
868 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
870 // uint32_t pred = *predecessor;
871 // if (pred == 0xffffffff) return;
872 Argument *Arg = Fn->arg_begin();
873 Arg->setName("predecessor");
874 Value *Pred = Builder.CreateLoad(Arg, "pred");
875 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
876 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
878 Builder.SetInsertPoint(PredNotNegOne);
880 // uint64_t *counter = counters[pred];
881 // if (!counter) return;
882 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
883 Arg = llvm::next(Fn->arg_begin());
884 Arg->setName("counters");
885 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
886 Value *Counter = Builder.CreateLoad(GEP, "counter");
887 Cond = Builder.CreateICmpEQ(Counter,
888 Constant::getNullValue(
889 Builder.getInt64Ty()->getPointerTo()));
890 Builder.CreateCondBr(Cond, Exit, CounterEnd);
893 Builder.SetInsertPoint(CounterEnd);
894 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
895 Builder.getInt64(1));
896 Builder.CreateStore(Add, Counter);
897 Builder.CreateBr(Exit);
899 // Fill in the exit block.
900 Builder.SetInsertPoint(Exit);
901 Builder.CreateRetVoid();
904 Function *GCOVProfiler::
905 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
906 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
907 Function *FlushF = M->getFunction("__llvm_gcov_flush");
909 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
910 "__llvm_gcov_flush", M);
912 FlushF->setLinkage(GlobalValue::InternalLinkage);
913 FlushF->setUnnamedAddr(true);
914 FlushF->addFnAttr(Attribute::NoInline);
915 if (Options.NoRedZone)
916 FlushF->addFnAttr(Attribute::NoRedZone);
918 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
920 // Write out the current counters.
921 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
922 assert(WriteoutF && "Need to create the writeout function first!");
924 IRBuilder<> Builder(Entry);
925 Builder.CreateCall(WriteoutF);
927 // Zero out the counters.
928 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
929 I = CountersBySP.begin(), E = CountersBySP.end();
931 GlobalVariable *GV = I->first;
932 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
933 Builder.CreateStore(Null, GV);
936 Type *RetTy = FlushF->getReturnType();
937 if (RetTy == Type::getVoidTy(*Ctx))
938 Builder.CreateRetVoid();
939 else if (RetTy->isIntegerTy())
940 // Used if __llvm_gcov_flush was implicitly declared.
941 Builder.CreateRet(ConstantInt::get(RetTy, 0));
943 report_fatal_error("invalid return type for __llvm_gcov_flush");