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 {
43 bool runOnModule(Module &M);
46 GCOVProfiler() : ModulePass(ID) {
47 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49 virtual const char *getPassName() const {
50 return "GCOV Profiler";
54 // Create the GCNO files for the Module based on DebugInfo.
55 void EmitGCNO(DebugInfoFinder &DIF);
57 // Get pointers to the functions in the runtime library.
58 Constant *getStartFileFunc();
59 Constant *getEmitFunctionFunc();
60 Constant *getEmitArcsFunc();
61 Constant *getEndFileFunc();
63 // Add the function to write out all our counters to the global destructor
65 void InsertCounterWriteout(DebugInfoFinder &,
66 SmallVector<std::pair<GlobalVariable *,
74 char GCOVProfiler::ID = 0;
75 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
76 "Insert instrumentation for GCOV profiling", false, false)
78 ModulePass *llvm::createGCOVProfilerPass() { return new GCOVProfiler(); }
80 static DISubprogram FindSubprogram(DIScope scope) {
81 while (!scope.isSubprogram()) {
82 assert(scope.isLexicalBlock() &&
83 "Debug location not lexical block or subprogram");
84 scope = DILexicalBlock(scope).getContext();
86 return DISubprogram(scope);
92 static const char *lines_tag;
93 static const char *function_tag;
94 static const char *block_tag;
95 static const char *edge_tag;
99 void WriteBytes(const char *b, int size) {
103 void Write(uint32_t i) {
104 WriteBytes(reinterpret_cast<char*>(&i), 4);
107 // Returns the length measured in 4-byte blocks that will be used to
108 // represent this string in a GCOV file
109 unsigned LengthOfGCOVString(StringRef s) {
110 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
111 // padding out to the next 4-byte word. The length is measured in 4-byte words
112 // including padding, not bytes of actual string.
113 return (s.size() + 5) / 4;
116 void WriteGCOVString(StringRef s) {
117 uint32_t len = LengthOfGCOVString(s);
119 WriteBytes(s.data(), s.size());
121 // Write 1 to 4 bytes of NUL padding.
122 assert((unsigned)(5 - ((s.size() + 1) % 4)) > 0);
123 assert((unsigned)(5 - ((s.size() + 1) % 4)) <= 4);
124 WriteBytes("\0\0\0\0", 5 - ((s.size() + 1) % 4));
129 const char *GCOVRecord::lines_tag = "\0\0\x45\x01";
130 const char *GCOVRecord::function_tag = "\0\0\0\1";
131 const char *GCOVRecord::block_tag = "\0\0\x41\x01";
132 const char *GCOVRecord::edge_tag = "\0\0\x43\x01";
137 // Constructed only by requesting it from a GCOVBlock, this object stores a
138 // list of line numbers and a single filename, representing lines that belong
140 class GCOVLines : public GCOVRecord {
142 void AddLine(uint32_t line) {
143 lines.push_back(line);
147 return LengthOfGCOVString(filename) + 2 + lines.size();
151 friend class GCOVBlock;
153 GCOVLines(std::string filename, raw_ostream *os)
154 : filename(filename) {
158 std::string filename;
159 SmallVector<uint32_t, 32> lines;
162 // Represent a basic block in GCOV. Each block has a unique number in the
163 // function, number of lines belonging to each block, and a set of edges to
165 class GCOVBlock : public GCOVRecord {
167 GCOVLines &GetFile(std::string filename) {
168 GCOVLines *&lines = lines_by_file[filename];
170 lines = new GCOVLines(filename, os);
175 void AddEdge(GCOVBlock &successor) {
176 out_edges.push_back(&successor);
181 for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
182 E = lines_by_file.end(); I != E; ++I) {
183 len += I->second->Length();
186 WriteBytes(lines_tag, 4);
189 for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
190 E = lines_by_file.end(); I != E; ++I) {
192 WriteGCOVString(I->second->filename);
193 for (int i = 0, e = I->second->lines.size(); i != e; ++i) {
194 Write(I->second->lines[i]);
202 DeleteContainerSeconds(lines_by_file);
206 friend class GCOVFunction;
208 GCOVBlock(uint32_t number, raw_ostream *os)
215 StringMap<GCOVLines *> lines_by_file;
216 SmallVector<GCOVBlock *, 4> out_edges;
219 // A function has a unique identifier, a checksum (we leave as zero) and a
220 // set of blocks and a map of edges between blocks. This is the only GCOV
221 // object users can construct, the blocks and lines will be rooted here.
222 class GCOVFunction : public GCOVRecord {
224 GCOVFunction(DISubprogram SP, raw_ostream *os) {
227 Function *F = SP.getFunction();
229 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
230 blocks[BB] = new GCOVBlock(i++, os);
233 WriteBytes(function_tag, 4);
234 uint32_t block_len = 1 + 1 + 1 + LengthOfGCOVString(SP.getName()) +
235 1 + LengthOfGCOVString(SP.getFilename()) + 1;
237 uint32_t ident = reinterpret_cast<intptr_t>((MDNode*)SP);
239 Write(0); // checksum
240 WriteGCOVString(SP.getName());
241 WriteGCOVString(SP.getFilename());
242 Write(SP.getLineNumber());
246 DeleteContainerSeconds(blocks);
249 GCOVBlock &GetBlock(BasicBlock *BB) {
254 // Emit count of blocks.
255 WriteBytes(block_tag, 4);
256 Write(blocks.size());
257 for (int i = 0, e = blocks.size(); i != e; ++i) {
258 Write(0); // No flags on our blocks.
261 // Emit edges between blocks.
262 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
263 E = blocks.end(); I != E; ++I) {
264 GCOVBlock &block = *I->second;
265 if (block.out_edges.empty()) continue;
267 WriteBytes(edge_tag, 4);
268 Write(block.out_edges.size() * 2 + 1);
270 for (int i = 0, e = block.out_edges.size(); i != e; ++i) {
271 Write(block.out_edges[i]->number);
272 Write(0); // no flags
276 // Emit lines for each block.
277 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
278 E = blocks.end(); I != E; ++I) {
279 I->second->WriteOut();
284 DenseMap<BasicBlock *, GCOVBlock *> blocks;
288 void GCOVProfiler::EmitGCNO(DebugInfoFinder &DIF) {
289 DenseMap<const MDNode *, raw_fd_ostream *> gcno_files;
290 for (DebugInfoFinder::iterator I = DIF.compile_unit_begin(),
291 E = DIF.compile_unit_end(); I != E; ++I) {
292 // Each compile unit gets its own .gcno file. This means that whether we run
293 // this pass over the original .o's as they're produced, or run it after
294 // LTO, we'll generate the same .gcno files.
296 DICompileUnit CU(*I);
297 raw_fd_ostream *&Out = gcno_files[CU];
298 std::string ErrorInfo;
299 Out = new raw_fd_ostream(
300 (sys::path::stem(CU.getFilename()) + ".gcno").str().c_str(),
301 ErrorInfo, raw_fd_ostream::F_Binary);
302 Out->write("oncg*404MVLL", 12);
305 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
306 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
307 DISubprogram SP(*SPI);
308 raw_fd_ostream *&os = gcno_files[SP.getCompileUnit()];
310 GCOVFunction function(SP, os);
311 Function *F = SP.getFunction();
312 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
313 GCOVBlock &block = function.GetBlock(BB);
314 TerminatorInst *TI = BB->getTerminator();
315 if (int successors = TI->getNumSuccessors()) {
316 for (int i = 0; i != successors; ++i) {
317 block.AddEdge(function.GetBlock(TI->getSuccessor(i)));
322 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
323 const DebugLoc &loc = I->getDebugLoc();
324 if (loc.isUnknown()) continue;
325 if (line == loc.getLine()) continue;
326 line = loc.getLine();
327 if (SP != FindSubprogram(DIScope(loc.getScope(*Ctx)))) continue;
329 GCOVLines &lines = block.GetFile(SP.getFilename());
330 lines.AddLine(loc.getLine());
336 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
337 I = gcno_files.begin(), E = gcno_files.end(); I != E; ++I) {
338 raw_fd_ostream *&Out = I->second;
339 Out->write("\0\0\0\0\0\0\0\0", 4); // EOF
345 bool GCOVProfiler::runOnModule(Module &M) {
347 Ctx = &M.getContext();
350 DIF.processModule(*Mod);
354 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> counters_by_ident;
355 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
356 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
357 DISubprogram SP(*SPI);
358 Function *F = SP.getFunction();
360 // TODO: GCOV format requires a distinct unified exit block.
362 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
363 TerminatorInst *TI = BB->getTerminator();
364 edges += TI->getNumSuccessors();
367 const ArrayType *counter_type =
368 ArrayType::get(Type::getInt64Ty(*Ctx), edges);
369 GlobalVariable *counter =
370 new GlobalVariable(*Mod, counter_type, false,
371 GlobalValue::InternalLinkage,
372 Constant::getNullValue(counter_type),
373 "__llvm_gcov_ctr", 0, false, 0);
374 counters_by_ident.push_back(
375 std::make_pair(counter, reinterpret_cast<intptr_t>((MDNode*)SP)));
377 UniqueVector<BasicBlock *> complex_edge_preds;
378 UniqueVector<BasicBlock *> complex_edge_succs;
380 unsigned edge_num = 0;
381 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
382 TerminatorInst *TI = BB->getTerminator();
383 if (int successors = TI->getNumSuccessors()) {
384 IRBuilder<> builder(TI);
386 if (successors == 1) {
387 Value *ctr = builder.CreateConstInBoundsGEP2_64(counter, 0, edge_num);
388 Value *count = builder.CreateLoad(ctr);
389 count = builder.CreateAdd(count,
390 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
391 builder.CreateStore(count, ctr);
392 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
393 Value *sel = builder.CreateSelect(
395 ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num),
396 ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num + 1));
397 SmallVector<Value *, 2> idx;
398 idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
400 Value *ctr = builder.CreateInBoundsGEP(counter,
401 idx.begin(), idx.end());
402 Value *count = builder.CreateLoad(ctr);
403 count = builder.CreateAdd(count,
404 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
405 builder.CreateStore(count, ctr);
407 complex_edge_preds.insert(BB);
408 for (int i = 0; i != successors; ++i) {
409 complex_edge_succs.insert(TI->getSuccessor(i));
412 edge_num += successors;
416 // TODO: support switch, invoke, indirectbr
417 if (!complex_edge_preds.empty()) {
418 // emit a [preds x [succs x i64*]].
419 for (int i = 0, e = complex_edge_preds.size(); i != e; ++i) {
420 // call runtime to state save
422 for (int i = 0, e = complex_edge_succs.size(); i != e; ++i) {
423 // call runtime to perform increment
428 InsertCounterWriteout(DIF, counters_by_ident);
433 Constant *GCOVProfiler::getStartFileFunc() {
434 const Type *Args[1] = { Type::getInt8PtrTy(*Ctx) };
435 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
437 return Mod->getOrInsertFunction("llvm_gcda_start_file", FTy);
440 Constant *GCOVProfiler::getEmitFunctionFunc() {
441 const Type *Args[1] = { Type::getInt32Ty(*Ctx) };
442 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
444 return Mod->getOrInsertFunction("llvm_gcda_emit_function", FTy);
447 Constant *GCOVProfiler::getEmitArcsFunc() {
448 const Type *Args[] = {
449 Type::getInt32Ty(*Ctx), // uint32_t num_counters
450 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
452 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
454 return Mod->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
457 Constant *GCOVProfiler::getEndFileFunc() {
458 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
459 return Mod->getOrInsertFunction("llvm_gcda_end_file", FTy);
462 static std::string ReplaceStem(std::string orig_filename, std::string new_stem){
463 return (sys::path::stem(orig_filename) + "." + new_stem).str();
466 void GCOVProfiler::InsertCounterWriteout(
467 DebugInfoFinder &DIF,
468 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> &counters_by_ident) {
470 const FunctionType *WriteoutFTy =
471 FunctionType::get(Type::getVoidTy(*Ctx), false);
472 Function *WriteoutF = Function::Create(WriteoutFTy,
473 GlobalValue::InternalLinkage,
474 "__llvm_gcda_writeout", Mod);
475 WriteoutF->setUnnamedAddr(true);
476 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
477 IRBuilder<> builder(BB);
479 Constant *StartFile = getStartFileFunc();
480 Constant *EmitFunction = getEmitFunctionFunc();
481 Constant *EmitArcs = getEmitArcsFunc();
482 Constant *EndFile = getEndFileFunc();
484 for (DebugInfoFinder::iterator CUI = DIF.compile_unit_begin(),
485 CUE = DIF.compile_unit_end(); CUI != CUE; ++CUI) {
486 DICompileUnit compile_unit(*CUI);
487 std::string filename_gcda = ReplaceStem(compile_unit.getFilename(), "gcda");
488 builder.CreateCall(StartFile,
489 builder.CreateGlobalStringPtr(filename_gcda));
490 for (SmallVector<std::pair<GlobalVariable *, uint32_t>, 8>::iterator
491 I = counters_by_ident.begin(), E = counters_by_ident.end();
493 builder.CreateCall(EmitFunction, ConstantInt::get(Type::getInt32Ty(*Ctx),
495 GlobalVariable *GV = I->first;
497 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
500 ConstantInt::get(Type::getInt32Ty(*Ctx), num_arcs),
501 builder.CreateConstGEP2_64(GV, 0, 0));
503 builder.CreateCall(EndFile);
505 builder.CreateRetVoid();
507 InsertProfilingShutdownCall(WriteoutF, Mod);