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 "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/Support/IRBuilder.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/UniqueVector.h"
42 class GCOVProfiler : public ModulePass {
46 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false) {
47 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false)
50 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
51 Use402Format(use402Format) {
52 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
53 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
55 virtual const char *getPassName() const {
56 return "GCOV Profiler";
60 bool runOnModule(Module &M);
62 // Create the GCNO files for the Module based on DebugInfo.
65 // Modify the program to track transitions along edges and call into the
66 // profiling runtime to emit .gcda files when run.
67 bool emitProfileArcs();
69 // Get pointers to the functions in the runtime library.
70 Constant *getStartFileFunc();
71 Constant *getIncrementIndirectCounterFunc();
72 Constant *getEmitFunctionFunc();
73 Constant *getEmitArcsFunc();
74 Constant *getEndFileFunc();
76 // Create or retrieve an i32 state value that is used to represent the
77 // pred block number for certain non-trivial edges.
78 GlobalVariable *getEdgeStateValue();
80 // Produce a table of pointers to counters, by predecessor and successor
82 GlobalVariable *buildEdgeLookupTable(Function *F,
83 GlobalVariable *Counter,
84 const UniqueVector<BasicBlock *> &Preds,
85 const UniqueVector<BasicBlock *> &Succs);
87 // Add the function to write out all our counters to the global destructor
89 void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
92 std::string mangleName(DICompileUnit CU, std::string NewStem);
103 char GCOVProfiler::ID = 0;
104 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
105 "Insert instrumentation for GCOV profiling", false, false)
107 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
109 return new GCOVProfiler(EmitNotes, EmitData, Use402Format);
115 static const char *LinesTag;
116 static const char *FunctionTag;
117 static const char *BlockTag;
118 static const char *EdgeTag;
122 void writeBytes(const char *Bytes, int Size) {
123 os->write(Bytes, Size);
126 void write(uint32_t i) {
127 writeBytes(reinterpret_cast<char*>(&i), 4);
130 // Returns the length measured in 4-byte blocks that will be used to
131 // represent this string in a GCOV file
132 unsigned lengthOfGCOVString(StringRef s) {
133 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
134 // padding out to the next 4-byte word. The length is measured in 4-byte
135 // words including padding, not bytes of actual string.
136 return (s.size() / 4) + 1;
139 void writeGCOVString(StringRef s) {
140 uint32_t Len = lengthOfGCOVString(s);
142 writeBytes(s.data(), s.size());
144 // Write 1 to 4 bytes of NUL padding.
145 assert((unsigned)(4 - (s.size() % 4)) > 0);
146 assert((unsigned)(4 - (s.size() % 4)) <= 4);
147 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
152 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
153 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
154 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
155 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
160 // Constructed only by requesting it from a GCOVBlock, this object stores a
161 // list of line numbers and a single filename, representing lines that belong
163 class GCOVLines : public GCOVRecord {
165 void addLine(uint32_t Line) {
166 Lines.push_back(Line);
170 // FIXME: ??? What is the significance of 2 here ?
171 return 2 + Lines.size();
175 friend class GCOVBlock;
177 GCOVLines(raw_ostream *os) {
181 SmallVector<uint32_t, 32> Lines;
184 // Represent a basic block in GCOV. Each block has a unique number in the
185 // function, number of lines belonging to each block, and a set of edges to
187 class GCOVBlock : public GCOVRecord {
189 GCOVLines &getFile(std::string Filename) {
190 GCOVLines *&Lines = LinesByFile[Filename];
192 Lines = new GCOVLines(os);
197 void addEdge(GCOVBlock &Successor) {
198 OutEdges.push_back(&Successor);
203 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
204 E = LinesByFile.end(); I != E; ++I) {
205 Len = Len + lengthOfGCOVString(I->first()) + I->second->length();
208 writeBytes(LinesTag, 4);
211 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
212 E = LinesByFile.end(); I != E; ++I) {
214 writeGCOVString(I->first());
215 for (int i = 0, e = I->second->Lines.size(); i != e; ++i) {
216 write(I->second->Lines[i]);
224 DeleteContainerSeconds(LinesByFile);
228 friend class GCOVFunction;
230 GCOVBlock(uint32_t Number, raw_ostream *os)
236 StringMap<GCOVLines *> LinesByFile;
237 SmallVector<GCOVBlock *, 4> OutEdges;
240 // A function has a unique identifier, a checksum (we leave as zero) and a
241 // set of blocks and a map of edges between blocks. This is the only GCOV
242 // object users can construct, the blocks and lines will be rooted here.
243 class GCOVFunction : public GCOVRecord {
245 GCOVFunction(DISubprogram SP, raw_ostream *os, bool Use402Format) {
248 Function *F = SP.getFunction();
250 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
251 Blocks[BB] = new GCOVBlock(i++, os);
253 ReturnBlock = new GCOVBlock(i++, os);
255 writeBytes(FunctionTag, 4);
256 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
257 1 + lengthOfGCOVString(SP.getFilename()) + 1;
259 ++BlockLen; // For second checksum.
261 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
263 write(0); // checksum #1
265 write(0); // checksum #2
266 writeGCOVString(SP.getName());
267 writeGCOVString(SP.getFilename());
268 write(SP.getLineNumber());
272 DeleteContainerSeconds(Blocks);
276 GCOVBlock &getBlock(BasicBlock *BB) {
280 GCOVBlock &getReturnBlock() {
285 // Emit count of blocks.
286 writeBytes(BlockTag, 4);
287 write(Blocks.size() + 1);
288 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
289 write(0); // No flags on our blocks.
292 // Emit edges between blocks.
293 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
294 E = Blocks.end(); I != E; ++I) {
295 GCOVBlock &Block = *I->second;
296 if (Block.OutEdges.empty()) continue;
298 writeBytes(EdgeTag, 4);
299 write(Block.OutEdges.size() * 2 + 1);
301 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
302 write(Block.OutEdges[i]->Number);
303 write(0); // no flags
307 // Emit lines for each block.
308 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
309 E = Blocks.end(); I != E; ++I) {
310 I->second->writeOut();
315 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
316 GCOVBlock *ReturnBlock;
320 std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
321 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
322 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
323 MDNode *N = GCov->getOperand(i);
324 if (N->getNumOperands() != 2) continue;
325 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
326 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
327 if (!GCovFile || !CompileUnit) continue;
328 if (CompileUnit == CU) {
329 SmallString<128> Filename = GCovFile->getString();
330 sys::path::replace_extension(Filename, NewStem);
331 return Filename.str();
336 SmallString<128> Filename = CU.getFilename();
337 sys::path::replace_extension(Filename, NewStem);
338 return sys::path::filename(Filename.str());
341 bool GCOVProfiler::runOnModule(Module &M) {
343 Ctx = &M.getContext();
345 if (EmitNotes) emitGCNO();
346 if (EmitData) return emitProfileArcs();
350 void GCOVProfiler::emitGCNO() {
351 DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
352 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
354 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
355 // Each compile unit gets its own .gcno file. This means that whether we run
356 // this pass over the original .o's as they're produced, or run it after
357 // LTO, we'll generate the same .gcno files.
359 DICompileUnit CU(CU_Nodes->getOperand(i));
360 raw_fd_ostream *&out = GcnoFiles[CU];
361 std::string ErrorInfo;
362 out = new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
363 raw_fd_ostream::F_Binary);
365 out->write("oncg*404MVLL", 12);
367 out->write("oncg*204MVLL", 12);
369 DIArray SPs = CU.getSubprograms();
370 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
371 DISubprogram SP(SPs.getElement(i));
372 if (!SP.Verify()) continue;
373 raw_fd_ostream *&os = GcnoFiles[CU];
375 Function *F = SP.getFunction();
377 GCOVFunction Func(SP, os, Use402Format);
379 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
380 GCOVBlock &Block = Func.getBlock(BB);
381 TerminatorInst *TI = BB->getTerminator();
382 if (int successors = TI->getNumSuccessors()) {
383 for (int i = 0; i != successors; ++i) {
384 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
386 } else if (isa<ReturnInst>(TI)) {
387 Block.addEdge(Func.getReturnBlock());
391 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
392 const DebugLoc &Loc = I->getDebugLoc();
393 if (Loc.isUnknown()) continue;
394 if (Line == Loc.getLine()) continue;
395 Line = Loc.getLine();
396 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
398 GCOVLines &Lines = Block.getFile(SP.getFilename());
399 Lines.addLine(Loc.getLine());
407 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
408 I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
409 raw_fd_ostream *&out = I->second;
410 out->write("\0\0\0\0\0\0\0\0", 8); // EOF
416 bool GCOVProfiler::emitProfileArcs() {
417 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
418 if (!CU_Nodes) return false;
421 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
422 DICompileUnit CU(CU_Nodes->getOperand(i));
423 DIArray SPs = CU.getSubprograms();
424 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
425 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
426 DISubprogram SP(SPs.getElement(i));
427 if (!SP.Verify()) continue;
428 Function *F = SP.getFunction();
430 if (!Result) Result = true;
432 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
433 TerminatorInst *TI = BB->getTerminator();
434 if (isa<ReturnInst>(TI))
437 Edges += TI->getNumSuccessors();
440 ArrayType *CounterTy =
441 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
442 GlobalVariable *Counters =
443 new GlobalVariable(*M, CounterTy, false,
444 GlobalValue::InternalLinkage,
445 Constant::getNullValue(CounterTy),
446 "__llvm_gcov_ctr", 0, false, 0);
447 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
449 UniqueVector<BasicBlock *> ComplexEdgePreds;
450 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
453 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
454 TerminatorInst *TI = BB->getTerminator();
455 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
457 IRBuilder<> Builder(TI);
459 if (Successors == 1) {
460 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
462 Value *Count = Builder.CreateLoad(Counter);
463 Count = Builder.CreateAdd(Count,
464 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
465 Builder.CreateStore(Count, Counter);
466 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
467 Value *Sel = Builder.CreateSelect(
469 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
470 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
471 SmallVector<Value *, 2> Idx;
472 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
474 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
475 Value *Count = Builder.CreateLoad(Counter);
476 Count = Builder.CreateAdd(Count,
477 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
478 Builder.CreateStore(Count, Counter);
480 ComplexEdgePreds.insert(BB);
481 for (int i = 0; i != Successors; ++i)
482 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
488 if (!ComplexEdgePreds.empty()) {
489 GlobalVariable *EdgeTable =
490 buildEdgeLookupTable(F, Counters,
491 ComplexEdgePreds, ComplexEdgeSuccs);
492 GlobalVariable *EdgeState = getEdgeStateValue();
494 Type *Int32Ty = Type::getInt32Ty(*Ctx);
495 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
496 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
497 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
499 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
500 // call runtime to perform increment
501 BasicBlock::iterator InsertPt =
502 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
503 IRBuilder<> Builder(InsertPt);
504 Value *CounterPtrArray =
505 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
506 i * ComplexEdgePreds.size());
507 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
508 EdgeState, CounterPtrArray);
509 // clear the predecessor number
510 Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
514 insertCounterWriteout(CountersBySP);
519 // All edges with successors that aren't branches are "complex", because it
520 // requires complex logic to pick which counter to update.
521 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
523 GlobalVariable *Counters,
524 const UniqueVector<BasicBlock *> &Preds,
525 const UniqueVector<BasicBlock *> &Succs) {
526 // TODO: support invoke, threads. We rely on the fact that nothing can modify
527 // the whole-Module pred edge# between the time we set it and the time we next
528 // read it. Threads and invoke make this untrue.
530 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
531 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
532 ArrayType *EdgeTableTy = ArrayType::get(
533 Int64PtrTy, Succs.size() * Preds.size());
535 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
536 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
537 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
538 EdgeTable[i] = NullValue;
541 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
542 TerminatorInst *TI = BB->getTerminator();
543 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
544 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
545 for (int i = 0; i != Successors; ++i) {
546 BasicBlock *Succ = TI->getSuccessor(i);
547 IRBuilder<> builder(Succ);
548 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
550 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
551 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
557 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
558 GlobalVariable *EdgeTableGV =
560 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
561 ConstantArray::get(EdgeTableTy, V),
562 "__llvm_gcda_edge_table");
563 EdgeTableGV->setUnnamedAddr(true);
567 Constant *GCOVProfiler::getStartFileFunc() {
568 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
569 Type::getInt8PtrTy(*Ctx), false);
570 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
573 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
575 Type::getInt32PtrTy(*Ctx), // uint32_t *predecessor
576 Type::getInt64PtrTy(*Ctx)->getPointerTo(), // uint64_t **state_table_row
578 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
580 return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
583 Constant *GCOVProfiler::getEmitFunctionFunc() {
585 Type::getInt32Ty(*Ctx), // uint32_t ident
586 Type::getInt8PtrTy(*Ctx), // const char *function_name
588 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
590 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
593 Constant *GCOVProfiler::getEmitArcsFunc() {
595 Type::getInt32Ty(*Ctx), // uint32_t num_counters
596 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
598 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
600 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
603 Constant *GCOVProfiler::getEndFileFunc() {
604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
605 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
608 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
609 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
611 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
612 GlobalValue::InternalLinkage,
613 ConstantInt::get(Type::getInt32Ty(*Ctx),
615 "__llvm_gcov_global_state_pred");
616 GV->setUnnamedAddr(true);
621 void GCOVProfiler::insertCounterWriteout(
622 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
623 FunctionType *WriteoutFTy =
624 FunctionType::get(Type::getVoidTy(*Ctx), false);
625 Function *WriteoutF = Function::Create(WriteoutFTy,
626 GlobalValue::InternalLinkage,
627 "__llvm_gcov_writeout", M);
628 WriteoutF->setUnnamedAddr(true);
629 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
630 IRBuilder<> Builder(BB);
632 Constant *StartFile = getStartFileFunc();
633 Constant *EmitFunction = getEmitFunctionFunc();
634 Constant *EmitArcs = getEmitArcsFunc();
635 Constant *EndFile = getEndFileFunc();
637 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
639 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
640 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
641 std::string FilenameGcda = mangleName(compile_unit, "gcda");
642 Builder.CreateCall(StartFile,
643 Builder.CreateGlobalStringPtr(FilenameGcda));
644 for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
645 I = CountersBySP.begin(), E = CountersBySP.end();
647 DISubprogram SP(I->second);
648 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
649 Builder.CreateCall2(EmitFunction,
650 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
651 Builder.CreateGlobalStringPtr(SP.getName()));
653 GlobalVariable *GV = I->first;
655 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
656 Builder.CreateCall2(EmitArcs,
657 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
658 Builder.CreateConstGEP2_64(GV, 0, 0));
660 Builder.CreateCall(EndFile);
663 Builder.CreateRetVoid();
665 InsertProfilingShutdownCall(WriteoutF, M);