blob: fe3fe1c74a040f92d73386ec146cfa1ff7db066d [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"
Bill Wendling39c41c32013-03-26 22:47:50 +000035#include "llvm/Support/FileSystem.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000036#include "llvm/Support/InstIterator.h"
Rafael Espindolaa11c3e22013-06-11 22:21:28 +000037#include "llvm/Support/Path.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000038#include "llvm/Support/raw_ostream.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyc4e6b542013-06-18 06:38:21 +000040#include <algorithm>
Nick Lewyckyb1928702011-04-16 01:20:23 +000041#include <string>
42#include <utility>
43using namespace llvm;
44
Nick Lewyckya204ef32013-03-14 05:13:26 +000045static cl::opt<std::string>
46DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
47 cl::ValueRequired);
48
49GCOVOptions GCOVOptions::getDefault() {
50 GCOVOptions Options;
51 Options.EmitNotes = true;
52 Options.EmitData = true;
53 Options.UseCfgChecksum = false;
54 Options.NoRedZone = false;
55 Options.FunctionNamesInData = true;
56
57 if (DefaultGCOVVersion.size() != 4) {
58 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
59 DefaultGCOVVersion);
60 }
61 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
62 return Options;
63}
64
Nick Lewyckyb1928702011-04-16 01:20:23 +000065namespace {
66 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000067 public:
68 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000069 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
70 ReversedVersion[0] = Options.Version[3];
71 ReversedVersion[1] = Options.Version[2];
72 ReversedVersion[2] = Options.Version[1];
73 ReversedVersion[3] = Options.Version[0];
74 ReversedVersion[4] = '\0';
Nick Lewyckya61e52c2011-04-21 01:56:25 +000075 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
76 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000077 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
78 assert((Options.EmitNotes || Options.EmitData) &&
79 "GCOVProfiler asked to do nothing?");
80 ReversedVersion[0] = Options.Version[3];
81 ReversedVersion[1] = Options.Version[2];
82 ReversedVersion[2] = Options.Version[1];
83 ReversedVersion[3] = Options.Version[0];
84 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000085 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
86 }
87 virtual const char *getPassName() const {
88 return "GCOV Profiler";
89 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000090
Nick Lewyckyb1928702011-04-16 01:20:23 +000091 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000092 bool runOnModule(Module &M);
93
Nick Lewycky64a0a332013-03-13 22:55:42 +000094 // Create the .gcno files for the Module based on DebugInfo.
95 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000096
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000097 // Modify the program to track transitions along edges and call into the
98 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000099 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000100
Nick Lewyckyb1928702011-04-16 01:20:23 +0000101 // Get pointers to the functions in the runtime library.
102 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000103 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000104 Constant *getEmitFunctionFunc();
105 Constant *getEmitArcsFunc();
Bill Wendling18764712013-03-19 21:03:22 +0000106 Constant *getDeleteWriteoutFunctionListFunc();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000107 Constant *getDeleteFlushFunctionListFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000108 Constant *getEndFileFunc();
109
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000110 // Create or retrieve an i32 state value that is used to represent the
111 // pred block number for certain non-trivial edges.
112 GlobalVariable *getEdgeStateValue();
113
114 // Produce a table of pointers to counters, by predecessor and successor
115 // block number.
116 GlobalVariable *buildEdgeLookupTable(Function *F,
117 GlobalVariable *Counter,
Nick Lewycky64a0a332013-03-13 22:55:42 +0000118 const UniqueVector<BasicBlock *>&Preds,
119 const UniqueVector<BasicBlock*>&Succs);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000120
Nick Lewyckyb1928702011-04-16 01:20:23 +0000121 // Add the function to write out all our counters to the global destructor
122 // list.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000123 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
124 MDNode*> >);
125 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +0000126 void insertIndirectCounterIncrement();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000127
Bill Wendlingf2a28062013-03-28 22:40:08 +0000128 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000129
Nick Lewyckya204ef32013-03-14 05:13:26 +0000130 GCOVOptions Options;
131
132 // Reversed, NUL-terminated copy of Options.Version.
133 char ReversedVersion[5];
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000134
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000135 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000136 LLVMContext *Ctx;
137 };
138}
139
140char GCOVProfiler::ID = 0;
141INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
142 "Insert instrumentation for GCOV profiling", false, false)
143
Nick Lewyckya204ef32013-03-14 05:13:26 +0000144ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
145 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000146}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000147
Nick Lewycky5d22d022013-03-19 01:37:55 +0000148static std::string getFunctionName(DISubprogram SP) {
149 if (!SP.getLinkageName().empty())
150 return SP.getLinkageName();
151 return SP.getName();
152}
153
Nick Lewyckyb1928702011-04-16 01:20:23 +0000154namespace {
155 class GCOVRecord {
156 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000157 static const char *LinesTag;
158 static const char *FunctionTag;
159 static const char *BlockTag;
160 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000161
162 GCOVRecord() {}
163
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000164 void writeBytes(const char *Bytes, int Size) {
165 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000166 }
167
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000168 void write(uint32_t i) {
169 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000170 }
171
172 // Returns the length measured in 4-byte blocks that will be used to
173 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000174 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000175 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000176 // padding out to the next 4-byte word. The length is measured in 4-byte
177 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000178 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000179 }
180
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000181 void writeGCOVString(StringRef s) {
182 uint32_t Len = lengthOfGCOVString(s);
183 write(Len);
184 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000185
186 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000187 assert((unsigned)(4 - (s.size() % 4)) > 0);
188 assert((unsigned)(4 - (s.size() % 4)) <= 4);
189 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000190 }
191
192 raw_ostream *os;
193 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000194 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
195 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
196 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
197 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198
199 class GCOVFunction;
200 class GCOVBlock;
201
202 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000203 // list of line numbers and a single filename, representing lines that belong
204 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000205 class GCOVLines : public GCOVRecord {
206 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000207 void addLine(uint32_t Line) {
208 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000209 }
210
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000211 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000212 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000213 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000214 }
215
Devang Patel16c19a12011-09-20 18:35:00 +0000216 void writeOut() {
217 write(0);
218 writeGCOVString(Filename);
219 for (int i = 0, e = Lines.size(); i != e; ++i)
220 write(Lines[i]);
221 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000222
Devang Patel16c19a12011-09-20 18:35:00 +0000223 GCOVLines(StringRef F, raw_ostream *os)
224 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000225 this->os = os;
226 }
227
Devang Patel680018f2011-09-20 18:48:56 +0000228 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000229 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 };
232
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000233
234 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
235 struct StringKeySort {
236 bool operator()(StringMapEntry<GCOVLines *> *LHS,
237 StringMapEntry<GCOVLines *> *RHS) const {
238 return LHS->getKey() < RHS->getKey();
239 }
240 };
241
Nick Lewyckyb1928702011-04-16 01:20:23 +0000242 // Represent a basic block in GCOV. Each block has a unique number in the
243 // function, number of lines belonging to each block, and a set of edges to
244 // other blocks.
245 class GCOVBlock : public GCOVRecord {
246 public:
Devang Patel68155d32011-09-20 17:55:19 +0000247 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000248 GCOVLines *&Lines = LinesByFile[Filename];
249 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000250 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000251 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000252 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000253 }
254
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000255 void addEdge(GCOVBlock &Successor) {
256 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000257 }
258
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000259 void writeOut() {
260 uint32_t Len = 3;
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000261 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000262 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
263 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000264 Len += I->second->length();
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000265 SortedLinesByFile.push_back(&*I);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000266 }
267
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 writeBytes(LinesTag, 4);
269 write(Len);
270 write(Number);
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000271
272 StringKeySort Sorter;
273 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
274 for (SmallVector<StringMapEntry<GCOVLines *> *, 32>::iterator
275 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
276 I != E; ++I)
277 (*I)->getValue()->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000278 write(0);
279 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000280 }
281
282 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000283 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000284 }
285
286 private:
287 friend class GCOVFunction;
288
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000289 GCOVBlock(uint32_t Number, raw_ostream *os)
290 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000291 this->os = os;
292 }
293
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 uint32_t Number;
295 StringMap<GCOVLines *> LinesByFile;
296 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000297 };
298
299 // A function has a unique identifier, a checksum (we leave as zero) and a
300 // set of blocks and a map of edges between blocks. This is the only GCOV
301 // object users can construct, the blocks and lines will be rooted here.
302 class GCOVFunction : public GCOVRecord {
303 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000304 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Nick Lewyckya204ef32013-03-14 05:13:26 +0000305 bool UseCfgChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000306 this->os = os;
307
308 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000309 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000310 uint32_t i = 0;
311 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000313 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000314 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000315
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 writeBytes(FunctionTag, 4);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000317 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000318 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000319 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000320 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000321 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000322 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000323 write(0); // lineno checksum
Nick Lewyckya204ef32013-03-14 05:13:26 +0000324 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000325 write(0); // cfg checksum
Nick Lewycky5d22d022013-03-19 01:37:55 +0000326 writeGCOVString(getFunctionName(SP));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000327 writeGCOVString(SP.getFilename());
328 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000329 }
330
331 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000332 DeleteContainerSeconds(Blocks);
333 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000334 }
335
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000336 GCOVBlock &getBlock(BasicBlock *BB) {
337 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000338 }
339
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000340 GCOVBlock &getReturnBlock() {
341 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000342 }
343
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000344 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000345 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000346 writeBytes(BlockTag, 4);
347 write(Blocks.size() + 1);
348 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
349 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000350 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000351 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000352
353 // Emit edges between blocks.
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000354 if (Blocks.empty()) return;
355 Function *F = Blocks.begin()->first->getParent();
356 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
357 GCOVBlock &Block = *Blocks[I];
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000358 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000359
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000360 writeBytes(EdgeTag, 4);
361 write(Block.OutEdges.size() * 2 + 1);
362 write(Block.Number);
363 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000364 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
365 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000366 write(Block.OutEdges[i]->Number);
367 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000368 }
369 }
370
371 // Emit lines for each block.
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000372 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
373 Blocks[I]->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000374 }
375 }
376
377 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000378 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
379 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000380 };
381}
382
Bill Wendlingf2a28062013-03-28 22:40:08 +0000383std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000384 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
385 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
386 MDNode *N = GCov->getOperand(i);
387 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000388 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000389 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000390 if (!GCovFile || !CompileUnit) continue;
391 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000392 SmallString<128> Filename = GCovFile->getString();
393 sys::path::replace_extension(Filename, NewStem);
394 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000395 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000396 }
397 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000398
Bill Wendling6e5190c2012-08-30 00:34:21 +0000399 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000400 sys::path::replace_extension(Filename, NewStem);
Bill Wendling39c41c32013-03-26 22:47:50 +0000401 StringRef FName = sys::path::filename(Filename);
Bill Wendling39c41c32013-03-26 22:47:50 +0000402 SmallString<128> CurPath;
403 if (sys::fs::current_path(CurPath)) return FName;
404 sys::path::append(CurPath, FName.str());
405 return CurPath.str();
Nick Lewycky269687f2011-05-04 04:03:04 +0000406}
407
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000408bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000409 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000410 Ctx = &M.getContext();
411
Nick Lewyckya204ef32013-03-14 05:13:26 +0000412 if (Options.EmitNotes) emitProfileNotes();
413 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000414 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000415}
416
Nick Lewycky64a0a332013-03-13 22:55:42 +0000417void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000418 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000419 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000420
Nick Lewyckybba40db2011-11-27 23:22:20 +0000421 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
422 // Each compile unit gets its own .gcno file. This means that whether we run
423 // this pass over the original .o's as they're produced, or run it after
424 // LTO, we'll generate the same .gcno files.
425
426 DICompileUnit CU(CU_Nodes->getOperand(i));
427 std::string ErrorInfo;
Bill Wendlingf2a28062013-03-28 22:40:08 +0000428 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
Nick Lewyckybba40db2011-11-27 23:22:20 +0000429 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000430 out.write("oncg", 4);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000431 out.write(ReversedVersion, 4);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000432 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000433
434 DIArray SPs = CU.getSubprograms();
435 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
436 DISubprogram SP(SPs.getElement(i));
Manman Ren02e75022013-06-26 21:26:10 +0000437 assert(SP.isSubprogram());
Nick Lewyckybba40db2011-11-27 23:22:20 +0000438
439 Function *F = SP.getFunction();
440 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000441 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000442
443 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
444 GCOVBlock &Block = Func.getBlock(BB);
445 TerminatorInst *TI = BB->getTerminator();
446 if (int successors = TI->getNumSuccessors()) {
447 for (int i = 0; i != successors; ++i) {
448 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
449 }
450 } else if (isa<ReturnInst>(TI)) {
451 Block.addEdge(Func.getReturnBlock());
452 }
453
454 uint32_t Line = 0;
455 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
456 I != IE; ++I) {
457 const DebugLoc &Loc = I->getDebugLoc();
458 if (Loc.isUnknown()) continue;
459 if (Line == Loc.getLine()) continue;
460 Line = Loc.getLine();
461 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
462
463 GCOVLines &Lines = Block.getFile(SP.getFilename());
464 Lines.addLine(Loc.getLine());
465 }
466 }
467 Func.writeOut();
468 }
469 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
470 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000471 }
472}
473
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000474bool GCOVProfiler::emitProfileArcs() {
475 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
476 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000477
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000478 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000479 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000480 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
481 DICompileUnit CU(CU_Nodes->getOperand(i));
482 DIArray SPs = CU.getSubprograms();
483 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
484 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
485 DISubprogram SP(SPs.getElement(i));
Manman Ren02e75022013-06-26 21:26:10 +0000486 assert(SP.isSubprogram());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000487 Function *F = SP.getFunction();
488 if (!F) continue;
489 if (!Result) Result = true;
490 unsigned Edges = 0;
491 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
492 TerminatorInst *TI = BB->getTerminator();
493 if (isa<ReturnInst>(TI))
494 ++Edges;
495 else
496 Edges += TI->getNumSuccessors();
497 }
498
499 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000500 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000501 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000502 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000503 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000504 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000505 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000506 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
507
508 UniqueVector<BasicBlock *> ComplexEdgePreds;
509 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
510
511 unsigned Edge = 0;
512 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
513 TerminatorInst *TI = BB->getTerminator();
514 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
515 if (Successors) {
516 IRBuilder<> Builder(TI);
517
518 if (Successors == 1) {
519 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
520 Edge);
521 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000522 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000523 Builder.CreateStore(Count, Counter);
524 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000525 Value *Sel = Builder.CreateSelect(BI->getCondition(),
526 Builder.getInt64(Edge),
527 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000528 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000529 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000530 Idx.push_back(Sel);
531 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
532 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000533 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000534 Builder.CreateStore(Count, Counter);
535 } else {
536 ComplexEdgePreds.insert(BB);
537 for (int i = 0; i != Successors; ++i)
538 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
539 }
540 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000541 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000542 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000543
544 if (!ComplexEdgePreds.empty()) {
545 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000546 buildEdgeLookupTable(F, Counters,
547 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000548 GlobalVariable *EdgeState = getEdgeStateValue();
549
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000550 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
551 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000552 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000553 }
554 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
555 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000556 BasicBlock::iterator InsertPt =
557 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000558 IRBuilder<> Builder(InsertPt);
559 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000560 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
561 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000562
563 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000564 InsertIndCounterIncrCode = true;
565 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
566 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000567 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000568 }
569 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000570
Bill Wendlingd195eb62013-03-18 23:04:39 +0000571 Function *WriteoutF = insertCounterWriteout(CountersBySP);
572 Function *FlushF = insertFlush(CountersBySP);
573
574 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling18764712013-03-19 21:03:22 +0000575 // be executed at exit and the "__llvm_gcov_flush" function to be executed
576 // when "__gcov_flush" is called.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000577 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
578 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
579 "__llvm_gcov_init", M);
580 F->setUnnamedAddr(true);
581 F->setLinkage(GlobalValue::InternalLinkage);
582 F->addFnAttr(Attribute::NoInline);
583 if (Options.NoRedZone)
584 F->addFnAttr(Attribute::NoRedZone);
585
586 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
587 IRBuilder<> Builder(BB);
588
Bill Wendlingd195eb62013-03-18 23:04:39 +0000589 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling8640c6a2013-03-20 21:13:59 +0000590 Type *Params[] = {
591 PointerType::get(FTy, 0),
592 PointerType::get(FTy, 0)
593 };
594 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling18764712013-03-19 21:03:22 +0000595
Bill Wendling8640c6a2013-03-20 21:13:59 +0000596 // Inialize the environment and register the local writeout and flush
597 // functions.
598 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
599 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000600 Builder.CreateRetVoid();
601
602 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000603 }
Bill Wendling77b19132012-05-28 06:10:56 +0000604
605 if (InsertIndCounterIncrCode)
606 insertIndirectCounterIncrement();
607
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000608 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000609}
610
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000611// All edges with successors that aren't branches are "complex", because it
612// requires complex logic to pick which counter to update.
613GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
614 Function *F,
615 GlobalVariable *Counters,
616 const UniqueVector<BasicBlock *> &Preds,
617 const UniqueVector<BasicBlock *> &Succs) {
618 // TODO: support invoke, threads. We rely on the fact that nothing can modify
619 // the whole-Module pred edge# between the time we set it and the time we next
620 // read it. Threads and invoke make this untrue.
621
622 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000623 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000624 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000625 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000626
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000627 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000628 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000629 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000630 EdgeTable[i] = NullValue;
631
632 unsigned Edge = 0;
633 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
634 TerminatorInst *TI = BB->getTerminator();
635 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000636 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000637 for (int i = 0; i != Successors; ++i) {
638 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000639 IRBuilder<> Builder(Succ);
640 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000641 Edge + i);
642 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
643 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
644 }
645 }
646 Edge += Successors;
647 }
648
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000649 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000650 GlobalVariable *EdgeTableGV =
651 new GlobalVariable(
652 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000653 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000654 "__llvm_gcda_edge_table");
655 EdgeTableGV->setUnnamedAddr(true);
656 return EdgeTableGV;
657}
658
Nick Lewyckyb1928702011-04-16 01:20:23 +0000659Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000660 Type *Args[] = {
661 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
662 Type::getInt8PtrTy(*Ctx), // const char version[4]
663 };
664 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000665 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
666}
667
Bill Wendling77b19132012-05-28 06:10:56 +0000668Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
669 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000670 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000671 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000672 Int32Ty->getPointerTo(), // uint32_t *predecessor
673 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000674 };
675 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
676 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000677}
678
679Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000680 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000681 Type::getInt32Ty(*Ctx), // uint32_t ident
682 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000683 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000684 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000685 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000686 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000687}
688
689Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000690 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000691 Type::getInt32Ty(*Ctx), // uint32_t num_counters
692 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
693 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000694 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000695 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000696}
697
Bill Wendling18764712013-03-19 21:03:22 +0000698Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
699 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
700 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
701}
702
Bill Wendlingd195eb62013-03-18 23:04:39 +0000703Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
704 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
705 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
706}
707
Nick Lewyckyb1928702011-04-16 01:20:23 +0000708Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000709 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000710 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000711}
712
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000713GlobalVariable *GCOVProfiler::getEdgeStateValue() {
714 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
715 if (!GV) {
716 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
717 GlobalValue::InternalLinkage,
718 ConstantInt::get(Type::getInt32Ty(*Ctx),
719 0xffffffff),
720 "__llvm_gcov_global_state_pred");
721 GV->setUnnamedAddr(true);
722 }
723 return GV;
724}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000725
Bill Wendlingd195eb62013-03-18 23:04:39 +0000726Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000727 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000728 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
729 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
730 if (!WriteoutF)
731 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
732 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000733 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000734 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000735 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000736 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000737
738 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000739 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000740
741 Constant *StartFile = getStartFileFunc();
742 Constant *EmitFunction = getEmitFunctionFunc();
743 Constant *EmitArcs = getEmitArcsFunc();
744 Constant *EndFile = getEndFileFunc();
745
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000746 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
747 if (CU_Nodes) {
748 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000749 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendlingf2a28062013-03-28 22:40:08 +0000750 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000751 Builder.CreateCall2(StartFile,
752 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000753 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000754 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
755 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000756 Builder.CreateCall3(
757 EmitFunction, Builder.getInt32(j),
758 Options.FunctionNamesInData ?
759 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
760 Constant::getNullValue(Builder.getInt8PtrTy()),
761 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000762
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000763 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000764 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000765 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000766 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000767 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000768 Builder.CreateConstGEP2_64(GV, 0, 0));
769 }
770 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000771 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000772 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000773
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000774 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000775 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000776}
Bill Wendling77b19132012-05-28 06:10:56 +0000777
778void GCOVProfiler::insertIndirectCounterIncrement() {
779 Function *Fn =
780 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
781 Fn->setUnnamedAddr(true);
782 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000783 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000784 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000785 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000786
Bill Wendling77b19132012-05-28 06:10:56 +0000787 // Create basic blocks for function.
788 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
789 IRBuilder<> Builder(BB);
790
791 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
792 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
793 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
794
795 // uint32_t pred = *predecessor;
796 // if (pred == 0xffffffff) return;
797 Argument *Arg = Fn->arg_begin();
798 Arg->setName("predecessor");
799 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000800 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000801 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
802
803 Builder.SetInsertPoint(PredNotNegOne);
804
805 // uint64_t *counter = counters[pred];
806 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000807 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000808 Arg = llvm::next(Fn->arg_begin());
809 Arg->setName("counters");
810 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
811 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000812 Cond = Builder.CreateICmpEQ(Counter,
813 Constant::getNullValue(
814 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000815 Builder.CreateCondBr(Cond, Exit, CounterEnd);
816
817 // ++*counter;
818 Builder.SetInsertPoint(CounterEnd);
819 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000820 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000821 Builder.CreateStore(Add, Counter);
822 Builder.CreateBr(Exit);
823
824 // Fill in the exit block.
825 Builder.SetInsertPoint(Exit);
826 Builder.CreateRetVoid();
827}
Bill Wendling253353c2012-09-13 00:09:55 +0000828
Bill Wendlingd195eb62013-03-18 23:04:39 +0000829Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000830insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
831 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000832 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000833 if (!FlushF)
834 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000835 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000836 else
837 FlushF->setLinkage(GlobalValue::InternalLinkage);
838 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000839 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000840 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000841 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000842
Bill Wendling253353c2012-09-13 00:09:55 +0000843 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
844
845 // Write out the current counters.
846 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
847 assert(WriteoutF && "Need to create the writeout function first!");
848
849 IRBuilder<> Builder(Entry);
850 Builder.CreateCall(WriteoutF);
851
Bill Wendling032dbee2012-09-13 14:32:30 +0000852 // Zero out the counters.
853 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
854 I = CountersBySP.begin(), E = CountersBySP.end();
855 I != E; ++I) {
856 GlobalVariable *GV = I->first;
857 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000858 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000859 }
Bill Wendling253353c2012-09-13 00:09:55 +0000860
861 Type *RetTy = FlushF->getReturnType();
862 if (RetTy == Type::getVoidTy(*Ctx))
863 Builder.CreateRetVoid();
864 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000865 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000866 Builder.CreateRet(ConstantInt::get(RetTy, 0));
867 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000868 report_fatal_error("invalid return type for __llvm_gcov_flush");
869
870 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000871}