blob: 7447cb8c23c35f54296739383ba0786a90457de0 [file] [log] [blame]
Nick Lewycky966edd02011-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
Nick Lewycky966edd02011-04-16 01:20:23 +000017#include "llvm/ADT/DenseMap.h"
Yuchen Wubabe7492013-11-20 04:15:05 +000018#include "llvm/ADT/Hashing.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth71c3a3f2018-05-02 22:24:39 +000020#include "llvm/ADT/Sequence.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000021#include "llvm/ADT/Statistic.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000022#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/StringMap.h"
24#include "llvm/ADT/UniqueVector.h"
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +000025#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000026#include "llvm/IR/DebugInfo.h"
Chandler Carruth92051402014-03-05 10:30:38 +000027#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000029#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Instructions.h"
Bob Wilson055a0b42014-01-31 05:24:01 +000031#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Pass.h"
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000035#include "llvm/Support/Debug.h"
Bill Wendling5aa82392013-03-26 22:47:50 +000036#include "llvm/Support/FileSystem.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000037#include "llvm/Support/Path.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000038#include "llvm/Support/raw_ostream.h"
Xinliang David Li64dbb292016-06-05 05:12:23 +000039#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth71c3a3f2018-05-02 22:24:39 +000040#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000041#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewycky0fdd0192013-06-18 06:38:21 +000042#include <algorithm>
David Blaikie229de502014-04-21 20:41:55 +000043#include <memory>
Nick Lewycky966edd02011-04-16 01:20:23 +000044#include <string>
45#include <utility>
46using namespace llvm;
47
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "insert-gcov-profiling"
49
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000050static cl::opt<std::string>
51DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
52 cl::ValueRequired);
Justin Bogner3faa76b2015-03-16 23:52:03 +000053static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
54 cl::init(false), cl::Hidden);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000055
56GCOVOptions GCOVOptions::getDefault() {
57 GCOVOptions Options;
58 Options.EmitNotes = true;
59 Options.EmitData = true;
60 Options.UseCfgChecksum = false;
61 Options.NoRedZone = false;
62 Options.FunctionNamesInData = true;
Justin Bogner3faa76b2015-03-16 23:52:03 +000063 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000064
65 if (DefaultGCOVVersion.size() != 4) {
66 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
67 DefaultGCOVVersion);
68 }
69 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
70 return Options;
71}
72
Nick Lewycky966edd02011-04-16 01:20:23 +000073namespace {
Xinliang David Lifb3137c2016-06-05 03:40:03 +000074class GCOVFunction;
Yuchen Wubabe7492013-11-20 04:15:05 +000075
Xinliang David Lifb3137c2016-06-05 03:40:03 +000076class GCOVProfiler {
77public:
78 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
79 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
80 assert((Options.EmitNotes || Options.EmitData) &&
81 "GCOVProfiler asked to do nothing?");
82 ReversedVersion[0] = Options.Version[3];
83 ReversedVersion[1] = Options.Version[2];
84 ReversedVersion[2] = Options.Version[1];
85 ReversedVersion[3] = Options.Version[0];
86 ReversedVersion[4] = '\0';
87 }
88 bool runOnModule(Module &M);
Benjamin Kramer298a3a02015-03-06 16:21:15 +000089
Xinliang David Lifb3137c2016-06-05 03:40:03 +000090private:
91 // Create the .gcno files for the Module based on DebugInfo.
92 void emitProfileNotes();
Nick Lewycky6d9f0612011-05-04 04:03:04 +000093
Xinliang David Lifb3137c2016-06-05 03:40:03 +000094 // Modify the program to track transitions along edges and call into the
95 // profiling runtime to emit .gcda files when run.
96 bool emitProfileArcs();
Nick Lewycky966edd02011-04-16 01:20:23 +000097
Xinliang David Lifb3137c2016-06-05 03:40:03 +000098 // Get pointers to the functions in the runtime library.
99 Constant *getStartFileFunc();
100 Constant *getIncrementIndirectCounterFunc();
101 Constant *getEmitFunctionFunc();
102 Constant *getEmitArcsFunc();
103 Constant *getSummaryInfoFunc();
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000104 Constant *getEndFileFunc();
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000105
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000106 // Create or retrieve an i32 state value that is used to represent the
107 // pred block number for certain non-trivial edges.
108 GlobalVariable *getEdgeStateValue();
Nick Lewycky966edd02011-04-16 01:20:23 +0000109
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000110 // Produce a table of pointers to counters, by predecessor and successor
111 // block number.
112 GlobalVariable *buildEdgeLookupTable(Function *F, GlobalVariable *Counter,
113 const UniqueVector<BasicBlock *> &Preds,
114 const UniqueVector<BasicBlock *> &Succs);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000115
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000116 // Add the function to write out all our counters to the global destructor
117 // list.
118 Function *
119 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
120 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
121 void insertIndirectCounterIncrement();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000122
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000123 enum class GCovFileType { GCNO, GCDA };
124 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
Nick Lewycky966edd02011-04-16 01:20:23 +0000125
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000126 GCOVOptions Options;
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000127
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000128 // Reversed, NUL-terminated copy of Options.Version.
129 char ReversedVersion[5];
130 // Checksum, produced by hash of EdgeDestinations
131 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000132
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000133 Module *M;
134 LLVMContext *Ctx;
135 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
136};
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000137
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000138class GCOVProfilerLegacyPass : public ModulePass {
139public:
140 static char ID;
141 GCOVProfilerLegacyPass()
142 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
143 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
144 : ModulePass(ID), Profiler(Opts) {
145 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
146 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000147 StringRef getPassName() const override { return "GCOV Profiler"; }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000148
149 bool runOnModule(Module &M) override { return Profiler.runOnModule(M); }
150
151private:
152 GCOVProfiler Profiler;
153};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000154}
Nick Lewycky966edd02011-04-16 01:20:23 +0000155
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000156char GCOVProfilerLegacyPass::ID = 0;
157INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling",
Nick Lewycky966edd02011-04-16 01:20:23 +0000158 "Insert instrumentation for GCOV profiling", false, false)
159
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000160ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000161 return new GCOVProfilerLegacyPass(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000162}
Nick Lewycky966edd02011-04-16 01:20:23 +0000163
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000164static StringRef getFunctionName(const DISubprogram *SP) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000165 if (!SP->getLinkageName().empty())
166 return SP->getLinkageName();
167 return SP->getName();
Nick Lewyckyd6718632013-03-19 01:37:55 +0000168}
169
Nick Lewycky966edd02011-04-16 01:20:23 +0000170namespace {
171 class GCOVRecord {
172 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000173 static const char *const LinesTag;
174 static const char *const FunctionTag;
175 static const char *const BlockTag;
176 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000177
Benjamin Kramer79de6e62015-04-11 18:57:14 +0000178 GCOVRecord() = default;
Nick Lewycky966edd02011-04-16 01:20:23 +0000179
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000180 void writeBytes(const char *Bytes, int Size) {
181 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000182 }
183
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000184 void write(uint32_t i) {
185 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000186 }
187
188 // Returns the length measured in 4-byte blocks that will be used to
189 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000190 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000191 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000192 // padding out to the next 4-byte word. The length is measured in 4-byte
193 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000194 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000195 }
196
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000197 void writeGCOVString(StringRef s) {
198 uint32_t Len = lengthOfGCOVString(s);
199 write(Len);
200 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000201
202 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000203 assert((unsigned)(4 - (s.size() % 4)) > 0);
204 assert((unsigned)(4 - (s.size() % 4)) <= 4);
205 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000206 }
207
208 raw_ostream *os;
209 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000210 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
211 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
212 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
213 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000214
215 class GCOVFunction;
216 class GCOVBlock;
217
218 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000219 // list of line numbers and a single filename, representing lines that belong
220 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000221 class GCOVLines : public GCOVRecord {
222 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000223 void addLine(uint32_t Line) {
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000224 assert(Line != 0 && "Line zero is not a valid real line number.");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000225 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000226 }
227
Craig Topper24048c92013-07-17 03:54:53 +0000228 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000229 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000230 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000231 }
232
Devang Pateladd1f172011-09-20 18:35:00 +0000233 void writeOut() {
234 write(0);
235 writeGCOVString(Filename);
236 for (int i = 0, e = Lines.size(); i != e; ++i)
237 write(Lines[i]);
238 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000239
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000240 GCOVLines(StringRef F, raw_ostream *os)
Devang Pateladd1f172011-09-20 18:35:00 +0000241 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000242 this->os = os;
243 }
244
Devang Patel7d06f5c2011-09-20 18:48:56 +0000245 private:
Devang Pateladd1f172011-09-20 18:35:00 +0000246 StringRef Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000247 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000248 };
249
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000250
Nick Lewycky966edd02011-04-16 01:20:23 +0000251 // Represent a basic block in GCOV. Each block has a unique number in the
252 // function, number of lines belonging to each block, and a set of edges to
253 // other blocks.
254 class GCOVBlock : public GCOVRecord {
255 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000256 GCOVLines &getFile(StringRef Filename) {
Benjamin Kramereab3d362016-07-21 13:37:48 +0000257 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000258 }
259
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000260 void addEdge(GCOVBlock &Successor) {
261 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000262 }
263
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000264 void writeOut() {
265 uint32_t Len = 3;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000266 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000267 for (auto &I : LinesByFile) {
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000268 Len += I.second.length();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000269 SortedLinesByFile.push_back(&I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000270 }
271
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000272 writeBytes(LinesTag, 4);
273 write(Len);
274 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000275
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000276 llvm::sort(
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000277 SortedLinesByFile.begin(), SortedLinesByFile.end(),
278 [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
279 return LHS->getKey() < RHS->getKey();
280 });
Benjamin Kramer135f7352016-06-26 12:28:59 +0000281 for (auto &I : SortedLinesByFile)
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000282 I->getValue().writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000283 write(0);
284 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000285 }
286
David Blaikieea37c112014-12-22 23:12:42 +0000287 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
288 // Only allow copy before edges and lines have been added. After that,
289 // there are inter-block pointers (eg: edges) that won't take kindly to
290 // blocks being copied or moved around.
291 assert(LinesByFile.empty());
292 assert(OutEdges.empty());
293 }
294
Nick Lewycky966edd02011-04-16 01:20:23 +0000295 private:
296 friend class GCOVFunction;
297
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000298 GCOVBlock(uint32_t Number, raw_ostream *os)
299 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000300 this->os = os;
301 }
302
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000303 uint32_t Number;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000304 StringMap<GCOVLines> LinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000305 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000306 };
307
308 // A function has a unique identifier, a checksum (we leave as zero) and a
309 // set of blocks and a map of edges between blocks. This is the only GCOV
310 // object users can construct, the blocks and lines will be rooted here.
311 class GCOVFunction : public GCOVRecord {
312 public:
Peter Collingbourned4bff302015-11-05 22:03:56 +0000313 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
314 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
David Blaikieea37c112014-12-22 23:12:42 +0000315 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
316 ReturnBlock(1, os) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000317 this->os = os;
318
Daniel Jasper87a24d52013-12-04 08:57:17 +0000319 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewycky2e8a6212014-12-03 02:45:01 +0000320
David Blaikieea37c112014-12-22 23:12:42 +0000321 uint32_t i = 0;
322 for (auto &BB : *F) {
Justin Bogner3faa76b2015-03-16 23:52:03 +0000323 // Skip index 1 if it's assigned to the ReturnBlock.
324 if (i == 1 && ExitBlockBeforeBody)
325 ++i;
326 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
Nick Lewycky966edd02011-04-16 01:20:23 +0000327 }
Justin Bogner3faa76b2015-03-16 23:52:03 +0000328 if (!ExitBlockBeforeBody)
329 ReturnBlock.Number = i;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000330
Alp Tokere69170a2014-06-26 22:52:05 +0000331 std::string FunctionNameAndLine;
332 raw_string_ostream FNLOS(FunctionNameAndLine);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000333 FNLOS << getFunctionName(SP) << SP->getLine();
Alp Tokere69170a2014-06-26 22:52:05 +0000334 FNLOS.flush();
335 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewycky966edd02011-04-16 01:20:23 +0000336 }
337
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000338 GCOVBlock &getBlock(BasicBlock *BB) {
David Blaikieea37c112014-12-22 23:12:42 +0000339 return Blocks.find(BB)->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000340 }
341
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000342 GCOVBlock &getReturnBlock() {
David Blaikieea37c112014-12-22 23:12:42 +0000343 return ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000344 }
345
Yuchen Wubabe7492013-11-20 04:15:05 +0000346 std::string getEdgeDestinations() {
Alp Tokere69170a2014-06-26 22:52:05 +0000347 std::string EdgeDestinations;
348 raw_string_ostream EDOS(EdgeDestinations);
Yuchen Wubabe7492013-11-20 04:15:05 +0000349 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000350 for (BasicBlock &I : *F) {
351 GCOVBlock &Block = getBlock(&I);
Yuchen Wubabe7492013-11-20 04:15:05 +0000352 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
Alp Tokere69170a2014-06-26 22:52:05 +0000353 EDOS << Block.OutEdges[i]->Number;
Yuchen Wubabe7492013-11-20 04:15:05 +0000354 }
Alp Tokere69170a2014-06-26 22:52:05 +0000355 return EdgeDestinations;
Yuchen Wubabe7492013-11-20 04:15:05 +0000356 }
357
Daniel Jasper87a24d52013-12-04 08:57:17 +0000358 uint32_t getFuncChecksum() {
359 return FuncChecksum;
360 }
361
Yuchen Wubabe7492013-11-20 04:15:05 +0000362 void setCfgChecksum(uint32_t Checksum) {
363 CfgChecksum = Checksum;
364 }
365
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000366 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000367 writeBytes(FunctionTag, 4);
368 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000369 1 + lengthOfGCOVString(SP->getFilename()) + 1;
Yuchen Wubabe7492013-11-20 04:15:05 +0000370 if (UseCfgChecksum)
371 ++BlockLen;
372 write(BlockLen);
373 write(Ident);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000374 write(FuncChecksum);
Yuchen Wubabe7492013-11-20 04:15:05 +0000375 if (UseCfgChecksum)
376 write(CfgChecksum);
377 writeGCOVString(getFunctionName(SP));
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000378 writeGCOVString(SP->getFilename());
379 write(SP->getLine());
Yuchen Wubabe7492013-11-20 04:15:05 +0000380
Nick Lewycky966edd02011-04-16 01:20:23 +0000381 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000382 writeBytes(BlockTag, 4);
383 write(Blocks.size() + 1);
384 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
385 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000386 }
Nick Lewycky6404d972011-11-27 23:22:20 +0000387 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000388
389 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000390 if (Blocks.empty()) return;
391 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000392 for (BasicBlock &I : *F) {
393 GCOVBlock &Block = getBlock(&I);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000394 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000395
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000396 writeBytes(EdgeTag, 4);
397 write(Block.OutEdges.size() * 2 + 1);
398 write(Block.Number);
399 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewycky6404d972011-11-27 23:22:20 +0000400 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
401 << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000402 write(Block.OutEdges[i]->Number);
403 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000404 }
405 }
406
407 // Emit lines for each block.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000408 for (BasicBlock &I : *F)
409 getBlock(&I).writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000410 }
411
412 private:
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000413 const DISubprogram *SP;
Yuchen Wubabe7492013-11-20 04:15:05 +0000414 uint32_t Ident;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000415 uint32_t FuncChecksum;
Yuchen Wubabe7492013-11-20 04:15:05 +0000416 bool UseCfgChecksum;
417 uint32_t CfgChecksum;
David Blaikieea37c112014-12-22 23:12:42 +0000418 DenseMap<BasicBlock *, GCOVBlock> Blocks;
419 GCOVBlock ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000420 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000421}
Nick Lewycky966edd02011-04-16 01:20:23 +0000422
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000423std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000424 GCovFileType OutputType) {
425 bool Notes = OutputType == GCovFileType::GCNO;
426
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000427 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
428 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000429 MDNode *N = GCov->getOperand(i);
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000430 bool ThreeElement = N->getNumOperands() == 3;
431 if (!ThreeElement && N->getNumOperands() != 2)
432 continue;
Nick Lewycky8dd4dad2016-08-31 23:24:43 +0000433 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000434 continue;
435
436 if (ThreeElement) {
437 // These nodes have no mangling to apply, it's stored mangled in the
438 // bitcode.
439 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
440 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
441 if (!NotesFile || !DataFile)
442 continue;
443 return Notes ? NotesFile->getString() : DataFile->getString();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000444 }
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000445
446 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
447 if (!GCovFile)
448 continue;
449
450 SmallString<128> Filename = GCovFile->getString();
451 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
452 return Filename.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000453 }
454 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000455
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000456 SmallString<128> Filename = CU->getFilename();
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000457 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
Bill Wendling5aa82392013-03-26 22:47:50 +0000458 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000459 SmallString<128> CurPath;
460 if (sys::fs::current_path(CurPath)) return FName;
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000461 sys::path::append(CurPath, FName);
Bill Wendling5aa82392013-03-26 22:47:50 +0000462 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000463}
464
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000465bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000466 this->M = &M;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000467 Ctx = &M.getContext();
468
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000469 if (Options.EmitNotes) emitProfileNotes();
470 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000471 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000472}
473
Xinliang David Li64dbb292016-06-05 05:12:23 +0000474PreservedAnalyses GCOVProfilerPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000475 ModuleAnalysisManager &AM) {
Xinliang David Li64dbb292016-06-05 05:12:23 +0000476
477 GCOVProfiler Profiler(GCOVOpts);
478
479 if (!Profiler.runOnModule(M))
480 return PreservedAnalyses::all();
481
482 return PreservedAnalyses::none();
483}
484
Adrian Prantl75819ae2016-04-15 15:57:41 +0000485static bool functionHasLines(Function &F) {
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000486 // Check whether this function actually has any source lines. Not only
487 // do these waste space, they also can crash gcov.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000488 for (auto &BB : F) {
489 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000490 // Debug intrinsic locations correspond to the location of the
491 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000492 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000493
Adrian Prantl75819ae2016-04-15 15:57:41 +0000494 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000495 if (!Loc)
496 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000497
498 // Artificial lines such as calls to the global constructors.
Justin Bogner3faa76b2015-03-16 23:52:03 +0000499 if (Loc.getLine() == 0) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000500
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000501 return true;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000502 }
503 }
504 return false;
505}
506
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000507static bool isUsingFuncletBasedEH(Function &F) {
508 if (!F.hasPersonalityFn()) return false;
509
510 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
511 return isFuncletEHPersonality(Personality);
512}
513
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000514static bool shouldKeepInEntry(BasicBlock::iterator It) {
515 if (isa<AllocaInst>(*It)) return true;
516 if (isa<DbgInfoIntrinsic>(*It)) return true;
517 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
518 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
519 }
520
521 return false;
522}
523
Nick Lewyckyad145502013-03-13 22:55:42 +0000524void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000525 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000526 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000527
Nick Lewycky6404d972011-11-27 23:22:20 +0000528 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
529 // Each compile unit gets its own .gcno file. This means that whether we run
530 // this pass over the original .o's as they're produced, or run it after
531 // LTO, we'll generate the same .gcno files.
532
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000533 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
Vedant Kumar61035fa2016-01-21 17:04:42 +0000534
535 // Skip module skeleton (and module) CUs.
536 if (CU->getDWOId())
537 continue;
538
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000539 std::error_code EC;
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000540 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
Reid Kleckner1aa4ea82017-09-18 21:31:48 +0000541 if (EC) {
542 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
543 EC.message());
544 continue;
545 }
546
Yuchen Wubabe7492013-11-20 04:15:05 +0000547 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000548
Justin Bogner58e41342014-11-06 06:55:02 +0000549 unsigned FunctionIdent = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000550 for (auto &F : M->functions()) {
551 DISubprogram *SP = F.getSubprogram();
552 if (!SP) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000553 if (!functionHasLines(F)) continue;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000554 // TODO: Functions using funclet-based EH are currently not supported.
555 if (isUsingFuncletBasedEH(F)) continue;
Bob Wilson055a0b42014-01-31 05:24:01 +0000556
557 // gcov expects every function to start with an entry block that has a
558 // single successor, so split the entry block to make sure of that.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000559 BasicBlock &EntryBlock = F.getEntryBlock();
Bob Wilson055a0b42014-01-31 05:24:01 +0000560 BasicBlock::iterator It = EntryBlock.begin();
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000561 while (shouldKeepInEntry(It))
Bob Wilson055a0b42014-01-31 05:24:01 +0000562 ++It;
563 EntryBlock.splitBasicBlock(It);
Yuchen Wuc87ca322013-11-22 23:07:45 +0000564
Adrian Prantl75819ae2016-04-15 15:57:41 +0000565 Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
Justin Bogner3faa76b2015-03-16 23:52:03 +0000566 Options.UseCfgChecksum,
567 Options.ExitBlockBeforeBody));
David Blaikie229de502014-04-21 20:41:55 +0000568 GCOVFunction &Func = *Funcs.back();
Nick Lewycky6404d972011-11-27 23:22:20 +0000569
Adrian Prantl75819ae2016-04-15 15:57:41 +0000570 for (auto &BB : F) {
571 GCOVBlock &Block = Func.getBlock(&BB);
572 TerminatorInst *TI = BB.getTerminator();
Nick Lewycky6404d972011-11-27 23:22:20 +0000573 if (int successors = TI->getNumSuccessors()) {
574 for (int i = 0; i != successors; ++i) {
David Blaikie229de502014-04-21 20:41:55 +0000575 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000576 }
577 } else if (isa<ReturnInst>(TI)) {
David Blaikie229de502014-04-21 20:41:55 +0000578 Block.addEdge(Func.getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000579 }
580
581 uint32_t Line = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000582 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000583 // Debug intrinsic locations correspond to the location of the
584 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000585 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000586
Adrian Prantl75819ae2016-04-15 15:57:41 +0000587 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000588 if (!Loc)
589 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000590
591 // Artificial lines such as calls to the global constructors.
592 if (Loc.getLine() == 0) continue;
593
Nick Lewycky6404d972011-11-27 23:22:20 +0000594 if (Line == Loc.getLine()) continue;
595 Line = Loc.getLine();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000596 if (SP != getDISubprogram(Loc.getScope()))
597 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000598
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000599 GCOVLines &Lines = Block.getFile(SP->getFilename());
Nick Lewycky6404d972011-11-27 23:22:20 +0000600 Lines.addLine(Loc.getLine());
601 }
602 }
David Blaikie229de502014-04-21 20:41:55 +0000603 EdgeDestinations += Func.getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000604 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000605
Yuchen Wu664dc762013-11-21 04:01:05 +0000606 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000607 out.write("oncg", 4);
608 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000609 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000610
David Blaikie229de502014-04-21 20:41:55 +0000611 for (auto &Func : Funcs) {
Yuchen Wu664dc762013-11-21 04:01:05 +0000612 Func->setCfgChecksum(FileChecksums.back());
613 Func->writeOut();
614 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000615
Nick Lewycky6404d972011-11-27 23:22:20 +0000616 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
617 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000618 }
619}
620
Devang Patel2b21d862011-08-17 22:49:38 +0000621bool GCOVProfiler::emitProfileArcs() {
622 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
623 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000624
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000625 bool Result = false;
Bill Wendling15605172012-05-28 06:10:56 +0000626 bool InsertIndCounterIncrCode = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000627 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Devang Patel2b21d862011-08-17 22:49:38 +0000628 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000629 for (auto &F : M->functions()) {
630 DISubprogram *SP = F.getSubprogram();
631 if (!SP) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000632 if (!functionHasLines(F)) continue;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000633 // TODO: Functions using funclet-based EH are currently not supported.
634 if (isUsingFuncletBasedEH(F)) continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000635 if (!Result) Result = true;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000636
Devang Patel2b21d862011-08-17 22:49:38 +0000637 unsigned Edges = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000638 for (auto &BB : F) {
639 TerminatorInst *TI = BB.getTerminator();
Devang Patel2b21d862011-08-17 22:49:38 +0000640 if (isa<ReturnInst>(TI))
641 ++Edges;
642 else
643 Edges += TI->getNumSuccessors();
644 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000645
Devang Patel2b21d862011-08-17 22:49:38 +0000646 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000647 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000648 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000649 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000650 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000651 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000652 "__llvm_gcov_ctr");
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000653 CountersBySP.push_back(std::make_pair(Counters, SP));
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000654
Devang Patel2b21d862011-08-17 22:49:38 +0000655 UniqueVector<BasicBlock *> ComplexEdgePreds;
656 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000657
Devang Patel2b21d862011-08-17 22:49:38 +0000658 unsigned Edge = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000659 for (auto &BB : F) {
660 TerminatorInst *TI = BB.getTerminator();
Devang Patel2b21d862011-08-17 22:49:38 +0000661 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
662 if (Successors) {
Devang Patel2b21d862011-08-17 22:49:38 +0000663 if (Successors == 1) {
Adrian Prantl75819ae2016-04-15 15:57:41 +0000664 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000665 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
666 Edge);
667 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000668 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000669 Builder.CreateStore(Count, Counter);
670 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Bill Wendling707f6012013-08-20 23:52:00 +0000671 IRBuilder<> Builder(BI);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000672 Value *Sel = Builder.CreateSelect(BI->getCondition(),
673 Builder.getInt64(Edge),
674 Builder.getInt64(Edge + 1));
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +0000675 Value *Counter = Builder.CreateInBoundsGEP(
676 Counters->getValueType(), Counters, {Builder.getInt64(0), Sel});
Devang Patel2b21d862011-08-17 22:49:38 +0000677 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000678 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000679 Builder.CreateStore(Count, Counter);
680 } else {
Adrian Prantl75819ae2016-04-15 15:57:41 +0000681 ComplexEdgePreds.insert(&BB);
Devang Patel2b21d862011-08-17 22:49:38 +0000682 for (int i = 0; i != Successors; ++i)
683 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
684 }
Bill Wendling707f6012013-08-20 23:52:00 +0000685
Devang Patel2b21d862011-08-17 22:49:38 +0000686 Edge += Successors;
Nick Lewycky966edd02011-04-16 01:20:23 +0000687 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000688 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000689
Devang Patel2b21d862011-08-17 22:49:38 +0000690 if (!ComplexEdgePreds.empty()) {
691 GlobalVariable *EdgeTable =
Adrian Prantl75819ae2016-04-15 15:57:41 +0000692 buildEdgeLookupTable(&F, Counters,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000693 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patel2b21d862011-08-17 22:49:38 +0000694 GlobalVariable *EdgeState = getEdgeStateValue();
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000695
Devang Patel2b21d862011-08-17 22:49:38 +0000696 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000697 IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
Nick Lewycky8e94d802013-02-27 05:46:30 +0000698 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patel2b21d862011-08-17 22:49:38 +0000699 }
Bill Wendling707f6012013-08-20 23:52:00 +0000700
Devang Patel2b21d862011-08-17 22:49:38 +0000701 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Bill Wendling707f6012013-08-20 23:52:00 +0000702 // Call runtime to perform increment.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000703 IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000704 Value *CounterPtrArray =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000705 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
706 i * ComplexEdgePreds.size());
Bill Wendling8ed07492012-05-25 23:55:00 +0000707
708 // Build code to increment the counter.
Bill Wendling15605172012-05-28 06:10:56 +0000709 InsertIndCounterIncrCode = true;
David Blaikieff6409d2015-05-18 22:13:54 +0000710 Builder.CreateCall(getIncrementIndirectCounterFunc(),
711 {EdgeState, CounterPtrArray});
Devang Patel2b21d862011-08-17 22:49:38 +0000712 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000713 }
714 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000715
Bill Wendlingc3cab812013-03-18 23:04:39 +0000716 Function *WriteoutF = insertCounterWriteout(CountersBySP);
717 Function *FlushF = insertFlush(CountersBySP);
718
719 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000720 // be executed at exit and the "__llvm_gcov_flush" function to be executed
721 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000722 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
723 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
724 "__llvm_gcov_init", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000725 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000726 F->setLinkage(GlobalValue::InternalLinkage);
727 F->addFnAttr(Attribute::NoInline);
728 if (Options.NoRedZone)
729 F->addFnAttr(Attribute::NoRedZone);
730
731 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
732 IRBuilder<> Builder(BB);
733
Bill Wendlingc3cab812013-03-18 23:04:39 +0000734 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000735 Type *Params[] = {
736 PointerType::get(FTy, 0),
737 PointerType::get(FTy, 0)
738 };
739 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000740
Yuchen Wu3197b252013-10-23 20:35:00 +0000741 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000742 // functions.
743 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000744 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
Bill Wendlingc3cab812013-03-18 23:04:39 +0000745 Builder.CreateRetVoid();
746
747 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000748 }
Bill Wendling15605172012-05-28 06:10:56 +0000749
750 if (InsertIndCounterIncrCode)
751 insertIndirectCounterIncrement();
752
Devang Patel2b21d862011-08-17 22:49:38 +0000753 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000754}
755
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000756// All edges with successors that aren't branches are "complex", because it
757// requires complex logic to pick which counter to update.
758GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
759 Function *F,
760 GlobalVariable *Counters,
761 const UniqueVector<BasicBlock *> &Preds,
762 const UniqueVector<BasicBlock *> &Succs) {
763 // TODO: support invoke, threads. We rely on the fact that nothing can modify
764 // the whole-Module pred edge# between the time we set it and the time we next
765 // read it. Threads and invoke make this untrue.
766
767 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000768 size_t TableSize = Succs.size() * Preds.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000769 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000770 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000771
Ahmed Charles56440fd2014-03-06 05:51:42 +0000772 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000773 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000774 for (size_t i = 0; i != TableSize; ++i)
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000775 EdgeTable[i] = NullValue;
776
777 unsigned Edge = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000778 for (BasicBlock &BB : *F) {
779 TerminatorInst *TI = BB.getTerminator();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000780 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky6aa79492011-04-28 21:35:49 +0000781 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000782 for (int i = 0; i != Successors; ++i) {
783 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000784 IRBuilder<> Builder(Succ);
785 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000786 Edge + i);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000787 EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
Benjamin Kramer135f7352016-06-26 12:28:59 +0000788 (Preds.idFor(&BB) - 1)] = cast<Constant>(Counter);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000789 }
790 }
791 Edge += Successors;
792 }
793
794 GlobalVariable *EdgeTableGV =
795 new GlobalVariable(
796 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Craig Toppere1d12942014-08-27 05:25:25 +0000797 ConstantArray::get(EdgeTableTy,
798 makeArrayRef(&EdgeTable[0],TableSize)),
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000799 "__llvm_gcda_edge_table");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000800 EdgeTableGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000801 return EdgeTableGV;
802}
803
Nick Lewycky966edd02011-04-16 01:20:23 +0000804Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000805 Type *Args[] = {
806 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
807 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000808 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000809 };
810 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000811 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
812}
813
Bill Wendling15605172012-05-28 06:10:56 +0000814Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
815 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendling8ed07492012-05-25 23:55:00 +0000816 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling15605172012-05-28 06:10:56 +0000817 Type *Args[] = {
Micah Villmow51e72462012-10-24 17:25:11 +0000818 Int32Ty->getPointerTo(), // uint32_t *predecessor
819 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling15605172012-05-28 06:10:56 +0000820 };
821 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
822 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000823}
824
825Constant *GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000826 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000827 Type::getInt32Ty(*Ctx), // uint32_t ident
828 Type::getInt8PtrTy(*Ctx), // const char *function_name
Daniel Jasper87a24d52013-12-04 08:57:17 +0000829 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000830 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000831 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000832 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000833 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000834 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000835}
836
837Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000838 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000839 Type::getInt32Ty(*Ctx), // uint32_t num_counters
840 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
841 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000842 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000843 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000844}
845
Yuchen Wu062f24c2013-11-12 04:59:08 +0000846Constant *GCOVProfiler::getSummaryInfoFunc() {
847 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
848 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
849}
850
Nick Lewycky966edd02011-04-16 01:20:23 +0000851Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000852 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000853 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000854}
855
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000856GlobalVariable *GCOVProfiler::getEdgeStateValue() {
857 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
858 if (!GV) {
859 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
860 GlobalValue::InternalLinkage,
861 ConstantInt::get(Type::getInt32Ty(*Ctx),
862 0xffffffff),
863 "__llvm_gcov_global_state_pred");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000864 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000865 }
866 return GV;
867}
Nick Lewycky966edd02011-04-16 01:20:23 +0000868
Bill Wendlingc3cab812013-03-18 23:04:39 +0000869Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000870 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000871 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
872 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
873 if (!WriteoutF)
874 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
875 "__llvm_gcov_writeout", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000876 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000877 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000878 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000879 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000880
881 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000882 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000883
884 Constant *StartFile = getStartFileFunc();
885 Constant *EmitFunction = getEmitFunctionFunc();
886 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000887 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000888 Constant *EndFile = getEndFileFunc();
889
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000890 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
891 if (!CUNodes) {
892 Builder.CreateRetVoid();
893 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000894 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000895
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000896 // Collect the relevant data into a large constant data structure that we can
897 // walk to write out everything.
898 StructType *StartFileCallArgsTy = StructType::create(
899 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
900 StructType *EmitFunctionCallArgsTy = StructType::create(
901 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
902 Builder.getInt8Ty(), Builder.getInt32Ty()});
903 StructType *EmitArcsCallArgsTy = StructType::create(
904 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
905 StructType *FileInfoTy =
906 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
907 EmitFunctionCallArgsTy->getPointerTo(),
908 EmitArcsCallArgsTy->getPointerTo()});
909
910 Constant *Zero32 = Builder.getInt32(0);
911
912 SmallVector<Constant *, 8> FileInfos;
913 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
914 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
915
916 // Skip module skeleton (and module) CUs.
917 if (CU->getDWOId())
918 continue;
919
920 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
921 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
922 auto *StartFileCallArgs = ConstantStruct::get(
923 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
924 Builder.CreateGlobalStringPtr(ReversedVersion),
925 Builder.getInt32(CfgChecksum)});
926
927 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
928 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
929 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
930 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
931 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
932 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
933 EmitFunctionCallArgsTy,
934 {Builder.getInt32(j),
935 Options.FunctionNamesInData
936 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
937 : Constant::getNullValue(Builder.getInt8PtrTy()),
938 Builder.getInt32(FuncChecksum),
939 Builder.getInt8(Options.UseCfgChecksum),
940 Builder.getInt32(CfgChecksum)}));
941
942 GlobalVariable *GV = CountersBySP[j].first;
943 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
944 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
945 EmitArcsCallArgsTy,
946 {Builder.getInt32(Arcs),
947 ConstantExpr::getInBoundsGetElementPtr(
948 GV->getValueType(), GV,
949 makeArrayRef<Constant *>({Zero32, Zero32}))}));
950 }
951 // Create global arrays for the two emit calls.
952 int CountersSize = CountersBySP.size();
953 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
954 "Mismatched array size!");
955 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
956 "Mismatched array size!");
957 auto *EmitFunctionCallArgsArrayTy =
958 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
959 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
960 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
961 GlobalValue::InternalLinkage,
962 ConstantArray::get(EmitFunctionCallArgsArrayTy,
963 EmitFunctionCallArgsArray),
964 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
965 auto *EmitArcsCallArgsArrayTy =
966 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
967 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
968 GlobalValue::UnnamedAddr::Global);
969 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
970 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
971 GlobalValue::InternalLinkage,
972 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
973 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
974 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
975
976 FileInfos.push_back(ConstantStruct::get(
977 FileInfoTy,
978 {StartFileCallArgs, Builder.getInt32(CountersSize),
979 ConstantExpr::getInBoundsGetElementPtr(
980 EmitFunctionCallArgsArrayTy, EmitFunctionCallArgsArrayGV,
981 makeArrayRef<Constant *>({Zero32, Zero32})),
982 ConstantExpr::getInBoundsGetElementPtr(
983 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV,
984 makeArrayRef<Constant *>({Zero32, Zero32}))}));
985 }
986
987 // If we didn't find anything to actually emit, bail on out.
988 if (FileInfos.empty()) {
989 Builder.CreateRetVoid();
990 return WriteoutF;
991 }
992
993 // To simplify code, we cap the number of file infos we write out to fit
994 // easily in a 32-bit signed integer. This gives consistent behavior between
995 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
996 // operations on 32-bit systems. It also seems unreasonable to try to handle
997 // more than 2 billion files.
998 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
999 FileInfos.resize(INT_MAX);
1000
1001 // Create a global for the entire data structure so we can walk it more
1002 // easily.
1003 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1004 auto *FileInfoArrayGV = new GlobalVariable(
1005 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1006 ConstantArray::get(FileInfoArrayTy, FileInfos),
1007 "__llvm_internal_gcov_emit_file_info");
1008 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1009
1010 // Create the CFG for walking this data structure.
1011 auto *FileLoopHeader =
1012 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1013 auto *CounterLoopHeader =
1014 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1015 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1016 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1017
1018 // We always have at least one file, so just branch to the header.
1019 Builder.CreateBr(FileLoopHeader);
1020
1021 // The index into the files structure is our loop induction variable.
1022 Builder.SetInsertPoint(FileLoopHeader);
1023 PHINode *IV =
1024 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1025 IV->addIncoming(Builder.getInt32(0), BB);
1026 auto *FileInfoPtr =
1027 Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
1028 auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
1029 Builder.CreateCall(
1030 StartFile,
1031 {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
1032 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
1033 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
1034 auto *NumCounters =
1035 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
1036 auto *EmitFunctionCallArgsArray =
1037 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
1038 auto *EmitArcsCallArgsArray =
1039 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
1040 auto *EnterCounterLoopCond =
1041 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1042 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1043
1044 Builder.SetInsertPoint(CounterLoopHeader);
1045 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1046 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1047 auto *EmitFunctionCallArgsPtr =
1048 Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
1049 Builder.CreateCall(
1050 EmitFunction,
1051 {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
1052 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
1053 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
1054 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
1055 Builder.CreateLoad(
1056 Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
1057 auto *EmitArcsCallArgsPtr =
1058 Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
1059 Builder.CreateCall(
1060 EmitArcs,
1061 {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
1062 Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
1063 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1064 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1065 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1066 JV->addIncoming(NextJV, CounterLoopHeader);
1067
1068 Builder.SetInsertPoint(FileLoopLatch);
1069 Builder.CreateCall(SummaryInfo, {});
1070 Builder.CreateCall(EndFile, {});
1071 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1072 auto *FileLoopCond =
1073 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1074 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1075 IV->addIncoming(NextIV, FileLoopLatch);
1076
1077 Builder.SetInsertPoint(ExitBB);
Nick Lewyckyc58d2932011-04-26 03:54:16 +00001078 Builder.CreateRetVoid();
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001079
Bill Wendlingc3cab812013-03-18 23:04:39 +00001080 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +00001081}
Bill Wendling15605172012-05-28 06:10:56 +00001082
1083void GCOVProfiler::insertIndirectCounterIncrement() {
1084 Function *Fn =
1085 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001086 Fn->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling15605172012-05-28 06:10:56 +00001087 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001088 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +00001089 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001090 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling15605172012-05-28 06:10:56 +00001091
Bill Wendling15605172012-05-28 06:10:56 +00001092 // Create basic blocks for function.
1093 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
1094 IRBuilder<> Builder(BB);
1095
1096 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
1097 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
1098 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
1099
1100 // uint32_t pred = *predecessor;
1101 // if (pred == 0xffffffff) return;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001102 Argument *Arg = &*Fn->arg_begin();
Bill Wendling15605172012-05-28 06:10:56 +00001103 Arg->setName("predecessor");
1104 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewycky8e94d802013-02-27 05:46:30 +00001105 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling15605172012-05-28 06:10:56 +00001106 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
1107
1108 Builder.SetInsertPoint(PredNotNegOne);
1109
1110 // uint64_t *counter = counters[pred];
1111 // if (!counter) return;
Nick Lewycky8e94d802013-02-27 05:46:30 +00001112 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001113 Arg = &*std::next(Fn->arg_begin());
Bill Wendling15605172012-05-28 06:10:56 +00001114 Arg->setName("counters");
David Blaikie93c54442015-04-03 19:41:44 +00001115 Value *GEP = Builder.CreateGEP(Type::getInt64PtrTy(*Ctx), Arg, ZExtPred);
Bill Wendling15605172012-05-28 06:10:56 +00001116 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky625f3952013-02-27 06:21:30 +00001117 Cond = Builder.CreateICmpEQ(Counter,
1118 Constant::getNullValue(
1119 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling15605172012-05-28 06:10:56 +00001120 Builder.CreateCondBr(Cond, Exit, CounterEnd);
1121
1122 // ++*counter;
1123 Builder.SetInsertPoint(CounterEnd);
1124 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewycky8e94d802013-02-27 05:46:30 +00001125 Builder.getInt64(1));
Bill Wendling15605172012-05-28 06:10:56 +00001126 Builder.CreateStore(Add, Counter);
1127 Builder.CreateBr(Exit);
1128
1129 // Fill in the exit block.
1130 Builder.SetInsertPoint(Exit);
1131 Builder.CreateRetVoid();
1132}
Bill Wendling2e6e8662012-09-13 00:09:55 +00001133
Bill Wendlingc3cab812013-03-18 23:04:39 +00001134Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +00001135insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1136 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +00001137 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +00001138 if (!FlushF)
1139 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +00001140 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001141 else
1142 FlushF->setLinkage(GlobalValue::InternalLinkage);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001143 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001144 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +00001145 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001146 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001147
Bill Wendling2e6e8662012-09-13 00:09:55 +00001148 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1149
1150 // Write out the current counters.
1151 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1152 assert(WriteoutF && "Need to create the writeout function first!");
1153
1154 IRBuilder<> Builder(Entry);
David Blaikieff6409d2015-05-18 22:13:54 +00001155 Builder.CreateCall(WriteoutF, {});
Bill Wendling2e6e8662012-09-13 00:09:55 +00001156
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001157 // Zero out the counters.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001158 for (const auto &I : CountersBySP) {
1159 GlobalVariable *GV = I.first;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001160 Constant *Null = Constant::getNullValue(GV->getValueType());
Bill Wendling8d26bc32012-09-14 22:35:49 +00001161 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001162 }
Bill Wendling2e6e8662012-09-13 00:09:55 +00001163
1164 Type *RetTy = FlushF->getReturnType();
1165 if (RetTy == Type::getVoidTy(*Ctx))
1166 Builder.CreateRetVoid();
1167 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +00001168 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +00001169 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1170 else
Bill Wendlingc3cab812013-03-18 23:04:39 +00001171 report_fatal_error("invalid return type for __llvm_gcov_flush");
1172
1173 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +00001174}