blob: 5e064cd70d6e791fd2e85943d8d1463737196362 [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
Nick Lewyckyb1928702011-04-16 01:20:23 +000019#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "ProfilingUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000021#include "llvm/ADT/DenseMap.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000023#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/UniqueVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DebugInfo.h"
28#include "llvm/IRBuilder.h"
29#include "llvm/Instructions.h"
30#include "llvm/Module.h"
31#include "llvm/Pass.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),
Bill Wendling08e13e42012-12-10 19:46:49 +000048 UseExtraChecksum(false), NoRedZone(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,
Bill Wendling08e13e42012-12-10 19:46:49 +000052 bool useExtraChecksum = false, bool NoRedZone = 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();
Bill Wendling253353c2012-09-13 00:09:55 +000093 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Nick Lewyckyb1928702011-04-16 01:20:23 +000094
Bill Wendling73996f42012-08-30 01:32:31 +000095 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +000096
Nick Lewyckya61e52c2011-04-21 01:56:25 +000097 bool EmitNotes;
98 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +000099 bool Use402Format;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000100 bool UseExtraChecksum;
Bill Wendling08e13e42012-12-10 19:46:49 +0000101 bool NoRedZone;
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,
Bill Wendling08e13e42012-12-10 19:46:49 +0000114 bool UseExtraChecksum,
115 bool NoRedZone) {
116 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum,
117 NoRedZone);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000118}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000119
Nick Lewyckyb1928702011-04-16 01:20:23 +0000120namespace {
121 class GCOVRecord {
122 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000123 static const char *LinesTag;
124 static const char *FunctionTag;
125 static const char *BlockTag;
126 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000127
128 GCOVRecord() {}
129
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000130 void writeBytes(const char *Bytes, int Size) {
131 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000132 }
133
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000134 void write(uint32_t i) {
135 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000136 }
137
138 // Returns the length measured in 4-byte blocks that will be used to
139 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000140 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000141 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000142 // padding out to the next 4-byte word. The length is measured in 4-byte
143 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000144 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000145 }
146
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000147 void writeGCOVString(StringRef s) {
148 uint32_t Len = lengthOfGCOVString(s);
149 write(Len);
150 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000151
152 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000153 assert((unsigned)(4 - (s.size() % 4)) > 0);
154 assert((unsigned)(4 - (s.size() % 4)) <= 4);
155 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000156 }
157
158 raw_ostream *os;
159 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000160 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
161 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
162 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
163 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000164
165 class GCOVFunction;
166 class GCOVBlock;
167
168 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000169 // list of line numbers and a single filename, representing lines that belong
170 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000171 class GCOVLines : public GCOVRecord {
172 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000173 void addLine(uint32_t Line) {
174 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000175 }
176
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000177 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000178 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000179 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000180 }
181
Devang Patel16c19a12011-09-20 18:35:00 +0000182 void writeOut() {
183 write(0);
184 writeGCOVString(Filename);
185 for (int i = 0, e = Lines.size(); i != e; ++i)
186 write(Lines[i]);
187 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000188
Devang Patel16c19a12011-09-20 18:35:00 +0000189 GCOVLines(StringRef F, raw_ostream *os)
190 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000191 this->os = os;
192 }
193
Devang Patel680018f2011-09-20 18:48:56 +0000194 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000195 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000196 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000197 };
198
199 // Represent a basic block in GCOV. Each block has a unique number in the
200 // function, number of lines belonging to each block, and a set of edges to
201 // other blocks.
202 class GCOVBlock : public GCOVRecord {
203 public:
Devang Patel68155d32011-09-20 17:55:19 +0000204 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000205 GCOVLines *&Lines = LinesByFile[Filename];
206 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000207 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000208 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000209 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000210 }
211
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000212 void addEdge(GCOVBlock &Successor) {
213 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000214 }
215
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000216 void writeOut() {
217 uint32_t Len = 3;
218 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
219 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000220 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000221 }
222
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000223 writeBytes(LinesTag, 4);
224 write(Len);
225 write(Number);
226 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000227 E = LinesByFile.end(); I != E; ++I)
228 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000229 write(0);
230 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 }
232
233 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000234 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000235 }
236
237 private:
238 friend class GCOVFunction;
239
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000240 GCOVBlock(uint32_t Number, raw_ostream *os)
241 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000242 this->os = os;
243 }
244
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000245 uint32_t Number;
246 StringMap<GCOVLines *> LinesByFile;
247 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000248 };
249
250 // A function has a unique identifier, a checksum (we leave as zero) and a
251 // set of blocks and a map of edges between blocks. This is the only GCOV
252 // object users can construct, the blocks and lines will be rooted here.
253 class GCOVFunction : public GCOVRecord {
254 public:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000255 GCOVFunction(DISubprogram SP, raw_ostream *os,
256 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000257 this->os = os;
258
259 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000260 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000261 uint32_t i = 0;
262 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000263 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000264 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000265 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000266
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000267 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000268 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000269 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000270 if (UseExtraChecksum)
271 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000272 write(BlockLen);
273 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
274 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000275 write(0); // lineno checksum
276 if (UseExtraChecksum)
277 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000278 writeGCOVString(SP.getName());
279 writeGCOVString(SP.getFilename());
280 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000281 }
282
283 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 DeleteContainerSeconds(Blocks);
285 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000286 }
287
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000288 GCOVBlock &getBlock(BasicBlock *BB) {
289 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000290 }
291
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000292 GCOVBlock &getReturnBlock() {
293 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000294 }
295
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000296 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000297 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000298 writeBytes(BlockTag, 4);
299 write(Blocks.size() + 1);
300 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
301 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000302 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000303 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000304
305 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000306 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
307 E = Blocks.end(); I != E; ++I) {
308 GCOVBlock &Block = *I->second;
309 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000310
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000311 writeBytes(EdgeTag, 4);
312 write(Block.OutEdges.size() * 2 + 1);
313 write(Block.Number);
314 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000315 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
316 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000317 write(Block.OutEdges[i]->Number);
318 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000319 }
320 }
321
322 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000323 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
324 E = Blocks.end(); I != E; ++I) {
325 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000326 }
327 }
328
329 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000330 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
331 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000332 };
333}
334
Bill Wendling73996f42012-08-30 01:32:31 +0000335std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000336 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
337 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
338 MDNode *N = GCov->getOperand(i);
339 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000340 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000341 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000342 if (!GCovFile || !CompileUnit) continue;
343 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000344 SmallString<128> Filename = GCovFile->getString();
345 sys::path::replace_extension(Filename, NewStem);
346 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000347 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000348 }
349 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000350
Bill Wendling6e5190c2012-08-30 00:34:21 +0000351 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000352 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000353 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000354}
355
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000356bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000357 this->M = &M;
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*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000546 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000547 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000548 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000549
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000550 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000551 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000552 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000553 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
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000572 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
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[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000592 Int32Ty->getPointerTo(), // uint32_t *predecessor
593 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000594 };
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 Wendling08e13e42012-12-10 19:46:49 +0000644 WriteoutF->addFnAttr(Attributes::NoInline);
645 if (NoRedZone)
646 WriteoutF->addFnAttr(Attributes::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000647
648 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000649 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000650
651 Constant *StartFile = getStartFileFunc();
652 Constant *EmitFunction = getEmitFunctionFunc();
653 Constant *EmitArcs = getEmitArcsFunc();
654 Constant *EndFile = getEndFileFunc();
655
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000656 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
657 if (CU_Nodes) {
658 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000659 DICompileUnit CU(CU_Nodes->getOperand(i));
660 std::string FilenameGcda = mangleName(CU, "gcda");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000661 Builder.CreateCall(StartFile,
662 Builder.CreateGlobalStringPtr(FilenameGcda));
Bill Wendling21b742f2012-08-29 18:45:41 +0000663 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000664 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000665 I != E; ++I) {
666 DISubprogram SP(I->second);
667 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
668 Builder.CreateCall2(EmitFunction,
669 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
670 Builder.CreateGlobalStringPtr(SP.getName()));
671
672 GlobalVariable *GV = I->first;
673 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000674 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000675 Builder.CreateCall2(EmitArcs,
676 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
677 Builder.CreateConstGEP2_64(GV, 0, 0));
678 }
679 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000680 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000681 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000682 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000683
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000684 // Create a small bit of code that registers the "__llvm_gcov_writeout"
685 // function to be executed at exit.
686 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
687 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
688 "__llvm_gcov_init", M);
689 F->setUnnamedAddr(true);
690 F->setLinkage(GlobalValue::InternalLinkage);
Bill Wendlingf5e6d702012-10-10 03:12:49 +0000691 F->addFnAttr(Attributes::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000692 if (NoRedZone)
693 F->addFnAttr(Attributes::NoRedZone);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000694
695 BB = BasicBlock::Create(*Ctx, "entry", F);
696 Builder.SetInsertPoint(BB);
697
698 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
699 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000700 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000701 Builder.CreateCall(AtExitFn, WriteoutF);
702 Builder.CreateRetVoid();
703
704 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000705}
Bill Wendling77b19132012-05-28 06:10:56 +0000706
707void GCOVProfiler::insertIndirectCounterIncrement() {
708 Function *Fn =
709 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
710 Fn->setUnnamedAddr(true);
711 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendlingf5e6d702012-10-10 03:12:49 +0000712 Fn->addFnAttr(Attributes::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000713 if (NoRedZone)
714 Fn->addFnAttr(Attributes::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000715
716 Type *Int32Ty = Type::getInt32Ty(*Ctx);
717 Type *Int64Ty = Type::getInt64Ty(*Ctx);
718 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
719
720 // Create basic blocks for function.
721 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
722 IRBuilder<> Builder(BB);
723
724 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
725 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
726 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
727
728 // uint32_t pred = *predecessor;
729 // if (pred == 0xffffffff) return;
730 Argument *Arg = Fn->arg_begin();
731 Arg->setName("predecessor");
732 Value *Pred = Builder.CreateLoad(Arg, "pred");
733 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
734 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
735
736 Builder.SetInsertPoint(PredNotNegOne);
737
738 // uint64_t *counter = counters[pred];
739 // if (!counter) return;
740 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
741 Arg = llvm::next(Fn->arg_begin());
742 Arg->setName("counters");
743 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
744 Value *Counter = Builder.CreateLoad(GEP, "counter");
745 Cond = Builder.CreateICmpEQ(Counter,
Micah Villmowb8bce922012-10-24 17:25:11 +0000746 Constant::getNullValue(Int64Ty->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000747 Builder.CreateCondBr(Cond, Exit, CounterEnd);
748
749 // ++*counter;
750 Builder.SetInsertPoint(CounterEnd);
751 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
752 ConstantInt::get(Int64Ty, 1));
753 Builder.CreateStore(Add, Counter);
754 Builder.CreateBr(Exit);
755
756 // Fill in the exit block.
757 Builder.SetInsertPoint(Exit);
758 Builder.CreateRetVoid();
759}
Bill Wendling253353c2012-09-13 00:09:55 +0000760
761void GCOVProfiler::
762insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
763 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling78fff8e2012-09-17 17:57:05 +0000764 Function *FlushF = M->getFunction("__gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000765 if (!FlushF)
766 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendling78fff8e2012-09-17 17:57:05 +0000767 "__gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000768 else
769 FlushF->setLinkage(GlobalValue::InternalLinkage);
770 FlushF->setUnnamedAddr(true);
Bill Wendling08e13e42012-12-10 19:46:49 +0000771 FlushF->addFnAttr(Attributes::NoInline);
772 if (NoRedZone)
773 FlushF->addFnAttr(Attributes::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000774
Bill Wendling253353c2012-09-13 00:09:55 +0000775 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
776
777 // Write out the current counters.
778 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
779 assert(WriteoutF && "Need to create the writeout function first!");
780
781 IRBuilder<> Builder(Entry);
782 Builder.CreateCall(WriteoutF);
783
Bill Wendling032dbee2012-09-13 14:32:30 +0000784 // Zero out the counters.
785 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
786 I = CountersBySP.begin(), E = CountersBySP.end();
787 I != E; ++I) {
788 GlobalVariable *GV = I->first;
789 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000790 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000791 }
Bill Wendling253353c2012-09-13 00:09:55 +0000792
793 Type *RetTy = FlushF->getReturnType();
794 if (RetTy == Type::getVoidTy(*Ctx))
795 Builder.CreateRetVoid();
796 else if (RetTy->isIntegerTy())
Bill Wendling78fff8e2012-09-17 17:57:05 +0000797 // Used if __gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000798 Builder.CreateRet(ConstantInt::get(RetTy, 0));
799 else
Bill Wendling78fff8e2012-09-17 17:57:05 +0000800 report_fatal_error("invalid return type for __gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000801}