blob: f01c6d5a9e2540dd21c3e4d238b4e926a311fc5e [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"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000021#include "llvm/DebugInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IRBuilder.h"
23#include "llvm/Instructions.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000026#include "llvm/ADT/DenseMap.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000027#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000028#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000029#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/UniqueVector.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/DebugLoc.h"
34#include "llvm/Support/InstIterator.h"
35#include "llvm/Support/PathV2.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000038#include <string>
39#include <utility>
40using namespace llvm;
41
42namespace {
43 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000044 public:
45 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000046 GCOVProfiler()
Nick Lewyckybba40db2011-11-27 23:22:20 +000047 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
48 UseExtraChecksum(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000049 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
50 }
Nick Lewyckybba40db2011-11-27 23:22:20 +000051 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
52 bool useExtraChecksum = false)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000053 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Nick Lewyckybba40db2011-11-27 23:22:20 +000054 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000055 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000056 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
57 }
58 virtual const char *getPassName() const {
59 return "GCOV Profiler";
60 }
Nick Lewyckyb1928702011-04-16 01:20:23 +000061 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000062 bool runOnModule(Module &M);
63
Nick Lewyckyb1928702011-04-16 01:20:23 +000064 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000065 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000066
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000067 // Modify the program to track transitions along edges and call into the
68 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000069 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000070
Nick Lewyckyb1928702011-04-16 01:20:23 +000071 // Get pointers to the functions in the runtime library.
72 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +000073 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000074 Constant *getEmitFunctionFunc();
75 Constant *getEmitArcsFunc();
76 Constant *getEndFileFunc();
77
Nick Lewycky1790c9c2011-04-26 03:54:16 +000078 // Create or retrieve an i32 state value that is used to represent the
79 // pred block number for certain non-trivial edges.
80 GlobalVariable *getEdgeStateValue();
81
82 // Produce a table of pointers to counters, by predecessor and successor
83 // block number.
84 GlobalVariable *buildEdgeLookupTable(Function *F,
85 GlobalVariable *Counter,
86 const UniqueVector<BasicBlock *> &Preds,
87 const UniqueVector<BasicBlock *> &Succs);
88
Nick Lewyckyb1928702011-04-16 01:20:23 +000089 // Add the function to write out all our counters to the global destructor
90 // list.
Bill Wendling21b742f2012-08-29 18:45:41 +000091 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +000092 void insertIndirectCounterIncrement();
Nick Lewyckyb1928702011-04-16 01:20:23 +000093
Bill Wendling0e76db92012-08-29 20:30:44 +000094 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +000095
Nick Lewyckya61e52c2011-04-21 01:56:25 +000096 bool EmitNotes;
97 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +000098 bool Use402Format;
Nick Lewyckybba40db2011-11-27 23:22:20 +000099 bool UseExtraChecksum;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000100
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000101 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000102 LLVMContext *Ctx;
103 };
104}
105
106char GCOVProfiler::ID = 0;
107INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
108 "Insert instrumentation for GCOV profiling", false, false)
109
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000110ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
Nick Lewycky7c067412011-12-06 00:29:13 +0000111 bool Use402Format,
112 bool UseExtraChecksum) {
113 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000114}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000115
Nick Lewyckyb1928702011-04-16 01:20:23 +0000116namespace {
117 class GCOVRecord {
118 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000119 static const char *LinesTag;
120 static const char *FunctionTag;
121 static const char *BlockTag;
122 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000123
124 GCOVRecord() {}
125
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000126 void writeBytes(const char *Bytes, int Size) {
127 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000128 }
129
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000130 void write(uint32_t i) {
131 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000132 }
133
134 // Returns the length measured in 4-byte blocks that will be used to
135 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000136 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000137 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000138 // padding out to the next 4-byte word. The length is measured in 4-byte
139 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000140 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000141 }
142
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000143 void writeGCOVString(StringRef s) {
144 uint32_t Len = lengthOfGCOVString(s);
145 write(Len);
146 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000147
148 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000149 assert((unsigned)(4 - (s.size() % 4)) > 0);
150 assert((unsigned)(4 - (s.size() % 4)) <= 4);
151 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000152 }
153
154 raw_ostream *os;
155 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000156 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
157 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
158 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
159 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000160
161 class GCOVFunction;
162 class GCOVBlock;
163
164 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000165 // list of line numbers and a single filename, representing lines that belong
166 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000167 class GCOVLines : public GCOVRecord {
168 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000169 void addLine(uint32_t Line) {
170 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000171 }
172
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000173 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000174 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000175 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000176 }
177
Devang Patel16c19a12011-09-20 18:35:00 +0000178 void writeOut() {
179 write(0);
180 writeGCOVString(Filename);
181 for (int i = 0, e = Lines.size(); i != e; ++i)
182 write(Lines[i]);
183 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000184
Devang Patel16c19a12011-09-20 18:35:00 +0000185 GCOVLines(StringRef F, raw_ostream *os)
186 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000187 this->os = os;
188 }
189
Devang Patel680018f2011-09-20 18:48:56 +0000190 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000191 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000192 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000193 };
194
195 // Represent a basic block in GCOV. Each block has a unique number in the
196 // function, number of lines belonging to each block, and a set of edges to
197 // other blocks.
198 class GCOVBlock : public GCOVRecord {
199 public:
Devang Patel68155d32011-09-20 17:55:19 +0000200 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000201 GCOVLines *&Lines = LinesByFile[Filename];
202 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000203 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000204 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000205 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000206 }
207
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000208 void addEdge(GCOVBlock &Successor) {
209 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000210 }
211
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000212 void writeOut() {
213 uint32_t Len = 3;
214 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
215 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000216 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000217 }
218
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000219 writeBytes(LinesTag, 4);
220 write(Len);
221 write(Number);
222 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000223 E = LinesByFile.end(); I != E; ++I)
224 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000225 write(0);
226 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000227 }
228
229 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 }
232
233 private:
234 friend class GCOVFunction;
235
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000236 GCOVBlock(uint32_t Number, raw_ostream *os)
237 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000238 this->os = os;
239 }
240
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000241 uint32_t Number;
242 StringMap<GCOVLines *> LinesByFile;
243 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000244 };
245
246 // A function has a unique identifier, a checksum (we leave as zero) and a
247 // set of blocks and a map of edges between blocks. This is the only GCOV
248 // object users can construct, the blocks and lines will be rooted here.
249 class GCOVFunction : public GCOVRecord {
250 public:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000251 GCOVFunction(DISubprogram SP, raw_ostream *os,
252 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000253 this->os = os;
254
255 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000256 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000257 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);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000264 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000265 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000266 if (UseExtraChecksum)
267 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 write(BlockLen);
269 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
270 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000271 write(0); // lineno checksum
272 if (UseExtraChecksum)
273 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000274 writeGCOVString(SP.getName());
275 writeGCOVString(SP.getFilename());
276 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000277 }
278
279 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000280 DeleteContainerSeconds(Blocks);
281 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000282 }
283
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 GCOVBlock &getBlock(BasicBlock *BB) {
285 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000286 }
287
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000288 GCOVBlock &getReturnBlock() {
289 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000290 }
291
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000292 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000293 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 writeBytes(BlockTag, 4);
295 write(Blocks.size() + 1);
296 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
297 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000298 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000299 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000300
301 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000302 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
303 E = Blocks.end(); I != E; ++I) {
304 GCOVBlock &Block = *I->second;
305 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000306
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000307 writeBytes(EdgeTag, 4);
308 write(Block.OutEdges.size() * 2 + 1);
309 write(Block.Number);
310 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000311 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
312 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000313 write(Block.OutEdges[i]->Number);
314 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000315 }
316 }
317
318 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000319 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
320 E = Blocks.end(); I != E; ++I) {
321 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000322 }
323 }
324
325 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000326 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
327 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000328 };
329}
330
Bill Wendling0e76db92012-08-29 20:30:44 +0000331std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
332 SmallString<128> Filename = CU.getFilename();
333 bool AsString = false;
334
Nick Lewycky269687f2011-05-04 04:03:04 +0000335 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
336 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
337 MDNode *N = GCov->getOperand(i);
338 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000339 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000340 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000341 if (!GCovFile || !CompileUnit) continue;
342 if (CompileUnit == CU) {
Bill Wendling0e76db92012-08-29 20:30:44 +0000343 Filename = GCovFile->getString();
344 AsString = true;
345 break;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000346 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000347 }
348 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000349
Bill Wendling0e76db92012-08-29 20:30:44 +0000350 if (sys::path::is_relative(Filename.c_str())) {
351 SmallString<128> FullPath = CU.getDirectory();
352 sys::path::append(FullPath, Filename.begin(), Filename.end());
353 Filename = FullPath;
354 }
355
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000356 sys::path::replace_extension(Filename, NewStem);
Bill Wendling0e76db92012-08-29 20:30:44 +0000357
358 if (!AsString)
359 return sys::path::filename(Filename.str());
360
361 return Filename.str();
Nick Lewycky269687f2011-05-04 04:03:04 +0000362}
363
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000364bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000365 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000366 Ctx = &M.getContext();
367
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000368 if (EmitNotes) emitGCNO();
369 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000370 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000371}
372
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000373void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000374 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000375 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000376
Nick Lewyckybba40db2011-11-27 23:22:20 +0000377 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
378 // Each compile unit gets its own .gcno file. This means that whether we run
379 // this pass over the original .o's as they're produced, or run it after
380 // LTO, we'll generate the same .gcno files.
381
382 DICompileUnit CU(CU_Nodes->getOperand(i));
383 std::string ErrorInfo;
384 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
385 raw_fd_ostream::F_Binary);
386 if (!Use402Format)
387 out.write("oncg*404MVLL", 12);
388 else
389 out.write("oncg*204MVLL", 12);
390
391 DIArray SPs = CU.getSubprograms();
392 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
393 DISubprogram SP(SPs.getElement(i));
394 if (!SP.Verify()) continue;
395
396 Function *F = SP.getFunction();
397 if (!F) continue;
398 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
399
400 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
401 GCOVBlock &Block = Func.getBlock(BB);
402 TerminatorInst *TI = BB->getTerminator();
403 if (int successors = TI->getNumSuccessors()) {
404 for (int i = 0; i != successors; ++i) {
405 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
406 }
407 } else if (isa<ReturnInst>(TI)) {
408 Block.addEdge(Func.getReturnBlock());
409 }
410
411 uint32_t Line = 0;
412 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
413 I != IE; ++I) {
414 const DebugLoc &Loc = I->getDebugLoc();
415 if (Loc.isUnknown()) continue;
416 if (Line == Loc.getLine()) continue;
417 Line = Loc.getLine();
418 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
419
420 GCOVLines &Lines = Block.getFile(SP.getFilename());
421 Lines.addLine(Loc.getLine());
422 }
423 }
424 Func.writeOut();
425 }
426 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
427 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000428 }
429}
430
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000431bool GCOVProfiler::emitProfileArcs() {
432 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
433 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000434
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000435 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000436 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000437 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
438 DICompileUnit CU(CU_Nodes->getOperand(i));
439 DIArray SPs = CU.getSubprograms();
440 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
441 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
442 DISubprogram SP(SPs.getElement(i));
443 if (!SP.Verify()) continue;
444 Function *F = SP.getFunction();
445 if (!F) continue;
446 if (!Result) Result = true;
447 unsigned Edges = 0;
448 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
449 TerminatorInst *TI = BB->getTerminator();
450 if (isa<ReturnInst>(TI))
451 ++Edges;
452 else
453 Edges += TI->getNumSuccessors();
454 }
455
456 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000457 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000458 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000459 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000460 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000461 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000462 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000463 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
464
465 UniqueVector<BasicBlock *> ComplexEdgePreds;
466 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
467
468 unsigned Edge = 0;
469 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
470 TerminatorInst *TI = BB->getTerminator();
471 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
472 if (Successors) {
473 IRBuilder<> Builder(TI);
474
475 if (Successors == 1) {
476 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
477 Edge);
478 Value *Count = Builder.CreateLoad(Counter);
479 Count = Builder.CreateAdd(Count,
480 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
481 Builder.CreateStore(Count, Counter);
482 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
483 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000484 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000485 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
486 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000487 SmallVector<Value *, 2> Idx;
488 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
489 Idx.push_back(Sel);
490 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
491 Value *Count = Builder.CreateLoad(Counter);
492 Count = Builder.CreateAdd(Count,
493 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
494 Builder.CreateStore(Count, Counter);
495 } else {
496 ComplexEdgePreds.insert(BB);
497 for (int i = 0; i != Successors; ++i)
498 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
499 }
500 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000501 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000502 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000503
504 if (!ComplexEdgePreds.empty()) {
505 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000506 buildEdgeLookupTable(F, Counters,
507 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000508 GlobalVariable *EdgeState = getEdgeStateValue();
509
510 Type *Int32Ty = Type::getInt32Ty(*Ctx);
511 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
512 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
513 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
514 }
515 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
516 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000517 BasicBlock::iterator InsertPt =
518 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000519 IRBuilder<> Builder(InsertPt);
520 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000521 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
522 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000523
524 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000525 InsertIndCounterIncrCode = true;
526 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
527 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000528 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000529 }
530 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000531
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000532 insertCounterWriteout(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000533 }
Bill Wendling77b19132012-05-28 06:10:56 +0000534
535 if (InsertIndCounterIncrCode)
536 insertIndirectCounterIncrement();
537
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000538 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000539}
540
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000541// All edges with successors that aren't branches are "complex", because it
542// requires complex logic to pick which counter to update.
543GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
544 Function *F,
545 GlobalVariable *Counters,
546 const UniqueVector<BasicBlock *> &Preds,
547 const UniqueVector<BasicBlock *> &Succs) {
548 // TODO: support invoke, threads. We rely on the fact that nothing can modify
549 // the whole-Module pred edge# between the time we set it and the time we next
550 // read it. Threads and invoke make this untrue.
551
552 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000553 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
554 ArrayType *EdgeTableTy = ArrayType::get(
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000555 Int64PtrTy, Succs.size() * Preds.size());
556
557 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
558 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
559 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
560 EdgeTable[i] = NullValue;
561
562 unsigned Edge = 0;
563 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
564 TerminatorInst *TI = BB->getTerminator();
565 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000566 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000567 for (int i = 0; i != Successors; ++i) {
568 BasicBlock *Succ = TI->getSuccessor(i);
569 IRBuilder<> builder(Succ);
570 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
571 Edge + i);
572 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
573 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
574 }
575 }
576 Edge += Successors;
577 }
578
Jay Foad26701082011-06-22 09:24:39 +0000579 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000580 GlobalVariable *EdgeTableGV =
581 new GlobalVariable(
582 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000583 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000584 "__llvm_gcda_edge_table");
585 EdgeTableGV->setUnnamedAddr(true);
586 return EdgeTableGV;
587}
588
Nick Lewyckyb1928702011-04-16 01:20:23 +0000589Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000590 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000591 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000592 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
593}
594
Bill Wendling77b19132012-05-28 06:10:56 +0000595Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
596 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000597 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000598 Type *Args[] = {
599 Int32Ty->getPointerTo(), // uint32_t *predecessor
600 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
601 };
602 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
603 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000604}
605
606Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000607 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000608 Type::getInt32Ty(*Ctx), // uint32_t ident
609 Type::getInt8PtrTy(*Ctx), // const char *function_name
610 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000611 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000612 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000613}
614
615Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000616 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000617 Type::getInt32Ty(*Ctx), // uint32_t num_counters
618 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
619 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000620 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000621 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000622 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000623}
624
625Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000626 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000627 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000628}
629
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000630GlobalVariable *GCOVProfiler::getEdgeStateValue() {
631 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
632 if (!GV) {
633 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
634 GlobalValue::InternalLinkage,
635 ConstantInt::get(Type::getInt32Ty(*Ctx),
636 0xffffffff),
637 "__llvm_gcov_global_state_pred");
638 GV->setUnnamedAddr(true);
639 }
640 return GV;
641}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000642
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000643void GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000644 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000645 FunctionType *WriteoutFTy =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000646 FunctionType::get(Type::getVoidTy(*Ctx), false);
647 Function *WriteoutF = Function::Create(WriteoutFTy,
648 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000649 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000650 WriteoutF->setUnnamedAddr(true);
651 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000652 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000653
654 Constant *StartFile = getStartFileFunc();
655 Constant *EmitFunction = getEmitFunctionFunc();
656 Constant *EmitArcs = getEmitArcsFunc();
657 Constant *EndFile = getEndFileFunc();
658
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000659 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
660 if (CU_Nodes) {
661 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
662 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
663 std::string FilenameGcda = mangleName(compile_unit, "gcda");
664 Builder.CreateCall(StartFile,
665 Builder.CreateGlobalStringPtr(FilenameGcda));
Bill Wendling21b742f2012-08-29 18:45:41 +0000666 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000667 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000668 I != E; ++I) {
669 DISubprogram SP(I->second);
670 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
671 Builder.CreateCall2(EmitFunction,
672 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
673 Builder.CreateGlobalStringPtr(SP.getName()));
674
675 GlobalVariable *GV = I->first;
676 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000677 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000678 Builder.CreateCall2(EmitArcs,
679 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
680 Builder.CreateConstGEP2_64(GV, 0, 0));
681 }
682 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000683 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000684 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000685 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000686
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000687 // Create a small bit of code that registers the "__llvm_gcov_writeout"
688 // function to be executed at exit.
689 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
690 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
691 "__llvm_gcov_init", M);
692 F->setUnnamedAddr(true);
693 F->setLinkage(GlobalValue::InternalLinkage);
694 F->addFnAttr(Attribute::NoInline);
695
696 BB = BasicBlock::Create(*Ctx, "entry", F);
697 Builder.SetInsertPoint(BB);
698
699 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
700 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000701 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000702 Builder.CreateCall(AtExitFn, WriteoutF);
703 Builder.CreateRetVoid();
704
705 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000706}
Bill Wendling77b19132012-05-28 06:10:56 +0000707
708void GCOVProfiler::insertIndirectCounterIncrement() {
709 Function *Fn =
710 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
711 Fn->setUnnamedAddr(true);
712 Fn->setLinkage(GlobalValue::InternalLinkage);
713 Fn->addFnAttr(Attribute::NoInline);
714
715 Type *Int32Ty = Type::getInt32Ty(*Ctx);
716 Type *Int64Ty = Type::getInt64Ty(*Ctx);
717 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
718
719 // Create basic blocks for function.
720 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
721 IRBuilder<> Builder(BB);
722
723 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
724 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
725 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
726
727 // uint32_t pred = *predecessor;
728 // if (pred == 0xffffffff) return;
729 Argument *Arg = Fn->arg_begin();
730 Arg->setName("predecessor");
731 Value *Pred = Builder.CreateLoad(Arg, "pred");
732 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
733 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
734
735 Builder.SetInsertPoint(PredNotNegOne);
736
737 // uint64_t *counter = counters[pred];
738 // if (!counter) return;
739 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
740 Arg = llvm::next(Fn->arg_begin());
741 Arg->setName("counters");
742 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
743 Value *Counter = Builder.CreateLoad(GEP, "counter");
744 Cond = Builder.CreateICmpEQ(Counter,
745 Constant::getNullValue(Int64Ty->getPointerTo()));
746 Builder.CreateCondBr(Cond, Exit, CounterEnd);
747
748 // ++*counter;
749 Builder.SetInsertPoint(CounterEnd);
750 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
751 ConstantInt::get(Int64Ty, 1));
752 Builder.CreateStore(Add, Counter);
753 Builder.CreateBr(Exit);
754
755 // Fill in the exit block.
756 Builder.SetInsertPoint(Exit);
757 Builder.CreateRetVoid();
758}