blob: 8dd82d3a9a993181eb4ec7fe3e799ca6f1b39467 [file] [log] [blame]
Nick Lewyckyb1928702011-04-16 01:20:23 +00001//===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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"
13// file on exit.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "insert-gcov-profiling"
18
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"
37#include <string>
38#include <utility>
39using namespace llvm;
40
41namespace {
42 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000043 public:
44 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000045 GCOVProfiler()
46 : ModulePass(ID), EmitNotes(true), EmitData(true) {
47 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
48 }
49 GCOVProfiler(bool EmitNotes, bool EmitData)
50 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData) {
51 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000052 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
53 }
54 virtual const char *getPassName() const {
55 return "GCOV Profiler";
56 }
57
58 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000059 bool runOnModule(Module &M);
60
Nick Lewyckyb1928702011-04-16 01:20:23 +000061 // Create the GCNO files for the Module based on DebugInfo.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000062 void emitGCNO(DebugInfoFinder &DIF);
Nick Lewyckyb1928702011-04-16 01:20:23 +000063
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000064 // Modify the program to track transitions along edges and call into the
65 // profiling runtime to emit .gcda files when run.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000066 bool emitProfileArcs(DebugInfoFinder &DIF);
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000067
Nick Lewyckyb1928702011-04-16 01:20:23 +000068 // Get pointers to the functions in the runtime library.
69 Constant *getStartFileFunc();
Nick Lewycky1790c9c2011-04-26 03:54:16 +000070 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000071 Constant *getEmitFunctionFunc();
72 Constant *getEmitArcsFunc();
73 Constant *getEndFileFunc();
74
Nick Lewycky1790c9c2011-04-26 03:54:16 +000075 // Create or retrieve an i32 state value that is used to represent the
76 // pred block number for certain non-trivial edges.
77 GlobalVariable *getEdgeStateValue();
78
79 // Produce a table of pointers to counters, by predecessor and successor
80 // block number.
81 GlobalVariable *buildEdgeLookupTable(Function *F,
82 GlobalVariable *Counter,
83 const UniqueVector<BasicBlock *> &Preds,
84 const UniqueVector<BasicBlock *> &Succs);
85
Nick Lewyckyb1928702011-04-16 01:20:23 +000086 // Add the function to write out all our counters to the global destructor
87 // list.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000088 void insertCounterWriteout(DebugInfoFinder &,
Nick Lewyckyb1928702011-04-16 01:20:23 +000089 SmallVector<std::pair<GlobalVariable *,
90 uint32_t>, 8> &);
91
Nick Lewycky269687f2011-05-04 04:03:04 +000092 std::string mangleName(DICompileUnit CU, std::string NewStem);
93
Nick Lewyckya61e52c2011-04-21 01:56:25 +000094 bool EmitNotes;
95 bool EmitData;
96
Nick Lewycky1790c9c2011-04-26 03:54:16 +000097 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +000098 LLVMContext *Ctx;
99 };
100}
101
102char GCOVProfiler::ID = 0;
103INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
104 "Insert instrumentation for GCOV profiling", false, false)
105
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000106ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData) {
107 return new GCOVProfiler(EmitNotes, EmitData);
108}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000109
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000110static DISubprogram findSubprogram(DIScope Scope) {
111 while (!Scope.isSubprogram()) {
112 assert(Scope.isLexicalBlock() &&
Nick Lewyckyb1928702011-04-16 01:20:23 +0000113 "Debug location not lexical block or subprogram");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000114 Scope = DILexicalBlock(Scope).getContext();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000115 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000116 return DISubprogram(Scope);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000117}
118
119namespace {
120 class GCOVRecord {
121 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000122 static const char *LinesTag;
123 static const char *FunctionTag;
124 static const char *BlockTag;
125 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000126
127 GCOVRecord() {}
128
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000129 void writeBytes(const char *Bytes, int Size) {
130 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000131 }
132
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000133 void write(uint32_t i) {
134 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000135 }
136
137 // Returns the length measured in 4-byte blocks that will be used to
138 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000139 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000140 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000141 // padding out to the next 4-byte word. The length is measured in 4-byte
142 // words including padding, not bytes of actual string.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143 return (s.size() + 5) / 4;
144 }
145
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000146 void writeGCOVString(StringRef s) {
147 uint32_t Len = lengthOfGCOVString(s);
148 write(Len);
149 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000150
151 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000152 assert((unsigned)(4 - (s.size() % 4)) > 0);
153 assert((unsigned)(4 - (s.size() % 4)) <= 4);
154 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000155 }
156
157 raw_ostream *os;
158 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000159 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
160 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
161 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
162 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000163
164 class GCOVFunction;
165 class GCOVBlock;
166
167 // Constructed only by requesting it from a GCOVBlock, this object stores a
168 // list of line numbers and a single filename, representing lines that belong
169 // to the block.
170 class GCOVLines : public GCOVRecord {
171 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000172 void addLine(uint32_t Line) {
173 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000174 }
175
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000176 uint32_t length() {
177 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000178 }
179
180 private:
181 friend class GCOVBlock;
182
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000183 GCOVLines(std::string Filename, raw_ostream *os)
184 : Filename(Filename) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000185 this->os = os;
186 }
187
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000188 std::string Filename;
189 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000190 };
191
192 // Represent a basic block in GCOV. Each block has a unique number in the
193 // function, number of lines belonging to each block, and a set of edges to
194 // other blocks.
195 class GCOVBlock : public GCOVRecord {
196 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000197 GCOVLines &getFile(std::string Filename) {
198 GCOVLines *&Lines = LinesByFile[Filename];
199 if (!Lines) {
200 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000201 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000202 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000203 }
204
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000205 void addEdge(GCOVBlock &Successor) {
206 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000207 }
208
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000209 void writeOut() {
210 uint32_t Len = 3;
211 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
212 E = LinesByFile.end(); I != E; ++I) {
213 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000214 }
215
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000216 writeBytes(LinesTag, 4);
217 write(Len);
218 write(Number);
219 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
220 E = LinesByFile.end(); I != E; ++I) {
221 write(0);
222 writeGCOVString(I->second->Filename);
223 for (int i = 0, e = I->second->Lines.size(); i != e; ++i) {
224 write(I->second->Lines[i]);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000225 }
226 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000227 write(0);
228 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000229 }
230
231 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000232 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000233 }
234
235 private:
236 friend class GCOVFunction;
237
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000238 GCOVBlock(uint32_t Number, raw_ostream *os)
239 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000240 this->os = os;
241 }
242
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000243 uint32_t Number;
244 StringMap<GCOVLines *> LinesByFile;
245 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000246 };
247
248 // A function has a unique identifier, a checksum (we leave as zero) and a
249 // set of blocks and a map of edges between blocks. This is the only GCOV
250 // object users can construct, the blocks and lines will be rooted here.
251 class GCOVFunction : public GCOVRecord {
252 public:
253 GCOVFunction(DISubprogram SP, raw_ostream *os) {
254 this->os = os;
255
256 Function *F = SP.getFunction();
257 uint32_t i = 0;
258 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000259 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000260 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000261 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000262
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000263 writeBytes(FunctionTag, 4);
264 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
265 1 + lengthOfGCOVString(SP.getFilename()) + 1;
266 write(BlockLen);
267 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
268 write(Ident);
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000269 write(0); // checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000270 writeGCOVString(SP.getName());
271 writeGCOVString(SP.getFilename());
272 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000273 }
274
275 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000276 DeleteContainerSeconds(Blocks);
277 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000278 }
279
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000280 GCOVBlock &getBlock(BasicBlock *BB) {
281 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000282 }
283
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 GCOVBlock &getReturnBlock() {
285 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000286 }
287
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000288 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000289 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 writeBytes(BlockTag, 4);
291 write(Blocks.size() + 1);
292 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
293 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000294 }
295
296 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000297 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
298 E = Blocks.end(); I != E; ++I) {
299 GCOVBlock &Block = *I->second;
300 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000301
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000302 writeBytes(EdgeTag, 4);
303 write(Block.OutEdges.size() * 2 + 1);
304 write(Block.Number);
305 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
306 write(Block.OutEdges[i]->Number);
307 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000308 }
309 }
310
311 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
313 E = Blocks.end(); I != E; ++I) {
314 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000315 }
316 }
317
318 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000319 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
320 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000321 };
322}
323
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000324// Replace the stem of a file, or add one if missing.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000325static std::string replaceStem(std::string OrigFilename, std::string NewStem) {
326 return (sys::path::stem(OrigFilename) + "." + NewStem).str();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000327}
328
Nick Lewycky269687f2011-05-04 04:03:04 +0000329std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
330 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
331 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
332 MDNode *N = GCov->getOperand(i);
333 if (N->getNumOperands() != 2) continue;
334 MDString *Path = dyn_cast<MDString>(N->getOperand(0));
335 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
336 if (!Path || !CompileUnit) continue;
337 if (CompileUnit == CU)
338 return (Path->getString() + "/" +
339 replaceStem(CU.getFilename(), NewStem)).str();
340 }
341 }
342 return replaceStem(CU.getFilename(), NewStem);
343}
344
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000345bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000346 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000347 Ctx = &M.getContext();
348
349 DebugInfoFinder DIF;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000350 DIF.processModule(M);
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000351
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000352 if (EmitNotes) emitGCNO(DIF);
353 if (EmitData) return emitProfileArcs(DIF);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000354 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000355}
356
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000357void GCOVProfiler::emitGCNO(DebugInfoFinder &DIF) {
358 DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000359 for (DebugInfoFinder::iterator I = DIF.compile_unit_begin(),
360 E = DIF.compile_unit_end(); I != E; ++I) {
361 // Each compile unit gets its own .gcno file. This means that whether we run
362 // this pass over the original .o's as they're produced, or run it after
363 // LTO, we'll generate the same .gcno files.
364
365 DICompileUnit CU(*I);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000366 raw_fd_ostream *&out = GcnoFiles[CU];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000367 std::string ErrorInfo;
Nick Lewycky269687f2011-05-04 04:03:04 +0000368 out = new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
369 raw_fd_ostream::F_Binary);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000370 out->write("oncg*404MVLL", 12);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000371 }
372
373 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
374 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
375 DISubprogram SP(*SPI);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000376 raw_fd_ostream *&os = GcnoFiles[SP.getCompileUnit()];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000377
Nick Lewyckyb1928702011-04-16 01:20:23 +0000378 Function *F = SP.getFunction();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000379 if (!F) continue;
380 GCOVFunction Func(SP, os);
381
Nick Lewyckyb1928702011-04-16 01:20:23 +0000382 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000383 GCOVBlock &Block = Func.getBlock(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000384 TerminatorInst *TI = BB->getTerminator();
385 if (int successors = TI->getNumSuccessors()) {
386 for (int i = 0; i != successors; ++i) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000387 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000388 }
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000389 } else if (isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000390 Block.addEdge(Func.getReturnBlock());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000391 }
392
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000393 uint32_t Line = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000394 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000395 const DebugLoc &Loc = I->getDebugLoc();
396 if (Loc.isUnknown()) continue;
397 if (Line == Loc.getLine()) continue;
398 Line = Loc.getLine();
399 if (SP != findSubprogram(DIScope(Loc.getScope(*Ctx)))) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000400
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000401 GCOVLines &Lines = Block.getFile(SP.getFilename());
402 Lines.addLine(Loc.getLine());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000403 }
404 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000405 Func.writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000406 }
407
408 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000409 I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
410 raw_fd_ostream *&out = I->second;
411 out->write("\0\0\0\0\0\0\0\0", 8); // EOF
412 out->close();
413 delete out;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000414 }
415}
416
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000417bool GCOVProfiler::emitProfileArcs(DebugInfoFinder &DIF) {
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000418 if (DIF.subprogram_begin() == DIF.subprogram_end())
419 return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000420
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000421 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> CountersByIdent;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000422 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
423 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
424 DISubprogram SP(*SPI);
425 Function *F = SP.getFunction();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000426 if (!F) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000427
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000428 unsigned Edges = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000429 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
430 TerminatorInst *TI = BB->getTerminator();
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000431 if (isa<ReturnInst>(TI))
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000432 ++Edges;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000433 else
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000434 Edges += TI->getNumSuccessors();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000435 }
436
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000437 const ArrayType *CounterTy =
438 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
439 GlobalVariable *Counters =
440 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000441 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000442 Constant::getNullValue(CounterTy),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000443 "__llvm_gcov_ctr", 0, false, 0);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000444 CountersByIdent.push_back(
445 std::make_pair(Counters, reinterpret_cast<intptr_t>((MDNode*)SP)));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000446
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000447 UniqueVector<BasicBlock *> ComplexEdgePreds;
448 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000449
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000450 unsigned Edge = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000451 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
452 TerminatorInst *TI = BB->getTerminator();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000453 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
454 if (Successors) {
455 IRBuilder<> Builder(TI);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000456
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000457 if (Successors == 1) {
458 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
459 Edge);
460 Value *Count = Builder.CreateLoad(Counter);
461 Count = Builder.CreateAdd(Count,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000462 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000463 Builder.CreateStore(Count, Counter);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000464 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000465 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000466 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000467 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
468 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
469 SmallVector<Value *, 2> Idx;
470 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
471 Idx.push_back(Sel);
472 Value *Counter = Builder.CreateInBoundsGEP(Counters,
473 Idx.begin(), Idx.end());
474 Value *Count = Builder.CreateLoad(Counter);
475 Count = Builder.CreateAdd(Count,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000476 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000477 Builder.CreateStore(Count, Counter);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000478 } else {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000479 ComplexEdgePreds.insert(BB);
480 for (int i = 0; i != Successors; ++i)
481 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000482 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000483 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000484 }
485 }
486
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000487 if (!ComplexEdgePreds.empty()) {
488 GlobalVariable *EdgeTable =
489 buildEdgeLookupTable(F, Counters,
490 ComplexEdgePreds, ComplexEdgeSuccs);
491 GlobalVariable *EdgeState = getEdgeStateValue();
492
493 const Type *Int32Ty = Type::getInt32Ty(*Ctx);
494 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
495 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000496 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000497 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000498 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000499 // call runtime to perform increment
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000500 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstNonPHI());
501 Value *CounterPtrArray =
502 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
503 i * ComplexEdgePreds.size());
504 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
505 EdgeState, CounterPtrArray);
506 // clear the predecessor number
507 Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000508 }
509 }
510 }
511
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000512 insertCounterWriteout(DIF, CountersByIdent);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000513
514 return true;
515}
516
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000517// All edges with successors that aren't branches are "complex", because it
518// requires complex logic to pick which counter to update.
519GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
520 Function *F,
521 GlobalVariable *Counters,
522 const UniqueVector<BasicBlock *> &Preds,
523 const UniqueVector<BasicBlock *> &Succs) {
524 // TODO: support invoke, threads. We rely on the fact that nothing can modify
525 // the whole-Module pred edge# between the time we set it and the time we next
526 // read it. Threads and invoke make this untrue.
527
528 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
529 const Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
530 const ArrayType *EdgeTableTy = ArrayType::get(
531 Int64PtrTy, Succs.size() * Preds.size());
532
533 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
534 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
535 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
536 EdgeTable[i] = NullValue;
537
538 unsigned Edge = 0;
539 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
540 TerminatorInst *TI = BB->getTerminator();
541 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000542 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000543 for (int i = 0; i != Successors; ++i) {
544 BasicBlock *Succ = TI->getSuccessor(i);
545 IRBuilder<> builder(Succ);
546 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
547 Edge + i);
548 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
549 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
550 }
551 }
552 Edge += Successors;
553 }
554
555 GlobalVariable *EdgeTableGV =
556 new GlobalVariable(
557 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
558 ConstantArray::get(EdgeTableTy,
559 &EdgeTable[0], Succs.size() * Preds.size()),
560 "__llvm_gcda_edge_table");
561 EdgeTableGV->setUnnamedAddr(true);
562 return EdgeTableGV;
563}
564
Nick Lewyckyb1928702011-04-16 01:20:23 +0000565Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000566 const Type *Args[] = { Type::getInt8PtrTy(*Ctx) };
Nick Lewyckyb1928702011-04-16 01:20:23 +0000567 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
568 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000569 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
570}
571
572Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
573 const Type *Args[] = {
574 Type::getInt32PtrTy(*Ctx), // uint32_t *predecessor
575 Type::getInt64PtrTy(*Ctx)->getPointerTo(), // uint64_t **state_table_row
576 };
577 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
578 Args, false);
579 return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000580}
581
582Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000583 const Type *Args[] = { Type::getInt32Ty(*Ctx) };
Nick Lewyckyb1928702011-04-16 01:20:23 +0000584 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
585 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000586 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000587}
588
589Constant *GCOVProfiler::getEmitArcsFunc() {
590 const Type *Args[] = {
591 Type::getInt32Ty(*Ctx), // uint32_t num_counters
592 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
593 };
594 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
595 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000596 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000597}
598
599Constant *GCOVProfiler::getEndFileFunc() {
600 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000601 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000602}
603
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000604GlobalVariable *GCOVProfiler::getEdgeStateValue() {
605 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
606 if (!GV) {
607 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
608 GlobalValue::InternalLinkage,
609 ConstantInt::get(Type::getInt32Ty(*Ctx),
610 0xffffffff),
611 "__llvm_gcov_global_state_pred");
612 GV->setUnnamedAddr(true);
613 }
614 return GV;
615}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000616
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000617void GCOVProfiler::insertCounterWriteout(
618 DebugInfoFinder &DIF,
619 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> &CountersByIdent) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000620 const FunctionType *WriteoutFTy =
621 FunctionType::get(Type::getVoidTy(*Ctx), false);
622 Function *WriteoutF = Function::Create(WriteoutFTy,
623 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000624 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000625 WriteoutF->setUnnamedAddr(true);
626 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000627 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000628
629 Constant *StartFile = getStartFileFunc();
630 Constant *EmitFunction = getEmitFunctionFunc();
631 Constant *EmitArcs = getEmitArcsFunc();
632 Constant *EndFile = getEndFileFunc();
633
634 for (DebugInfoFinder::iterator CUI = DIF.compile_unit_begin(),
635 CUE = DIF.compile_unit_end(); CUI != CUE; ++CUI) {
636 DICompileUnit compile_unit(*CUI);
Nick Lewycky269687f2011-05-04 04:03:04 +0000637 std::string FilenameGcda = mangleName(compile_unit, "gcda");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000638 Builder.CreateCall(StartFile,
639 Builder.CreateGlobalStringPtr(FilenameGcda));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000640 for (SmallVector<std::pair<GlobalVariable *, uint32_t>, 8>::iterator
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000641 I = CountersByIdent.begin(), E = CountersByIdent.end();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000642 I != E; ++I) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000643 Builder.CreateCall(EmitFunction, ConstantInt::get(Type::getInt32Ty(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000644 I->second));
645 GlobalVariable *GV = I->first;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000646 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000647 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000648 Builder.CreateCall2(EmitArcs,
649 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
650 Builder.CreateConstGEP2_64(GV, 0, 0));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000651 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000652 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000653 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000654 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000655
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000656 InsertProfilingShutdownCall(WriteoutF, M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000657}