blob: e8d4ac8ebcba4bb29eff5963ebe64d1d793154c8 [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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Nick Lewyckya204ef32013-03-14 05:13:26 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/DebugLoc.h"
35#include "llvm/Support/InstIterator.h"
36#include "llvm/Support/PathV2.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000039#include <string>
40#include <utility>
41using namespace llvm;
42
Nick Lewyckya204ef32013-03-14 05:13:26 +000043static cl::opt<std::string>
44DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
45 cl::ValueRequired);
46
47GCOVOptions GCOVOptions::getDefault() {
48 GCOVOptions Options;
49 Options.EmitNotes = true;
50 Options.EmitData = true;
51 Options.UseCfgChecksum = false;
52 Options.NoRedZone = false;
53 Options.FunctionNamesInData = true;
54
55 if (DefaultGCOVVersion.size() != 4) {
56 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
57 DefaultGCOVVersion);
58 }
59 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
60 return Options;
61}
62
Nick Lewyckyb1928702011-04-16 01:20:23 +000063namespace {
64 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000065 public:
66 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000067 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
68 ReversedVersion[0] = Options.Version[3];
69 ReversedVersion[1] = Options.Version[2];
70 ReversedVersion[2] = Options.Version[1];
71 ReversedVersion[3] = Options.Version[0];
72 ReversedVersion[4] = '\0';
Nick Lewyckya61e52c2011-04-21 01:56:25 +000073 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
74 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000075 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
78 ReversedVersion[0] = Options.Version[3];
79 ReversedVersion[1] = Options.Version[2];
80 ReversedVersion[2] = Options.Version[1];
81 ReversedVersion[3] = Options.Version[0];
82 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000083 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
84 }
85 virtual const char *getPassName() const {
86 return "GCOV Profiler";
87 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000088
Nick Lewyckyb1928702011-04-16 01:20:23 +000089 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000090 bool runOnModule(Module &M);
91
Nick Lewycky64a0a332013-03-13 22:55:42 +000092 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000094
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000095 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000097 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000098
Nick Lewyckyb1928702011-04-16 01:20:23 +000099 // Get pointers to the functions in the runtime library.
100 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000101 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000102 Constant *getEmitFunctionFunc();
103 Constant *getEmitArcsFunc();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000104 Constant *getDeleteFlushFunctionListFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000105 Constant *getEndFileFunc();
106
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000107 // Create or retrieve an i32 state value that is used to represent the
108 // pred block number for certain non-trivial edges.
109 GlobalVariable *getEdgeStateValue();
110
111 // Produce a table of pointers to counters, by predecessor and successor
112 // block number.
113 GlobalVariable *buildEdgeLookupTable(Function *F,
114 GlobalVariable *Counter,
Nick Lewycky64a0a332013-03-13 22:55:42 +0000115 const UniqueVector<BasicBlock *>&Preds,
116 const UniqueVector<BasicBlock*>&Succs);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000117
Nick Lewyckyb1928702011-04-16 01:20:23 +0000118 // Add the function to write out all our counters to the global destructor
119 // list.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000120 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
121 MDNode*> >);
122 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +0000123 void insertIndirectCounterIncrement();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000124
Bill Wendling73996f42012-08-30 01:32:31 +0000125 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000126
Nick Lewyckya204ef32013-03-14 05:13:26 +0000127 GCOVOptions Options;
128
129 // Reversed, NUL-terminated copy of Options.Version.
130 char ReversedVersion[5];
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000131
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000132 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000133 LLVMContext *Ctx;
134 };
135}
136
137char GCOVProfiler::ID = 0;
138INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
139 "Insert instrumentation for GCOV profiling", false, false)
140
Nick Lewyckya204ef32013-03-14 05:13:26 +0000141ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
142 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000143}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000144
Nick Lewyckyb1928702011-04-16 01:20:23 +0000145namespace {
146 class GCOVRecord {
147 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000148 static const char *LinesTag;
149 static const char *FunctionTag;
150 static const char *BlockTag;
151 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000152
153 GCOVRecord() {}
154
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000155 void writeBytes(const char *Bytes, int Size) {
156 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000157 }
158
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000159 void write(uint32_t i) {
160 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000161 }
162
163 // Returns the length measured in 4-byte blocks that will be used to
164 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000165 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000166 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000167 // padding out to the next 4-byte word. The length is measured in 4-byte
168 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000169 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000170 }
171
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000172 void writeGCOVString(StringRef s) {
173 uint32_t Len = lengthOfGCOVString(s);
174 write(Len);
175 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000176
177 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000178 assert((unsigned)(4 - (s.size() % 4)) > 0);
179 assert((unsigned)(4 - (s.size() % 4)) <= 4);
180 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000181 }
182
183 raw_ostream *os;
184 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000185 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
186 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
187 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
188 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000189
190 class GCOVFunction;
191 class GCOVBlock;
192
193 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000194 // list of line numbers and a single filename, representing lines that belong
195 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000196 class GCOVLines : public GCOVRecord {
197 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000198 void addLine(uint32_t Line) {
199 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000200 }
201
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000202 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000203 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000204 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000205 }
206
Devang Patel16c19a12011-09-20 18:35:00 +0000207 void writeOut() {
208 write(0);
209 writeGCOVString(Filename);
210 for (int i = 0, e = Lines.size(); i != e; ++i)
211 write(Lines[i]);
212 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000213
Devang Patel16c19a12011-09-20 18:35:00 +0000214 GCOVLines(StringRef F, raw_ostream *os)
215 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000216 this->os = os;
217 }
218
Devang Patel680018f2011-09-20 18:48:56 +0000219 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000220 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000221 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000222 };
223
224 // Represent a basic block in GCOV. Each block has a unique number in the
225 // function, number of lines belonging to each block, and a set of edges to
226 // other blocks.
227 class GCOVBlock : public GCOVRecord {
228 public:
Devang Patel68155d32011-09-20 17:55:19 +0000229 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 GCOVLines *&Lines = LinesByFile[Filename];
231 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000232 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000233 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000234 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000235 }
236
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000237 void addEdge(GCOVBlock &Successor) {
238 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000239 }
240
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000241 void writeOut() {
242 uint32_t Len = 3;
243 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
244 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000245 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000246 }
247
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000248 writeBytes(LinesTag, 4);
249 write(Len);
250 write(Number);
251 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000252 E = LinesByFile.end(); I != E; ++I)
253 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000254 write(0);
255 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000256 }
257
258 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000259 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000260 }
261
262 private:
263 friend class GCOVFunction;
264
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000265 GCOVBlock(uint32_t Number, raw_ostream *os)
266 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000267 this->os = os;
268 }
269
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000270 uint32_t Number;
271 StringMap<GCOVLines *> LinesByFile;
272 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000273 };
274
275 // A function has a unique identifier, a checksum (we leave as zero) and a
276 // set of blocks and a map of edges between blocks. This is the only GCOV
277 // object users can construct, the blocks and lines will be rooted here.
278 class GCOVFunction : public GCOVRecord {
279 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000280 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Nick Lewyckya204ef32013-03-14 05:13:26 +0000281 bool UseCfgChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000282 this->os = os;
283
284 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000285 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000286 uint32_t i = 0;
287 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000288 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000289 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000291
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000292 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000293 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000295 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000296 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000297 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000298 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000299 write(0); // lineno checksum
Nick Lewyckya204ef32013-03-14 05:13:26 +0000300 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000301 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000302 writeGCOVString(SP.getName());
303 writeGCOVString(SP.getFilename());
304 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000305 }
306
307 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000308 DeleteContainerSeconds(Blocks);
309 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000310 }
311
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 GCOVBlock &getBlock(BasicBlock *BB) {
313 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000314 }
315
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 GCOVBlock &getReturnBlock() {
317 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000318 }
319
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000320 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000321 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000322 writeBytes(BlockTag, 4);
323 write(Blocks.size() + 1);
324 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
325 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000326 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000327 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000328
329 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000330 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
331 E = Blocks.end(); I != E; ++I) {
332 GCOVBlock &Block = *I->second;
333 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000334
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000335 writeBytes(EdgeTag, 4);
336 write(Block.OutEdges.size() * 2 + 1);
337 write(Block.Number);
338 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000339 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
340 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000341 write(Block.OutEdges[i]->Number);
342 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000343 }
344 }
345
346 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000347 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
348 E = Blocks.end(); I != E; ++I) {
349 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000350 }
351 }
352
353 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000354 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
355 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000356 };
357}
358
Bill Wendling73996f42012-08-30 01:32:31 +0000359std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000360 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
361 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
362 MDNode *N = GCov->getOperand(i);
363 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000364 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000365 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000366 if (!GCovFile || !CompileUnit) continue;
367 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000368 SmallString<128> Filename = GCovFile->getString();
369 sys::path::replace_extension(Filename, NewStem);
370 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000371 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000372 }
373 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000374
Bill Wendling6e5190c2012-08-30 00:34:21 +0000375 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000376 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000377 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000378}
379
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000380bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000381 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000382 Ctx = &M.getContext();
383
Nick Lewyckya204ef32013-03-14 05:13:26 +0000384 if (Options.EmitNotes) emitProfileNotes();
385 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000386 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000387}
388
Nick Lewycky64a0a332013-03-13 22:55:42 +0000389void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000390 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000391 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000392
Nick Lewyckybba40db2011-11-27 23:22:20 +0000393 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
394 // Each compile unit gets its own .gcno file. This means that whether we run
395 // this pass over the original .o's as they're produced, or run it after
396 // LTO, we'll generate the same .gcno files.
397
398 DICompileUnit CU(CU_Nodes->getOperand(i));
399 std::string ErrorInfo;
400 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
401 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000402 out.write("oncg", 4);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000403 out.write(ReversedVersion, 4);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000404 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000405
406 DIArray SPs = CU.getSubprograms();
407 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
408 DISubprogram SP(SPs.getElement(i));
409 if (!SP.Verify()) continue;
410
411 Function *F = SP.getFunction();
412 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000413 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000414
415 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
416 GCOVBlock &Block = Func.getBlock(BB);
417 TerminatorInst *TI = BB->getTerminator();
418 if (int successors = TI->getNumSuccessors()) {
419 for (int i = 0; i != successors; ++i) {
420 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
421 }
422 } else if (isa<ReturnInst>(TI)) {
423 Block.addEdge(Func.getReturnBlock());
424 }
425
426 uint32_t Line = 0;
427 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
428 I != IE; ++I) {
429 const DebugLoc &Loc = I->getDebugLoc();
430 if (Loc.isUnknown()) continue;
431 if (Line == Loc.getLine()) continue;
432 Line = Loc.getLine();
433 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
434
435 GCOVLines &Lines = Block.getFile(SP.getFilename());
436 Lines.addLine(Loc.getLine());
437 }
438 }
439 Func.writeOut();
440 }
441 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
442 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000443 }
444}
445
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000446bool GCOVProfiler::emitProfileArcs() {
447 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
448 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000449
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000450 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000451 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000452 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
453 DICompileUnit CU(CU_Nodes->getOperand(i));
454 DIArray SPs = CU.getSubprograms();
455 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
456 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
457 DISubprogram SP(SPs.getElement(i));
458 if (!SP.Verify()) continue;
459 Function *F = SP.getFunction();
460 if (!F) continue;
461 if (!Result) Result = true;
462 unsigned Edges = 0;
463 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
464 TerminatorInst *TI = BB->getTerminator();
465 if (isa<ReturnInst>(TI))
466 ++Edges;
467 else
468 Edges += TI->getNumSuccessors();
469 }
470
471 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000472 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000473 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000474 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000475 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000476 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000477 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000478 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
479
480 UniqueVector<BasicBlock *> ComplexEdgePreds;
481 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
482
483 unsigned Edge = 0;
484 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
485 TerminatorInst *TI = BB->getTerminator();
486 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
487 if (Successors) {
488 IRBuilder<> Builder(TI);
489
490 if (Successors == 1) {
491 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
492 Edge);
493 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000494 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000495 Builder.CreateStore(Count, Counter);
496 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000497 Value *Sel = Builder.CreateSelect(BI->getCondition(),
498 Builder.getInt64(Edge),
499 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000500 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000501 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000502 Idx.push_back(Sel);
503 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
504 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000505 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000506 Builder.CreateStore(Count, Counter);
507 } else {
508 ComplexEdgePreds.insert(BB);
509 for (int i = 0; i != Successors; ++i)
510 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
511 }
512 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000513 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000514 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000515
516 if (!ComplexEdgePreds.empty()) {
517 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000518 buildEdgeLookupTable(F, Counters,
519 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000520 GlobalVariable *EdgeState = getEdgeStateValue();
521
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000522 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
523 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000524 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000525 }
526 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
527 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000528 BasicBlock::iterator InsertPt =
529 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000530 IRBuilder<> Builder(InsertPt);
531 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000532 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
533 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000534
535 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000536 InsertIndCounterIncrCode = true;
537 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
538 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000539 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000540 }
541 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000542
Bill Wendlingd195eb62013-03-18 23:04:39 +0000543 Function *WriteoutF = insertCounterWriteout(CountersBySP);
544 Function *FlushF = insertFlush(CountersBySP);
545
546 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
547 // be executed at exit and the "__llvm_gcov_flush" function to be executed
548 // when "__gcov_flush" is called.
549 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
550 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
551 "__llvm_gcov_init", M);
552 F->setUnnamedAddr(true);
553 F->setLinkage(GlobalValue::InternalLinkage);
554 F->addFnAttr(Attribute::NoInline);
555 if (Options.NoRedZone)
556 F->addFnAttr(Attribute::NoRedZone);
557
558 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
559 IRBuilder<> Builder(BB);
560
561 FTy = FunctionType::get(Builder.getInt32Ty(),
562 PointerType::get(FTy, 0), false);
563 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
564 Builder.CreateCall(AtExitFn, WriteoutF);
565
566 // Register the local flush function.
567 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
568 FTy = FunctionType::get(Builder.getVoidTy(),
569 PointerType::get(FTy, 0), false);
570 Constant *RegFlush =
571 M->getOrInsertFunction("llvm_register_flush_function", FTy);
572 Builder.CreateCall(RegFlush, FlushF);
573
574 // Make sure that all the flush function list is deleted.
575 Builder.CreateCall(AtExitFn, getDeleteFlushFunctionListFunc());
576 Builder.CreateRetVoid();
577
578 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000579 }
Bill Wendling77b19132012-05-28 06:10:56 +0000580
581 if (InsertIndCounterIncrCode)
582 insertIndirectCounterIncrement();
583
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000584 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000585}
586
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000587// All edges with successors that aren't branches are "complex", because it
588// requires complex logic to pick which counter to update.
589GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
590 Function *F,
591 GlobalVariable *Counters,
592 const UniqueVector<BasicBlock *> &Preds,
593 const UniqueVector<BasicBlock *> &Succs) {
594 // TODO: support invoke, threads. We rely on the fact that nothing can modify
595 // the whole-Module pred edge# between the time we set it and the time we next
596 // read it. Threads and invoke make this untrue.
597
598 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000599 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000600 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000601 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000602
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000603 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000604 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000605 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000606 EdgeTable[i] = NullValue;
607
608 unsigned Edge = 0;
609 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
610 TerminatorInst *TI = BB->getTerminator();
611 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000612 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000613 for (int i = 0; i != Successors; ++i) {
614 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000615 IRBuilder<> Builder(Succ);
616 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000617 Edge + i);
618 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
619 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
620 }
621 }
622 Edge += Successors;
623 }
624
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000625 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000626 GlobalVariable *EdgeTableGV =
627 new GlobalVariable(
628 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000629 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000630 "__llvm_gcda_edge_table");
631 EdgeTableGV->setUnnamedAddr(true);
632 return EdgeTableGV;
633}
634
Nick Lewyckyb1928702011-04-16 01:20:23 +0000635Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000636 Type *Args[] = {
637 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
638 Type::getInt8PtrTy(*Ctx), // const char version[4]
639 };
640 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000641 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
642}
643
Bill Wendling77b19132012-05-28 06:10:56 +0000644Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
645 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000646 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000647 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000648 Int32Ty->getPointerTo(), // uint32_t *predecessor
649 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000650 };
651 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
652 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000653}
654
655Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000656 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000657 Type::getInt32Ty(*Ctx), // uint32_t ident
658 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000659 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000660 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000661 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000662 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000663}
664
665Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000666 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000667 Type::getInt32Ty(*Ctx), // uint32_t num_counters
668 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
669 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000670 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000671 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000672}
673
Bill Wendlingd195eb62013-03-18 23:04:39 +0000674Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
675 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
676 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
677}
678
Nick Lewyckyb1928702011-04-16 01:20:23 +0000679Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000680 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000681 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000682}
683
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000684GlobalVariable *GCOVProfiler::getEdgeStateValue() {
685 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
686 if (!GV) {
687 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
688 GlobalValue::InternalLinkage,
689 ConstantInt::get(Type::getInt32Ty(*Ctx),
690 0xffffffff),
691 "__llvm_gcov_global_state_pred");
692 GV->setUnnamedAddr(true);
693 }
694 return GV;
695}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000696
Bill Wendlingd195eb62013-03-18 23:04:39 +0000697Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000698 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000699 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
700 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
701 if (!WriteoutF)
702 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
703 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000704 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000705 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000706 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000707 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000708
709 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000710 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000711
712 Constant *StartFile = getStartFileFunc();
713 Constant *EmitFunction = getEmitFunctionFunc();
714 Constant *EmitArcs = getEmitArcsFunc();
715 Constant *EndFile = getEndFileFunc();
716
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000717 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
718 if (CU_Nodes) {
719 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000720 DICompileUnit CU(CU_Nodes->getOperand(i));
721 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000722 Builder.CreateCall2(StartFile,
723 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000724 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000725 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
726 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky17d2f772013-03-09 01:33:06 +0000727 Builder.CreateCall3(EmitFunction,
Nick Lewycky60d16a22013-03-09 10:13:26 +0000728 Builder.getInt32(j),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000729 Options.FunctionNamesInData ?
730 Builder.CreateGlobalStringPtr(SP.getName()) :
731 Constant::getNullValue(Builder.getInt8PtrTy()),
732 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000733
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000734 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000735 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000736 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000737 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000738 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000739 Builder.CreateConstGEP2_64(GV, 0, 0));
740 }
741 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000742 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000743 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000744
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000745 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000746 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000747}
Bill Wendling77b19132012-05-28 06:10:56 +0000748
749void GCOVProfiler::insertIndirectCounterIncrement() {
750 Function *Fn =
751 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
752 Fn->setUnnamedAddr(true);
753 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000754 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000755 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000756 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000757
Bill Wendling77b19132012-05-28 06:10:56 +0000758 // Create basic blocks for function.
759 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
760 IRBuilder<> Builder(BB);
761
762 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
763 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
764 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
765
766 // uint32_t pred = *predecessor;
767 // if (pred == 0xffffffff) return;
768 Argument *Arg = Fn->arg_begin();
769 Arg->setName("predecessor");
770 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000771 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000772 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
773
774 Builder.SetInsertPoint(PredNotNegOne);
775
776 // uint64_t *counter = counters[pred];
777 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000778 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000779 Arg = llvm::next(Fn->arg_begin());
780 Arg->setName("counters");
781 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
782 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000783 Cond = Builder.CreateICmpEQ(Counter,
784 Constant::getNullValue(
785 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000786 Builder.CreateCondBr(Cond, Exit, CounterEnd);
787
788 // ++*counter;
789 Builder.SetInsertPoint(CounterEnd);
790 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000791 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000792 Builder.CreateStore(Add, Counter);
793 Builder.CreateBr(Exit);
794
795 // Fill in the exit block.
796 Builder.SetInsertPoint(Exit);
797 Builder.CreateRetVoid();
798}
Bill Wendling253353c2012-09-13 00:09:55 +0000799
Bill Wendlingd195eb62013-03-18 23:04:39 +0000800Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000801insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
802 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000803 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000804 if (!FlushF)
805 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000806 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000807 else
808 FlushF->setLinkage(GlobalValue::InternalLinkage);
809 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000810 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000811 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000812 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000813
Bill Wendling253353c2012-09-13 00:09:55 +0000814 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
815
816 // Write out the current counters.
817 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
818 assert(WriteoutF && "Need to create the writeout function first!");
819
820 IRBuilder<> Builder(Entry);
821 Builder.CreateCall(WriteoutF);
822
Bill Wendling032dbee2012-09-13 14:32:30 +0000823 // Zero out the counters.
824 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
825 I = CountersBySP.begin(), E = CountersBySP.end();
826 I != E; ++I) {
827 GlobalVariable *GV = I->first;
828 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000829 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000830 }
Bill Wendling253353c2012-09-13 00:09:55 +0000831
832 Type *RetTy = FlushF->getReturnType();
833 if (RetTy == Type::getVoidTy(*Ctx))
834 Builder.CreateRetVoid();
835 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000836 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000837 Builder.CreateRet(ConstantInt::get(RetTy, 0));
838 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000839 report_fatal_error("invalid return type for __llvm_gcov_flush");
840
841 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000842}