blob: b4da53fd9749b4c8fdd3a22b8bb537cf706b6326 [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"
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +000024#include "llvm/Analysis/EHPersonalities.h"
Ulrich Weigandb961fdc2018-07-10 16:05:47 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
Vedant Kumar727d8952018-09-11 18:38:34 +000026#include "llvm/IR/CFG.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth92051402014-03-05 10:30:38 +000028#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000030#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Instructions.h"
Bob Wilson055a0b42014-01-31 05:24:01 +000032#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Pass.h"
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000035#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000036#include "llvm/Support/Debug.h"
Bill Wendling5aa82392013-03-26 22:47:50 +000037#include "llvm/Support/FileSystem.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000038#include "llvm/Support/Path.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
Xinliang David Li64dbb292016-06-05 05:12:23 +000040#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth71c3a3f2018-05-02 22:24:39 +000041#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewycky0fdd0192013-06-18 06:38:21 +000043#include <algorithm>
David Blaikie229de502014-04-21 20:41:55 +000044#include <memory>
Nick Lewycky966edd02011-04-16 01:20:23 +000045#include <string>
46#include <utility>
47using namespace llvm;
48
Chandler Carruth964daaa2014-04-22 02:55:47 +000049#define DEBUG_TYPE "insert-gcov-profiling"
50
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000051static cl::opt<std::string>
52DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
53 cl::ValueRequired);
Justin Bogner3faa76b2015-03-16 23:52:03 +000054static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
55 cl::init(false), cl::Hidden);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000056
57GCOVOptions GCOVOptions::getDefault() {
58 GCOVOptions Options;
59 Options.EmitNotes = true;
60 Options.EmitData = true;
61 Options.UseCfgChecksum = false;
62 Options.NoRedZone = false;
63 Options.FunctionNamesInData = true;
Justin Bogner3faa76b2015-03-16 23:52:03 +000064 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000065
66 if (DefaultGCOVVersion.size() != 4) {
67 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
68 DefaultGCOVVersion);
69 }
70 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
71 return Options;
72}
73
Nick Lewycky966edd02011-04-16 01:20:23 +000074namespace {
Xinliang David Lifb3137c2016-06-05 03:40:03 +000075class GCOVFunction;
Yuchen Wubabe7492013-11-20 04:15:05 +000076
Xinliang David Lifb3137c2016-06-05 03:40:03 +000077class GCOVProfiler {
78public:
79 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
80 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
81 assert((Options.EmitNotes || Options.EmitData) &&
82 "GCOVProfiler asked to do nothing?");
83 ReversedVersion[0] = Options.Version[3];
84 ReversedVersion[1] = Options.Version[2];
85 ReversedVersion[2] = Options.Version[1];
86 ReversedVersion[3] = Options.Version[0];
87 ReversedVersion[4] = '\0';
88 }
Ulrich Weigandb961fdc2018-07-10 16:05:47 +000089 bool runOnModule(Module &M, const TargetLibraryInfo &TLI);
Benjamin Kramer298a3a02015-03-06 16:21:15 +000090
Xinliang David Lifb3137c2016-06-05 03:40:03 +000091private:
92 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
Nick Lewycky6d9f0612011-05-04 04:03:04 +000094
Xinliang David Lifb3137c2016-06-05 03:40:03 +000095 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
97 bool emitProfileArcs();
Nick Lewycky966edd02011-04-16 01:20:23 +000098
Xinliang David Lifb3137c2016-06-05 03:40:03 +000099 // Get pointers to the functions in the runtime library.
100 Constant *getStartFileFunc();
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000101 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 // Add the function to write out all our counters to the global destructor
107 // list.
108 Function *
109 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
110 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000111
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000112 enum class GCovFileType { GCNO, GCDA };
113 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
Nick Lewycky966edd02011-04-16 01:20:23 +0000114
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000115 GCOVOptions Options;
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000116
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000117 // Reversed, NUL-terminated copy of Options.Version.
118 char ReversedVersion[5];
119 // Checksum, produced by hash of EdgeDestinations
120 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000121
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000122 Module *M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000123 const TargetLibraryInfo *TLI;
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000124 LLVMContext *Ctx;
125 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
126};
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000127
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000128class GCOVProfilerLegacyPass : public ModulePass {
129public:
130 static char ID;
131 GCOVProfilerLegacyPass()
132 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
133 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
134 : ModulePass(ID), Profiler(Opts) {
135 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
136 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000137 StringRef getPassName() const override { return "GCOV Profiler"; }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000138
Fangrui Songf78650a2018-07-30 19:41:25 +0000139 bool runOnModule(Module &M) override {
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000140 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
141 return Profiler.runOnModule(M, TLI);
142 }
143
144 void getAnalysisUsage(AnalysisUsage &AU) const override {
145 AU.addRequired<TargetLibraryInfoWrapperPass>();
146 }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000147
148private:
149 GCOVProfiler Profiler;
150};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000151}
Nick Lewycky966edd02011-04-16 01:20:23 +0000152
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000153char GCOVProfilerLegacyPass::ID = 0;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000154INITIALIZE_PASS_BEGIN(
155 GCOVProfilerLegacyPass, "insert-gcov-profiling",
156 "Insert instrumentation for GCOV profiling", false, false)
157INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
158INITIALIZE_PASS_END(
159 GCOVProfilerLegacyPass, "insert-gcov-profiling",
160 "Insert instrumentation for GCOV profiling", false, false)
Nick Lewycky966edd02011-04-16 01:20:23 +0000161
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000162ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000163 return new GCOVProfilerLegacyPass(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000164}
Nick Lewycky966edd02011-04-16 01:20:23 +0000165
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000166static StringRef getFunctionName(const DISubprogram *SP) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000167 if (!SP->getLinkageName().empty())
168 return SP->getLinkageName();
169 return SP->getName();
Nick Lewyckyd6718632013-03-19 01:37:55 +0000170}
171
Nick Lewycky966edd02011-04-16 01:20:23 +0000172namespace {
173 class GCOVRecord {
174 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000175 static const char *const LinesTag;
176 static const char *const FunctionTag;
177 static const char *const BlockTag;
178 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000179
Benjamin Kramer79de6e62015-04-11 18:57:14 +0000180 GCOVRecord() = default;
Nick Lewycky966edd02011-04-16 01:20:23 +0000181
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000182 void writeBytes(const char *Bytes, int Size) {
183 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000184 }
185
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000186 void write(uint32_t i) {
187 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000188 }
189
190 // Returns the length measured in 4-byte blocks that will be used to
191 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000192 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000193 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000194 // padding out to the next 4-byte word. The length is measured in 4-byte
195 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000196 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000197 }
198
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000199 void writeGCOVString(StringRef s) {
200 uint32_t Len = lengthOfGCOVString(s);
201 write(Len);
202 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000203
204 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000205 assert((unsigned)(4 - (s.size() % 4)) > 0);
206 assert((unsigned)(4 - (s.size() % 4)) <= 4);
207 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000208 }
209
210 raw_ostream *os;
211 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000212 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
213 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
214 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
215 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000216
217 class GCOVFunction;
218 class GCOVBlock;
219
220 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000221 // list of line numbers and a single filename, representing lines that belong
222 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000223 class GCOVLines : public GCOVRecord {
224 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000225 void addLine(uint32_t Line) {
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000226 assert(Line != 0 && "Line zero is not a valid real line number.");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000227 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000228 }
229
Craig Topper24048c92013-07-17 03:54:53 +0000230 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000231 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000232 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000233 }
234
Devang Pateladd1f172011-09-20 18:35:00 +0000235 void writeOut() {
236 write(0);
237 writeGCOVString(Filename);
238 for (int i = 0, e = Lines.size(); i != e; ++i)
239 write(Lines[i]);
240 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000241
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000242 GCOVLines(StringRef F, raw_ostream *os)
Devang Pateladd1f172011-09-20 18:35:00 +0000243 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000244 this->os = os;
245 }
246
Devang Patel7d06f5c2011-09-20 18:48:56 +0000247 private:
Devang Pateladd1f172011-09-20 18:35:00 +0000248 StringRef Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000249 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000250 };
251
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000252
Nick Lewycky966edd02011-04-16 01:20:23 +0000253 // Represent a basic block in GCOV. Each block has a unique number in the
254 // function, number of lines belonging to each block, and a set of edges to
255 // other blocks.
256 class GCOVBlock : public GCOVRecord {
257 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000258 GCOVLines &getFile(StringRef Filename) {
Benjamin Kramereab3d362016-07-21 13:37:48 +0000259 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000260 }
261
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000262 void addEdge(GCOVBlock &Successor) {
263 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000264 }
265
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000266 void writeOut() {
267 uint32_t Len = 3;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000268 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000269 for (auto &I : LinesByFile) {
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000270 Len += I.second.length();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000271 SortedLinesByFile.push_back(&I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000272 }
273
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000274 writeBytes(LinesTag, 4);
275 write(Len);
276 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000277
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000278 llvm::sort(
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000279 SortedLinesByFile.begin(), SortedLinesByFile.end(),
280 [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
281 return LHS->getKey() < RHS->getKey();
282 });
Benjamin Kramer135f7352016-06-26 12:28:59 +0000283 for (auto &I : SortedLinesByFile)
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000284 I->getValue().writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000285 write(0);
286 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000287 }
288
David Blaikieea37c112014-12-22 23:12:42 +0000289 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
290 // Only allow copy before edges and lines have been added. After that,
291 // there are inter-block pointers (eg: edges) that won't take kindly to
292 // blocks being copied or moved around.
293 assert(LinesByFile.empty());
294 assert(OutEdges.empty());
295 }
296
Nick Lewycky966edd02011-04-16 01:20:23 +0000297 private:
298 friend class GCOVFunction;
299
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000300 GCOVBlock(uint32_t Number, raw_ostream *os)
301 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000302 this->os = os;
303 }
304
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000305 uint32_t Number;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000306 StringMap<GCOVLines> LinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000307 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000308 };
309
310 // A function has a unique identifier, a checksum (we leave as zero) and a
311 // set of blocks and a map of edges between blocks. This is the only GCOV
312 // object users can construct, the blocks and lines will be rooted here.
313 class GCOVFunction : public GCOVRecord {
314 public:
Peter Collingbourned4bff302015-11-05 22:03:56 +0000315 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
316 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
David Blaikieea37c112014-12-22 23:12:42 +0000317 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
318 ReturnBlock(1, os) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000319 this->os = os;
320
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000321 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewycky2e8a6212014-12-03 02:45:01 +0000322
David Blaikieea37c112014-12-22 23:12:42 +0000323 uint32_t i = 0;
324 for (auto &BB : *F) {
Justin Bogner3faa76b2015-03-16 23:52:03 +0000325 // Skip index 1 if it's assigned to the ReturnBlock.
326 if (i == 1 && ExitBlockBeforeBody)
327 ++i;
328 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
Nick Lewycky966edd02011-04-16 01:20:23 +0000329 }
Justin Bogner3faa76b2015-03-16 23:52:03 +0000330 if (!ExitBlockBeforeBody)
331 ReturnBlock.Number = i;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000332
Alp Tokere69170a2014-06-26 22:52:05 +0000333 std::string FunctionNameAndLine;
334 raw_string_ostream FNLOS(FunctionNameAndLine);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000335 FNLOS << getFunctionName(SP) << SP->getLine();
Alp Tokere69170a2014-06-26 22:52:05 +0000336 FNLOS.flush();
337 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewycky966edd02011-04-16 01:20:23 +0000338 }
339
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000340 GCOVBlock &getBlock(BasicBlock *BB) {
David Blaikieea37c112014-12-22 23:12:42 +0000341 return Blocks.find(BB)->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000342 }
343
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000344 GCOVBlock &getReturnBlock() {
David Blaikieea37c112014-12-22 23:12:42 +0000345 return ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000346 }
347
Yuchen Wubabe7492013-11-20 04:15:05 +0000348 std::string getEdgeDestinations() {
Alp Tokere69170a2014-06-26 22:52:05 +0000349 std::string EdgeDestinations;
350 raw_string_ostream EDOS(EdgeDestinations);
Yuchen Wubabe7492013-11-20 04:15:05 +0000351 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000352 for (BasicBlock &I : *F) {
353 GCOVBlock &Block = getBlock(&I);
Yuchen Wubabe7492013-11-20 04:15:05 +0000354 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
Alp Tokere69170a2014-06-26 22:52:05 +0000355 EDOS << Block.OutEdges[i]->Number;
Yuchen Wubabe7492013-11-20 04:15:05 +0000356 }
Alp Tokere69170a2014-06-26 22:52:05 +0000357 return EdgeDestinations;
Yuchen Wubabe7492013-11-20 04:15:05 +0000358 }
359
Daniel Jasper87a24d52013-12-04 08:57:17 +0000360 uint32_t getFuncChecksum() {
361 return FuncChecksum;
362 }
363
Yuchen Wubabe7492013-11-20 04:15:05 +0000364 void setCfgChecksum(uint32_t Checksum) {
365 CfgChecksum = Checksum;
366 }
367
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000368 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000369 writeBytes(FunctionTag, 4);
370 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000371 1 + lengthOfGCOVString(SP->getFilename()) + 1;
Yuchen Wubabe7492013-11-20 04:15:05 +0000372 if (UseCfgChecksum)
373 ++BlockLen;
374 write(BlockLen);
375 write(Ident);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000376 write(FuncChecksum);
Yuchen Wubabe7492013-11-20 04:15:05 +0000377 if (UseCfgChecksum)
378 write(CfgChecksum);
379 writeGCOVString(getFunctionName(SP));
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000380 writeGCOVString(SP->getFilename());
381 write(SP->getLine());
Yuchen Wubabe7492013-11-20 04:15:05 +0000382
Nick Lewycky966edd02011-04-16 01:20:23 +0000383 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000384 writeBytes(BlockTag, 4);
385 write(Blocks.size() + 1);
386 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
387 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000388 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000389 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000390
391 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000392 if (Blocks.empty()) return;
393 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000394 for (BasicBlock &I : *F) {
395 GCOVBlock &Block = getBlock(&I);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000396 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000397
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000398 writeBytes(EdgeTag, 4);
399 write(Block.OutEdges.size() * 2 + 1);
400 write(Block.Number);
401 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000402 LLVM_DEBUG(dbgs() << Block.Number << " -> "
403 << Block.OutEdges[i]->Number << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000404 write(Block.OutEdges[i]->Number);
405 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000406 }
407 }
408
409 // Emit lines for each block.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000410 for (BasicBlock &I : *F)
411 getBlock(&I).writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000412 }
413
414 private:
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000415 const DISubprogram *SP;
Yuchen Wubabe7492013-11-20 04:15:05 +0000416 uint32_t Ident;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000417 uint32_t FuncChecksum;
Yuchen Wubabe7492013-11-20 04:15:05 +0000418 bool UseCfgChecksum;
419 uint32_t CfgChecksum;
David Blaikieea37c112014-12-22 23:12:42 +0000420 DenseMap<BasicBlock *, GCOVBlock> Blocks;
421 GCOVBlock ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000422 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000423}
Nick Lewycky966edd02011-04-16 01:20:23 +0000424
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000425std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000426 GCovFileType OutputType) {
427 bool Notes = OutputType == GCovFileType::GCNO;
428
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000429 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
430 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000431 MDNode *N = GCov->getOperand(i);
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000432 bool ThreeElement = N->getNumOperands() == 3;
433 if (!ThreeElement && N->getNumOperands() != 2)
434 continue;
Nick Lewycky8dd4dad2016-08-31 23:24:43 +0000435 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000436 continue;
437
438 if (ThreeElement) {
439 // These nodes have no mangling to apply, it's stored mangled in the
440 // bitcode.
441 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
442 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
443 if (!NotesFile || !DataFile)
444 continue;
445 return Notes ? NotesFile->getString() : DataFile->getString();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000446 }
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000447
448 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
449 if (!GCovFile)
450 continue;
451
452 SmallString<128> Filename = GCovFile->getString();
453 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
454 return Filename.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000455 }
456 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000457
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000458 SmallString<128> Filename = CU->getFilename();
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000459 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
Bill Wendling5aa82392013-03-26 22:47:50 +0000460 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000461 SmallString<128> CurPath;
462 if (sys::fs::current_path(CurPath)) return FName;
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000463 sys::path::append(CurPath, FName);
Bill Wendling5aa82392013-03-26 22:47:50 +0000464 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000465}
466
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000467bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000468 this->M = &M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000469 this->TLI = &TLI;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000470 Ctx = &M.getContext();
471
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000472 if (Options.EmitNotes) emitProfileNotes();
473 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000474 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000475}
476
Xinliang David Li64dbb292016-06-05 05:12:23 +0000477PreservedAnalyses GCOVProfilerPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000478 ModuleAnalysisManager &AM) {
Xinliang David Li64dbb292016-06-05 05:12:23 +0000479
480 GCOVProfiler Profiler(GCOVOpts);
481
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000482 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
483 if (!Profiler.runOnModule(M, TLI))
Xinliang David Li64dbb292016-06-05 05:12:23 +0000484 return PreservedAnalyses::all();
485
486 return PreservedAnalyses::none();
487}
488
Adrian Prantl75819ae2016-04-15 15:57:41 +0000489static bool functionHasLines(Function &F) {
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000490 // Check whether this function actually has any source lines. Not only
491 // do these waste space, they also can crash gcov.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000492 for (auto &BB : F) {
493 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000494 // Debug intrinsic locations correspond to the location of the
495 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000496 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000497
Adrian Prantl75819ae2016-04-15 15:57:41 +0000498 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000499 if (!Loc)
500 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000501
502 // Artificial lines such as calls to the global constructors.
Justin Bogner3faa76b2015-03-16 23:52:03 +0000503 if (Loc.getLine() == 0) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000504
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000505 return true;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000506 }
507 }
508 return false;
509}
510
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000511static bool isUsingScopeBasedEH(Function &F) {
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000512 if (!F.hasPersonalityFn()) return false;
513
514 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000515 return isScopedEHPersonality(Personality);
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000516}
517
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000518static bool shouldKeepInEntry(BasicBlock::iterator It) {
519 if (isa<AllocaInst>(*It)) return true;
520 if (isa<DbgInfoIntrinsic>(*It)) return true;
521 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
522 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
523 }
524
525 return false;
526}
527
Nick Lewyckyad145502013-03-13 22:55:42 +0000528void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000529 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000530 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000531
Nick Lewycky6404d972011-11-27 23:22:20 +0000532 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
533 // Each compile unit gets its own .gcno file. This means that whether we run
534 // this pass over the original .o's as they're produced, or run it after
535 // LTO, we'll generate the same .gcno files.
536
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000537 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
Vedant Kumar61035fa2016-01-21 17:04:42 +0000538
539 // Skip module skeleton (and module) CUs.
540 if (CU->getDWOId())
541 continue;
542
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000543 std::error_code EC;
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000544 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
Reid Kleckner1aa4ea82017-09-18 21:31:48 +0000545 if (EC) {
546 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
547 EC.message());
548 continue;
549 }
550
Yuchen Wubabe7492013-11-20 04:15:05 +0000551 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000552
Justin Bogner58e41342014-11-06 06:55:02 +0000553 unsigned FunctionIdent = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000554 for (auto &F : M->functions()) {
555 DISubprogram *SP = F.getSubprogram();
556 if (!SP) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000557 if (!functionHasLines(F)) continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000558 // TODO: Functions using scope-based EH are currently not supported.
559 if (isUsingScopeBasedEH(F)) continue;
Bob Wilson055a0b42014-01-31 05:24:01 +0000560
561 // gcov expects every function to start with an entry block that has a
562 // single successor, so split the entry block to make sure of that.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000563 BasicBlock &EntryBlock = F.getEntryBlock();
Bob Wilson055a0b42014-01-31 05:24:01 +0000564 BasicBlock::iterator It = EntryBlock.begin();
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000565 while (shouldKeepInEntry(It))
Bob Wilson055a0b42014-01-31 05:24:01 +0000566 ++It;
567 EntryBlock.splitBasicBlock(It);
Yuchen Wuc87ca322013-11-22 23:07:45 +0000568
Adrian Prantl75819ae2016-04-15 15:57:41 +0000569 Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
Justin Bogner3faa76b2015-03-16 23:52:03 +0000570 Options.UseCfgChecksum,
571 Options.ExitBlockBeforeBody));
David Blaikie229de502014-04-21 20:41:55 +0000572 GCOVFunction &Func = *Funcs.back();
Nick Lewycky6404d972011-11-27 23:22:20 +0000573
Adrian Prantl75819ae2016-04-15 15:57:41 +0000574 for (auto &BB : F) {
575 GCOVBlock &Block = Func.getBlock(&BB);
576 TerminatorInst *TI = BB.getTerminator();
Nick Lewycky6404d972011-11-27 23:22:20 +0000577 if (int successors = TI->getNumSuccessors()) {
578 for (int i = 0; i != successors; ++i) {
David Blaikie229de502014-04-21 20:41:55 +0000579 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000580 }
581 } else if (isa<ReturnInst>(TI)) {
David Blaikie229de502014-04-21 20:41:55 +0000582 Block.addEdge(Func.getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000583 }
584
585 uint32_t Line = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000586 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000587 // Debug intrinsic locations correspond to the location of the
588 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000589 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000590
Adrian Prantl75819ae2016-04-15 15:57:41 +0000591 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000592 if (!Loc)
593 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000594
595 // Artificial lines such as calls to the global constructors.
Calixte Denizeteb7f6022018-09-20 08:53:06 +0000596 if (Loc.getLine() == 0 || Loc.isImplicitCode())
597 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000598
Nick Lewycky6404d972011-11-27 23:22:20 +0000599 if (Line == Loc.getLine()) continue;
600 Line = Loc.getLine();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000601 if (SP != getDISubprogram(Loc.getScope()))
602 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000603
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000604 GCOVLines &Lines = Block.getFile(SP->getFilename());
Nick Lewycky6404d972011-11-27 23:22:20 +0000605 Lines.addLine(Loc.getLine());
606 }
607 }
David Blaikie229de502014-04-21 20:41:55 +0000608 EdgeDestinations += Func.getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000609 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000610
Yuchen Wu664dc762013-11-21 04:01:05 +0000611 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000612 out.write("oncg", 4);
613 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000614 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000615
David Blaikie229de502014-04-21 20:41:55 +0000616 for (auto &Func : Funcs) {
Yuchen Wu664dc762013-11-21 04:01:05 +0000617 Func->setCfgChecksum(FileChecksums.back());
618 Func->writeOut();
619 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000620
Nick Lewycky6404d972011-11-27 23:22:20 +0000621 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
622 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000623 }
624}
625
Devang Patel2b21d862011-08-17 22:49:38 +0000626bool GCOVProfiler::emitProfileArcs() {
627 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
628 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000629
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000630 bool Result = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000631 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Devang Patel2b21d862011-08-17 22:49:38 +0000632 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000633 for (auto &F : M->functions()) {
634 DISubprogram *SP = F.getSubprogram();
635 if (!SP) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000636 if (!functionHasLines(F)) continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000637 // TODO: Functions using scope-based EH are currently not supported.
638 if (isUsingScopeBasedEH(F)) continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000639 if (!Result) Result = true;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000640
Vedant Kumar727d8952018-09-11 18:38:34 +0000641 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
Devang Patel2b21d862011-08-17 22:49:38 +0000642 unsigned Edges = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000643 for (auto &BB : F) {
644 TerminatorInst *TI = BB.getTerminator();
Vedant Kumar727d8952018-09-11 18:38:34 +0000645 if (isa<ReturnInst>(TI)) {
646 EdgeToCounter[{&BB, nullptr}] = Edges++;
647 } else {
648 for (BasicBlock *Succ : successors(TI)) {
649 EdgeToCounter[{&BB, Succ}] = Edges++;
650 }
651 }
Devang Patel2b21d862011-08-17 22:49:38 +0000652 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000653
Devang Patel2b21d862011-08-17 22:49:38 +0000654 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000655 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000656 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000657 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000658 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000659 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000660 "__llvm_gcov_ctr");
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000661 CountersBySP.push_back(std::make_pair(Counters, SP));
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000662
Vedant Kumar727d8952018-09-11 18:38:34 +0000663 // If a BB has several predecessors, use a PHINode to select
664 // the correct counter.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000665 for (auto &BB : F) {
Vedant Kumar727d8952018-09-11 18:38:34 +0000666 const unsigned EdgeCount =
667 std::distance(pred_begin(&BB), pred_end(&BB));
668 if (EdgeCount) {
669 // The phi node must be at the begin of the BB.
670 IRBuilder<> BuilderForPhi(&*BB.begin());
671 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
672 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
673 for (BasicBlock *Pred : predecessors(&BB)) {
674 auto It = EdgeToCounter.find({Pred, &BB});
675 assert(It != EdgeToCounter.end());
676 const unsigned Edge = It->second;
677 Value *EdgeCounter =
678 BuilderForPhi.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
679 Phi->addIncoming(EdgeCounter, Pred);
Devang Patel2b21d862011-08-17 22:49:38 +0000680 }
Bill Wendling707f6012013-08-20 23:52:00 +0000681
Vedant Kumar727d8952018-09-11 18:38:34 +0000682 // Skip phis, landingpads.
683 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
684 Value *Count = Builder.CreateLoad(Phi);
685 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
686 Builder.CreateStore(Count, Phi);
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000687
Vedant Kumar727d8952018-09-11 18:38:34 +0000688 TerminatorInst *TI = BB.getTerminator();
689 if (isa<ReturnInst>(TI)) {
690 auto It = EdgeToCounter.find({&BB, nullptr});
691 assert(It != EdgeToCounter.end());
692 const unsigned Edge = It->second;
693 Value *Counter =
694 Builder.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
695 Value *Count = Builder.CreateLoad(Counter);
696 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
697 Builder.CreateStore(Count, Counter);
698 }
Devang Patel2b21d862011-08-17 22:49:38 +0000699 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000700 }
701 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000702
Bill Wendlingc3cab812013-03-18 23:04:39 +0000703 Function *WriteoutF = insertCounterWriteout(CountersBySP);
704 Function *FlushF = insertFlush(CountersBySP);
705
706 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000707 // be executed at exit and the "__llvm_gcov_flush" function to be executed
708 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000709 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
710 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
711 "__llvm_gcov_init", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000712 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000713 F->setLinkage(GlobalValue::InternalLinkage);
714 F->addFnAttr(Attribute::NoInline);
715 if (Options.NoRedZone)
716 F->addFnAttr(Attribute::NoRedZone);
717
718 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
719 IRBuilder<> Builder(BB);
720
Bill Wendlingc3cab812013-03-18 23:04:39 +0000721 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000722 Type *Params[] = {
723 PointerType::get(FTy, 0),
724 PointerType::get(FTy, 0)
725 };
726 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000727
Yuchen Wu3197b252013-10-23 20:35:00 +0000728 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000729 // functions.
730 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000731 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
Bill Wendlingc3cab812013-03-18 23:04:39 +0000732 Builder.CreateRetVoid();
733
734 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000735 }
Bill Wendling15605172012-05-28 06:10:56 +0000736
Devang Patel2b21d862011-08-17 22:49:38 +0000737 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000738}
739
740Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000741 Type *Args[] = {
742 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
743 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000744 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000745 };
746 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000747 auto *Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy);
748 if (Function *FunRes = dyn_cast<Function>(Res))
749 if (auto AK = TLI->getExtAttrForI32Param(false))
750 FunRes->addParamAttr(2, AK);
751 return Res;
752
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000753}
754
Nick Lewycky966edd02011-04-16 01:20:23 +0000755Constant *GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000756 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000757 Type::getInt32Ty(*Ctx), // uint32_t ident
758 Type::getInt8PtrTy(*Ctx), // const char *function_name
Daniel Jasper87a24d52013-12-04 08:57:17 +0000759 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000760 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000761 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000762 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000763 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000764 auto *Res = M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
765 if (Function *FunRes = dyn_cast<Function>(Res))
766 if (auto AK = TLI->getExtAttrForI32Param(false)) {
767 FunRes->addParamAttr(0, AK);
768 FunRes->addParamAttr(2, AK);
769 FunRes->addParamAttr(3, AK);
770 FunRes->addParamAttr(4, AK);
771 }
772 return Res;
Nick Lewycky966edd02011-04-16 01:20:23 +0000773}
774
775Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000776 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000777 Type::getInt32Ty(*Ctx), // uint32_t num_counters
778 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
779 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000780 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000781 auto *Res = M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
782 if (Function *FunRes = dyn_cast<Function>(Res))
783 if (auto AK = TLI->getExtAttrForI32Param(false))
784 FunRes->addParamAttr(0, AK);
785 return Res;
Nick Lewycky966edd02011-04-16 01:20:23 +0000786}
787
Yuchen Wu062f24c2013-11-12 04:59:08 +0000788Constant *GCOVProfiler::getSummaryInfoFunc() {
789 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
790 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
791}
792
Nick Lewycky966edd02011-04-16 01:20:23 +0000793Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000794 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000795 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000796}
797
Bill Wendlingc3cab812013-03-18 23:04:39 +0000798Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000799 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000800 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
801 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
802 if (!WriteoutF)
803 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
804 "__llvm_gcov_writeout", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000805 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000806 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000807 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000808 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000809
810 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000811 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000812
813 Constant *StartFile = getStartFileFunc();
814 Constant *EmitFunction = getEmitFunctionFunc();
815 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000816 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000817 Constant *EndFile = getEndFileFunc();
818
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000819 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
820 if (!CUNodes) {
821 Builder.CreateRetVoid();
822 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000823 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000824
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000825 // Collect the relevant data into a large constant data structure that we can
826 // walk to write out everything.
827 StructType *StartFileCallArgsTy = StructType::create(
828 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
829 StructType *EmitFunctionCallArgsTy = StructType::create(
830 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
831 Builder.getInt8Ty(), Builder.getInt32Ty()});
832 StructType *EmitArcsCallArgsTy = StructType::create(
833 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
834 StructType *FileInfoTy =
835 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
836 EmitFunctionCallArgsTy->getPointerTo(),
837 EmitArcsCallArgsTy->getPointerTo()});
838
839 Constant *Zero32 = Builder.getInt32(0);
Chandler Carruthe74c3542018-05-03 00:11:03 +0000840 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
841 Constant *TwoZero32s[] = {Zero32, Zero32};
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000842
843 SmallVector<Constant *, 8> FileInfos;
844 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
845 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
846
847 // Skip module skeleton (and module) CUs.
848 if (CU->getDWOId())
849 continue;
850
851 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
852 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
853 auto *StartFileCallArgs = ConstantStruct::get(
854 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
855 Builder.CreateGlobalStringPtr(ReversedVersion),
856 Builder.getInt32(CfgChecksum)});
857
858 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
859 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
860 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
861 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
862 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
863 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
864 EmitFunctionCallArgsTy,
865 {Builder.getInt32(j),
866 Options.FunctionNamesInData
867 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
868 : Constant::getNullValue(Builder.getInt8PtrTy()),
869 Builder.getInt32(FuncChecksum),
870 Builder.getInt8(Options.UseCfgChecksum),
871 Builder.getInt32(CfgChecksum)}));
872
873 GlobalVariable *GV = CountersBySP[j].first;
874 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
875 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
876 EmitArcsCallArgsTy,
Chandler Carruthe74c3542018-05-03 00:11:03 +0000877 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
878 GV->getValueType(), GV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000879 }
880 // Create global arrays for the two emit calls.
881 int CountersSize = CountersBySP.size();
882 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
883 "Mismatched array size!");
884 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
885 "Mismatched array size!");
886 auto *EmitFunctionCallArgsArrayTy =
887 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
888 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
889 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
890 GlobalValue::InternalLinkage,
891 ConstantArray::get(EmitFunctionCallArgsArrayTy,
892 EmitFunctionCallArgsArray),
893 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
894 auto *EmitArcsCallArgsArrayTy =
895 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
896 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
897 GlobalValue::UnnamedAddr::Global);
898 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
899 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
900 GlobalValue::InternalLinkage,
901 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
902 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
903 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
904
905 FileInfos.push_back(ConstantStruct::get(
906 FileInfoTy,
907 {StartFileCallArgs, Builder.getInt32(CountersSize),
Chandler Carruthe74c3542018-05-03 00:11:03 +0000908 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
909 EmitFunctionCallArgsArrayGV,
910 TwoZero32s),
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000911 ConstantExpr::getInBoundsGetElementPtr(
Chandler Carruthe74c3542018-05-03 00:11:03 +0000912 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000913 }
914
915 // If we didn't find anything to actually emit, bail on out.
916 if (FileInfos.empty()) {
917 Builder.CreateRetVoid();
918 return WriteoutF;
919 }
920
921 // To simplify code, we cap the number of file infos we write out to fit
922 // easily in a 32-bit signed integer. This gives consistent behavior between
923 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
924 // operations on 32-bit systems. It also seems unreasonable to try to handle
925 // more than 2 billion files.
926 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
927 FileInfos.resize(INT_MAX);
928
929 // Create a global for the entire data structure so we can walk it more
930 // easily.
931 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
932 auto *FileInfoArrayGV = new GlobalVariable(
933 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
934 ConstantArray::get(FileInfoArrayTy, FileInfos),
935 "__llvm_internal_gcov_emit_file_info");
936 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
937
938 // Create the CFG for walking this data structure.
939 auto *FileLoopHeader =
940 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
941 auto *CounterLoopHeader =
942 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
943 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
944 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
945
946 // We always have at least one file, so just branch to the header.
947 Builder.CreateBr(FileLoopHeader);
948
949 // The index into the files structure is our loop induction variable.
950 Builder.SetInsertPoint(FileLoopHeader);
951 PHINode *IV =
952 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
953 IV->addIncoming(Builder.getInt32(0), BB);
954 auto *FileInfoPtr =
955 Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
956 auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000957 auto *StartFileCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000958 StartFile,
959 {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
960 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
961 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000962 if (auto AK = TLI->getExtAttrForI32Param(false))
963 StartFileCall->addParamAttr(2, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000964 auto *NumCounters =
965 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
966 auto *EmitFunctionCallArgsArray =
967 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
968 auto *EmitArcsCallArgsArray =
969 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
970 auto *EnterCounterLoopCond =
971 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
972 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
973
974 Builder.SetInsertPoint(CounterLoopHeader);
975 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
976 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
977 auto *EmitFunctionCallArgsPtr =
978 Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000979 auto *EmitFunctionCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000980 EmitFunction,
981 {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
982 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
983 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
984 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
985 Builder.CreateLoad(
986 Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000987 if (auto AK = TLI->getExtAttrForI32Param(false)) {
988 EmitFunctionCall->addParamAttr(0, AK);
989 EmitFunctionCall->addParamAttr(2, AK);
990 EmitFunctionCall->addParamAttr(3, AK);
991 EmitFunctionCall->addParamAttr(4, AK);
992 }
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000993 auto *EmitArcsCallArgsPtr =
994 Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000995 auto *EmitArcsCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000996 EmitArcs,
997 {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
998 Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000999 if (auto AK = TLI->getExtAttrForI32Param(false))
1000 EmitArcsCall->addParamAttr(0, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001001 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1002 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1003 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1004 JV->addIncoming(NextJV, CounterLoopHeader);
1005
1006 Builder.SetInsertPoint(FileLoopLatch);
1007 Builder.CreateCall(SummaryInfo, {});
1008 Builder.CreateCall(EndFile, {});
1009 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1010 auto *FileLoopCond =
1011 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1012 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1013 IV->addIncoming(NextIV, FileLoopLatch);
1014
1015 Builder.SetInsertPoint(ExitBB);
Nick Lewyckyc58d2932011-04-26 03:54:16 +00001016 Builder.CreateRetVoid();
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001017
Bill Wendlingc3cab812013-03-18 23:04:39 +00001018 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +00001019}
Bill Wendling15605172012-05-28 06:10:56 +00001020
Bill Wendlingc3cab812013-03-18 23:04:39 +00001021Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +00001022insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1023 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +00001024 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +00001025 if (!FlushF)
1026 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +00001027 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001028 else
1029 FlushF->setLinkage(GlobalValue::InternalLinkage);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001030 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001031 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +00001032 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001033 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001034
Bill Wendling2e6e8662012-09-13 00:09:55 +00001035 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1036
1037 // Write out the current counters.
1038 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1039 assert(WriteoutF && "Need to create the writeout function first!");
1040
1041 IRBuilder<> Builder(Entry);
David Blaikieff6409d2015-05-18 22:13:54 +00001042 Builder.CreateCall(WriteoutF, {});
Bill Wendling2e6e8662012-09-13 00:09:55 +00001043
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001044 // Zero out the counters.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001045 for (const auto &I : CountersBySP) {
1046 GlobalVariable *GV = I.first;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001047 Constant *Null = Constant::getNullValue(GV->getValueType());
Bill Wendling8d26bc32012-09-14 22:35:49 +00001048 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001049 }
Bill Wendling2e6e8662012-09-13 00:09:55 +00001050
1051 Type *RetTy = FlushF->getReturnType();
1052 if (RetTy == Type::getVoidTy(*Ctx))
1053 Builder.CreateRetVoid();
1054 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +00001055 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +00001056 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1057 else
Bill Wendlingc3cab812013-03-18 23:04:39 +00001058 report_fatal_error("invalid return type for __llvm_gcov_flush");
1059
1060 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +00001061}