blob: 197a329feb7f0d7c035ba1e68103eeff6b70d70f [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"
Bill Wendling253353c2012-09-13 00:09:55 +000037#include "llvm/Target/TargetData.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000038#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000039#include <string>
40#include <utility>
41using namespace llvm;
42
43namespace {
44 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000045 public:
46 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000047 GCOVProfiler()
Nick Lewyckybba40db2011-11-27 23:22:20 +000048 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
49 UseExtraChecksum(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000050 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
51 }
Nick Lewyckybba40db2011-11-27 23:22:20 +000052 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
53 bool useExtraChecksum = false)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000054 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Nick Lewyckybba40db2011-11-27 23:22:20 +000055 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000056 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000057 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
58 }
59 virtual const char *getPassName() const {
60 return "GCOV Profiler";
61 }
Nick Lewyckyb1928702011-04-16 01:20:23 +000062 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000063 bool runOnModule(Module &M);
64
Nick Lewyckyb1928702011-04-16 01:20:23 +000065 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000066 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000067
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000068 // Modify the program to track transitions along edges and call into the
69 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000070 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000071
Nick Lewyckyb1928702011-04-16 01:20:23 +000072 // Get pointers to the functions in the runtime library.
73 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +000074 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000075 Constant *getEmitFunctionFunc();
76 Constant *getEmitArcsFunc();
77 Constant *getEndFileFunc();
78
Nick Lewycky1790c9c2011-04-26 03:54:16 +000079 // Create or retrieve an i32 state value that is used to represent the
80 // pred block number for certain non-trivial edges.
81 GlobalVariable *getEdgeStateValue();
82
83 // Produce a table of pointers to counters, by predecessor and successor
84 // block number.
85 GlobalVariable *buildEdgeLookupTable(Function *F,
86 GlobalVariable *Counter,
87 const UniqueVector<BasicBlock *> &Preds,
88 const UniqueVector<BasicBlock *> &Succs);
89
Nick Lewyckyb1928702011-04-16 01:20:23 +000090 // Add the function to write out all our counters to the global destructor
91 // list.
Bill Wendling21b742f2012-08-29 18:45:41 +000092 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +000093 void insertIndirectCounterIncrement();
Bill Wendling253353c2012-09-13 00:09:55 +000094 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Nick Lewyckyb1928702011-04-16 01:20:23 +000095
Bill Wendling73996f42012-08-30 01:32:31 +000096 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +000097
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;
Bill Wendling253353c2012-09-13 00:09:55 +0000105 const TargetData *TD;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000106 };
107}
108
109char GCOVProfiler::ID = 0;
110INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
111 "Insert instrumentation for GCOV profiling", false, false)
112
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000113ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
Nick Lewycky7c067412011-12-06 00:29:13 +0000114 bool Use402Format,
115 bool UseExtraChecksum) {
116 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000117}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000118
Nick Lewyckyb1928702011-04-16 01:20:23 +0000119namespace {
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 Lewyckyd363ff32011-05-05 23:52:18 +0000143 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000144 }
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
Devang Patel16c19a12011-09-20 18:35:00 +0000168 // list of line numbers and a single filename, representing lines that belong
169 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000170 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() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000177 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000178 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000179 }
180
Devang Patel16c19a12011-09-20 18:35:00 +0000181 void writeOut() {
182 write(0);
183 writeGCOVString(Filename);
184 for (int i = 0, e = Lines.size(); i != e; ++i)
185 write(Lines[i]);
186 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000187
Devang Patel16c19a12011-09-20 18:35:00 +0000188 GCOVLines(StringRef F, raw_ostream *os)
189 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000190 this->os = os;
191 }
192
Devang Patel680018f2011-09-20 18:48:56 +0000193 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000194 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000195 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000196 };
197
198 // Represent a basic block in GCOV. Each block has a unique number in the
199 // function, number of lines belonging to each block, and a set of edges to
200 // other blocks.
201 class GCOVBlock : public GCOVRecord {
202 public:
Devang Patel68155d32011-09-20 17:55:19 +0000203 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000204 GCOVLines *&Lines = LinesByFile[Filename];
205 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000206 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000207 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000208 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000209 }
210
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000211 void addEdge(GCOVBlock &Successor) {
212 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000213 }
214
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000215 void writeOut() {
216 uint32_t Len = 3;
217 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
218 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000219 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000220 }
221
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000222 writeBytes(LinesTag, 4);
223 write(Len);
224 write(Number);
225 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000226 E = LinesByFile.end(); I != E; ++I)
227 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000228 write(0);
229 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000230 }
231
232 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000233 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000234 }
235
236 private:
237 friend class GCOVFunction;
238
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000239 GCOVBlock(uint32_t Number, raw_ostream *os)
240 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000241 this->os = os;
242 }
243
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000244 uint32_t Number;
245 StringMap<GCOVLines *> LinesByFile;
246 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000247 };
248
249 // A function has a unique identifier, a checksum (we leave as zero) and a
250 // set of blocks and a map of edges between blocks. This is the only GCOV
251 // object users can construct, the blocks and lines will be rooted here.
252 class GCOVFunction : public GCOVRecord {
253 public:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000254 GCOVFunction(DISubprogram SP, raw_ostream *os,
255 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000256 this->os = os;
257
258 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000259 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000260 uint32_t i = 0;
261 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000262 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000263 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000264 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000265
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000266 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000267 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000269 if (UseExtraChecksum)
270 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000271 write(BlockLen);
272 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
273 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000274 write(0); // lineno checksum
275 if (UseExtraChecksum)
276 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000277 writeGCOVString(SP.getName());
278 writeGCOVString(SP.getFilename());
279 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000280 }
281
282 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000283 DeleteContainerSeconds(Blocks);
284 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000285 }
286
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000287 GCOVBlock &getBlock(BasicBlock *BB) {
288 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000289 }
290
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000291 GCOVBlock &getReturnBlock() {
292 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000293 }
294
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000295 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000296 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000297 writeBytes(BlockTag, 4);
298 write(Blocks.size() + 1);
299 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
300 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000301 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000302 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000303
304 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000305 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
306 E = Blocks.end(); I != E; ++I) {
307 GCOVBlock &Block = *I->second;
308 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000309
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000310 writeBytes(EdgeTag, 4);
311 write(Block.OutEdges.size() * 2 + 1);
312 write(Block.Number);
313 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000314 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
315 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 write(Block.OutEdges[i]->Number);
317 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000318 }
319 }
320
321 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000322 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
323 E = Blocks.end(); I != E; ++I) {
324 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000325 }
326 }
327
328 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000329 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
330 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000331 };
332}
333
Bill Wendling73996f42012-08-30 01:32:31 +0000334std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
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 Wendling6e5190c2012-08-30 00:34:21 +0000343 SmallString<128> Filename = GCovFile->getString();
344 sys::path::replace_extension(Filename, NewStem);
345 return Filename.str();
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 Wendling6e5190c2012-08-30 00:34:21 +0000350 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000351 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000352 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000353}
354
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000355bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000356 this->M = &M;
Bill Wendling253353c2012-09-13 00:09:55 +0000357 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000358 Ctx = &M.getContext();
359
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000360 if (EmitNotes) emitGCNO();
361 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000362 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000363}
364
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000365void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000366 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000367 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000368
Nick Lewyckybba40db2011-11-27 23:22:20 +0000369 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
370 // Each compile unit gets its own .gcno file. This means that whether we run
371 // this pass over the original .o's as they're produced, or run it after
372 // LTO, we'll generate the same .gcno files.
373
374 DICompileUnit CU(CU_Nodes->getOperand(i));
375 std::string ErrorInfo;
376 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
377 raw_fd_ostream::F_Binary);
378 if (!Use402Format)
379 out.write("oncg*404MVLL", 12);
380 else
381 out.write("oncg*204MVLL", 12);
382
383 DIArray SPs = CU.getSubprograms();
384 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
385 DISubprogram SP(SPs.getElement(i));
386 if (!SP.Verify()) continue;
387
388 Function *F = SP.getFunction();
389 if (!F) continue;
390 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
391
392 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
393 GCOVBlock &Block = Func.getBlock(BB);
394 TerminatorInst *TI = BB->getTerminator();
395 if (int successors = TI->getNumSuccessors()) {
396 for (int i = 0; i != successors; ++i) {
397 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
398 }
399 } else if (isa<ReturnInst>(TI)) {
400 Block.addEdge(Func.getReturnBlock());
401 }
402
403 uint32_t Line = 0;
404 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
405 I != IE; ++I) {
406 const DebugLoc &Loc = I->getDebugLoc();
407 if (Loc.isUnknown()) continue;
408 if (Line == Loc.getLine()) continue;
409 Line = Loc.getLine();
410 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
411
412 GCOVLines &Lines = Block.getFile(SP.getFilename());
413 Lines.addLine(Loc.getLine());
414 }
415 }
416 Func.writeOut();
417 }
418 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
419 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000420 }
421}
422
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000423bool GCOVProfiler::emitProfileArcs() {
424 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
425 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000426
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000427 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000428 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000429 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
430 DICompileUnit CU(CU_Nodes->getOperand(i));
431 DIArray SPs = CU.getSubprograms();
432 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
433 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
434 DISubprogram SP(SPs.getElement(i));
435 if (!SP.Verify()) continue;
436 Function *F = SP.getFunction();
437 if (!F) continue;
438 if (!Result) Result = true;
439 unsigned Edges = 0;
440 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
441 TerminatorInst *TI = BB->getTerminator();
442 if (isa<ReturnInst>(TI))
443 ++Edges;
444 else
445 Edges += TI->getNumSuccessors();
446 }
447
448 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000449 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000450 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000451 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000452 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000453 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000454 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000455 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
456
457 UniqueVector<BasicBlock *> ComplexEdgePreds;
458 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
459
460 unsigned Edge = 0;
461 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
462 TerminatorInst *TI = BB->getTerminator();
463 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
464 if (Successors) {
465 IRBuilder<> Builder(TI);
466
467 if (Successors == 1) {
468 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
469 Edge);
470 Value *Count = Builder.CreateLoad(Counter);
471 Count = Builder.CreateAdd(Count,
472 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
473 Builder.CreateStore(Count, Counter);
474 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
475 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000476 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000477 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
478 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000479 SmallVector<Value *, 2> Idx;
480 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
481 Idx.push_back(Sel);
482 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
483 Value *Count = Builder.CreateLoad(Counter);
484 Count = Builder.CreateAdd(Count,
485 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
486 Builder.CreateStore(Count, Counter);
487 } else {
488 ComplexEdgePreds.insert(BB);
489 for (int i = 0; i != Successors; ++i)
490 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
491 }
492 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000493 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000494 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000495
496 if (!ComplexEdgePreds.empty()) {
497 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000498 buildEdgeLookupTable(F, Counters,
499 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000500 GlobalVariable *EdgeState = getEdgeStateValue();
501
502 Type *Int32Ty = Type::getInt32Ty(*Ctx);
503 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
504 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
505 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
506 }
507 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
508 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000509 BasicBlock::iterator InsertPt =
510 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000511 IRBuilder<> Builder(InsertPt);
512 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000513 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
514 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000515
516 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000517 InsertIndCounterIncrCode = true;
518 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
519 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000520 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000521 }
522 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000523
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000524 insertCounterWriteout(CountersBySP);
Bill Wendling253353c2012-09-13 00:09:55 +0000525 insertFlush(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000526 }
Bill Wendling77b19132012-05-28 06:10:56 +0000527
528 if (InsertIndCounterIncrCode)
529 insertIndirectCounterIncrement();
530
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000531 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000532}
533
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000534// All edges with successors that aren't branches are "complex", because it
535// requires complex logic to pick which counter to update.
536GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
537 Function *F,
538 GlobalVariable *Counters,
539 const UniqueVector<BasicBlock *> &Preds,
540 const UniqueVector<BasicBlock *> &Succs) {
541 // TODO: support invoke, threads. We rely on the fact that nothing can modify
542 // the whole-Module pred edge# between the time we set it and the time we next
543 // read it. Threads and invoke make this untrue.
544
545 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000546 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
547 ArrayType *EdgeTableTy = ArrayType::get(
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000548 Int64PtrTy, Succs.size() * Preds.size());
549
550 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
551 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
552 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
553 EdgeTable[i] = NullValue;
554
555 unsigned Edge = 0;
556 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
557 TerminatorInst *TI = BB->getTerminator();
558 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000559 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000560 for (int i = 0; i != Successors; ++i) {
561 BasicBlock *Succ = TI->getSuccessor(i);
562 IRBuilder<> builder(Succ);
563 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
564 Edge + i);
565 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
566 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
567 }
568 }
569 Edge += Successors;
570 }
571
Jay Foad26701082011-06-22 09:24:39 +0000572 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000573 GlobalVariable *EdgeTableGV =
574 new GlobalVariable(
575 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000576 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000577 "__llvm_gcda_edge_table");
578 EdgeTableGV->setUnnamedAddr(true);
579 return EdgeTableGV;
580}
581
Nick Lewyckyb1928702011-04-16 01:20:23 +0000582Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000583 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000584 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000585 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
586}
587
Bill Wendling77b19132012-05-28 06:10:56 +0000588Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
589 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000590 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000591 Type *Args[] = {
592 Int32Ty->getPointerTo(), // uint32_t *predecessor
593 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
594 };
595 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
596 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000597}
598
599Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000600 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000601 Type::getInt32Ty(*Ctx), // uint32_t ident
602 Type::getInt8PtrTy(*Ctx), // const char *function_name
603 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000605 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000606}
607
608Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000609 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000610 Type::getInt32Ty(*Ctx), // uint32_t num_counters
611 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
612 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000613 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000614 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000615 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000616}
617
618Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000620 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000621}
622
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000623GlobalVariable *GCOVProfiler::getEdgeStateValue() {
624 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
625 if (!GV) {
626 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
627 GlobalValue::InternalLinkage,
628 ConstantInt::get(Type::getInt32Ty(*Ctx),
629 0xffffffff),
630 "__llvm_gcov_global_state_pred");
631 GV->setUnnamedAddr(true);
632 }
633 return GV;
634}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000635
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000636void GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000637 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000638 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
639 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
640 if (!WriteoutF)
641 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
642 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000643 WriteoutF->setUnnamedAddr(true);
Bill Wendling253353c2012-09-13 00:09:55 +0000644
645 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000646 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000647
648 Constant *StartFile = getStartFileFunc();
649 Constant *EmitFunction = getEmitFunctionFunc();
650 Constant *EmitArcs = getEmitArcsFunc();
651 Constant *EndFile = getEndFileFunc();
652
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000653 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
654 if (CU_Nodes) {
655 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
656 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
657 std::string FilenameGcda = mangleName(compile_unit, "gcda");
658 Builder.CreateCall(StartFile,
659 Builder.CreateGlobalStringPtr(FilenameGcda));
Bill Wendling21b742f2012-08-29 18:45:41 +0000660 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000661 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000662 I != E; ++I) {
663 DISubprogram SP(I->second);
664 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
665 Builder.CreateCall2(EmitFunction,
666 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
667 Builder.CreateGlobalStringPtr(SP.getName()));
668
669 GlobalVariable *GV = I->first;
670 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000671 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000672 Builder.CreateCall2(EmitArcs,
673 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
674 Builder.CreateConstGEP2_64(GV, 0, 0));
675 }
676 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000677 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000678 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000679 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000680
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000681 // Create a small bit of code that registers the "__llvm_gcov_writeout"
682 // function to be executed at exit.
683 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
685 "__llvm_gcov_init", M);
686 F->setUnnamedAddr(true);
687 F->setLinkage(GlobalValue::InternalLinkage);
688 F->addFnAttr(Attribute::NoInline);
689
690 BB = BasicBlock::Create(*Ctx, "entry", F);
691 Builder.SetInsertPoint(BB);
692
693 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
694 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000695 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000696 Builder.CreateCall(AtExitFn, WriteoutF);
697 Builder.CreateRetVoid();
698
699 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000700}
Bill Wendling77b19132012-05-28 06:10:56 +0000701
702void GCOVProfiler::insertIndirectCounterIncrement() {
703 Function *Fn =
704 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
705 Fn->setUnnamedAddr(true);
706 Fn->setLinkage(GlobalValue::InternalLinkage);
707 Fn->addFnAttr(Attribute::NoInline);
708
709 Type *Int32Ty = Type::getInt32Ty(*Ctx);
710 Type *Int64Ty = Type::getInt64Ty(*Ctx);
711 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
712
713 // Create basic blocks for function.
714 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
715 IRBuilder<> Builder(BB);
716
717 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
718 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
719 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
720
721 // uint32_t pred = *predecessor;
722 // if (pred == 0xffffffff) return;
723 Argument *Arg = Fn->arg_begin();
724 Arg->setName("predecessor");
725 Value *Pred = Builder.CreateLoad(Arg, "pred");
726 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
727 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
728
729 Builder.SetInsertPoint(PredNotNegOne);
730
731 // uint64_t *counter = counters[pred];
732 // if (!counter) return;
733 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
734 Arg = llvm::next(Fn->arg_begin());
735 Arg->setName("counters");
736 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
737 Value *Counter = Builder.CreateLoad(GEP, "counter");
738 Cond = Builder.CreateICmpEQ(Counter,
739 Constant::getNullValue(Int64Ty->getPointerTo()));
740 Builder.CreateCondBr(Cond, Exit, CounterEnd);
741
742 // ++*counter;
743 Builder.SetInsertPoint(CounterEnd);
744 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
745 ConstantInt::get(Int64Ty, 1));
746 Builder.CreateStore(Add, Counter);
747 Builder.CreateBr(Exit);
748
749 // Fill in the exit block.
750 Builder.SetInsertPoint(Exit);
751 Builder.CreateRetVoid();
752}
Bill Wendling253353c2012-09-13 00:09:55 +0000753
754void GCOVProfiler::
755insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
756 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
757 Function *FlushF = M->getFunction("__llvm_gcov_flush");
758 if (!FlushF)
759 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
760 "__llvm_gcov_flush", M);
761 else
762 FlushF->setLinkage(GlobalValue::InternalLinkage);
763 FlushF->setUnnamedAddr(true);
764
765 Type *Int8Ty = Type::getInt8Ty(*Ctx);
766 Type *Int64Ty = Type::getInt64Ty(*Ctx);
767 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
768
769 // Write out the current counters.
770 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
771 assert(WriteoutF && "Need to create the writeout function first!");
772
773 IRBuilder<> Builder(Entry);
774 Builder.CreateCall(WriteoutF);
775
776 if (TD)
777 // Zero out the counters.
778 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
779 I = CountersBySP.begin(), E = CountersBySP.end();
780 I != E; ++I) {
781 GlobalVariable *GV = I->first;
782 uint64_t NumBytes = TD->getTypeAllocSize(GV->getType()->getElementType());
783 Builder.CreateMemSet(Builder.CreateConstGEP2_64(GV, 0, 0),
784 ConstantInt::get(Int8Ty, 0),
785 ConstantInt::get(Int64Ty, NumBytes), false);
786 }
787
788 Type *RetTy = FlushF->getReturnType();
789 if (RetTy == Type::getVoidTy(*Ctx))
790 Builder.CreateRetVoid();
791 else if (RetTy->isIntegerTy())
792 // Used if __llvm_gcov_flush was implicitly declared.
793 Builder.CreateRet(ConstantInt::get(RetTy, 0));
794 else
795 report_fatal_error("invalid return type for __llvm_gcov_flush");
796}