blob: 1b0cc00bce40341427c77e21ecfb0c15fc3ccca6 [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()
Nick Lewyckybba40db2011-11-27 23:22:20 +000046 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
47 UseExtraChecksum(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000048 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49 }
Nick Lewyckybba40db2011-11-27 23:22:20 +000050 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
51 bool useExtraChecksum = false)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000052 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Nick Lewyckybba40db2011-11-27 23:22:20 +000053 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000054 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000055 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
56 }
57 virtual const char *getPassName() const {
58 return "GCOV Profiler";
59 }
60
61 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 Wendlingc7a88402012-05-25 23:55:00 +000073 void incrementIndirectCounter(IRBuilder<> &Builder, BasicBlock *Exit,
74 GlobalVariable *EdgeState,
75 Value *CounterPtrArray);
Nick Lewyckyb1928702011-04-16 01:20:23 +000076 Constant *getEmitFunctionFunc();
77 Constant *getEmitArcsFunc();
78 Constant *getEndFileFunc();
79
Nick Lewycky1790c9c2011-04-26 03:54:16 +000080 // Create or retrieve an i32 state value that is used to represent the
81 // pred block number for certain non-trivial edges.
82 GlobalVariable *getEdgeStateValue();
83
84 // Produce a table of pointers to counters, by predecessor and successor
85 // block number.
86 GlobalVariable *buildEdgeLookupTable(Function *F,
87 GlobalVariable *Counter,
88 const UniqueVector<BasicBlock *> &Preds,
89 const UniqueVector<BasicBlock *> &Succs);
90
Nick Lewyckyb1928702011-04-16 01:20:23 +000091 // Add the function to write out all our counters to the global destructor
92 // list.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000093 void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
Nick Lewycky5409a182011-05-05 02:46:38 +000094 MDNode *>, 8> &);
Nick Lewyckyb1928702011-04-16 01:20:23 +000095
Nick Lewycky269687f2011-05-04 04:03:04 +000096 std::string mangleName(DICompileUnit CU, std::string NewStem);
97
Nick Lewyckya61e52c2011-04-21 01:56:25 +000098 bool EmitNotes;
99 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000100 bool Use402Format;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000101 bool UseExtraChecksum;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000102
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000103 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000104 LLVMContext *Ctx;
105 };
106}
107
108char GCOVProfiler::ID = 0;
109INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
110 "Insert instrumentation for GCOV profiling", false, false)
111
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000112ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
Nick Lewycky7c067412011-12-06 00:29:13 +0000113 bool Use402Format,
114 bool UseExtraChecksum) {
115 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000116}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000117
Nick Lewyckyb1928702011-04-16 01:20:23 +0000118namespace {
119 class GCOVRecord {
120 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000121 static const char *LinesTag;
122 static const char *FunctionTag;
123 static const char *BlockTag;
124 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000125
126 GCOVRecord() {}
127
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000128 void writeBytes(const char *Bytes, int Size) {
129 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000130 }
131
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000132 void write(uint32_t i) {
133 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000134 }
135
136 // Returns the length measured in 4-byte blocks that will be used to
137 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000138 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000139 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000140 // padding out to the next 4-byte word. The length is measured in 4-byte
141 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000142 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143 }
144
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000145 void writeGCOVString(StringRef s) {
146 uint32_t Len = lengthOfGCOVString(s);
147 write(Len);
148 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000149
150 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000151 assert((unsigned)(4 - (s.size() % 4)) > 0);
152 assert((unsigned)(4 - (s.size() % 4)) <= 4);
153 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000154 }
155
156 raw_ostream *os;
157 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000158 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
159 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
160 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
161 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000162
163 class GCOVFunction;
164 class GCOVBlock;
165
166 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000167 // list of line numbers and a single filename, representing lines that belong
168 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000169 class GCOVLines : public GCOVRecord {
170 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000171 void addLine(uint32_t Line) {
172 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000173 }
174
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000175 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000176 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000177 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000178 }
179
Devang Patel16c19a12011-09-20 18:35:00 +0000180 void writeOut() {
181 write(0);
182 writeGCOVString(Filename);
183 for (int i = 0, e = Lines.size(); i != e; ++i)
184 write(Lines[i]);
185 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000186
Devang Patel16c19a12011-09-20 18:35:00 +0000187 GCOVLines(StringRef F, raw_ostream *os)
188 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000189 this->os = os;
190 }
191
Devang Patel680018f2011-09-20 18:48:56 +0000192 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000193 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000194 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000195 };
196
197 // Represent a basic block in GCOV. Each block has a unique number in the
198 // function, number of lines belonging to each block, and a set of edges to
199 // other blocks.
200 class GCOVBlock : public GCOVRecord {
201 public:
Devang Patel68155d32011-09-20 17:55:19 +0000202 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000203 GCOVLines *&Lines = LinesByFile[Filename];
204 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000205 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000206 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000207 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000208 }
209
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000210 void addEdge(GCOVBlock &Successor) {
211 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000212 }
213
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000214 void writeOut() {
215 uint32_t Len = 3;
216 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
217 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000218 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000219 }
220
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000221 writeBytes(LinesTag, 4);
222 write(Len);
223 write(Number);
224 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000225 E = LinesByFile.end(); I != E; ++I)
226 I->second->writeOut();
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:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000253 GCOVFunction(DISubprogram SP, raw_ostream *os,
254 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000255 this->os = os;
256
257 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000258 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000259 uint32_t i = 0;
260 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000261 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000262 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000263 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000264
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000265 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000266 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000267 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000268 if (UseExtraChecksum)
269 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000270 write(BlockLen);
271 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
272 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000273 write(0); // lineno checksum
274 if (UseExtraChecksum)
275 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000276 writeGCOVString(SP.getName());
277 writeGCOVString(SP.getFilename());
278 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000279 }
280
281 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000282 DeleteContainerSeconds(Blocks);
283 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000284 }
285
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000286 GCOVBlock &getBlock(BasicBlock *BB) {
287 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000288 }
289
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 GCOVBlock &getReturnBlock() {
291 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000292 }
293
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000295 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000296 writeBytes(BlockTag, 4);
297 write(Blocks.size() + 1);
298 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
299 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000300 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000301 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000302
303 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000304 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
305 E = Blocks.end(); I != E; ++I) {
306 GCOVBlock &Block = *I->second;
307 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000308
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000309 writeBytes(EdgeTag, 4);
310 write(Block.OutEdges.size() * 2 + 1);
311 write(Block.Number);
312 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000313 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
314 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000315 write(Block.OutEdges[i]->Number);
316 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000317 }
318 }
319
320 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000321 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
322 E = Blocks.end(); I != E; ++I) {
323 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000324 }
325 }
326
327 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000328 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
329 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000330 };
331}
332
Nick Lewycky269687f2011-05-04 04:03:04 +0000333std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
334 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
335 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
336 MDNode *N = GCov->getOperand(i);
337 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000338 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000339 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000340 if (!GCovFile || !CompileUnit) continue;
341 if (CompileUnit == CU) {
342 SmallString<128> Filename = GCovFile->getString();
343 sys::path::replace_extension(Filename, NewStem);
344 return Filename.str();
345 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000346 }
347 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000348
349 SmallString<128> Filename = CU.getFilename();
350 sys::path::replace_extension(Filename, NewStem);
351 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000352}
353
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000354bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000355 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000356 Ctx = &M.getContext();
357
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000358 if (EmitNotes) emitGCNO();
359 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000360 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000361}
362
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000363void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000364 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000365 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000366
Nick Lewyckybba40db2011-11-27 23:22:20 +0000367 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
368 // Each compile unit gets its own .gcno file. This means that whether we run
369 // this pass over the original .o's as they're produced, or run it after
370 // LTO, we'll generate the same .gcno files.
371
372 DICompileUnit CU(CU_Nodes->getOperand(i));
373 std::string ErrorInfo;
374 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
375 raw_fd_ostream::F_Binary);
376 if (!Use402Format)
377 out.write("oncg*404MVLL", 12);
378 else
379 out.write("oncg*204MVLL", 12);
380
381 DIArray SPs = CU.getSubprograms();
382 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
383 DISubprogram SP(SPs.getElement(i));
384 if (!SP.Verify()) continue;
385
386 Function *F = SP.getFunction();
387 if (!F) continue;
388 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
389
390 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
391 GCOVBlock &Block = Func.getBlock(BB);
392 TerminatorInst *TI = BB->getTerminator();
393 if (int successors = TI->getNumSuccessors()) {
394 for (int i = 0; i != successors; ++i) {
395 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
396 }
397 } else if (isa<ReturnInst>(TI)) {
398 Block.addEdge(Func.getReturnBlock());
399 }
400
401 uint32_t Line = 0;
402 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
403 I != IE; ++I) {
404 const DebugLoc &Loc = I->getDebugLoc();
405 if (Loc.isUnknown()) continue;
406 if (Line == Loc.getLine()) continue;
407 Line = Loc.getLine();
408 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
409
410 GCOVLines &Lines = Block.getFile(SP.getFilename());
411 Lines.addLine(Loc.getLine());
412 }
413 }
414 Func.writeOut();
415 }
416 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
417 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000418 }
419}
420
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000421bool GCOVProfiler::emitProfileArcs() {
422 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
423 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000424
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000425 bool Result = false;
426 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
427 DICompileUnit CU(CU_Nodes->getOperand(i));
428 DIArray SPs = CU.getSubprograms();
429 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
430 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
431 DISubprogram SP(SPs.getElement(i));
432 if (!SP.Verify()) continue;
433 Function *F = SP.getFunction();
434 if (!F) continue;
435 if (!Result) Result = true;
436 unsigned Edges = 0;
437 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
438 TerminatorInst *TI = BB->getTerminator();
439 if (isa<ReturnInst>(TI))
440 ++Edges;
441 else
442 Edges += TI->getNumSuccessors();
443 }
444
445 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000446 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000447 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000448 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000449 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000450 Constant::getNullValue(CounterTy),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000451 "__llvm_gcov_ctr", 0, false, 0);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000452 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
453
454 UniqueVector<BasicBlock *> ComplexEdgePreds;
455 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
456
457 unsigned Edge = 0;
458 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
459 TerminatorInst *TI = BB->getTerminator();
460 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
461 if (Successors) {
462 IRBuilder<> Builder(TI);
463
464 if (Successors == 1) {
465 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
466 Edge);
467 Value *Count = Builder.CreateLoad(Counter);
468 Count = Builder.CreateAdd(Count,
469 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
470 Builder.CreateStore(Count, Counter);
471 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
472 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000473 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000474 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
475 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000476 SmallVector<Value *, 2> Idx;
477 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
478 Idx.push_back(Sel);
479 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
480 Value *Count = Builder.CreateLoad(Counter);
481 Count = Builder.CreateAdd(Count,
482 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
483 Builder.CreateStore(Count, Counter);
484 } else {
485 ComplexEdgePreds.insert(BB);
486 for (int i = 0; i != Successors; ++i)
487 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
488 }
489 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000490 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000491 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000492
493 if (!ComplexEdgePreds.empty()) {
494 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000495 buildEdgeLookupTable(F, Counters,
496 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000497 GlobalVariable *EdgeState = getEdgeStateValue();
498
499 Type *Int32Ty = Type::getInt32Ty(*Ctx);
500 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
501 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
502 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
503 }
504 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
505 // call runtime to perform increment
Bill Wendlingc7a88402012-05-25 23:55:00 +0000506 BasicBlock *BB = ComplexEdgeSuccs[i+1];
507 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
508 BasicBlock *Split = BB->splitBasicBlock(InsertPt);
509 InsertPt = BB->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000510 IRBuilder<> Builder(InsertPt);
511 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000512 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
513 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000514
515 // Build code to increment the counter.
516 incrementIndirectCounter(Builder, Split, EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000517 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000518 }
519 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000520 insertCounterWriteout(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000521 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000522 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000523}
524
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000525// All edges with successors that aren't branches are "complex", because it
526// requires complex logic to pick which counter to update.
527GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
528 Function *F,
529 GlobalVariable *Counters,
530 const UniqueVector<BasicBlock *> &Preds,
531 const UniqueVector<BasicBlock *> &Succs) {
532 // TODO: support invoke, threads. We rely on the fact that nothing can modify
533 // the whole-Module pred edge# between the time we set it and the time we next
534 // read it. Threads and invoke make this untrue.
535
536 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000537 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
538 ArrayType *EdgeTableTy = ArrayType::get(
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000539 Int64PtrTy, Succs.size() * Preds.size());
540
541 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
542 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
543 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
544 EdgeTable[i] = NullValue;
545
546 unsigned Edge = 0;
547 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
548 TerminatorInst *TI = BB->getTerminator();
549 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000550 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000551 for (int i = 0; i != Successors; ++i) {
552 BasicBlock *Succ = TI->getSuccessor(i);
553 IRBuilder<> builder(Succ);
554 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
555 Edge + i);
556 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
557 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
558 }
559 }
560 Edge += Successors;
561 }
562
Jay Foad26701082011-06-22 09:24:39 +0000563 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000564 GlobalVariable *EdgeTableGV =
565 new GlobalVariable(
566 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000567 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000568 "__llvm_gcda_edge_table");
569 EdgeTableGV->setUnnamedAddr(true);
570 return EdgeTableGV;
571}
572
Nick Lewyckyb1928702011-04-16 01:20:23 +0000573Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000574 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000575 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000576 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
577}
578
Bill Wendlingc7a88402012-05-25 23:55:00 +0000579/// incrementIndirectCounter - Emit code that increments the indirect
580/// counter. The code is meant to copy the llvm_gcda_increment_indirect_counter
581/// function, but because it's inlined into the function, we don't have to worry
582/// about the runtime library possibly writing into a protected area.
583void GCOVProfiler::incrementIndirectCounter(IRBuilder<> &Builder,
584 BasicBlock *Exit,
585 GlobalVariable *EdgeState,
586 Value *CounterPtrArray) {
587 Type *Int64Ty = Type::getInt64Ty(*Ctx);
588 ConstantInt *NegOne = ConstantInt::get(Type::getInt32Ty(*Ctx), 0xffffffff);
589
590 // Create exiting blocks.
591 BasicBlock *InsBB = Builder.GetInsertBlock();
592 Function *Fn = InsBB->getParent();
593 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn, Exit);
594 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn, Exit);
595
596 // uint32_t pred = *EdgeState;
597 // if (pred == 0xffffffff) return;
598 Value *Pred = Builder.CreateLoad(EdgeState, "predecessor");
599 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
600 InsBB->getTerminator()->eraseFromParent();
601 BranchInst::Create(Exit, PredNotNegOne, Cond, InsBB);
602
603 Builder.SetInsertPoint(PredNotNegOne);
604
605 // uint64_t *counter = CounterPtrArray[pred];
606 // if (!counter) return;
607 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
608 Value *GEP = Builder.CreateGEP(CounterPtrArray, ZExtPred);
609 Value *Counter = Builder.CreateLoad(GEP, "counter");
610 Cond = Builder.CreateICmpEQ(Counter,
611 Constant::getNullValue(Type::getInt64PtrTy(*Ctx, 0)));
612 Builder.CreateCondBr(Cond, Exit, CounterEnd);
613
614 Builder.SetInsertPoint(CounterEnd);
615
616 // ++*counter;
617 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
618 ConstantInt::get(Int64Ty, 1));
619 Builder.CreateStore(Add, Counter);
620 Builder.CreateBr(Exit);
621
622 // Clear the predecessor number
623 Builder.SetInsertPoint(Exit->getFirstInsertionPt());
624 Builder.CreateStore(NegOne, EdgeState);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000625}
626
627Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000628 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000629 Type::getInt32Ty(*Ctx), // uint32_t ident
630 Type::getInt8PtrTy(*Ctx), // const char *function_name
631 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000632 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000633 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000634}
635
636Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000637 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000638 Type::getInt32Ty(*Ctx), // uint32_t num_counters
639 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
640 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000641 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000642 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000643 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000644}
645
646Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000647 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000648 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000649}
650
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000651GlobalVariable *GCOVProfiler::getEdgeStateValue() {
652 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
653 if (!GV) {
654 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
655 GlobalValue::InternalLinkage,
656 ConstantInt::get(Type::getInt32Ty(*Ctx),
657 0xffffffff),
658 "__llvm_gcov_global_state_pred");
659 GV->setUnnamedAddr(true);
660 }
661 return GV;
662}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000663
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000664void GCOVProfiler::insertCounterWriteout(
Nick Lewycky5409a182011-05-05 02:46:38 +0000665 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 FunctionType *WriteoutFTy =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000667 FunctionType::get(Type::getVoidTy(*Ctx), false);
668 Function *WriteoutF = Function::Create(WriteoutFTy,
669 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000670 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000671 WriteoutF->setUnnamedAddr(true);
672 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000673 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000674
675 Constant *StartFile = getStartFileFunc();
676 Constant *EmitFunction = getEmitFunctionFunc();
677 Constant *EmitArcs = getEmitArcsFunc();
678 Constant *EndFile = getEndFileFunc();
679
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000680 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
681 if (CU_Nodes) {
682 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
683 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
684 std::string FilenameGcda = mangleName(compile_unit, "gcda");
685 Builder.CreateCall(StartFile,
686 Builder.CreateGlobalStringPtr(FilenameGcda));
687 for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000688 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000689 I != E; ++I) {
690 DISubprogram SP(I->second);
691 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
692 Builder.CreateCall2(EmitFunction,
693 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
694 Builder.CreateGlobalStringPtr(SP.getName()));
695
696 GlobalVariable *GV = I->first;
697 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000698 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000699 Builder.CreateCall2(EmitArcs,
700 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
701 Builder.CreateConstGEP2_64(GV, 0, 0));
702 }
703 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000704 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000705 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000706 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000707
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000708 InsertProfilingShutdownCall(WriteoutF, M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000709}