blob: 829123911c61b4f6c54bc0a832d72b9bccf36925 [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"
Calixte Denizetc6fabea2018-11-12 09:01:43 +000039#include "llvm/Support/Regex.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Support/raw_ostream.h"
Xinliang David Li64dbb292016-06-05 05:12:23 +000041#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth71c3a3f2018-05-02 22:24:39 +000042#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewycky0fdd0192013-06-18 06:38:21 +000044#include <algorithm>
David Blaikie229de502014-04-21 20:41:55 +000045#include <memory>
Nick Lewycky966edd02011-04-16 01:20:23 +000046#include <string>
47#include <utility>
48using namespace llvm;
49
Chandler Carruth964daaa2014-04-22 02:55:47 +000050#define DEBUG_TYPE "insert-gcov-profiling"
51
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000052static cl::opt<std::string>
53DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
54 cl::ValueRequired);
Justin Bogner3faa76b2015-03-16 23:52:03 +000055static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
56 cl::init(false), cl::Hidden);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000057
58GCOVOptions GCOVOptions::getDefault() {
59 GCOVOptions Options;
60 Options.EmitNotes = true;
61 Options.EmitData = true;
62 Options.UseCfgChecksum = false;
63 Options.NoRedZone = false;
64 Options.FunctionNamesInData = true;
Justin Bogner3faa76b2015-03-16 23:52:03 +000065 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000066
67 if (DefaultGCOVVersion.size() != 4) {
68 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
69 DefaultGCOVVersion);
70 }
71 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
72 return Options;
73}
74
Nick Lewycky966edd02011-04-16 01:20:23 +000075namespace {
Xinliang David Lifb3137c2016-06-05 03:40:03 +000076class GCOVFunction;
Yuchen Wubabe7492013-11-20 04:15:05 +000077
Xinliang David Lifb3137c2016-06-05 03:40:03 +000078class GCOVProfiler {
79public:
80 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
81 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
82 assert((Options.EmitNotes || Options.EmitData) &&
83 "GCOVProfiler asked to do nothing?");
84 ReversedVersion[0] = Options.Version[3];
85 ReversedVersion[1] = Options.Version[2];
86 ReversedVersion[2] = Options.Version[1];
87 ReversedVersion[3] = Options.Version[0];
88 ReversedVersion[4] = '\0';
89 }
Ulrich Weigandb961fdc2018-07-10 16:05:47 +000090 bool runOnModule(Module &M, const TargetLibraryInfo &TLI);
Benjamin Kramer298a3a02015-03-06 16:21:15 +000091
Xinliang David Lifb3137c2016-06-05 03:40:03 +000092private:
93 // Create the .gcno files for the Module based on DebugInfo.
94 void emitProfileNotes();
Nick Lewycky6d9f0612011-05-04 04:03:04 +000095
Xinliang David Lifb3137c2016-06-05 03:40:03 +000096 // Modify the program to track transitions along edges and call into the
97 // profiling runtime to emit .gcda files when run.
98 bool emitProfileArcs();
Nick Lewycky966edd02011-04-16 01:20:23 +000099
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000100 bool isFunctionInstrumented(const Function &F);
101 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
102 static bool doesFilenameMatchARegex(StringRef Filename,
103 std::vector<Regex> &Regexes);
104
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000105 // Get pointers to the functions in the runtime library.
106 Constant *getStartFileFunc();
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000107 Constant *getEmitFunctionFunc();
108 Constant *getEmitArcsFunc();
109 Constant *getSummaryInfoFunc();
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000110 Constant *getEndFileFunc();
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000111
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000112 // Add the function to write out all our counters to the global destructor
113 // list.
114 Function *
115 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
116 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000117
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000118 void AddFlushBeforeForkAndExec();
119
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000120 enum class GCovFileType { GCNO, GCDA };
121 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
Nick Lewycky966edd02011-04-16 01:20:23 +0000122
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000123 GCOVOptions Options;
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000124
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000125 // Reversed, NUL-terminated copy of Options.Version.
126 char ReversedVersion[5];
127 // Checksum, produced by hash of EdgeDestinations
128 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000129
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000130 Module *M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000131 const TargetLibraryInfo *TLI;
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000132 LLVMContext *Ctx;
133 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000134 std::vector<Regex> FilterRe;
135 std::vector<Regex> ExcludeRe;
136 StringMap<bool> InstrumentedFiles;
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000137};
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000138
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000139class GCOVProfilerLegacyPass : public ModulePass {
140public:
141 static char ID;
142 GCOVProfilerLegacyPass()
143 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
144 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
145 : ModulePass(ID), Profiler(Opts) {
146 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
147 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000148 StringRef getPassName() const override { return "GCOV Profiler"; }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000149
Fangrui Songf78650a2018-07-30 19:41:25 +0000150 bool runOnModule(Module &M) override {
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000151 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
152 return Profiler.runOnModule(M, TLI);
153 }
154
155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.addRequired<TargetLibraryInfoWrapperPass>();
157 }
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000158
159private:
160 GCOVProfiler Profiler;
161};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000162}
Nick Lewycky966edd02011-04-16 01:20:23 +0000163
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000164char GCOVProfilerLegacyPass::ID = 0;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000165INITIALIZE_PASS_BEGIN(
166 GCOVProfilerLegacyPass, "insert-gcov-profiling",
167 "Insert instrumentation for GCOV profiling", false, false)
168INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
169INITIALIZE_PASS_END(
170 GCOVProfilerLegacyPass, "insert-gcov-profiling",
171 "Insert instrumentation for GCOV profiling", false, false)
Nick Lewycky966edd02011-04-16 01:20:23 +0000172
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000173ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
Xinliang David Lifb3137c2016-06-05 03:40:03 +0000174 return new GCOVProfilerLegacyPass(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000175}
Nick Lewycky966edd02011-04-16 01:20:23 +0000176
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000177static StringRef getFunctionName(const DISubprogram *SP) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000178 if (!SP->getLinkageName().empty())
179 return SP->getLinkageName();
180 return SP->getName();
Nick Lewyckyd6718632013-03-19 01:37:55 +0000181}
182
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000183/// Extract a filename for a DISubprogram.
184///
185/// Prefer relative paths in the coverage notes. Clang also may split
186/// up absolute paths into a directory and filename component. When
187/// the relative path doesn't exist, reconstruct the absolute path.
188SmallString<128> getFilename(const DISubprogram *SP) {
189 SmallString<128> Path;
190 StringRef RelPath = SP->getFilename();
191 if (sys::fs::exists(RelPath))
192 Path = RelPath;
193 else
194 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
195 return Path;
196}
197
Nick Lewycky966edd02011-04-16 01:20:23 +0000198namespace {
199 class GCOVRecord {
200 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000201 static const char *const LinesTag;
202 static const char *const FunctionTag;
203 static const char *const BlockTag;
204 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000205
Benjamin Kramer79de6e62015-04-11 18:57:14 +0000206 GCOVRecord() = default;
Nick Lewycky966edd02011-04-16 01:20:23 +0000207
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000208 void writeBytes(const char *Bytes, int Size) {
209 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000210 }
211
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000212 void write(uint32_t i) {
213 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000214 }
215
216 // Returns the length measured in 4-byte blocks that will be used to
217 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000218 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000219 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000220 // padding out to the next 4-byte word. The length is measured in 4-byte
221 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000222 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000223 }
224
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000225 void writeGCOVString(StringRef s) {
226 uint32_t Len = lengthOfGCOVString(s);
227 write(Len);
228 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000229
230 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000231 assert((unsigned)(4 - (s.size() % 4)) > 0);
232 assert((unsigned)(4 - (s.size() % 4)) <= 4);
233 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000234 }
235
236 raw_ostream *os;
237 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000238 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
239 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
240 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
241 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000242
243 class GCOVFunction;
244 class GCOVBlock;
245
246 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000247 // list of line numbers and a single filename, representing lines that belong
248 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000249 class GCOVLines : public GCOVRecord {
250 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000251 void addLine(uint32_t Line) {
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000252 assert(Line != 0 && "Line zero is not a valid real line number.");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000253 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000254 }
255
Craig Topper24048c92013-07-17 03:54:53 +0000256 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000257 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000258 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000259 }
260
Devang Pateladd1f172011-09-20 18:35:00 +0000261 void writeOut() {
262 write(0);
263 writeGCOVString(Filename);
264 for (int i = 0, e = Lines.size(); i != e; ++i)
265 write(Lines[i]);
266 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000267
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000268 GCOVLines(StringRef F, raw_ostream *os)
Devang Pateladd1f172011-09-20 18:35:00 +0000269 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000270 this->os = os;
271 }
272
Devang Patel7d06f5c2011-09-20 18:48:56 +0000273 private:
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000274 std::string Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000275 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000276 };
277
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000278
Nick Lewycky966edd02011-04-16 01:20:23 +0000279 // Represent a basic block in GCOV. Each block has a unique number in the
280 // function, number of lines belonging to each block, and a set of edges to
281 // other blocks.
282 class GCOVBlock : public GCOVRecord {
283 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000284 GCOVLines &getFile(StringRef Filename) {
Benjamin Kramereab3d362016-07-21 13:37:48 +0000285 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000286 }
287
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000288 void addEdge(GCOVBlock &Successor) {
289 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000290 }
291
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000292 void writeOut() {
293 uint32_t Len = 3;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000294 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000295 for (auto &I : LinesByFile) {
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000296 Len += I.second.length();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000297 SortedLinesByFile.push_back(&I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000298 }
299
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000300 writeBytes(LinesTag, 4);
301 write(Len);
302 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000303
Fangrui Song3507c6e2018-09-30 22:31:29 +0000304 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
305 StringMapEntry<GCOVLines> *RHS) {
306 return LHS->getKey() < RHS->getKey();
307 });
Benjamin Kramer135f7352016-06-26 12:28:59 +0000308 for (auto &I : SortedLinesByFile)
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000309 I->getValue().writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000310 write(0);
311 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000312 }
313
David Blaikieea37c112014-12-22 23:12:42 +0000314 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
315 // Only allow copy before edges and lines have been added. After that,
316 // there are inter-block pointers (eg: edges) that won't take kindly to
317 // blocks being copied or moved around.
318 assert(LinesByFile.empty());
319 assert(OutEdges.empty());
320 }
321
Nick Lewycky966edd02011-04-16 01:20:23 +0000322 private:
323 friend class GCOVFunction;
324
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000325 GCOVBlock(uint32_t Number, raw_ostream *os)
326 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000327 this->os = os;
328 }
329
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000330 uint32_t Number;
Benjamin Kramer2a185a22016-07-21 12:06:31 +0000331 StringMap<GCOVLines> LinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000332 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000333 };
334
335 // A function has a unique identifier, a checksum (we leave as zero) and a
336 // set of blocks and a map of edges between blocks. This is the only GCOV
337 // object users can construct, the blocks and lines will be rooted here.
338 class GCOVFunction : public GCOVRecord {
339 public:
Peter Collingbourned4bff302015-11-05 22:03:56 +0000340 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
341 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
David Blaikieea37c112014-12-22 23:12:42 +0000342 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
343 ReturnBlock(1, os) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000344 this->os = os;
345
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000346 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewycky2e8a6212014-12-03 02:45:01 +0000347
David Blaikieea37c112014-12-22 23:12:42 +0000348 uint32_t i = 0;
349 for (auto &BB : *F) {
Justin Bogner3faa76b2015-03-16 23:52:03 +0000350 // Skip index 1 if it's assigned to the ReturnBlock.
351 if (i == 1 && ExitBlockBeforeBody)
352 ++i;
353 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
Nick Lewycky966edd02011-04-16 01:20:23 +0000354 }
Justin Bogner3faa76b2015-03-16 23:52:03 +0000355 if (!ExitBlockBeforeBody)
356 ReturnBlock.Number = i;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000357
Alp Tokere69170a2014-06-26 22:52:05 +0000358 std::string FunctionNameAndLine;
359 raw_string_ostream FNLOS(FunctionNameAndLine);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000360 FNLOS << getFunctionName(SP) << SP->getLine();
Alp Tokere69170a2014-06-26 22:52:05 +0000361 FNLOS.flush();
362 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewycky966edd02011-04-16 01:20:23 +0000363 }
364
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000365 GCOVBlock &getBlock(BasicBlock *BB) {
David Blaikieea37c112014-12-22 23:12:42 +0000366 return Blocks.find(BB)->second;
Nick Lewycky966edd02011-04-16 01:20:23 +0000367 }
368
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000369 GCOVBlock &getReturnBlock() {
David Blaikieea37c112014-12-22 23:12:42 +0000370 return ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000371 }
372
Yuchen Wubabe7492013-11-20 04:15:05 +0000373 std::string getEdgeDestinations() {
Alp Tokere69170a2014-06-26 22:52:05 +0000374 std::string EdgeDestinations;
375 raw_string_ostream EDOS(EdgeDestinations);
Yuchen Wubabe7492013-11-20 04:15:05 +0000376 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000377 for (BasicBlock &I : *F) {
378 GCOVBlock &Block = getBlock(&I);
Yuchen Wubabe7492013-11-20 04:15:05 +0000379 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
Alp Tokere69170a2014-06-26 22:52:05 +0000380 EDOS << Block.OutEdges[i]->Number;
Yuchen Wubabe7492013-11-20 04:15:05 +0000381 }
Alp Tokere69170a2014-06-26 22:52:05 +0000382 return EdgeDestinations;
Yuchen Wubabe7492013-11-20 04:15:05 +0000383 }
384
Daniel Jasper87a24d52013-12-04 08:57:17 +0000385 uint32_t getFuncChecksum() {
386 return FuncChecksum;
387 }
388
Yuchen Wubabe7492013-11-20 04:15:05 +0000389 void setCfgChecksum(uint32_t Checksum) {
390 CfgChecksum = Checksum;
391 }
392
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000393 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000394 writeBytes(FunctionTag, 4);
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000395 SmallString<128> Filename = getFilename(SP);
Yuchen Wubabe7492013-11-20 04:15:05 +0000396 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000397 1 + lengthOfGCOVString(Filename) + 1;
Yuchen Wubabe7492013-11-20 04:15:05 +0000398 if (UseCfgChecksum)
399 ++BlockLen;
400 write(BlockLen);
401 write(Ident);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000402 write(FuncChecksum);
Yuchen Wubabe7492013-11-20 04:15:05 +0000403 if (UseCfgChecksum)
404 write(CfgChecksum);
405 writeGCOVString(getFunctionName(SP));
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000406 writeGCOVString(Filename);
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000407 write(SP->getLine());
Yuchen Wubabe7492013-11-20 04:15:05 +0000408
Nick Lewycky966edd02011-04-16 01:20:23 +0000409 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000410 writeBytes(BlockTag, 4);
411 write(Blocks.size() + 1);
412 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
413 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000414 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000415 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000416
417 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000418 if (Blocks.empty()) return;
419 Function *F = Blocks.begin()->first->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000420 for (BasicBlock &I : *F) {
421 GCOVBlock &Block = getBlock(&I);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000422 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000423
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000424 writeBytes(EdgeTag, 4);
425 write(Block.OutEdges.size() * 2 + 1);
426 write(Block.Number);
427 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000428 LLVM_DEBUG(dbgs() << Block.Number << " -> "
429 << Block.OutEdges[i]->Number << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000430 write(Block.OutEdges[i]->Number);
431 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000432 }
433 }
434
435 // Emit lines for each block.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000436 for (BasicBlock &I : *F)
437 getBlock(&I).writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000438 }
439
440 private:
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000441 const DISubprogram *SP;
Yuchen Wubabe7492013-11-20 04:15:05 +0000442 uint32_t Ident;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000443 uint32_t FuncChecksum;
Yuchen Wubabe7492013-11-20 04:15:05 +0000444 bool UseCfgChecksum;
445 uint32_t CfgChecksum;
David Blaikieea37c112014-12-22 23:12:42 +0000446 DenseMap<BasicBlock *, GCOVBlock> Blocks;
447 GCOVBlock ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000448 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000449}
Nick Lewycky966edd02011-04-16 01:20:23 +0000450
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000451// RegexesStr is a string containing differents regex separated by a semi-colon.
452// For example "foo\..*$;bar\..*$".
453std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
454 std::vector<Regex> Regexes;
455 while (!RegexesStr.empty()) {
456 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
457 if (!HeadTail.first.empty()) {
458 Regex Re(HeadTail.first);
459 std::string Err;
460 if (!Re.isValid(Err)) {
461 Ctx->emitError(Twine("Regex ") + HeadTail.first +
462 " is not valid: " + Err);
463 }
464 Regexes.emplace_back(std::move(Re));
465 }
466 RegexesStr = HeadTail.second;
467 }
468 return Regexes;
469}
470
471bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
472 std::vector<Regex> &Regexes) {
473 for (Regex &Re : Regexes) {
474 if (Re.match(Filename)) {
475 return true;
476 }
477 }
478 return false;
479}
480
481bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
482 if (FilterRe.empty() && ExcludeRe.empty()) {
483 return true;
484 }
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000485 SmallString<128> Filename = getFilename(F.getSubprogram());
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000486 auto It = InstrumentedFiles.find(Filename);
487 if (It != InstrumentedFiles.end()) {
488 return It->second;
489 }
490
491 SmallString<256> RealPath;
492 StringRef RealFilename;
493
494 // Path can be
495 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
496 // such a case we must get the real_path.
497 if (sys::fs::real_path(Filename, RealPath)) {
498 // real_path can fail with path like "foo.c".
499 RealFilename = Filename;
500 } else {
501 RealFilename = RealPath;
502 }
503
504 bool ShouldInstrument;
505 if (FilterRe.empty()) {
506 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
507 } else if (ExcludeRe.empty()) {
508 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
509 } else {
510 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
511 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
512 }
513 InstrumentedFiles[Filename] = ShouldInstrument;
514 return ShouldInstrument;
515}
516
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000517std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000518 GCovFileType OutputType) {
519 bool Notes = OutputType == GCovFileType::GCNO;
520
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000521 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
522 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000523 MDNode *N = GCov->getOperand(i);
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000524 bool ThreeElement = N->getNumOperands() == 3;
525 if (!ThreeElement && N->getNumOperands() != 2)
526 continue;
Nick Lewycky8dd4dad2016-08-31 23:24:43 +0000527 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000528 continue;
529
530 if (ThreeElement) {
531 // These nodes have no mangling to apply, it's stored mangled in the
532 // bitcode.
533 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
534 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
535 if (!NotesFile || !DataFile)
536 continue;
537 return Notes ? NotesFile->getString() : DataFile->getString();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000538 }
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000539
540 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
541 if (!GCovFile)
542 continue;
543
544 SmallString<128> Filename = GCovFile->getString();
545 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
546 return Filename.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000547 }
548 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000549
Ilya Biryukov449a7f02018-12-04 16:30:31 +0000550 SmallString<128> Filename = CU->getFilename();
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000551 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
Bill Wendling5aa82392013-03-26 22:47:50 +0000552 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000553 SmallString<128> CurPath;
554 if (sys::fs::current_path(CurPath)) return FName;
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000555 sys::path::append(CurPath, FName);
Bill Wendling5aa82392013-03-26 22:47:50 +0000556 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000557}
558
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000559bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000560 this->M = &M;
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000561 this->TLI = &TLI;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000562 Ctx = &M.getContext();
563
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000564 AddFlushBeforeForkAndExec();
565
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000566 FilterRe = createRegexesFromString(Options.Filter);
567 ExcludeRe = createRegexesFromString(Options.Exclude);
568
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000569 if (Options.EmitNotes) emitProfileNotes();
570 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000571 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000572}
573
Xinliang David Li64dbb292016-06-05 05:12:23 +0000574PreservedAnalyses GCOVProfilerPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000575 ModuleAnalysisManager &AM) {
Xinliang David Li64dbb292016-06-05 05:12:23 +0000576
577 GCOVProfiler Profiler(GCOVOpts);
578
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000579 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
580 if (!Profiler.runOnModule(M, TLI))
Xinliang David Li64dbb292016-06-05 05:12:23 +0000581 return PreservedAnalyses::all();
582
583 return PreservedAnalyses::none();
584}
585
Adrian Prantl75819ae2016-04-15 15:57:41 +0000586static bool functionHasLines(Function &F) {
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000587 // Check whether this function actually has any source lines. Not only
588 // do these waste space, they also can crash gcov.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000589 for (auto &BB : F) {
590 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000591 // Debug intrinsic locations correspond to the location of the
592 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000593 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000594
Adrian Prantl75819ae2016-04-15 15:57:41 +0000595 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000596 if (!Loc)
597 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000598
599 // Artificial lines such as calls to the global constructors.
Justin Bogner3faa76b2015-03-16 23:52:03 +0000600 if (Loc.getLine() == 0) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000601
Nick Lewycky5f53ddd2014-06-03 04:25:36 +0000602 return true;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000603 }
604 }
605 return false;
606}
607
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000608static bool isUsingScopeBasedEH(Function &F) {
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000609 if (!F.hasPersonalityFn()) return false;
610
611 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000612 return isScopedEHPersonality(Personality);
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000613}
614
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000615static bool shouldKeepInEntry(BasicBlock::iterator It) {
616 if (isa<AllocaInst>(*It)) return true;
617 if (isa<DbgInfoIntrinsic>(*It)) return true;
618 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
619 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
620 }
621
622 return false;
623}
624
Calixte Denizetc3bed1e2018-11-07 13:49:17 +0000625void GCOVProfiler::AddFlushBeforeForkAndExec() {
626 SmallVector<Instruction *, 2> ForkAndExecs;
627 for (auto &F : M->functions()) {
628 for (auto &I : instructions(F)) {
629 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
630 if (Function *Callee = CI->getCalledFunction()) {
631 LibFunc LF;
632 if (TLI->getLibFunc(*Callee, LF) &&
633 (LF == LibFunc_fork || LF == LibFunc_execl ||
634 LF == LibFunc_execle || LF == LibFunc_execlp ||
635 LF == LibFunc_execv || LF == LibFunc_execvp ||
636 LF == LibFunc_execve || LF == LibFunc_execvpe ||
637 LF == LibFunc_execvP)) {
638 ForkAndExecs.push_back(&I);
639 }
640 }
641 }
642 }
643 }
644
645 // We need to split the block after the fork/exec call
646 // because else the counters for the lines after will be
647 // the same as before the call.
648 for (auto I : ForkAndExecs) {
649 IRBuilder<> Builder(I);
650 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
651 Constant *GCOVFlush = M->getOrInsertFunction("__gcov_flush", FTy);
652 Builder.CreateCall(GCOVFlush);
653 I->getParent()->splitBasicBlock(I);
654 }
655}
656
Nick Lewyckyad145502013-03-13 22:55:42 +0000657void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000658 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000659 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000660
Nick Lewycky6404d972011-11-27 23:22:20 +0000661 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
662 // Each compile unit gets its own .gcno file. This means that whether we run
663 // this pass over the original .o's as they're produced, or run it after
664 // LTO, we'll generate the same .gcno files.
665
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000666 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
Vedant Kumar61035fa2016-01-21 17:04:42 +0000667
668 // Skip module skeleton (and module) CUs.
669 if (CU->getDWOId())
670 continue;
671
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000672 std::error_code EC;
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000673 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
Reid Kleckner1aa4ea82017-09-18 21:31:48 +0000674 if (EC) {
675 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
676 EC.message());
677 continue;
678 }
679
Yuchen Wubabe7492013-11-20 04:15:05 +0000680 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000681
Justin Bogner58e41342014-11-06 06:55:02 +0000682 unsigned FunctionIdent = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000683 for (auto &F : M->functions()) {
684 DISubprogram *SP = F.getSubprogram();
685 if (!SP) continue;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000686 if (!functionHasLines(F) || !isFunctionInstrumented(F))
687 continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000688 // TODO: Functions using scope-based EH are currently not supported.
689 if (isUsingScopeBasedEH(F)) continue;
Bob Wilson055a0b42014-01-31 05:24:01 +0000690
691 // gcov expects every function to start with an entry block that has a
692 // single successor, so split the entry block to make sure of that.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000693 BasicBlock &EntryBlock = F.getEntryBlock();
Bob Wilson055a0b42014-01-31 05:24:01 +0000694 BasicBlock::iterator It = EntryBlock.begin();
Sylvestre Ledrue7d4cd62017-09-26 11:56:43 +0000695 while (shouldKeepInEntry(It))
Bob Wilson055a0b42014-01-31 05:24:01 +0000696 ++It;
697 EntryBlock.splitBasicBlock(It);
Yuchen Wuc87ca322013-11-22 23:07:45 +0000698
Adrian Prantl75819ae2016-04-15 15:57:41 +0000699 Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
Justin Bogner3faa76b2015-03-16 23:52:03 +0000700 Options.UseCfgChecksum,
701 Options.ExitBlockBeforeBody));
David Blaikie229de502014-04-21 20:41:55 +0000702 GCOVFunction &Func = *Funcs.back();
Nick Lewycky6404d972011-11-27 23:22:20 +0000703
Calixte Denizetd2f290b2018-10-11 08:53:43 +0000704 // Add the function line number to the lines of the entry block
705 // to have a counter for the function definition.
Calixte Denizet38d50542018-10-30 18:41:31 +0000706 uint32_t Line = SP->getLine();
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000707 auto Filename = getFilename(SP);
708 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
Calixte Denizetd2f290b2018-10-11 08:53:43 +0000709
Adrian Prantl75819ae2016-04-15 15:57:41 +0000710 for (auto &BB : F) {
711 GCOVBlock &Block = Func.getBlock(&BB);
Chandler Carruthedb12a82018-10-15 10:04:59 +0000712 Instruction *TI = BB.getTerminator();
Nick Lewycky6404d972011-11-27 23:22:20 +0000713 if (int successors = TI->getNumSuccessors()) {
714 for (int i = 0; i != successors; ++i) {
David Blaikie229de502014-04-21 20:41:55 +0000715 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000716 }
717 } else if (isa<ReturnInst>(TI)) {
David Blaikie229de502014-04-21 20:41:55 +0000718 Block.addEdge(Func.getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000719 }
720
Adrian Prantl75819ae2016-04-15 15:57:41 +0000721 for (auto &I : BB) {
Nick Lewyckyce98b432014-06-04 21:47:19 +0000722 // Debug intrinsic locations correspond to the location of the
723 // declaration, not necessarily any statements or expressions.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000724 if (isa<DbgInfoIntrinsic>(&I)) continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000725
Adrian Prantl75819ae2016-04-15 15:57:41 +0000726 const DebugLoc &Loc = I.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000727 if (!Loc)
728 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000729
730 // Artificial lines such as calls to the global constructors.
Calixte Denizeteb7f6022018-09-20 08:53:06 +0000731 if (Loc.getLine() == 0 || Loc.isImplicitCode())
732 continue;
Nick Lewyckyff114da2014-06-05 04:31:43 +0000733
Nick Lewycky6404d972011-11-27 23:22:20 +0000734 if (Line == Loc.getLine()) continue;
735 Line = Loc.getLine();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000736 if (SP != getDISubprogram(Loc.getScope()))
737 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000738
Adrian Prantlfbeeac02018-12-06 18:44:48 +0000739 GCOVLines &Lines = Block.getFile(Filename);
Nick Lewycky6404d972011-11-27 23:22:20 +0000740 Lines.addLine(Loc.getLine());
741 }
Calixte Denizet38d50542018-10-30 18:41:31 +0000742 Line = 0;
Nick Lewycky6404d972011-11-27 23:22:20 +0000743 }
David Blaikie229de502014-04-21 20:41:55 +0000744 EdgeDestinations += Func.getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000745 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000746
Yuchen Wu664dc762013-11-21 04:01:05 +0000747 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000748 out.write("oncg", 4);
749 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000750 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000751
David Blaikie229de502014-04-21 20:41:55 +0000752 for (auto &Func : Funcs) {
Yuchen Wu664dc762013-11-21 04:01:05 +0000753 Func->setCfgChecksum(FileChecksums.back());
754 Func->writeOut();
755 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000756
Nick Lewycky6404d972011-11-27 23:22:20 +0000757 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
758 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000759 }
760}
761
Devang Patel2b21d862011-08-17 22:49:38 +0000762bool GCOVProfiler::emitProfileArcs() {
763 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
764 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000765
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000766 bool Result = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000767 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Devang Patel2b21d862011-08-17 22:49:38 +0000768 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000769 for (auto &F : M->functions()) {
770 DISubprogram *SP = F.getSubprogram();
771 if (!SP) continue;
Calixte Denizetc6fabea2018-11-12 09:01:43 +0000772 if (!functionHasLines(F) || !isFunctionInstrumented(F))
773 continue;
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000774 // TODO: Functions using scope-based EH are currently not supported.
775 if (isUsingScopeBasedEH(F)) continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000776 if (!Result) Result = true;
Marco Castelluccio0dcf64a2017-10-13 13:49:15 +0000777
Vedant Kumar727d8952018-09-11 18:38:34 +0000778 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
Devang Patel2b21d862011-08-17 22:49:38 +0000779 unsigned Edges = 0;
Adrian Prantl75819ae2016-04-15 15:57:41 +0000780 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000781 Instruction *TI = BB.getTerminator();
Vedant Kumar727d8952018-09-11 18:38:34 +0000782 if (isa<ReturnInst>(TI)) {
783 EdgeToCounter[{&BB, nullptr}] = Edges++;
784 } else {
785 for (BasicBlock *Succ : successors(TI)) {
786 EdgeToCounter[{&BB, Succ}] = Edges++;
787 }
788 }
Devang Patel2b21d862011-08-17 22:49:38 +0000789 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000790
Devang Patel2b21d862011-08-17 22:49:38 +0000791 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000792 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000793 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000794 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000795 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000796 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000797 "__llvm_gcov_ctr");
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000798 CountersBySP.push_back(std::make_pair(Counters, SP));
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000799
Vedant Kumar727d8952018-09-11 18:38:34 +0000800 // If a BB has several predecessors, use a PHINode to select
801 // the correct counter.
Adrian Prantl75819ae2016-04-15 15:57:41 +0000802 for (auto &BB : F) {
Vedant Kumar727d8952018-09-11 18:38:34 +0000803 const unsigned EdgeCount =
804 std::distance(pred_begin(&BB), pred_end(&BB));
805 if (EdgeCount) {
806 // The phi node must be at the begin of the BB.
807 IRBuilder<> BuilderForPhi(&*BB.begin());
808 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
809 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
810 for (BasicBlock *Pred : predecessors(&BB)) {
811 auto It = EdgeToCounter.find({Pred, &BB});
812 assert(It != EdgeToCounter.end());
813 const unsigned Edge = It->second;
814 Value *EdgeCounter =
815 BuilderForPhi.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
816 Phi->addIncoming(EdgeCounter, Pred);
Devang Patel2b21d862011-08-17 22:49:38 +0000817 }
Bill Wendling707f6012013-08-20 23:52:00 +0000818
Vedant Kumar727d8952018-09-11 18:38:34 +0000819 // Skip phis, landingpads.
820 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
821 Value *Count = Builder.CreateLoad(Phi);
822 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
823 Builder.CreateStore(Count, Phi);
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000824
Chandler Carruthedb12a82018-10-15 10:04:59 +0000825 Instruction *TI = BB.getTerminator();
Vedant Kumar727d8952018-09-11 18:38:34 +0000826 if (isa<ReturnInst>(TI)) {
827 auto It = EdgeToCounter.find({&BB, nullptr});
828 assert(It != EdgeToCounter.end());
829 const unsigned Edge = It->second;
830 Value *Counter =
831 Builder.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
832 Value *Count = Builder.CreateLoad(Counter);
833 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
834 Builder.CreateStore(Count, Counter);
835 }
Devang Patel2b21d862011-08-17 22:49:38 +0000836 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000837 }
838 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000839
Bill Wendlingc3cab812013-03-18 23:04:39 +0000840 Function *WriteoutF = insertCounterWriteout(CountersBySP);
841 Function *FlushF = insertFlush(CountersBySP);
842
843 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000844 // be executed at exit and the "__llvm_gcov_flush" function to be executed
845 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000846 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
847 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
848 "__llvm_gcov_init", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000849 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000850 F->setLinkage(GlobalValue::InternalLinkage);
851 F->addFnAttr(Attribute::NoInline);
852 if (Options.NoRedZone)
853 F->addFnAttr(Attribute::NoRedZone);
854
855 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
856 IRBuilder<> Builder(BB);
857
Bill Wendlingc3cab812013-03-18 23:04:39 +0000858 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000859 Type *Params[] = {
860 PointerType::get(FTy, 0),
861 PointerType::get(FTy, 0)
862 };
863 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000864
Yuchen Wu3197b252013-10-23 20:35:00 +0000865 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000866 // functions.
867 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000868 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
Bill Wendlingc3cab812013-03-18 23:04:39 +0000869 Builder.CreateRetVoid();
870
871 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000872 }
Bill Wendling15605172012-05-28 06:10:56 +0000873
Devang Patel2b21d862011-08-17 22:49:38 +0000874 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000875}
876
877Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000878 Type *Args[] = {
879 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
880 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000881 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000882 };
883 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000884 auto *Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy);
885 if (Function *FunRes = dyn_cast<Function>(Res))
886 if (auto AK = TLI->getExtAttrForI32Param(false))
887 FunRes->addParamAttr(2, AK);
888 return Res;
889
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000890}
891
Nick Lewycky966edd02011-04-16 01:20:23 +0000892Constant *GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000893 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000894 Type::getInt32Ty(*Ctx), // uint32_t ident
895 Type::getInt8PtrTy(*Ctx), // const char *function_name
Daniel Jasper87a24d52013-12-04 08:57:17 +0000896 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000897 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000898 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000899 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000900 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000901 auto *Res = M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
902 if (Function *FunRes = dyn_cast<Function>(Res))
903 if (auto AK = TLI->getExtAttrForI32Param(false)) {
904 FunRes->addParamAttr(0, AK);
905 FunRes->addParamAttr(2, AK);
906 FunRes->addParamAttr(3, AK);
907 FunRes->addParamAttr(4, AK);
908 }
909 return Res;
Nick Lewycky966edd02011-04-16 01:20:23 +0000910}
911
912Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000913 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000914 Type::getInt32Ty(*Ctx), // uint32_t num_counters
915 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
916 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000917 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +0000918 auto *Res = M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
919 if (Function *FunRes = dyn_cast<Function>(Res))
920 if (auto AK = TLI->getExtAttrForI32Param(false))
921 FunRes->addParamAttr(0, AK);
922 return Res;
Nick Lewycky966edd02011-04-16 01:20:23 +0000923}
924
Yuchen Wu062f24c2013-11-12 04:59:08 +0000925Constant *GCOVProfiler::getSummaryInfoFunc() {
926 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
927 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
928}
929
Nick Lewycky966edd02011-04-16 01:20:23 +0000930Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000931 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000932 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000933}
934
Bill Wendlingc3cab812013-03-18 23:04:39 +0000935Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000936 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000937 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
938 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
939 if (!WriteoutF)
940 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
941 "__llvm_gcov_writeout", M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000942 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000943 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000944 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000945 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000946
947 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000948 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000949
950 Constant *StartFile = getStartFileFunc();
951 Constant *EmitFunction = getEmitFunctionFunc();
952 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000953 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000954 Constant *EndFile = getEndFileFunc();
955
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000956 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
957 if (!CUNodes) {
958 Builder.CreateRetVoid();
959 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000960 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000961
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000962 // Collect the relevant data into a large constant data structure that we can
963 // walk to write out everything.
964 StructType *StartFileCallArgsTy = StructType::create(
965 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
966 StructType *EmitFunctionCallArgsTy = StructType::create(
967 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
968 Builder.getInt8Ty(), Builder.getInt32Ty()});
969 StructType *EmitArcsCallArgsTy = StructType::create(
970 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
971 StructType *FileInfoTy =
972 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
973 EmitFunctionCallArgsTy->getPointerTo(),
974 EmitArcsCallArgsTy->getPointerTo()});
975
976 Constant *Zero32 = Builder.getInt32(0);
Chandler Carruthe74c3542018-05-03 00:11:03 +0000977 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
978 Constant *TwoZero32s[] = {Zero32, Zero32};
Chandler Carruth71c3a3f2018-05-02 22:24:39 +0000979
980 SmallVector<Constant *, 8> FileInfos;
981 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
982 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
983
984 // Skip module skeleton (and module) CUs.
985 if (CU->getDWOId())
986 continue;
987
988 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
989 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
990 auto *StartFileCallArgs = ConstantStruct::get(
991 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
992 Builder.CreateGlobalStringPtr(ReversedVersion),
993 Builder.getInt32(CfgChecksum)});
994
995 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
996 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
997 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
998 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
999 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1000 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1001 EmitFunctionCallArgsTy,
1002 {Builder.getInt32(j),
1003 Options.FunctionNamesInData
1004 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
1005 : Constant::getNullValue(Builder.getInt8PtrTy()),
1006 Builder.getInt32(FuncChecksum),
1007 Builder.getInt8(Options.UseCfgChecksum),
1008 Builder.getInt32(CfgChecksum)}));
1009
1010 GlobalVariable *GV = CountersBySP[j].first;
1011 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1012 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1013 EmitArcsCallArgsTy,
Chandler Carruthe74c3542018-05-03 00:11:03 +00001014 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1015 GV->getValueType(), GV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001016 }
1017 // Create global arrays for the two emit calls.
1018 int CountersSize = CountersBySP.size();
1019 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1020 "Mismatched array size!");
1021 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1022 "Mismatched array size!");
1023 auto *EmitFunctionCallArgsArrayTy =
1024 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1025 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1026 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1027 GlobalValue::InternalLinkage,
1028 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1029 EmitFunctionCallArgsArray),
1030 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1031 auto *EmitArcsCallArgsArrayTy =
1032 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1033 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1034 GlobalValue::UnnamedAddr::Global);
1035 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1036 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1037 GlobalValue::InternalLinkage,
1038 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1039 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1040 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1041
1042 FileInfos.push_back(ConstantStruct::get(
1043 FileInfoTy,
1044 {StartFileCallArgs, Builder.getInt32(CountersSize),
Chandler Carruthe74c3542018-05-03 00:11:03 +00001045 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1046 EmitFunctionCallArgsArrayGV,
1047 TwoZero32s),
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001048 ConstantExpr::getInBoundsGetElementPtr(
Chandler Carruthe74c3542018-05-03 00:11:03 +00001049 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001050 }
1051
1052 // If we didn't find anything to actually emit, bail on out.
1053 if (FileInfos.empty()) {
1054 Builder.CreateRetVoid();
1055 return WriteoutF;
1056 }
1057
1058 // To simplify code, we cap the number of file infos we write out to fit
1059 // easily in a 32-bit signed integer. This gives consistent behavior between
1060 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1061 // operations on 32-bit systems. It also seems unreasonable to try to handle
1062 // more than 2 billion files.
1063 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1064 FileInfos.resize(INT_MAX);
1065
1066 // Create a global for the entire data structure so we can walk it more
1067 // easily.
1068 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1069 auto *FileInfoArrayGV = new GlobalVariable(
1070 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1071 ConstantArray::get(FileInfoArrayTy, FileInfos),
1072 "__llvm_internal_gcov_emit_file_info");
1073 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1074
1075 // Create the CFG for walking this data structure.
1076 auto *FileLoopHeader =
1077 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1078 auto *CounterLoopHeader =
1079 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1080 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1081 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1082
1083 // We always have at least one file, so just branch to the header.
1084 Builder.CreateBr(FileLoopHeader);
1085
1086 // The index into the files structure is our loop induction variable.
1087 Builder.SetInsertPoint(FileLoopHeader);
1088 PHINode *IV =
1089 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1090 IV->addIncoming(Builder.getInt32(0), BB);
1091 auto *FileInfoPtr =
1092 Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
1093 auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001094 auto *StartFileCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001095 StartFile,
1096 {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
1097 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
1098 Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001099 if (auto AK = TLI->getExtAttrForI32Param(false))
1100 StartFileCall->addParamAttr(2, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001101 auto *NumCounters =
1102 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
1103 auto *EmitFunctionCallArgsArray =
1104 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
1105 auto *EmitArcsCallArgsArray =
1106 Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
1107 auto *EnterCounterLoopCond =
1108 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1109 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1110
1111 Builder.SetInsertPoint(CounterLoopHeader);
1112 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1113 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1114 auto *EmitFunctionCallArgsPtr =
1115 Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001116 auto *EmitFunctionCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001117 EmitFunction,
1118 {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
1119 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
1120 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
1121 Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
1122 Builder.CreateLoad(
1123 Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001124 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1125 EmitFunctionCall->addParamAttr(0, AK);
1126 EmitFunctionCall->addParamAttr(2, AK);
1127 EmitFunctionCall->addParamAttr(3, AK);
1128 EmitFunctionCall->addParamAttr(4, AK);
1129 }
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001130 auto *EmitArcsCallArgsPtr =
1131 Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001132 auto *EmitArcsCall = Builder.CreateCall(
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001133 EmitArcs,
1134 {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
1135 Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
Ulrich Weigandb961fdc2018-07-10 16:05:47 +00001136 if (auto AK = TLI->getExtAttrForI32Param(false))
1137 EmitArcsCall->addParamAttr(0, AK);
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001138 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1139 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1140 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1141 JV->addIncoming(NextJV, CounterLoopHeader);
1142
1143 Builder.SetInsertPoint(FileLoopLatch);
1144 Builder.CreateCall(SummaryInfo, {});
1145 Builder.CreateCall(EndFile, {});
1146 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1147 auto *FileLoopCond =
1148 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1149 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1150 IV->addIncoming(NextIV, FileLoopLatch);
1151
1152 Builder.SetInsertPoint(ExitBB);
Nick Lewyckyc58d2932011-04-26 03:54:16 +00001153 Builder.CreateRetVoid();
Chandler Carruth71c3a3f2018-05-02 22:24:39 +00001154
Bill Wendlingc3cab812013-03-18 23:04:39 +00001155 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +00001156}
Bill Wendling15605172012-05-28 06:10:56 +00001157
Bill Wendlingc3cab812013-03-18 23:04:39 +00001158Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +00001159insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1160 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +00001161 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +00001162 if (!FlushF)
1163 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +00001164 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001165 else
1166 FlushF->setLinkage(GlobalValue::InternalLinkage);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001167 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001168 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +00001169 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001170 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +00001171
Bill Wendling2e6e8662012-09-13 00:09:55 +00001172 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1173
1174 // Write out the current counters.
1175 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1176 assert(WriteoutF && "Need to create the writeout function first!");
1177
1178 IRBuilder<> Builder(Entry);
David Blaikieff6409d2015-05-18 22:13:54 +00001179 Builder.CreateCall(WriteoutF, {});
Bill Wendling2e6e8662012-09-13 00:09:55 +00001180
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001181 // Zero out the counters.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001182 for (const auto &I : CountersBySP) {
1183 GlobalVariable *GV = I.first;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001184 Constant *Null = Constant::getNullValue(GV->getValueType());
Bill Wendling8d26bc32012-09-14 22:35:49 +00001185 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +00001186 }
Bill Wendling2e6e8662012-09-13 00:09:55 +00001187
1188 Type *RetTy = FlushF->getReturnType();
1189 if (RetTy == Type::getVoidTy(*Ctx))
1190 Builder.CreateRetVoid();
1191 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +00001192 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +00001193 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1194 else
Bill Wendlingc3cab812013-03-18 23:04:39 +00001195 report_fatal_error("invalid return type for __llvm_gcov_flush");
1196
1197 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +00001198}