blob: 206bffbb274e1f04e3dfb570d9f28d3adbaac3ad [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"
Nick Lewyckyb1928702011-04-16 01:20:23 +000020#include "llvm/ADT/DenseMap.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000023#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/UniqueVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Pass.h"
Nick Lewyckya204ef32013-03-14 05:13:26 +000031#include "llvm/Support/CommandLine.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/DebugLoc.h"
Bill Wendling39c41c32013-03-26 22:47:50 +000034#include "llvm/Support/FileSystem.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000035#include "llvm/Support/InstIterator.h"
Rafael Espindolaa11c3e22013-06-11 22:21:28 +000036#include "llvm/Support/Path.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000037#include "llvm/Support/raw_ostream.h"
38#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyc4e6b542013-06-18 06:38:21 +000039#include <algorithm>
Nick Lewyckyb1928702011-04-16 01:20:23 +000040#include <string>
41#include <utility>
42using namespace llvm;
43
Nick Lewyckya204ef32013-03-14 05:13:26 +000044static cl::opt<std::string>
45DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
46 cl::ValueRequired);
47
48GCOVOptions GCOVOptions::getDefault() {
49 GCOVOptions Options;
50 Options.EmitNotes = true;
51 Options.EmitData = true;
52 Options.UseCfgChecksum = false;
53 Options.NoRedZone = false;
54 Options.FunctionNamesInData = true;
55
56 if (DefaultGCOVVersion.size() != 4) {
57 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
58 DefaultGCOVVersion);
59 }
60 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
61 return Options;
62}
63
Nick Lewyckyb1928702011-04-16 01:20:23 +000064namespace {
65 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000066 public:
67 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000068 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
69 ReversedVersion[0] = Options.Version[3];
70 ReversedVersion[1] = Options.Version[2];
71 ReversedVersion[2] = Options.Version[1];
72 ReversedVersion[3] = Options.Version[0];
73 ReversedVersion[4] = '\0';
Nick Lewyckya61e52c2011-04-21 01:56:25 +000074 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
75 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000076 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
77 assert((Options.EmitNotes || Options.EmitData) &&
78 "GCOVProfiler asked to do nothing?");
79 ReversedVersion[0] = Options.Version[3];
80 ReversedVersion[1] = Options.Version[2];
81 ReversedVersion[2] = Options.Version[1];
82 ReversedVersion[3] = Options.Version[0];
83 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000084 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
85 }
86 virtual const char *getPassName() const {
87 return "GCOV Profiler";
88 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000089
Nick Lewyckyb1928702011-04-16 01:20:23 +000090 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000091 bool runOnModule(Module &M);
92
Nick Lewycky64a0a332013-03-13 22:55:42 +000093 // Create the .gcno files for the Module based on DebugInfo.
94 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000095
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000096 // Modify the program to track transitions along edges and call into the
97 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000098 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000099
Nick Lewyckyb1928702011-04-16 01:20:23 +0000100 // Get pointers to the functions in the runtime library.
101 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000102 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000103 Constant *getEmitFunctionFunc();
104 Constant *getEmitArcsFunc();
Yuchen Wuf42264e2013-11-12 04:59:08 +0000105 Constant *getSummaryInfoFunc();
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:
Craig Topperd6d6a972013-07-17 03:43:10 +0000157 static const char *const LinesTag;
158 static const char *const FunctionTag;
159 static const char *const BlockTag;
160 static const char *const 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
Craig Topper619850c2013-07-17 03:54:53 +0000174 static 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 };
Craig Topperd6d6a972013-07-17 03:43:10 +0000194 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
195 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
196 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
197 const char *const 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
Craig Topper619850c2013-07-17 03:54:53 +0000211 uint32_t length() const {
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);
Craig Topper6227d5c2013-07-04 01:31:24 +0000274 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000275 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,
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000429 sys::fs::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 Rencbafae62013-06-28 05:43:10 +0000437 assert((!SP || SP.isSubprogram()) &&
438 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
439 if (!SP)
440 continue;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000441
442 Function *F = SP.getFunction();
443 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000444 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000445
446 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
447 GCOVBlock &Block = Func.getBlock(BB);
448 TerminatorInst *TI = BB->getTerminator();
449 if (int successors = TI->getNumSuccessors()) {
450 for (int i = 0; i != successors; ++i) {
451 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
452 }
453 } else if (isa<ReturnInst>(TI)) {
454 Block.addEdge(Func.getReturnBlock());
455 }
456
457 uint32_t Line = 0;
458 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
459 I != IE; ++I) {
460 const DebugLoc &Loc = I->getDebugLoc();
461 if (Loc.isUnknown()) continue;
462 if (Line == Loc.getLine()) continue;
463 Line = Loc.getLine();
464 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
465
466 GCOVLines &Lines = Block.getFile(SP.getFilename());
467 Lines.addLine(Loc.getLine());
468 }
469 }
470 Func.writeOut();
471 }
472 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
473 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000474 }
475}
476
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000477bool GCOVProfiler::emitProfileArcs() {
478 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
479 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000480
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000481 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000482 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000483 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
484 DICompileUnit CU(CU_Nodes->getOperand(i));
485 DIArray SPs = CU.getSubprograms();
486 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
487 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
488 DISubprogram SP(SPs.getElement(i));
Manman Rencbafae62013-06-28 05:43:10 +0000489 assert((!SP || SP.isSubprogram()) &&
490 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
491 if (!SP)
492 continue;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000493 Function *F = SP.getFunction();
494 if (!F) continue;
495 if (!Result) Result = true;
496 unsigned Edges = 0;
497 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
498 TerminatorInst *TI = BB->getTerminator();
499 if (isa<ReturnInst>(TI))
500 ++Edges;
501 else
502 Edges += TI->getNumSuccessors();
503 }
504
505 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000506 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000507 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000508 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000509 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000510 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000511 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000512 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
513
514 UniqueVector<BasicBlock *> ComplexEdgePreds;
515 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
516
517 unsigned Edge = 0;
518 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
519 TerminatorInst *TI = BB->getTerminator();
520 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
521 if (Successors) {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000522 if (Successors == 1) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000523 IRBuilder<> Builder(BB->getFirstInsertionPt());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000524 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
525 Edge);
526 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000527 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000528 Builder.CreateStore(Count, Counter);
529 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000530 IRBuilder<> Builder(BI);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000531 Value *Sel = Builder.CreateSelect(BI->getCondition(),
532 Builder.getInt64(Edge),
533 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000534 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000535 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000536 Idx.push_back(Sel);
537 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
538 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000539 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000540 Builder.CreateStore(Count, Counter);
541 } else {
542 ComplexEdgePreds.insert(BB);
543 for (int i = 0; i != Successors; ++i)
544 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
545 }
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000546
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000547 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000548 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000549 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000550
551 if (!ComplexEdgePreds.empty()) {
552 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000553 buildEdgeLookupTable(F, Counters,
554 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000555 GlobalVariable *EdgeState = getEdgeStateValue();
556
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000557 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000558 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000559 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000560 }
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000561
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000562 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000563 // Call runtime to perform increment.
564 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000565 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000566 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
567 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000568
569 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000570 InsertIndCounterIncrCode = true;
571 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
572 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000573 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000574 }
575 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000576
Bill Wendlingd195eb62013-03-18 23:04:39 +0000577 Function *WriteoutF = insertCounterWriteout(CountersBySP);
578 Function *FlushF = insertFlush(CountersBySP);
579
580 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling18764712013-03-19 21:03:22 +0000581 // be executed at exit and the "__llvm_gcov_flush" function to be executed
582 // when "__gcov_flush" is called.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000583 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
584 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
585 "__llvm_gcov_init", M);
586 F->setUnnamedAddr(true);
587 F->setLinkage(GlobalValue::InternalLinkage);
588 F->addFnAttr(Attribute::NoInline);
589 if (Options.NoRedZone)
590 F->addFnAttr(Attribute::NoRedZone);
591
592 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
593 IRBuilder<> Builder(BB);
594
Bill Wendlingd195eb62013-03-18 23:04:39 +0000595 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling8640c6a2013-03-20 21:13:59 +0000596 Type *Params[] = {
597 PointerType::get(FTy, 0),
598 PointerType::get(FTy, 0)
599 };
600 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling18764712013-03-19 21:03:22 +0000601
Yuchen Wud7da5902013-10-23 20:35:00 +0000602 // Initialize the environment and register the local writeout and flush
Bill Wendling8640c6a2013-03-20 21:13:59 +0000603 // functions.
604 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
605 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000606 Builder.CreateRetVoid();
607
608 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000609 }
Bill Wendling77b19132012-05-28 06:10:56 +0000610
611 if (InsertIndCounterIncrCode)
612 insertIndirectCounterIncrement();
613
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000614 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000615}
616
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000617// All edges with successors that aren't branches are "complex", because it
618// requires complex logic to pick which counter to update.
619GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
620 Function *F,
621 GlobalVariable *Counters,
622 const UniqueVector<BasicBlock *> &Preds,
623 const UniqueVector<BasicBlock *> &Succs) {
624 // TODO: support invoke, threads. We rely on the fact that nothing can modify
625 // the whole-Module pred edge# between the time we set it and the time we next
626 // read it. Threads and invoke make this untrue.
627
628 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000629 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000630 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000631 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000632
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000633 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000634 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000635 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000636 EdgeTable[i] = NullValue;
637
638 unsigned Edge = 0;
639 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
640 TerminatorInst *TI = BB->getTerminator();
641 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000642 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000643 for (int i = 0; i != Successors; ++i) {
644 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000645 IRBuilder<> Builder(Succ);
646 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000647 Edge + i);
648 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
649 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
650 }
651 }
652 Edge += Successors;
653 }
654
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000655 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000656 GlobalVariable *EdgeTableGV =
657 new GlobalVariable(
658 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000659 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000660 "__llvm_gcda_edge_table");
661 EdgeTableGV->setUnnamedAddr(true);
662 return EdgeTableGV;
663}
664
Nick Lewyckyb1928702011-04-16 01:20:23 +0000665Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000666 Type *Args[] = {
667 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
668 Type::getInt8PtrTy(*Ctx), // const char version[4]
669 };
670 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000671 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
672}
673
Bill Wendling77b19132012-05-28 06:10:56 +0000674Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
675 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000676 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000677 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000678 Int32Ty->getPointerTo(), // uint32_t *predecessor
679 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000680 };
681 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
682 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000683}
684
685Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000686 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000687 Type::getInt32Ty(*Ctx), // uint32_t ident
688 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000689 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000690 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000691 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000692 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000693}
694
695Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000696 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000697 Type::getInt32Ty(*Ctx), // uint32_t num_counters
698 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
699 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000700 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000701 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000702}
703
Yuchen Wuf42264e2013-11-12 04:59:08 +0000704Constant *GCOVProfiler::getSummaryInfoFunc() {
705 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
706 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
707}
708
Bill Wendling18764712013-03-19 21:03:22 +0000709Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
710 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
711 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
712}
713
Bill Wendlingd195eb62013-03-18 23:04:39 +0000714Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
715 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
716 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
717}
718
Nick Lewyckyb1928702011-04-16 01:20:23 +0000719Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000720 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000721 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000722}
723
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000724GlobalVariable *GCOVProfiler::getEdgeStateValue() {
725 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
726 if (!GV) {
727 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
728 GlobalValue::InternalLinkage,
729 ConstantInt::get(Type::getInt32Ty(*Ctx),
730 0xffffffff),
731 "__llvm_gcov_global_state_pred");
732 GV->setUnnamedAddr(true);
733 }
734 return GV;
735}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000736
Bill Wendlingd195eb62013-03-18 23:04:39 +0000737Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000738 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000739 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
740 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
741 if (!WriteoutF)
742 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
743 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000744 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000745 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000746 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000747 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000748
749 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000750 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000751
752 Constant *StartFile = getStartFileFunc();
753 Constant *EmitFunction = getEmitFunctionFunc();
754 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wuf42264e2013-11-12 04:59:08 +0000755 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000756 Constant *EndFile = getEndFileFunc();
757
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000758 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
759 if (CU_Nodes) {
760 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000761 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendlingf2a28062013-03-28 22:40:08 +0000762 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000763 Builder.CreateCall2(StartFile,
764 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000765 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000766 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
767 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000768 Builder.CreateCall3(
769 EmitFunction, Builder.getInt32(j),
770 Options.FunctionNamesInData ?
771 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
772 Constant::getNullValue(Builder.getInt8PtrTy()),
773 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000774
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000775 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000776 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000777 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000778 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000779 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000780 Builder.CreateConstGEP2_64(GV, 0, 0));
781 }
Yuchen Wuf42264e2013-11-12 04:59:08 +0000782 Builder.CreateCall(SummaryInfo);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000783 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000784 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000785 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000786
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000787 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000788 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000789}
Bill Wendling77b19132012-05-28 06:10:56 +0000790
791void GCOVProfiler::insertIndirectCounterIncrement() {
792 Function *Fn =
793 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
794 Fn->setUnnamedAddr(true);
795 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000796 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000797 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000798 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000799
Bill Wendling77b19132012-05-28 06:10:56 +0000800 // Create basic blocks for function.
801 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
802 IRBuilder<> Builder(BB);
803
804 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
805 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
806 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
807
808 // uint32_t pred = *predecessor;
809 // if (pred == 0xffffffff) return;
810 Argument *Arg = Fn->arg_begin();
811 Arg->setName("predecessor");
812 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000813 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000814 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
815
816 Builder.SetInsertPoint(PredNotNegOne);
817
818 // uint64_t *counter = counters[pred];
819 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000820 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000821 Arg = llvm::next(Fn->arg_begin());
822 Arg->setName("counters");
823 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
824 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000825 Cond = Builder.CreateICmpEQ(Counter,
826 Constant::getNullValue(
827 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000828 Builder.CreateCondBr(Cond, Exit, CounterEnd);
829
830 // ++*counter;
831 Builder.SetInsertPoint(CounterEnd);
832 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000833 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000834 Builder.CreateStore(Add, Counter);
835 Builder.CreateBr(Exit);
836
837 // Fill in the exit block.
838 Builder.SetInsertPoint(Exit);
839 Builder.CreateRetVoid();
840}
Bill Wendling253353c2012-09-13 00:09:55 +0000841
Bill Wendlingd195eb62013-03-18 23:04:39 +0000842Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000843insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
844 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000845 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000846 if (!FlushF)
847 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000848 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000849 else
850 FlushF->setLinkage(GlobalValue::InternalLinkage);
851 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000852 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000853 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000854 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000855
Bill Wendling253353c2012-09-13 00:09:55 +0000856 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
857
858 // Write out the current counters.
859 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
860 assert(WriteoutF && "Need to create the writeout function first!");
861
862 IRBuilder<> Builder(Entry);
863 Builder.CreateCall(WriteoutF);
864
Bill Wendling032dbee2012-09-13 14:32:30 +0000865 // Zero out the counters.
866 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
867 I = CountersBySP.begin(), E = CountersBySP.end();
868 I != E; ++I) {
869 GlobalVariable *GV = I->first;
870 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000871 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000872 }
Bill Wendling253353c2012-09-13 00:09:55 +0000873
874 Type *RetTy = FlushF->getReturnType();
875 if (RetTy == Type::getVoidTy(*Ctx))
876 Builder.CreateRetVoid();
877 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000878 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000879 Builder.CreateRet(ConstantInt::get(RetTy, 0));
880 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000881 report_fatal_error("invalid return type for __llvm_gcov_flush");
882
883 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000884}