blob: eeaf214f0ab97ef8189a5bd847326ff8331a3eed [file] [log] [blame]
Nick Lewycky966edd02011-04-16 01:20:23 +00001//===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Nick Lewycky966edd02011-04-16 01:20:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements GCOV-style profiling. When this pass is run it emits
10// "gcno" files next to the existing source, and instruments the code that runs
11// to records the edges between blocks that run and emit a complementary "gcda"
12// file on exit.
13//
14//===----------------------------------------------------------------------===//
15
Nick Lewycky966edd02011-04-16 01:20:23 +000016#include "llvm/ADT/DenseMap.h"
Yuchen Wubabe7492013-11-20 04:15:05 +000017#include "llvm/ADT/Hashing.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth71c3a3f2018-05-02 22:24:39 +000019#include "llvm/ADT/Sequence.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000020#include "llvm/ADT/Statistic.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000021#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +000023#include "llvm/Analysis/EHPersonalities.h"
Ulrich Weigandb961fdc2018-07-10 16:05:47 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Vedant Kumar727d8952018-09-11 18:38:34 +000025#include "llvm/IR/CFG.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"
Calixte Denizetc6fabea2018-11-12 09:01:43 +000038#include "llvm/Support/Regex.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
Calixte Denizetc6fabea2018-11-12 09:01:43 +000099 bool isFunctionInstrumented(const Function &F);
100 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
101 static bool doesFilenameMatchARegex(StringRef Filename,
102 std::vector<Regex> &Regexes);
103
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000104 // Get pointers to the functions in the runtime library.
James Y Knight13680222019-02-01 02:28:03 +0000105 FunctionCallee getStartFileFunc();
106 FunctionCallee getEmitFunctionFunc();
107 FunctionCallee getEmitArcsFunc();
108 FunctionCallee getSummaryInfoFunc();
109 FunctionCallee getEndFileFunc();
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000110
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000111 // Add the function to write out all our counters to the global destructor
112 // list.
113 Function *
114 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
115 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000116
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000117 void AddFlushBeforeForkAndExec();
118
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000119 enum class GCovFileType { GCNO, GCDA };
120 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
Nick Lewycky966edd02011-04-16 01:20:23 +0000121
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000122 GCOVOptions Options;
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000123
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000124 // Reversed, NUL-terminated copy of Options.Version.
125 char ReversedVersion[5];
126 // Checksum, produced by hash of EdgeDestinations
127 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000128
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000129 Module *M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000130 const TargetLibraryInfo *TLI;
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000131 LLVMContext *Ctx;
132 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000133 std::vector<Regex> FilterRe;
134 std::vector<Regex> ExcludeRe;
135 StringMap<bool> InstrumentedFiles;
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000136};
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
Fangrui Songf78650a2018-07-30 19:41:25 +0000149 bool runOnModule(Module &M) override {
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000150 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
151 return Profiler.runOnModule(M, TLI);
152 }
153
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<TargetLibraryInfoWrapperPass>();
156 }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000157
158private:
159 GCOVProfiler Profiler;
160};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000161}
Nick Lewycky966edd02011-04-16 01:20:23 +0000162
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000163char GCOVProfilerLegacyPass::ID = 0;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000164INITIALIZE_PASS_BEGIN(
165 GCOVProfilerLegacyPass, "insert-gcov-profiling",
166 "Insert instrumentation for GCOV profiling", false, false)
167INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
168INITIALIZE_PASS_END(
169 GCOVProfilerLegacyPass, "insert-gcov-profiling",
170 "Insert instrumentation for GCOV profiling", false, false)
Nick Lewycky966edd02011-04-16 01:20:23 +0000171
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000172ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000173 return new GCOVProfilerLegacyPass(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000174}
Nick Lewycky966edd02011-04-16 01:20:23 +0000175
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000176static StringRef getFunctionName(const DISubprogram *SP) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000177 if (!SP->getLinkageName().empty())
178 return SP->getLinkageName();
179 return SP->getName();
Nick Lewyckyd6718632013-03-19 01:37:55 +0000180}
181
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000182/// Extract a filename for a DISubprogram.
183///
184/// Prefer relative paths in the coverage notes. Clang also may split
185/// up absolute paths into a directory and filename component. When
186/// the relative path doesn't exist, reconstruct the absolute path.
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000187static SmallString<128> getFilename(const DISubprogram *SP) {
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000188 SmallString<128> Path;
189 StringRef RelPath = SP->getFilename();
190 if (sys::fs::exists(RelPath))
191 Path = RelPath;
192 else
193 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
194 return Path;
195}
196
Nick Lewycky966edd02011-04-16 01:20:23 +0000197namespace {
198 class GCOVRecord {
199 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000200 static const char *const LinesTag;
201 static const char *const FunctionTag;
202 static const char *const BlockTag;
203 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000204
Benjamin Kramer79de6e62015-04-11 18:57:14 +0000205 GCOVRecord() = default;
Nick Lewycky966edd02011-04-16 01:20:23 +0000206
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000207 void writeBytes(const char *Bytes, int Size) {
208 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000209 }
210
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000211 void write(uint32_t i) {
212 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000213 }
214
215 // Returns the length measured in 4-byte blocks that will be used to
216 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000217 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000218 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000219 // padding out to the next 4-byte word. The length is measured in 4-byte
220 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000221 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000222 }
223
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000224 void writeGCOVString(StringRef s) {
225 uint32_t Len = lengthOfGCOVString(s);
226 write(Len);
227 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000228
229 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000230 assert((unsigned)(4 - (s.size() % 4)) > 0);
231 assert((unsigned)(4 - (s.size() % 4)) <= 4);
232 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000233 }
234
235 raw_ostream *os;
236 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000237 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
238 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
239 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
240 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000241
242 class GCOVFunction;
243 class GCOVBlock;
244
245 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000246 // list of line numbers and a single filename, representing lines that belong
247 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000248 class GCOVLines : public GCOVRecord {
249 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000250 void addLine(uint32_t Line) {
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000251 assert(Line != 0 && "Line zero is not a valid real line number.");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000252 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000253 }
254
Craig Topper24048c92013-07-17 03:54:53 +0000255 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000256 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000257 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000258 }
259
Devang Pateladd1f172011-09-20 18:35:00 +0000260 void writeOut() {
261 write(0);
262 writeGCOVString(Filename);
263 for (int i = 0, e = Lines.size(); i != e; ++i)
264 write(Lines[i]);
265 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000266
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000267 GCOVLines(StringRef F, raw_ostream *os)
Devang Pateladd1f172011-09-20 18:35:00 +0000268 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000269 this->os = os;
270 }
271
Devang Patel7d06f5c2011-09-20 18:48:56 +0000272 private:
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000273 std::string Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000274 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000275 };
276
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000277
Nick Lewycky966edd02011-04-16 01:20:23 +0000278 // Represent a basic block in GCOV. Each block has a unique number in the
279 // function, number of lines belonging to each block, and a set of edges to
280 // other blocks.
281 class GCOVBlock : public GCOVRecord {
282 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000283 GCOVLines &getFile(StringRef Filename) {
Benjamin Kramereab3d362016-07-21 13:37:48 +0000284 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000285 }
286
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000287 void addEdge(GCOVBlock &Successor) {
288 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000289 }
290
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000291 void writeOut() {
292 uint32_t Len = 3;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000293 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000294 for (auto &I : LinesByFile) {
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000295 Len += I.second.length();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000296 SortedLinesByFile.push_back(&I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000297 }
298
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000299 writeBytes(LinesTag, 4);
300 write(Len);
301 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000302
Fangrui Song3507c6e2018-09-30 22:31:29 +0000303 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
304 StringMapEntry<GCOVLines> *RHS) {
305 return LHS->getKey() < RHS->getKey();
306 });
Benjamin Kramer135f7352016-06-26 12:28:59 +0000307 for (auto &I : SortedLinesByFile)
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000308 I->getValue().writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000309 write(0);
310 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000311 }
312
David Blaikieea37c112014-12-22 23:12:42 +0000313 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
314 // Only allow copy before edges and lines have been added. After that,
315 // there are inter-block pointers (eg: edges) that won't take kindly to
316 // blocks being copied or moved around.
317 assert(LinesByFile.empty());
318 assert(OutEdges.empty());
319 }
320
Nick Lewycky966edd02011-04-16 01:20:23 +0000321 private:
322 friend class GCOVFunction;
323
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000324 GCOVBlock(uint32_t Number, raw_ostream *os)
325 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000326 this->os = os;
327 }
328
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000329 uint32_t Number;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000330 StringMap<GCOVLines> LinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000331 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000332 };
333
334 // A function has a unique identifier, a checksum (we leave as zero) and a
335 // set of blocks and a map of edges between blocks. This is the only GCOV
336 // object users can construct, the blocks and lines will be rooted here.
337 class GCOVFunction : public GCOVRecord {
338 public:
Peter Collingbourned4bff302015-11-05 22:03:56 +0000339 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
340 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
David Blaikieea37c112014-12-22 23:12:42 +0000341 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
342 ReturnBlock(1, os) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000343 this->os = os;
344
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000345 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewycky2e8a6212014-12-03 02:45:01 +0000346
David Blaikieea37c112014-12-22 23:12:42 +0000347 uint32_t i = 0;
348 for (auto &BB : *F) {
Justin Bogner3faa76b2015-03-16 23:52:03 +0000349 // Skip index 1 if it's assigned to the ReturnBlock.
350 if (i == 1 && ExitBlockBeforeBody)
351 ++i;
352 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
Nick Lewycky966edd02011-04-16 01:20:23 +0000353 }
Justin Bogner3faa76b2015-03-16 23:52:03 +0000354 if (!ExitBlockBeforeBody)
355 ReturnBlock.Number = i;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000356
Alp Tokere69170a2014-06-26 22:52:05 +0000357 std::string FunctionNameAndLine;
358 raw_string_ostream FNLOS(FunctionNameAndLine);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000359 FNLOS << getFunctionName(SP) << SP->getLine();
Alp Tokere69170a2014-06-26 22:52:05 +0000360 FNLOS.flush();
361 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewycky966edd02011-04-16 01:20:23 +0000362 }
363
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000364 GCOVBlock &getBlock(BasicBlock *BB) {
David Blaikieea37c112014-12-22 23:12:42 +0000365 return Blocks.find(BB)->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000366 }
367
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000368 GCOVBlock &getReturnBlock() {
David Blaikieea37c112014-12-22 23:12:42 +0000369 return ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000370 }
371
Yuchen Wubabe7492013-11-20 04:15:05 +0000372 std::string getEdgeDestinations() {
Alp Tokere69170a2014-06-26 22:52:05 +0000373 std::string EdgeDestinations;
374 raw_string_ostream EDOS(EdgeDestinations);
Yuchen Wubabe7492013-11-20 04:15:05 +0000375 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000376 for (BasicBlock &I : *F) {
377 GCOVBlock &Block = getBlock(&I);
Yuchen Wubabe7492013-11-20 04:15:05 +0000378 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
Alp Tokere69170a2014-06-26 22:52:05 +0000379 EDOS << Block.OutEdges[i]->Number;
Yuchen Wubabe7492013-11-20 04:15:05 +0000380 }
Alp Tokere69170a2014-06-26 22:52:05 +0000381 return EdgeDestinations;
Yuchen Wubabe7492013-11-20 04:15:05 +0000382 }
383
Daniel Jasper87a24d52013-12-04 08:57:17 +0000384 uint32_t getFuncChecksum() {
385 return FuncChecksum;
386 }
387
Yuchen Wubabe7492013-11-20 04:15:05 +0000388 void setCfgChecksum(uint32_t Checksum) {
389 CfgChecksum = Checksum;
390 }
391
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000392 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000393 writeBytes(FunctionTag, 4);
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000394 SmallString<128> Filename = getFilename(SP);
Yuchen Wubabe7492013-11-20 04:15:05 +0000395 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000396 1 + lengthOfGCOVString(Filename) + 1;
Yuchen Wubabe7492013-11-20 04:15:05 +0000397 if (UseCfgChecksum)
398 ++BlockLen;
399 write(BlockLen);
400 write(Ident);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000401 write(FuncChecksum);
Yuchen Wubabe7492013-11-20 04:15:05 +0000402 if (UseCfgChecksum)
403 write(CfgChecksum);
404 writeGCOVString(getFunctionName(SP));
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000405 writeGCOVString(Filename);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000406 write(SP->getLine());
Yuchen Wubabe7492013-11-20 04:15:05 +0000407
Nick Lewycky966edd02011-04-16 01:20:23 +0000408 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000409 writeBytes(BlockTag, 4);
410 write(Blocks.size() + 1);
411 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
412 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000413 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000414 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000415
416 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000417 if (Blocks.empty()) return;
418 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000419 for (BasicBlock &I : *F) {
420 GCOVBlock &Block = getBlock(&I);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000421 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000422
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000423 writeBytes(EdgeTag, 4);
424 write(Block.OutEdges.size() * 2 + 1);
425 write(Block.Number);
426 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000427 LLVM_DEBUG(dbgs() << Block.Number << " -> "
428 << Block.OutEdges[i]->Number << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000429 write(Block.OutEdges[i]->Number);
430 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000431 }
432 }
433
434 // Emit lines for each block.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000435 for (BasicBlock &I : *F)
436 getBlock(&I).writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000437 }
438
439 private:
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000440 const DISubprogram *SP;
Yuchen Wubabe7492013-11-20 04:15:05 +0000441 uint32_t Ident;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000442 uint32_t FuncChecksum;
Yuchen Wubabe7492013-11-20 04:15:05 +0000443 bool UseCfgChecksum;
444 uint32_t CfgChecksum;
David Blaikieea37c112014-12-22 23:12:42 +0000445 DenseMap<BasicBlock *, GCOVBlock> Blocks;
446 GCOVBlock ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000447 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000448}
Nick Lewycky966edd02011-04-16 01:20:23 +0000449
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000450// RegexesStr is a string containing differents regex separated by a semi-colon.
451// For example "foo\..*$;bar\..*$".
452std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
453 std::vector<Regex> Regexes;
454 while (!RegexesStr.empty()) {
455 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
456 if (!HeadTail.first.empty()) {
457 Regex Re(HeadTail.first);
458 std::string Err;
459 if (!Re.isValid(Err)) {
460 Ctx->emitError(Twine("Regex ") + HeadTail.first +
461 " is not valid: " + Err);
462 }
463 Regexes.emplace_back(std::move(Re));
464 }
465 RegexesStr = HeadTail.second;
466 }
467 return Regexes;
468}
469
470bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
471 std::vector<Regex> &Regexes) {
472 for (Regex &Re : Regexes) {
473 if (Re.match(Filename)) {
474 return true;
475 }
476 }
477 return false;
478}
479
480bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
481 if (FilterRe.empty() && ExcludeRe.empty()) {
482 return true;
483 }
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000484 SmallString<128> Filename = getFilename(F.getSubprogram());
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000485 auto It = InstrumentedFiles.find(Filename);
486 if (It != InstrumentedFiles.end()) {
487 return It->second;
488 }
489
490 SmallString<256> RealPath;
491 StringRef RealFilename;
492
493 // Path can be
494 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
495 // such a case we must get the real_path.
496 if (sys::fs::real_path(Filename, RealPath)) {
497 // real_path can fail with path like "foo.c".
498 RealFilename = Filename;
499 } else {
500 RealFilename = RealPath;
501 }
502
503 bool ShouldInstrument;
504 if (FilterRe.empty()) {
505 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
506 } else if (ExcludeRe.empty()) {
507 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
508 } else {
509 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
510 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
511 }
512 InstrumentedFiles[Filename] = ShouldInstrument;
513 return ShouldInstrument;
514}
515
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000516std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000517 GCovFileType OutputType) {
518 bool Notes = OutputType == GCovFileType::GCNO;
519
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000520 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
521 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000522 MDNode *N = GCov->getOperand(i);
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000523 bool ThreeElement = N->getNumOperands() == 3;
524 if (!ThreeElement && N->getNumOperands() != 2)
525 continue;
Nick Lewycky8dd4dad2016-08-31 23:24:43 +0000526 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000527 continue;
528
529 if (ThreeElement) {
530 // These nodes have no mangling to apply, it's stored mangled in the
531 // bitcode.
532 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
533 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
534 if (!NotesFile || !DataFile)
535 continue;
536 return Notes ? NotesFile->getString() : DataFile->getString();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000537 }
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000538
539 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
540 if (!GCovFile)
541 continue;
542
543 SmallString<128> Filename = GCovFile->getString();
544 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
545 return Filename.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000546 }
547 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000548
Ilya Biryukov449a7f02018-12-04 16:30:31 +0000549 SmallString<128> Filename = CU->getFilename();
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000550 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
Bill Wendling5aa82392013-03-26 22:47:50 +0000551 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000552 SmallString<128> CurPath;
553 if (sys::fs::current_path(CurPath)) return FName;
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000554 sys::path::append(CurPath, FName);
Bill Wendling5aa82392013-03-26 22:47:50 +0000555 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000556}
557
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000558bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000559 this->M = &M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000560 this->TLI = &TLI;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000561 Ctx = &M.getContext();
562
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000563 AddFlushBeforeForkAndExec();
564
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000565 FilterRe = createRegexesFromString(Options.Filter);
566 ExcludeRe = createRegexesFromString(Options.Exclude);
567
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000568 if (Options.EmitNotes) emitProfileNotes();
569 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000570 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000571}
572
Xinliang David Li64dbb292016-06-05 05:12:23 +0000573PreservedAnalyses GCOVProfilerPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000574 ModuleAnalysisManager &AM) {
Xinliang David Li64dbb292016-06-05 05:12:23 +0000575
576 GCOVProfiler Profiler(GCOVOpts);
577
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000578 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
579 if (!Profiler.runOnModule(M, TLI))
Xinliang David Li64dbb292016-06-05 05:12:23 +0000580 return PreservedAnalyses::all();
581
582 return PreservedAnalyses::none();
583}
584
Adrian Prantl75819ae2016-04-15 15:57:41 +0000585static bool functionHasLines(Function &F) {
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000586 // Check whether this function actually has any source lines. Not only
587 // do these waste space, they also can crash gcov.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000588 for (auto &BB : F) {
589 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000590 // Debug intrinsic locations correspond to the location of the
591 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000592 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000593
Adrian Prantl75819ae2016-04-15 15:57:41 +0000594 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000595 if (!Loc)
596 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000597
598 // Artificial lines such as calls to the global constructors.
Justin Bogner3faa76b2015-03-16 23:52:03 +0000599 if (Loc.getLine() == 0) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000600
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000601 return true;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000602 }
603 }
604 return false;
605}
606
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000607static bool isUsingScopeBasedEH(Function &F) {
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000608 if (!F.hasPersonalityFn()) return false;
609
610 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000611 return isScopedEHPersonality(Personality);
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000612}
613
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000614static bool shouldKeepInEntry(BasicBlock::iterator It) {
615 if (isa<AllocaInst>(*It)) return true;
616 if (isa<DbgInfoIntrinsic>(*It)) return true;
617 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
618 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
619 }
620
621 return false;
622}
623
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000624void GCOVProfiler::AddFlushBeforeForkAndExec() {
625 SmallVector<Instruction *, 2> ForkAndExecs;
626 for (auto &F : M->functions()) {
627 for (auto &I : instructions(F)) {
628 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
629 if (Function *Callee = CI->getCalledFunction()) {
630 LibFunc LF;
631 if (TLI->getLibFunc(*Callee, LF) &&
632 (LF == LibFunc_fork || LF == LibFunc_execl ||
633 LF == LibFunc_execle || LF == LibFunc_execlp ||
634 LF == LibFunc_execv || LF == LibFunc_execvp ||
635 LF == LibFunc_execve || LF == LibFunc_execvpe ||
636 LF == LibFunc_execvP)) {
637 ForkAndExecs.push_back(&I);
638 }
639 }
640 }
641 }
642 }
643
644 // We need to split the block after the fork/exec call
645 // because else the counters for the lines after will be
646 // the same as before the call.
647 for (auto I : ForkAndExecs) {
648 IRBuilder<> Builder(I);
649 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
James Y Knight13680222019-02-01 02:28:03 +0000650 FunctionCallee GCOVFlush = M->getOrInsertFunction("__gcov_flush", FTy);
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000651 Builder.CreateCall(GCOVFlush);
652 I->getParent()->splitBasicBlock(I);
653 }
654}
655
Nick Lewyckyad145502013-03-13 22:55:42 +0000656void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000657 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000658 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000659
Nick Lewycky6404d972011-11-27 23:22:20 +0000660 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
661 // Each compile unit gets its own .gcno file. This means that whether we run
662 // this pass over the original .o's as they're produced, or run it after
663 // LTO, we'll generate the same .gcno files.
664
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000665 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
Vedant Kumar61035fa2016-01-21 17:04:42 +0000666
667 // Skip module skeleton (and module) CUs.
668 if (CU->getDWOId())
669 continue;
670
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000671 std::error_code EC;
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000672 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
Reid Kleckner1aa4ea82017-09-18 21:31:48 +0000673 if (EC) {
674 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
675 EC.message());
676 continue;
677 }
678
Yuchen Wubabe7492013-11-20 04:15:05 +0000679 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000680
Justin Bogner58e41342014-11-06 06:55:02 +0000681 unsigned FunctionIdent = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000682 for (auto &F : M->functions()) {
683 DISubprogram *SP = F.getSubprogram();
684 if (!SP) continue;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000685 if (!functionHasLines(F) || !isFunctionInstrumented(F))
686 continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000687 // TODO: Functions using scope-based EH are currently not supported.
688 if (isUsingScopeBasedEH(F)) continue;
Bob Wilson055a0b42014-01-31 05:24:01 +0000689
690 // gcov expects every function to start with an entry block that has a
691 // single successor, so split the entry block to make sure of that.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000692 BasicBlock &EntryBlock = F.getEntryBlock();
Bob Wilson055a0b42014-01-31 05:24:01 +0000693 BasicBlock::iterator It = EntryBlock.begin();
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000694 while (shouldKeepInEntry(It))
Bob Wilson055a0b42014-01-31 05:24:01 +0000695 ++It;
696 EntryBlock.splitBasicBlock(It);
Yuchen Wuc87ca322013-11-22 23:07:45 +0000697
Adrian Prantl75819ae2016-04-15 15:57:41 +0000698 Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
Justin Bogner3faa76b2015-03-16 23:52:03 +0000699 Options.UseCfgChecksum,
700 Options.ExitBlockBeforeBody));
David Blaikie229de502014-04-21 20:41:55 +0000701 GCOVFunction &Func = *Funcs.back();
Nick Lewycky6404d972011-11-27 23:22:20 +0000702
Calixte Denizetd2f290b2018-10-11 08:53:43 +0000703 // Add the function line number to the lines of the entry block
704 // to have a counter for the function definition.
Calixte Denizet38d50542018-10-30 18:41:31 +0000705 uint32_t Line = SP->getLine();
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000706 auto Filename = getFilename(SP);
707 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
Calixte Denizetd2f290b2018-10-11 08:53:43 +0000708
Adrian Prantl75819ae2016-04-15 15:57:41 +0000709 for (auto &BB : F) {
710 GCOVBlock &Block = Func.getBlock(&BB);
Chandler Carruthedb12a82018-10-15 10:04:59 +0000711 Instruction *TI = BB.getTerminator();
Nick Lewycky6404d972011-11-27 23:22:20 +0000712 if (int successors = TI->getNumSuccessors()) {
713 for (int i = 0; i != successors; ++i) {
David Blaikie229de502014-04-21 20:41:55 +0000714 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000715 }
716 } else if (isa<ReturnInst>(TI)) {
David Blaikie229de502014-04-21 20:41:55 +0000717 Block.addEdge(Func.getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000718 }
719
Adrian Prantl75819ae2016-04-15 15:57:41 +0000720 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000721 // Debug intrinsic locations correspond to the location of the
722 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000723 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000724
Adrian Prantl75819ae2016-04-15 15:57:41 +0000725 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000726 if (!Loc)
727 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000728
729 // Artificial lines such as calls to the global constructors.
Calixte Denizeteb7f6022018-09-20 08:53:06 +0000730 if (Loc.getLine() == 0 || Loc.isImplicitCode())
731 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000732
Nick Lewycky6404d972011-11-27 23:22:20 +0000733 if (Line == Loc.getLine()) continue;
734 Line = Loc.getLine();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000735 if (SP != getDISubprogram(Loc.getScope()))
736 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000737
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000738 GCOVLines &Lines = Block.getFile(Filename);
Nick Lewycky6404d972011-11-27 23:22:20 +0000739 Lines.addLine(Loc.getLine());
740 }
Calixte Denizet38d50542018-10-30 18:41:31 +0000741 Line = 0;
Nick Lewycky6404d972011-11-27 23:22:20 +0000742 }
David Blaikie229de502014-04-21 20:41:55 +0000743 EdgeDestinations += Func.getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000744 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000745
Yuchen Wu664dc762013-11-21 04:01:05 +0000746 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000747 out.write("oncg", 4);
748 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000749 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000750
David Blaikie229de502014-04-21 20:41:55 +0000751 for (auto &Func : Funcs) {
Yuchen Wu664dc762013-11-21 04:01:05 +0000752 Func->setCfgChecksum(FileChecksums.back());
753 Func->writeOut();
754 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000755
Nick Lewycky6404d972011-11-27 23:22:20 +0000756 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
757 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000758 }
759}
760
Devang Patel2b21d862011-08-17 22:49:38 +0000761bool GCOVProfiler::emitProfileArcs() {
762 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
763 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000764
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000765 bool Result = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000766 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Devang Patel2b21d862011-08-17 22:49:38 +0000767 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000768 for (auto &F : M->functions()) {
769 DISubprogram *SP = F.getSubprogram();
770 if (!SP) continue;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000771 if (!functionHasLines(F) || !isFunctionInstrumented(F))
772 continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000773 // TODO: Functions using scope-based EH are currently not supported.
774 if (isUsingScopeBasedEH(F)) continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000775 if (!Result) Result = true;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000776
Vedant Kumar727d8952018-09-11 18:38:34 +0000777 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
Devang Patel2b21d862011-08-17 22:49:38 +0000778 unsigned Edges = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000779 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000780 Instruction *TI = BB.getTerminator();
Vedant Kumar727d8952018-09-11 18:38:34 +0000781 if (isa<ReturnInst>(TI)) {
782 EdgeToCounter[{&BB, nullptr}] = Edges++;
783 } else {
784 for (BasicBlock *Succ : successors(TI)) {
785 EdgeToCounter[{&BB, Succ}] = Edges++;
786 }
787 }
Devang Patel2b21d862011-08-17 22:49:38 +0000788 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000789
Devang Patel2b21d862011-08-17 22:49:38 +0000790 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000791 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000792 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000793 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000794 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000795 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000796 "__llvm_gcov_ctr");
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000797 CountersBySP.push_back(std::make_pair(Counters, SP));
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000798
Vedant Kumar727d8952018-09-11 18:38:34 +0000799 // If a BB has several predecessors, use a PHINode to select
800 // the correct counter.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000801 for (auto &BB : F) {
Vedant Kumar727d8952018-09-11 18:38:34 +0000802 const unsigned EdgeCount =
803 std::distance(pred_begin(&BB), pred_end(&BB));
804 if (EdgeCount) {
805 // The phi node must be at the begin of the BB.
806 IRBuilder<> BuilderForPhi(&*BB.begin());
807 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
808 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
809 for (BasicBlock *Pred : predecessors(&BB)) {
810 auto It = EdgeToCounter.find({Pred, &BB});
811 assert(It != EdgeToCounter.end());
812 const unsigned Edge = It->second;
813 Value *EdgeCounter =
814 BuilderForPhi.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
815 Phi->addIncoming(EdgeCounter, Pred);
Devang Patel2b21d862011-08-17 22:49:38 +0000816 }
Bill Wendling707f6012013-08-20 23:52:00 +0000817
Vedant Kumar727d8952018-09-11 18:38:34 +0000818 // Skip phis, landingpads.
819 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
820 Value *Count = Builder.CreateLoad(Phi);
821 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
822 Builder.CreateStore(Count, Phi);
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000823
Chandler Carruthedb12a82018-10-15 10:04:59 +0000824 Instruction *TI = BB.getTerminator();
Vedant Kumar727d8952018-09-11 18:38:34 +0000825 if (isa<ReturnInst>(TI)) {
826 auto It = EdgeToCounter.find({&BB, nullptr});
827 assert(It != EdgeToCounter.end());
828 const unsigned Edge = It->second;
829 Value *Counter =
830 Builder.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
831 Value *Count = Builder.CreateLoad(Counter);
832 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
833 Builder.CreateStore(Count, Counter);
834 }
Devang Patel2b21d862011-08-17 22:49:38 +0000835 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000836 }
837 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000838
Bill Wendlingc3cab812013-03-18 23:04:39 +0000839 Function *WriteoutF = insertCounterWriteout(CountersBySP);
840 Function *FlushF = insertFlush(CountersBySP);
841
842 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000843 // be executed at exit and the "__llvm_gcov_flush" function to be executed
844 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000845 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
846 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
847 "__llvm_gcov_init", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000848 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000849 F->setLinkage(GlobalValue::InternalLinkage);
850 F->addFnAttr(Attribute::NoInline);
851 if (Options.NoRedZone)
852 F->addFnAttr(Attribute::NoRedZone);
853
854 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
855 IRBuilder<> Builder(BB);
856
Bill Wendlingc3cab812013-03-18 23:04:39 +0000857 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000858 Type *Params[] = {
859 PointerType::get(FTy, 0),
860 PointerType::get(FTy, 0)
861 };
862 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000863
Yuchen Wu3197b252013-10-23 20:35:00 +0000864 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000865 // functions.
James Y Knight13680222019-02-01 02:28:03 +0000866 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000867 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
Bill Wendlingc3cab812013-03-18 23:04:39 +0000868 Builder.CreateRetVoid();
869
870 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000871 }
Bill Wendling15605172012-05-28 06:10:56 +0000872
Devang Patel2b21d862011-08-17 22:49:38 +0000873 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000874}
875
James Y Knight13680222019-02-01 02:28:03 +0000876FunctionCallee GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000877 Type *Args[] = {
878 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
879 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000880 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000881 };
882 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
James Y Knight13680222019-02-01 02:28:03 +0000883 AttributeList AL;
884 if (auto AK = TLI->getExtAttrForI32Param(false))
885 AL = AL.addParamAttribute(*Ctx, 2, AK);
886 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000887 return Res;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000888}
889
James Y Knight13680222019-02-01 02:28:03 +0000890FunctionCallee GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000891 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000892 Type::getInt32Ty(*Ctx), // uint32_t ident
893 Type::getInt8PtrTy(*Ctx), // const char *function_name
Daniel Jasper87a24d52013-12-04 08:57:17 +0000894 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000895 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000896 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000897 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000898 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
James Y Knight13680222019-02-01 02:28:03 +0000899 AttributeList AL;
900 if (auto AK = TLI->getExtAttrForI32Param(false)) {
901 AL = AL.addParamAttribute(*Ctx, 0, AK);
902 AL = AL.addParamAttribute(*Ctx, 2, AK);
903 AL = AL.addParamAttribute(*Ctx, 3, AK);
904 AL = AL.addParamAttribute(*Ctx, 4, AK);
905 }
906 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000907}
908
James Y Knight13680222019-02-01 02:28:03 +0000909FunctionCallee GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000910 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000911 Type::getInt32Ty(*Ctx), // uint32_t num_counters
912 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
913 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000914 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
James Y Knight13680222019-02-01 02:28:03 +0000915 AttributeList AL;
916 if (auto AK = TLI->getExtAttrForI32Param(false))
917 AL = AL.addParamAttribute(*Ctx, 0, AK);
918 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
Nick Lewycky966edd02011-04-16 01:20:23 +0000919}
920
James Y Knight13680222019-02-01 02:28:03 +0000921FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
Yuchen Wu062f24c2013-11-12 04:59:08 +0000922 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
923 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
924}
925
James Y Knight13680222019-02-01 02:28:03 +0000926FunctionCallee GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000927 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000928 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000929}
930
Bill Wendlingc3cab812013-03-18 23:04:39 +0000931Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000932 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000933 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
934 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
935 if (!WriteoutF)
936 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
937 "__llvm_gcov_writeout", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000938 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000939 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000940 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000941 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000942
943 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000944 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000945
James Y Knight13680222019-02-01 02:28:03 +0000946 FunctionCallee StartFile = getStartFileFunc();
947 FunctionCallee EmitFunction = getEmitFunctionFunc();
948 FunctionCallee EmitArcs = getEmitArcsFunc();
949 FunctionCallee SummaryInfo = getSummaryInfoFunc();
950 FunctionCallee EndFile = getEndFileFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000951
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000952 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
953 if (!CUNodes) {
954 Builder.CreateRetVoid();
955 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000956 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000957
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000958 // Collect the relevant data into a large constant data structure that we can
959 // walk to write out everything.
960 StructType *StartFileCallArgsTy = StructType::create(
961 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
962 StructType *EmitFunctionCallArgsTy = StructType::create(
963 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
964 Builder.getInt8Ty(), Builder.getInt32Ty()});
965 StructType *EmitArcsCallArgsTy = StructType::create(
966 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
967 StructType *FileInfoTy =
968 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
969 EmitFunctionCallArgsTy->getPointerTo(),
970 EmitArcsCallArgsTy->getPointerTo()});
971
972 Constant *Zero32 = Builder.getInt32(0);
Chandler Carruthe74c3542018-05-03 00:11:03 +0000973 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
974 Constant *TwoZero32s[] = {Zero32, Zero32};
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000975
976 SmallVector<Constant *, 8> FileInfos;
977 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
978 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
979
980 // Skip module skeleton (and module) CUs.
981 if (CU->getDWOId())
982 continue;
983
984 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
985 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
986 auto *StartFileCallArgs = ConstantStruct::get(
987 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
988 Builder.CreateGlobalStringPtr(ReversedVersion),
989 Builder.getInt32(CfgChecksum)});
990
991 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
992 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
993 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
994 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
995 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
996 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
997 EmitFunctionCallArgsTy,
998 {Builder.getInt32(j),
999 Options.FunctionNamesInData
1000 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
1001 : Constant::getNullValue(Builder.getInt8PtrTy()),
1002 Builder.getInt32(FuncChecksum),
1003 Builder.getInt8(Options.UseCfgChecksum),
1004 Builder.getInt32(CfgChecksum)}));
1005
1006 GlobalVariable *GV = CountersBySP[j].first;
1007 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1008 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1009 EmitArcsCallArgsTy,
Chandler Carruthe74c3542018-05-03 00:11:03 +00001010 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1011 GV->getValueType(), GV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001012 }
1013 // Create global arrays for the two emit calls.
1014 int CountersSize = CountersBySP.size();
1015 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1016 "Mismatched array size!");
1017 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1018 "Mismatched array size!");
1019 auto *EmitFunctionCallArgsArrayTy =
1020 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1021 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1022 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1023 GlobalValue::InternalLinkage,
1024 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1025 EmitFunctionCallArgsArray),
1026 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1027 auto *EmitArcsCallArgsArrayTy =
1028 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1029 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1030 GlobalValue::UnnamedAddr::Global);
1031 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1032 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1033 GlobalValue::InternalLinkage,
1034 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1035 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1036 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1037
1038 FileInfos.push_back(ConstantStruct::get(
1039 FileInfoTy,
1040 {StartFileCallArgs, Builder.getInt32(CountersSize),
Chandler Carruthe74c3542018-05-03 00:11:03 +00001041 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1042 EmitFunctionCallArgsArrayGV,
1043 TwoZero32s),
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001044 ConstantExpr::getInBoundsGetElementPtr(
Chandler Carruthe74c3542018-05-03 00:11:03 +00001045 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001046 }
1047
1048 // If we didn't find anything to actually emit, bail on out.
1049 if (FileInfos.empty()) {
1050 Builder.CreateRetVoid();
1051 return WriteoutF;
1052 }
1053
1054 // To simplify code, we cap the number of file infos we write out to fit
1055 // easily in a 32-bit signed integer. This gives consistent behavior between
1056 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1057 // operations on 32-bit systems. It also seems unreasonable to try to handle
1058 // more than 2 billion files.
1059 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1060 FileInfos.resize(INT_MAX);
1061
1062 // Create a global for the entire data structure so we can walk it more
1063 // easily.
1064 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1065 auto *FileInfoArrayGV = new GlobalVariable(
1066 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1067 ConstantArray::get(FileInfoArrayTy, FileInfos),
1068 "__llvm_internal_gcov_emit_file_info");
1069 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1070
1071 // Create the CFG for walking this data structure.
1072 auto *FileLoopHeader =
1073 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1074 auto *CounterLoopHeader =
1075 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1076 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1077 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1078
1079 // We always have at least one file, so just branch to the header.
1080 Builder.CreateBr(FileLoopHeader);
1081
1082 // The index into the files structure is our loop induction variable.
1083 Builder.SetInsertPoint(FileLoopHeader);
1084 PHINode *IV =
1085 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1086 IV->addIncoming(Builder.getInt32(0), BB);
1087 auto *FileInfoPtr =
1088 Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
1089 auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001090 auto *StartFileCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001091 StartFile,
1092 {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
1093 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
1094 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001095 if (auto AK = TLI->getExtAttrForI32Param(false))
1096 StartFileCall->addParamAttr(2, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001097 auto *NumCounters =
1098 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
1099 auto *EmitFunctionCallArgsArray =
1100 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
1101 auto *EmitArcsCallArgsArray =
1102 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
1103 auto *EnterCounterLoopCond =
1104 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1105 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1106
1107 Builder.SetInsertPoint(CounterLoopHeader);
1108 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1109 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1110 auto *EmitFunctionCallArgsPtr =
1111 Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001112 auto *EmitFunctionCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001113 EmitFunction,
1114 {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
1115 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
1116 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
1117 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
1118 Builder.CreateLoad(
1119 Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001120 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1121 EmitFunctionCall->addParamAttr(0, AK);
1122 EmitFunctionCall->addParamAttr(2, AK);
1123 EmitFunctionCall->addParamAttr(3, AK);
1124 EmitFunctionCall->addParamAttr(4, AK);
1125 }
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001126 auto *EmitArcsCallArgsPtr =
1127 Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001128 auto *EmitArcsCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001129 EmitArcs,
1130 {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
1131 Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001132 if (auto AK = TLI->getExtAttrForI32Param(false))
1133 EmitArcsCall->addParamAttr(0, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001134 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1135 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1136 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1137 JV->addIncoming(NextJV, CounterLoopHeader);
1138
1139 Builder.SetInsertPoint(FileLoopLatch);
1140 Builder.CreateCall(SummaryInfo, {});
1141 Builder.CreateCall(EndFile, {});
1142 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1143 auto *FileLoopCond =
1144 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1145 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1146 IV->addIncoming(NextIV, FileLoopLatch);
1147
1148 Builder.SetInsertPoint(ExitBB);
Nick Lewyckyc58d2932011-04-26 03:54:16 +00001149 Builder.CreateRetVoid();
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001150
Bill Wendlingc3cab812013-03-18 23:04:39 +00001151 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +00001152}
Bill Wendling15605172012-05-28 06:10:56 +00001153
Bill Wendlingc3cab812013-03-18 23:04:39 +00001154Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +00001155insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1156 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +00001157 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +00001158 if (!FlushF)
1159 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +00001160 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001161 else
1162 FlushF->setLinkage(GlobalValue::InternalLinkage);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001163 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001164 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +00001165 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001166 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001167
Bill Wendling2e6e8662012-09-13 00:09:55 +00001168 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1169
1170 // Write out the current counters.
1171 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1172 assert(WriteoutF && "Need to create the writeout function first!");
1173
1174 IRBuilder<> Builder(Entry);
David Blaikieff6409d2015-05-18 22:13:54 +00001175 Builder.CreateCall(WriteoutF, {});
Bill Wendling2e6e8662012-09-13 00:09:55 +00001176
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001177 // Zero out the counters.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001178 for (const auto &I : CountersBySP) {
1179 GlobalVariable *GV = I.first;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001180 Constant *Null = Constant::getNullValue(GV->getValueType());
Bill Wendling8d26bc32012-09-14 22:35:49 +00001181 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001182 }
Bill Wendling2e6e8662012-09-13 00:09:55 +00001183
1184 Type *RetTy = FlushF->getReturnType();
1185 if (RetTy == Type::getVoidTy(*Ctx))
1186 Builder.CreateRetVoid();
1187 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +00001188 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +00001189 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1190 else
Bill Wendlingc3cab812013-03-18 23:04:39 +00001191 report_fatal_error("invalid return type for __llvm_gcov_flush");
1192
1193 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +00001194}