Bug Summary

File:llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
Warning:line 181, column 8
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name GCOVProfiling.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Transforms/Instrumentation -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Transforms/Instrumentation -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
1//===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2//
3// 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
6//
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
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Analysis/EHPersonalities.h"
24#include "llvm/Analysis/TargetLibraryInfo.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/DebugInfo.h"
27#include "llvm/IR/DebugLoc.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InstIterator.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
33#include "llvm/InitializePasses.h"
34#include "llvm/Pass.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Regex.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Transforms/Instrumentation.h"
42#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
43#include "llvm/Transforms/Utils/ModuleUtils.h"
44#include <algorithm>
45#include <memory>
46#include <string>
47#include <utility>
48using namespace llvm;
49
50#define DEBUG_TYPE"insert-gcov-profiling" "insert-gcov-profiling"
51
52static cl::opt<std::string>
53DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
54 cl::ValueRequired);
55static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
56 cl::init(false), cl::Hidden);
57
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;
65 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
66
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
75namespace {
76class GCOVFunction;
77
78class GCOVProfiler {
79public:
80 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
81 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
82 assert((Options.EmitNotes || Options.EmitData) &&(((Options.EmitNotes || Options.EmitData) && "GCOVProfiler asked to do nothing?"
) ? static_cast<void> (0) : __assert_fail ("(Options.EmitNotes || Options.EmitData) && \"GCOVProfiler asked to do nothing?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 83, __PRETTY_FUNCTION__))
83 "GCOVProfiler asked to do nothing?")(((Options.EmitNotes || Options.EmitData) && "GCOVProfiler asked to do nothing?"
) ? static_cast<void> (0) : __assert_fail ("(Options.EmitNotes || Options.EmitData) && \"GCOVProfiler asked to do nothing?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 83, __PRETTY_FUNCTION__))
;
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 }
90 bool
91 runOnModule(Module &M,
92 std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
93
94private:
95 // Create the .gcno files for the Module based on DebugInfo.
96 void emitProfileNotes();
97
98 // Modify the program to track transitions along edges and call into the
99 // profiling runtime to emit .gcda files when run.
100 bool emitProfileArcs();
101
102 bool isFunctionInstrumented(const Function &F);
103 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
104 static bool doesFilenameMatchARegex(StringRef Filename,
105 std::vector<Regex> &Regexes);
106
107 // Get pointers to the functions in the runtime library.
108 FunctionCallee getStartFileFunc(const TargetLibraryInfo *TLI);
109 FunctionCallee getEmitFunctionFunc(const TargetLibraryInfo *TLI);
110 FunctionCallee getEmitArcsFunc(const TargetLibraryInfo *TLI);
111 FunctionCallee getSummaryInfoFunc();
112 FunctionCallee getEndFileFunc();
113
114 // Add the function to write out all our counters to the global destructor
115 // list.
116 Function *
117 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
118 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119
120 void AddFlushBeforeForkAndExec();
121
122 enum class GCovFileType { GCNO, GCDA };
123 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
124
125 GCOVOptions Options;
126
127 // Reversed, NUL-terminated copy of Options.Version.
128 char ReversedVersion[5];
129 // Checksum, produced by hash of EdgeDestinations
130 SmallVector<uint32_t, 4> FileChecksums;
131
132 Module *M = nullptr;
133 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
134 LLVMContext *Ctx = nullptr;
135 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
136 std::vector<Regex> FilterRe;
137 std::vector<Regex> ExcludeRe;
138 StringMap<bool> InstrumentedFiles;
139};
140
141class GCOVProfilerLegacyPass : public ModulePass {
142public:
143 static char ID;
144 GCOVProfilerLegacyPass()
145 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
146 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
147 : ModulePass(ID), Profiler(Opts) {
148 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
149 }
150 StringRef getPassName() const override { return "GCOV Profiler"; }
151
152 bool runOnModule(Module &M) override {
153 return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
154 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
155 });
156 }
157
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.addRequired<TargetLibraryInfoWrapperPass>();
160 }
161
162private:
163 GCOVProfiler Profiler;
164};
165}
166
167char GCOVProfilerLegacyPass::ID = 0;
168INITIALIZE_PASS_BEGIN(static void *initializeGCOVProfilerLegacyPassPassOnce(PassRegistry
&Registry) {
169 GCOVProfilerLegacyPass, "insert-gcov-profiling",static void *initializeGCOVProfilerLegacyPassPassOnce(PassRegistry
&Registry) {
170 "Insert instrumentation for GCOV profiling", false, false)static void *initializeGCOVProfilerLegacyPassPassOnce(PassRegistry
&Registry) {
171INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
172INITIALIZE_PASS_END(PassInfo *PI = new PassInfo( "Insert instrumentation for GCOV profiling"
, "insert-gcov-profiling", &GCOVProfilerLegacyPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<GCOVProfilerLegacyPass>)
, false, false); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeGCOVProfilerLegacyPassPassFlag
; void llvm::initializeGCOVProfilerLegacyPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeGCOVProfilerLegacyPassPassFlag
, initializeGCOVProfilerLegacyPassPassOnce, std::ref(Registry
)); }
173 GCOVProfilerLegacyPass, "insert-gcov-profiling",PassInfo *PI = new PassInfo( "Insert instrumentation for GCOV profiling"
, "insert-gcov-profiling", &GCOVProfilerLegacyPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<GCOVProfilerLegacyPass>)
, false, false); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeGCOVProfilerLegacyPassPassFlag
; void llvm::initializeGCOVProfilerLegacyPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeGCOVProfilerLegacyPassPassFlag
, initializeGCOVProfilerLegacyPassPassOnce, std::ref(Registry
)); }
174 "Insert instrumentation for GCOV profiling", false, false)PassInfo *PI = new PassInfo( "Insert instrumentation for GCOV profiling"
, "insert-gcov-profiling", &GCOVProfilerLegacyPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<GCOVProfilerLegacyPass>)
, false, false); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeGCOVProfilerLegacyPassPassFlag
; void llvm::initializeGCOVProfilerLegacyPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeGCOVProfilerLegacyPassPassFlag
, initializeGCOVProfilerLegacyPassPassOnce, std::ref(Registry
)); }
175
176ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
177 return new GCOVProfilerLegacyPass(Options);
178}
179
180static StringRef getFunctionName(const DISubprogram *SP) {
181 if (!SP->getLinkageName().empty())
29
Called C++ object pointer is null
182 return SP->getLinkageName();
183 return SP->getName();
184}
185
186/// Extract a filename for a DISubprogram.
187///
188/// Prefer relative paths in the coverage notes. Clang also may split
189/// up absolute paths into a directory and filename component. When
190/// the relative path doesn't exist, reconstruct the absolute path.
191static SmallString<128> getFilename(const DISubprogram *SP) {
192 SmallString<128> Path;
193 StringRef RelPath = SP->getFilename();
194 if (sys::fs::exists(RelPath))
195 Path = RelPath;
196 else
197 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
198 return Path;
199}
200
201namespace {
202 class GCOVRecord {
203 protected:
204 static const char *const LinesTag;
205 static const char *const FunctionTag;
206 static const char *const BlockTag;
207 static const char *const EdgeTag;
208
209 GCOVRecord() = default;
210
211 void writeBytes(const char *Bytes, int Size) {
212 os->write(Bytes, Size);
213 }
214
215 void write(uint32_t i) {
216 writeBytes(reinterpret_cast<char*>(&i), 4);
217 }
218
219 // Returns the length measured in 4-byte blocks that will be used to
220 // represent this string in a GCOV file
221 static unsigned lengthOfGCOVString(StringRef s) {
222 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
223 // padding out to the next 4-byte word. The length is measured in 4-byte
224 // words including padding, not bytes of actual string.
225 return (s.size() / 4) + 1;
226 }
227
228 void writeGCOVString(StringRef s) {
229 uint32_t Len = lengthOfGCOVString(s);
230 write(Len);
231 writeBytes(s.data(), s.size());
232
233 // Write 1 to 4 bytes of NUL padding.
234 assert((unsigned)(4 - (s.size() % 4)) > 0)(((unsigned)(4 - (s.size() % 4)) > 0) ? static_cast<void
> (0) : __assert_fail ("(unsigned)(4 - (s.size() % 4)) > 0"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 234, __PRETTY_FUNCTION__))
;
235 assert((unsigned)(4 - (s.size() % 4)) <= 4)(((unsigned)(4 - (s.size() % 4)) <= 4) ? static_cast<void
> (0) : __assert_fail ("(unsigned)(4 - (s.size() % 4)) <= 4"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 235, __PRETTY_FUNCTION__))
;
236 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
237 }
238
239 raw_ostream *os;
240 };
241 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
242 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
243 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
244 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
245
246 class GCOVFunction;
247 class GCOVBlock;
248
249 // Constructed only by requesting it from a GCOVBlock, this object stores a
250 // list of line numbers and a single filename, representing lines that belong
251 // to the block.
252 class GCOVLines : public GCOVRecord {
253 public:
254 void addLine(uint32_t Line) {
255 assert(Line != 0 && "Line zero is not a valid real line number.")((Line != 0 && "Line zero is not a valid real line number."
) ? static_cast<void> (0) : __assert_fail ("Line != 0 && \"Line zero is not a valid real line number.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 255, __PRETTY_FUNCTION__))
;
256 Lines.push_back(Line);
257 }
258
259 uint32_t length() const {
260 // Here 2 = 1 for string length + 1 for '0' id#.
261 return lengthOfGCOVString(Filename) + 2 + Lines.size();
262 }
263
264 void writeOut() {
265 write(0);
266 writeGCOVString(Filename);
267 for (int i = 0, e = Lines.size(); i != e; ++i)
268 write(Lines[i]);
269 }
270
271 GCOVLines(StringRef F, raw_ostream *os)
272 : Filename(F) {
273 this->os = os;
274 }
275
276 private:
277 std::string Filename;
278 SmallVector<uint32_t, 32> Lines;
279 };
280
281
282 // Represent a basic block in GCOV. Each block has a unique number in the
283 // function, number of lines belonging to each block, and a set of edges to
284 // other blocks.
285 class GCOVBlock : public GCOVRecord {
286 public:
287 GCOVLines &getFile(StringRef Filename) {
288 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
289 }
290
291 void addEdge(GCOVBlock &Successor) {
292 OutEdges.push_back(&Successor);
293 }
294
295 void writeOut() {
296 uint32_t Len = 3;
297 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
298 for (auto &I : LinesByFile) {
299 Len += I.second.length();
300 SortedLinesByFile.push_back(&I);
301 }
302
303 writeBytes(LinesTag, 4);
304 write(Len);
305 write(Number);
306
307 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
308 StringMapEntry<GCOVLines> *RHS) {
309 return LHS->getKey() < RHS->getKey();
310 });
311 for (auto &I : SortedLinesByFile)
312 I->getValue().writeOut();
313 write(0);
314 write(0);
315 }
316
317 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
318 // Only allow copy before edges and lines have been added. After that,
319 // there are inter-block pointers (eg: edges) that won't take kindly to
320 // blocks being copied or moved around.
321 assert(LinesByFile.empty())((LinesByFile.empty()) ? static_cast<void> (0) : __assert_fail
("LinesByFile.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 321, __PRETTY_FUNCTION__))
;
322 assert(OutEdges.empty())((OutEdges.empty()) ? static_cast<void> (0) : __assert_fail
("OutEdges.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 322, __PRETTY_FUNCTION__))
;
323 }
324
325 private:
326 friend class GCOVFunction;
327
328 GCOVBlock(uint32_t Number, raw_ostream *os)
329 : Number(Number) {
330 this->os = os;
331 }
332
333 uint32_t Number;
334 StringMap<GCOVLines> LinesByFile;
335 SmallVector<GCOVBlock *, 4> OutEdges;
336 };
337
338 // A function has a unique identifier, a checksum (we leave as zero) and a
339 // set of blocks and a map of edges between blocks. This is the only GCOV
340 // object users can construct, the blocks and lines will be rooted here.
341 class GCOVFunction : public GCOVRecord {
342 public:
343 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
344 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
345 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
346 ReturnBlock(1, os) {
347 this->os = os;
348
349 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("insert-gcov-profiling")) { dbgs() << "Function: " <<
getFunctionName(SP) << "\n"; } } while (false)
;
350
351 uint32_t i = 0;
352 for (auto &BB : *F) {
353 // Skip index 1 if it's assigned to the ReturnBlock.
354 if (i == 1 && ExitBlockBeforeBody)
355 ++i;
356 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
357 }
358 if (!ExitBlockBeforeBody)
359 ReturnBlock.Number = i;
360
361 std::string FunctionNameAndLine;
362 raw_string_ostream FNLOS(FunctionNameAndLine);
363 FNLOS << getFunctionName(SP) << SP->getLine();
364 FNLOS.flush();
365 FuncChecksum = hash_value(FunctionNameAndLine);
366 }
367
368 GCOVBlock &getBlock(BasicBlock *BB) {
369 return Blocks.find(BB)->second;
370 }
371
372 GCOVBlock &getReturnBlock() {
373 return ReturnBlock;
374 }
375
376 std::string getEdgeDestinations() {
377 std::string EdgeDestinations;
378 raw_string_ostream EDOS(EdgeDestinations);
379 Function *F = Blocks.begin()->first->getParent();
380 for (BasicBlock &I : *F) {
381 GCOVBlock &Block = getBlock(&I);
382 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
383 EDOS << Block.OutEdges[i]->Number;
384 }
385 return EdgeDestinations;
386 }
387
388 uint32_t getFuncChecksum() const {
389 return FuncChecksum;
390 }
391
392 void setCfgChecksum(uint32_t Checksum) {
393 CfgChecksum = Checksum;
394 }
395
396 void writeOut() {
397 writeBytes(FunctionTag, 4);
398 SmallString<128> Filename = getFilename(SP);
399 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
400 1 + lengthOfGCOVString(Filename) + 1;
401 if (UseCfgChecksum)
402 ++BlockLen;
403 write(BlockLen);
404 write(Ident);
405 write(FuncChecksum);
406 if (UseCfgChecksum)
407 write(CfgChecksum);
408 writeGCOVString(getFunctionName(SP));
409 writeGCOVString(Filename);
410 write(SP->getLine());
411
412 // Emit count of blocks.
413 writeBytes(BlockTag, 4);
414 write(Blocks.size() + 1);
415 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
416 write(0); // No flags on our blocks.
417 }
418 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("insert-gcov-profiling")) { dbgs() << Blocks.size() <<
" blocks.\n"; } } while (false)
;
419
420 // Emit edges between blocks.
421 if (Blocks.empty()) return;
422 Function *F = Blocks.begin()->first->getParent();
423 for (BasicBlock &I : *F) {
424 GCOVBlock &Block = getBlock(&I);
425 if (Block.OutEdges.empty()) continue;
426
427 writeBytes(EdgeTag, 4);
428 write(Block.OutEdges.size() * 2 + 1);
429 write(Block.Number);
430 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
431 LLVM_DEBUG(dbgs() << Block.Number << " -> "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("insert-gcov-profiling")) { dbgs() << Block.Number <<
" -> " << Block.OutEdges[i]->Number << "\n"
; } } while (false)
432 << Block.OutEdges[i]->Number << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("insert-gcov-profiling")) { dbgs() << Block.Number <<
" -> " << Block.OutEdges[i]->Number << "\n"
; } } while (false)
;
433 write(Block.OutEdges[i]->Number);
434 write(0); // no flags
435 }
436 }
437
438 // Emit lines for each block.
439 for (BasicBlock &I : *F)
440 getBlock(&I).writeOut();
441 }
442
443 private:
444 const DISubprogram *SP;
445 uint32_t Ident;
446 uint32_t FuncChecksum;
447 bool UseCfgChecksum;
448 uint32_t CfgChecksum;
449 DenseMap<BasicBlock *, GCOVBlock> Blocks;
450 GCOVBlock ReturnBlock;
451 };
452}
453
454// RegexesStr is a string containing differents regex separated by a semi-colon.
455// For example "foo\..*$;bar\..*$".
456std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
457 std::vector<Regex> Regexes;
458 while (!RegexesStr.empty()) {
459 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
460 if (!HeadTail.first.empty()) {
461 Regex Re(HeadTail.first);
462 std::string Err;
463 if (!Re.isValid(Err)) {
464 Ctx->emitError(Twine("Regex ") + HeadTail.first +
465 " is not valid: " + Err);
466 }
467 Regexes.emplace_back(std::move(Re));
468 }
469 RegexesStr = HeadTail.second;
470 }
471 return Regexes;
472}
473
474bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
475 std::vector<Regex> &Regexes) {
476 for (Regex &Re : Regexes) {
477 if (Re.match(Filename)) {
478 return true;
479 }
480 }
481 return false;
482}
483
484bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
485 if (FilterRe.empty() && ExcludeRe.empty()) {
486 return true;
487 }
488 SmallString<128> Filename = getFilename(F.getSubprogram());
489 auto It = InstrumentedFiles.find(Filename);
490 if (It != InstrumentedFiles.end()) {
491 return It->second;
492 }
493
494 SmallString<256> RealPath;
495 StringRef RealFilename;
496
497 // Path can be
498 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
499 // such a case we must get the real_path.
500 if (sys::fs::real_path(Filename, RealPath)) {
501 // real_path can fail with path like "foo.c".
502 RealFilename = Filename;
503 } else {
504 RealFilename = RealPath;
505 }
506
507 bool ShouldInstrument;
508 if (FilterRe.empty()) {
509 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
510 } else if (ExcludeRe.empty()) {
511 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
512 } else {
513 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
514 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
515 }
516 InstrumentedFiles[Filename] = ShouldInstrument;
517 return ShouldInstrument;
518}
519
520std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
521 GCovFileType OutputType) {
522 bool Notes = OutputType == GCovFileType::GCNO;
523
524 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
525 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
526 MDNode *N = GCov->getOperand(i);
527 bool ThreeElement = N->getNumOperands() == 3;
528 if (!ThreeElement && N->getNumOperands() != 2)
529 continue;
530 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
531 continue;
532
533 if (ThreeElement) {
534 // These nodes have no mangling to apply, it's stored mangled in the
535 // bitcode.
536 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
537 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
538 if (!NotesFile || !DataFile)
539 continue;
540 return Notes ? NotesFile->getString() : DataFile->getString();
541 }
542
543 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
544 if (!GCovFile)
545 continue;
546
547 SmallString<128> Filename = GCovFile->getString();
548 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
549 return Filename.str();
550 }
551 }
552
553 SmallString<128> Filename = CU->getFilename();
554 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
555 StringRef FName = sys::path::filename(Filename);
556 SmallString<128> CurPath;
557 if (sys::fs::current_path(CurPath)) return FName;
558 sys::path::append(CurPath, FName);
559 return CurPath.str();
560}
561
562bool GCOVProfiler::runOnModule(
563 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
564 this->M = &M;
565 this->GetTLI = std::move(GetTLI);
566 Ctx = &M.getContext();
567
568 AddFlushBeforeForkAndExec();
569
570 FilterRe = createRegexesFromString(Options.Filter);
571 ExcludeRe = createRegexesFromString(Options.Exclude);
572
573 if (Options.EmitNotes) emitProfileNotes();
2
Assuming field 'EmitNotes' is false
3
Taking false branch
574 if (Options.EmitData) return emitProfileArcs();
4
Assuming field 'EmitData' is true
5
Taking true branch
6
Calling 'GCOVProfiler::emitProfileArcs'
575 return false;
576}
577
578PreservedAnalyses GCOVProfilerPass::run(Module &M,
579 ModuleAnalysisManager &AM) {
580
581 GCOVProfiler Profiler(GCOVOpts);
582 FunctionAnalysisManager &FAM =
583 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
584
585 if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
1
Calling 'GCOVProfiler::runOnModule'
586 return FAM.getResult<TargetLibraryAnalysis>(F);
587 }))
588 return PreservedAnalyses::all();
589
590 return PreservedAnalyses::none();
591}
592
593static bool functionHasLines(Function &F) {
594 // Check whether this function actually has any source lines. Not only
595 // do these waste space, they also can crash gcov.
596 for (auto &BB : F) {
597 for (auto &I : BB) {
598 // Debug intrinsic locations correspond to the location of the
599 // declaration, not necessarily any statements or expressions.
600 if (isa<DbgInfoIntrinsic>(&I)) continue;
601
602 const DebugLoc &Loc = I.getDebugLoc();
603 if (!Loc)
604 continue;
605
606 // Artificial lines such as calls to the global constructors.
607 if (Loc.getLine() == 0) continue;
608
609 return true;
610 }
611 }
612 return false;
613}
614
615static bool isUsingScopeBasedEH(Function &F) {
616 if (!F.hasPersonalityFn()) return false;
617
618 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
619 return isScopedEHPersonality(Personality);
620}
621
622static bool shouldKeepInEntry(BasicBlock::iterator It) {
623 if (isa<AllocaInst>(*It)) return true;
624 if (isa<DbgInfoIntrinsic>(*It)) return true;
625 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
626 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
627 }
628
629 return false;
630}
631
632void GCOVProfiler::AddFlushBeforeForkAndExec() {
633 SmallVector<Instruction *, 2> ForkAndExecs;
634 for (auto &F : M->functions()) {
635 auto *TLI = &GetTLI(F);
636 for (auto &I : instructions(F)) {
637 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
638 if (Function *Callee = CI->getCalledFunction()) {
639 LibFunc LF;
640 if (TLI->getLibFunc(*Callee, LF) &&
641 (LF == LibFunc_fork || LF == LibFunc_execl ||
642 LF == LibFunc_execle || LF == LibFunc_execlp ||
643 LF == LibFunc_execv || LF == LibFunc_execvp ||
644 LF == LibFunc_execve || LF == LibFunc_execvpe ||
645 LF == LibFunc_execvP)) {
646 ForkAndExecs.push_back(&I);
647 }
648 }
649 }
650 }
651 }
652
653 // We need to split the block after the fork/exec call
654 // because else the counters for the lines after will be
655 // the same as before the call.
656 for (auto I : ForkAndExecs) {
657 IRBuilder<> Builder(I);
658 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
659 FunctionCallee GCOVFlush = M->getOrInsertFunction("__gcov_flush", FTy);
660 Builder.CreateCall(GCOVFlush);
661 I->getParent()->splitBasicBlock(I);
662 }
663}
664
665void GCOVProfiler::emitProfileNotes() {
666 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
667 if (!CU_Nodes) return;
668
669 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
670 // Each compile unit gets its own .gcno file. This means that whether we run
671 // this pass over the original .o's as they're produced, or run it after
672 // LTO, we'll generate the same .gcno files.
673
674 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
675
676 // Skip module skeleton (and module) CUs.
677 if (CU->getDWOId())
678 continue;
679
680 std::error_code EC;
681 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
682 sys::fs::OF_None);
683 if (EC) {
684 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
685 EC.message());
686 continue;
687 }
688
689 std::string EdgeDestinations;
690
691 unsigned FunctionIdent = 0;
692 for (auto &F : M->functions()) {
693 DISubprogram *SP = F.getSubprogram();
694 if (!SP) continue;
695 if (!functionHasLines(F) || !isFunctionInstrumented(F))
696 continue;
697 // TODO: Functions using scope-based EH are currently not supported.
698 if (isUsingScopeBasedEH(F)) continue;
699
700 // gcov expects every function to start with an entry block that has a
701 // single successor, so split the entry block to make sure of that.
702 BasicBlock &EntryBlock = F.getEntryBlock();
703 BasicBlock::iterator It = EntryBlock.begin();
704 while (shouldKeepInEntry(It))
705 ++It;
706 EntryBlock.splitBasicBlock(It);
707
708 Funcs.push_back(std::make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
709 Options.UseCfgChecksum,
710 Options.ExitBlockBeforeBody));
711 GCOVFunction &Func = *Funcs.back();
712
713 // Add the function line number to the lines of the entry block
714 // to have a counter for the function definition.
715 uint32_t Line = SP->getLine();
716 auto Filename = getFilename(SP);
717
718 // Artificial functions such as global initializers
719 if (!SP->isArtificial())
720 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
721
722 for (auto &BB : F) {
723 GCOVBlock &Block = Func.getBlock(&BB);
724 Instruction *TI = BB.getTerminator();
725 if (int successors = TI->getNumSuccessors()) {
726 for (int i = 0; i != successors; ++i) {
727 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
728 }
729 } else if (isa<ReturnInst>(TI)) {
730 Block.addEdge(Func.getReturnBlock());
731 }
732
733 for (auto &I : BB) {
734 // Debug intrinsic locations correspond to the location of the
735 // declaration, not necessarily any statements or expressions.
736 if (isa<DbgInfoIntrinsic>(&I)) continue;
737
738 const DebugLoc &Loc = I.getDebugLoc();
739 if (!Loc)
740 continue;
741
742 // Artificial lines such as calls to the global constructors.
743 if (Loc.getLine() == 0 || Loc.isImplicitCode())
744 continue;
745
746 if (Line == Loc.getLine()) continue;
747 Line = Loc.getLine();
748 if (SP != getDISubprogram(Loc.getScope()))
749 continue;
750
751 GCOVLines &Lines = Block.getFile(Filename);
752 Lines.addLine(Loc.getLine());
753 }
754 Line = 0;
755 }
756 EdgeDestinations += Func.getEdgeDestinations();
757 }
758
759 FileChecksums.push_back(hash_value(EdgeDestinations));
760 out.write("oncg", 4);
761 out.write(ReversedVersion, 4);
762 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
763
764 for (auto &Func : Funcs) {
765 Func->setCfgChecksum(FileChecksums.back());
766 Func->writeOut();
767 }
768
769 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
770 out.close();
771 }
772}
773
774bool GCOVProfiler::emitProfileArcs() {
775 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
776 if (!CU_Nodes) return false;
7
Assuming 'CU_Nodes' is non-null
8
Taking false branch
777
778 bool Result = false;
779 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
9
Assuming 'i' is not equal to 'e'
10
Loop condition is true. Entering loop body
780 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
781 for (auto &F : M->functions()) {
782 DISubprogram *SP = F.getSubprogram();
783 if (!SP) continue;
784 if (!functionHasLines(F) || !isFunctionInstrumented(F))
785 continue;
786 // TODO: Functions using scope-based EH are currently not supported.
787 if (isUsingScopeBasedEH(F)) continue;
788 if (!Result) Result = true;
789
790 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
791 unsigned Edges = 0;
792 for (auto &BB : F) {
793 Instruction *TI = BB.getTerminator();
794 if (isa<ReturnInst>(TI)) {
795 EdgeToCounter[{&BB, nullptr}] = Edges++;
796 } else {
797 for (BasicBlock *Succ : successors(TI)) {
798 EdgeToCounter[{&BB, Succ}] = Edges++;
799 }
800 }
801 }
802
803 ArrayType *CounterTy =
804 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
805 GlobalVariable *Counters =
806 new GlobalVariable(*M, CounterTy, false,
807 GlobalValue::InternalLinkage,
808 Constant::getNullValue(CounterTy),
809 "__llvm_gcov_ctr");
810 CountersBySP.push_back(std::make_pair(Counters, SP));
811
812 // If a BB has several predecessors, use a PHINode to select
813 // the correct counter.
814 for (auto &BB : F) {
815 const unsigned EdgeCount =
816 std::distance(pred_begin(&BB), pred_end(&BB));
817 if (EdgeCount) {
818 // The phi node must be at the begin of the BB.
819 IRBuilder<> BuilderForPhi(&*BB.begin());
820 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
821 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
822 for (BasicBlock *Pred : predecessors(&BB)) {
823 auto It = EdgeToCounter.find({Pred, &BB});
824 assert(It != EdgeToCounter.end())((It != EdgeToCounter.end()) ? static_cast<void> (0) : __assert_fail
("It != EdgeToCounter.end()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 824, __PRETTY_FUNCTION__))
;
825 const unsigned Edge = It->second;
826 Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
827 Counters->getValueType(), Counters, 0, Edge);
828 Phi->addIncoming(EdgeCounter, Pred);
829 }
830
831 // Skip phis, landingpads.
832 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
833 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
834 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
835 Builder.CreateStore(Count, Phi);
836
837 Instruction *TI = BB.getTerminator();
838 if (isa<ReturnInst>(TI)) {
839 auto It = EdgeToCounter.find({&BB, nullptr});
840 assert(It != EdgeToCounter.end())((It != EdgeToCounter.end()) ? static_cast<void> (0) : __assert_fail
("It != EdgeToCounter.end()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 840, __PRETTY_FUNCTION__))
;
841 const unsigned Edge = It->second;
842 Value *Counter = Builder.CreateConstInBoundsGEP2_64(
843 Counters->getValueType(), Counters, 0, Edge);
844 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
845 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
846 Builder.CreateStore(Count, Counter);
847 }
848 }
849 }
850 }
851
852 Function *WriteoutF = insertCounterWriteout(CountersBySP);
11
Calling 'GCOVProfiler::insertCounterWriteout'
853 Function *FlushF = insertFlush(CountersBySP);
854
855 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
856 // be executed at exit and the "__llvm_gcov_flush" function to be executed
857 // when "__gcov_flush" is called.
858 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
859 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
860 "__llvm_gcov_init", M);
861 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
862 F->setLinkage(GlobalValue::InternalLinkage);
863 F->addFnAttr(Attribute::NoInline);
864 if (Options.NoRedZone)
865 F->addFnAttr(Attribute::NoRedZone);
866
867 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
868 IRBuilder<> Builder(BB);
869
870 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
871 Type *Params[] = {
872 PointerType::get(FTy, 0),
873 PointerType::get(FTy, 0)
874 };
875 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
876
877 // Initialize the environment and register the local writeout and flush
878 // functions.
879 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
880 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
881 Builder.CreateRetVoid();
882
883 appendToGlobalCtors(*M, F, 0);
884 }
885
886 return Result;
887}
888
889FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
890 Type *Args[] = {
891 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
892 Type::getInt8PtrTy(*Ctx), // const char version[4]
893 Type::getInt32Ty(*Ctx), // uint32_t checksum
894 };
895 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
896 AttributeList AL;
897 if (auto AK = TLI->getExtAttrForI32Param(false))
898 AL = AL.addParamAttribute(*Ctx, 2, AK);
899 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
900 return Res;
901}
902
903FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
904 Type *Args[] = {
905 Type::getInt32Ty(*Ctx), // uint32_t ident
906 Type::getInt8PtrTy(*Ctx), // const char *function_name
907 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
908 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
909 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
910 };
911 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
912 AttributeList AL;
913 if (auto AK = TLI->getExtAttrForI32Param(false)) {
914 AL = AL.addParamAttribute(*Ctx, 0, AK);
915 AL = AL.addParamAttribute(*Ctx, 2, AK);
916 AL = AL.addParamAttribute(*Ctx, 3, AK);
917 AL = AL.addParamAttribute(*Ctx, 4, AK);
918 }
919 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
920}
921
922FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
923 Type *Args[] = {
924 Type::getInt32Ty(*Ctx), // uint32_t num_counters
925 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
926 };
927 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
928 AttributeList AL;
929 if (auto AK = TLI->getExtAttrForI32Param(false))
930 AL = AL.addParamAttribute(*Ctx, 0, AK);
931 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
932}
933
934FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
935 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
936 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
937}
938
939FunctionCallee GCOVProfiler::getEndFileFunc() {
940 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
941 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
942}
943
944Function *GCOVProfiler::insertCounterWriteout(
945 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
946 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
947 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
948 if (!WriteoutF)
12
Assuming 'WriteoutF' is non-null
13
Taking false branch
949 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
950 "__llvm_gcov_writeout", M);
951 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
952 WriteoutF->addFnAttr(Attribute::NoInline);
953 if (Options.NoRedZone)
14
Assuming field 'NoRedZone' is false
15
Taking false branch
954 WriteoutF->addFnAttr(Attribute::NoRedZone);
955
956 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
957 IRBuilder<> Builder(BB);
958
959 auto *TLI = &GetTLI(*WriteoutF);
960
961 FunctionCallee StartFile = getStartFileFunc(TLI);
962 FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
963 FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
964 FunctionCallee SummaryInfo = getSummaryInfoFunc();
965 FunctionCallee EndFile = getEndFileFunc();
966
967 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
968 if (!CUNodes) {
16
Assuming 'CUNodes' is non-null
17
Taking false branch
969 Builder.CreateRetVoid();
970 return WriteoutF;
971 }
972
973 // Collect the relevant data into a large constant data structure that we can
974 // walk to write out everything.
975 StructType *StartFileCallArgsTy = StructType::create(
976 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
977 StructType *EmitFunctionCallArgsTy = StructType::create(
978 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
979 Builder.getInt8Ty(), Builder.getInt32Ty()});
980 StructType *EmitArcsCallArgsTy = StructType::create(
981 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
982 StructType *FileInfoTy =
983 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
984 EmitFunctionCallArgsTy->getPointerTo(),
985 EmitArcsCallArgsTy->getPointerTo()});
986
987 Constant *Zero32 = Builder.getInt32(0);
988 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
989 Constant *TwoZero32s[] = {Zero32, Zero32};
990
991 SmallVector<Constant *, 8> FileInfos;
992 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
993 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
18
The object is a 'DICompileUnit'
994
995 // Skip module skeleton (and module) CUs.
996 if (CU->getDWOId())
19
Assuming the condition is false
20
Taking false branch
997 continue;
998
999 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1000 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
21
'?' condition is false
1001 auto *StartFileCallArgs = ConstantStruct::get(
1002 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
1003 Builder.CreateGlobalStringPtr(ReversedVersion),
1004 Builder.getInt32(CfgChecksum)});
1005
1006 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1007 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1008 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1009 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
22
Assuming null pointer is passed into cast
23
'SP' initialized to a null pointer value
1010 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
24
'?' condition is true
1011 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1012 EmitFunctionCallArgsTy,
1013 {Builder.getInt32(j),
1014 Options.FunctionNamesInData
25
Assuming field 'FunctionNamesInData' is true
26
'?' condition is true
1015 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
27
Passing null pointer value via 1st parameter 'SP'
28
Calling 'getFunctionName'
1016 : Constant::getNullValue(Builder.getInt8PtrTy()),
1017 Builder.getInt32(FuncChecksum),
1018 Builder.getInt8(Options.UseCfgChecksum),
1019 Builder.getInt32(CfgChecksum)}));
1020
1021 GlobalVariable *GV = CountersBySP[j].first;
1022 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1023 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1024 EmitArcsCallArgsTy,
1025 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1026 GV->getValueType(), GV, TwoZero32s)}));
1027 }
1028 // Create global arrays for the two emit calls.
1029 int CountersSize = CountersBySP.size();
1030 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&((CountersSize == (int)EmitFunctionCallArgsArray.size() &&
"Mismatched array size!") ? static_cast<void> (0) : __assert_fail
("CountersSize == (int)EmitFunctionCallArgsArray.size() && \"Mismatched array size!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 1031, __PRETTY_FUNCTION__))
1031 "Mismatched array size!")((CountersSize == (int)EmitFunctionCallArgsArray.size() &&
"Mismatched array size!") ? static_cast<void> (0) : __assert_fail
("CountersSize == (int)EmitFunctionCallArgsArray.size() && \"Mismatched array size!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 1031, __PRETTY_FUNCTION__))
;
1032 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&((CountersSize == (int)EmitArcsCallArgsArray.size() &&
"Mismatched array size!") ? static_cast<void> (0) : __assert_fail
("CountersSize == (int)EmitArcsCallArgsArray.size() && \"Mismatched array size!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 1033, __PRETTY_FUNCTION__))
1033 "Mismatched array size!")((CountersSize == (int)EmitArcsCallArgsArray.size() &&
"Mismatched array size!") ? static_cast<void> (0) : __assert_fail
("CountersSize == (int)EmitArcsCallArgsArray.size() && \"Mismatched array size!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 1033, __PRETTY_FUNCTION__))
;
1034 auto *EmitFunctionCallArgsArrayTy =
1035 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1036 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1037 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1038 GlobalValue::InternalLinkage,
1039 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1040 EmitFunctionCallArgsArray),
1041 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1042 auto *EmitArcsCallArgsArrayTy =
1043 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1044 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1045 GlobalValue::UnnamedAddr::Global);
1046 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1047 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1048 GlobalValue::InternalLinkage,
1049 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1050 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1051 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1052
1053 FileInfos.push_back(ConstantStruct::get(
1054 FileInfoTy,
1055 {StartFileCallArgs, Builder.getInt32(CountersSize),
1056 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1057 EmitFunctionCallArgsArrayGV,
1058 TwoZero32s),
1059 ConstantExpr::getInBoundsGetElementPtr(
1060 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1061 }
1062
1063 // If we didn't find anything to actually emit, bail on out.
1064 if (FileInfos.empty()) {
1065 Builder.CreateRetVoid();
1066 return WriteoutF;
1067 }
1068
1069 // To simplify code, we cap the number of file infos we write out to fit
1070 // easily in a 32-bit signed integer. This gives consistent behavior between
1071 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1072 // operations on 32-bit systems. It also seems unreasonable to try to handle
1073 // more than 2 billion files.
1074 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX2147483647)
1075 FileInfos.resize(INT_MAX2147483647);
1076
1077 // Create a global for the entire data structure so we can walk it more
1078 // easily.
1079 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1080 auto *FileInfoArrayGV = new GlobalVariable(
1081 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1082 ConstantArray::get(FileInfoArrayTy, FileInfos),
1083 "__llvm_internal_gcov_emit_file_info");
1084 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1085
1086 // Create the CFG for walking this data structure.
1087 auto *FileLoopHeader =
1088 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1089 auto *CounterLoopHeader =
1090 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1091 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1092 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1093
1094 // We always have at least one file, so just branch to the header.
1095 Builder.CreateBr(FileLoopHeader);
1096
1097 // The index into the files structure is our loop induction variable.
1098 Builder.SetInsertPoint(FileLoopHeader);
1099 PHINode *IV =
1100 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1101 IV->addIncoming(Builder.getInt32(0), BB);
1102 auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1103 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1104 auto *StartFileCallArgsPtr =
1105 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1106 auto *StartFileCall = Builder.CreateCall(
1107 StartFile,
1108 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1109 Builder.CreateStructGEP(StartFileCallArgsTy,
1110 StartFileCallArgsPtr, 0)),
1111 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1112 Builder.CreateStructGEP(StartFileCallArgsTy,
1113 StartFileCallArgsPtr, 1)),
1114 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1115 Builder.CreateStructGEP(StartFileCallArgsTy,
1116 StartFileCallArgsPtr, 2))});
1117 if (auto AK = TLI->getExtAttrForI32Param(false))
1118 StartFileCall->addParamAttr(2, AK);
1119 auto *NumCounters =
1120 Builder.CreateLoad(FileInfoTy->getElementType(1),
1121 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1122 auto *EmitFunctionCallArgsArray =
1123 Builder.CreateLoad(FileInfoTy->getElementType(2),
1124 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1125 auto *EmitArcsCallArgsArray =
1126 Builder.CreateLoad(FileInfoTy->getElementType(3),
1127 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1128 auto *EnterCounterLoopCond =
1129 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1130 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1131
1132 Builder.SetInsertPoint(CounterLoopHeader);
1133 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1134 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1135 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1136 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1137 auto *EmitFunctionCall = Builder.CreateCall(
1138 EmitFunction,
1139 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1140 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1141 EmitFunctionCallArgsPtr, 0)),
1142 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1143 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1144 EmitFunctionCallArgsPtr, 1)),
1145 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1146 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1147 EmitFunctionCallArgsPtr, 2)),
1148 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(3),
1149 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1150 EmitFunctionCallArgsPtr, 3)),
1151 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(4),
1152 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1153 EmitFunctionCallArgsPtr,
1154 4))});
1155 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1156 EmitFunctionCall->addParamAttr(0, AK);
1157 EmitFunctionCall->addParamAttr(2, AK);
1158 EmitFunctionCall->addParamAttr(3, AK);
1159 EmitFunctionCall->addParamAttr(4, AK);
1160 }
1161 auto *EmitArcsCallArgsPtr =
1162 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1163 auto *EmitArcsCall = Builder.CreateCall(
1164 EmitArcs,
1165 {Builder.CreateLoad(
1166 EmitArcsCallArgsTy->getElementType(0),
1167 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1168 Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1169 Builder.CreateStructGEP(EmitArcsCallArgsTy,
1170 EmitArcsCallArgsPtr, 1))});
1171 if (auto AK = TLI->getExtAttrForI32Param(false))
1172 EmitArcsCall->addParamAttr(0, AK);
1173 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1174 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1175 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1176 JV->addIncoming(NextJV, CounterLoopHeader);
1177
1178 Builder.SetInsertPoint(FileLoopLatch);
1179 Builder.CreateCall(SummaryInfo, {});
1180 Builder.CreateCall(EndFile, {});
1181 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1182 auto *FileLoopCond =
1183 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1184 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1185 IV->addIncoming(NextIV, FileLoopLatch);
1186
1187 Builder.SetInsertPoint(ExitBB);
1188 Builder.CreateRetVoid();
1189
1190 return WriteoutF;
1191}
1192
1193Function *GCOVProfiler::
1194insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1195 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1196 Function *FlushF = M->getFunction("__llvm_gcov_flush");
1197 if (!FlushF)
1198 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1199 "__llvm_gcov_flush", M);
1200 else
1201 FlushF->setLinkage(GlobalValue::InternalLinkage);
1202 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1203 FlushF->addFnAttr(Attribute::NoInline);
1204 if (Options.NoRedZone)
1205 FlushF->addFnAttr(Attribute::NoRedZone);
1206
1207 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1208
1209 // Write out the current counters.
1210 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1211 assert(WriteoutF && "Need to create the writeout function first!")((WriteoutF && "Need to create the writeout function first!"
) ? static_cast<void> (0) : __assert_fail ("WriteoutF && \"Need to create the writeout function first!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp"
, 1211, __PRETTY_FUNCTION__))
;
1212
1213 IRBuilder<> Builder(Entry);
1214 Builder.CreateCall(WriteoutF, {});
1215
1216 // Zero out the counters.
1217 for (const auto &I : CountersBySP) {
1218 GlobalVariable *GV = I.first;
1219 Constant *Null = Constant::getNullValue(GV->getValueType());
1220 Builder.CreateStore(Null, GV);
1221 }
1222
1223 Type *RetTy = FlushF->getReturnType();
1224 if (RetTy == Type::getVoidTy(*Ctx))
1225 Builder.CreateRetVoid();
1226 else if (RetTy->isIntegerTy())
1227 // Used if __llvm_gcov_flush was implicitly declared.
1228 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1229 else
1230 report_fatal_error("invalid return type for __llvm_gcov_flush");
1231
1232 return FlushF;
1233}