[ASan] Make insertion of version mismatch guard configurable
[llvm-core.git] / lib / Transforms / Instrumentation / GCOVProfiling.cpp
blob510a3ad57b3a03170540c0b4307e27e97d76a42e
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.
14 //===----------------------------------------------------------------------===//
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/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Regex.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 #include <algorithm>
44 #include <memory>
45 #include <string>
46 #include <utility>
47 using namespace llvm;
49 #define DEBUG_TYPE "insert-gcov-profiling"
51 static cl::opt<std::string>
52 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
53 cl::ValueRequired);
54 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
55 cl::init(false), cl::Hidden);
57 GCOVOptions GCOVOptions::getDefault() {
58 GCOVOptions Options;
59 Options.EmitNotes = true;
60 Options.EmitData = true;
61 Options.UseCfgChecksum = false;
62 Options.NoRedZone = false;
63 Options.FunctionNamesInData = true;
64 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
66 if (DefaultGCOVVersion.size() != 4) {
67 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
68 DefaultGCOVVersion);
70 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
71 return Options;
74 namespace {
75 class GCOVFunction;
77 class GCOVProfiler {
78 public:
79 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
80 GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
81 assert((Options.EmitNotes || Options.EmitData) &&
82 "GCOVProfiler asked to do nothing?");
83 ReversedVersion[0] = Options.Version[3];
84 ReversedVersion[1] = Options.Version[2];
85 ReversedVersion[2] = Options.Version[1];
86 ReversedVersion[3] = Options.Version[0];
87 ReversedVersion[4] = '\0';
89 bool runOnModule(Module &M, const TargetLibraryInfo &TLI);
91 private:
92 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
95 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
97 bool emitProfileArcs();
99 bool isFunctionInstrumented(const Function &F);
100 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
101 static bool doesFilenameMatchARegex(StringRef Filename,
102 std::vector<Regex> &Regexes);
104 // Get pointers to the functions in the runtime library.
105 FunctionCallee getStartFileFunc();
106 FunctionCallee getEmitFunctionFunc();
107 FunctionCallee getEmitArcsFunc();
108 FunctionCallee getSummaryInfoFunc();
109 FunctionCallee getEndFileFunc();
111 // Add the function to write out all our counters to the global destructor
112 // list.
113 Function *
114 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
115 Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
117 void AddFlushBeforeForkAndExec();
119 enum class GCovFileType { GCNO, GCDA };
120 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
122 GCOVOptions Options;
124 // Reversed, NUL-terminated copy of Options.Version.
125 char ReversedVersion[5];
126 // Checksum, produced by hash of EdgeDestinations
127 SmallVector<uint32_t, 4> FileChecksums;
129 Module *M;
130 const TargetLibraryInfo *TLI;
131 LLVMContext *Ctx;
132 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
133 std::vector<Regex> FilterRe;
134 std::vector<Regex> ExcludeRe;
135 StringMap<bool> InstrumentedFiles;
138 class GCOVProfilerLegacyPass : public ModulePass {
139 public:
140 static char ID;
141 GCOVProfilerLegacyPass()
142 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
143 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
144 : ModulePass(ID), Profiler(Opts) {
145 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
147 StringRef getPassName() const override { return "GCOV Profiler"; }
149 bool runOnModule(Module &M) override {
150 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
151 return Profiler.runOnModule(M, TLI);
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<TargetLibraryInfoWrapperPass>();
158 private:
159 GCOVProfiler Profiler;
163 char GCOVProfilerLegacyPass::ID = 0;
164 INITIALIZE_PASS_BEGIN(
165 GCOVProfilerLegacyPass, "insert-gcov-profiling",
166 "Insert instrumentation for GCOV profiling", false, false)
167 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
168 INITIALIZE_PASS_END(
169 GCOVProfilerLegacyPass, "insert-gcov-profiling",
170 "Insert instrumentation for GCOV profiling", false, false)
172 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
173 return new GCOVProfilerLegacyPass(Options);
176 static StringRef getFunctionName(const DISubprogram *SP) {
177 if (!SP->getLinkageName().empty())
178 return SP->getLinkageName();
179 return SP->getName();
182 /// Extract a filename for a DISubprogram.
184 /// Prefer relative paths in the coverage notes. Clang also may split
185 /// up absolute paths into a directory and filename component. When
186 /// the relative path doesn't exist, reconstruct the absolute path.
187 static SmallString<128> getFilename(const DISubprogram *SP) {
188 SmallString<128> Path;
189 StringRef RelPath = SP->getFilename();
190 if (sys::fs::exists(RelPath))
191 Path = RelPath;
192 else
193 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
194 return Path;
197 namespace {
198 class GCOVRecord {
199 protected:
200 static const char *const LinesTag;
201 static const char *const FunctionTag;
202 static const char *const BlockTag;
203 static const char *const EdgeTag;
205 GCOVRecord() = default;
207 void writeBytes(const char *Bytes, int Size) {
208 os->write(Bytes, Size);
211 void write(uint32_t i) {
212 writeBytes(reinterpret_cast<char*>(&i), 4);
215 // Returns the length measured in 4-byte blocks that will be used to
216 // represent this string in a GCOV file
217 static unsigned lengthOfGCOVString(StringRef s) {
218 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
219 // padding out to the next 4-byte word. The length is measured in 4-byte
220 // words including padding, not bytes of actual string.
221 return (s.size() / 4) + 1;
224 void writeGCOVString(StringRef s) {
225 uint32_t Len = lengthOfGCOVString(s);
226 write(Len);
227 writeBytes(s.data(), s.size());
229 // Write 1 to 4 bytes of NUL padding.
230 assert((unsigned)(4 - (s.size() % 4)) > 0);
231 assert((unsigned)(4 - (s.size() % 4)) <= 4);
232 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
235 raw_ostream *os;
237 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
238 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
239 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
240 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
242 class GCOVFunction;
243 class GCOVBlock;
245 // Constructed only by requesting it from a GCOVBlock, this object stores a
246 // list of line numbers and a single filename, representing lines that belong
247 // to the block.
248 class GCOVLines : public GCOVRecord {
249 public:
250 void addLine(uint32_t Line) {
251 assert(Line != 0 && "Line zero is not a valid real line number.");
252 Lines.push_back(Line);
255 uint32_t length() const {
256 // Here 2 = 1 for string length + 1 for '0' id#.
257 return lengthOfGCOVString(Filename) + 2 + Lines.size();
260 void writeOut() {
261 write(0);
262 writeGCOVString(Filename);
263 for (int i = 0, e = Lines.size(); i != e; ++i)
264 write(Lines[i]);
267 GCOVLines(StringRef F, raw_ostream *os)
268 : Filename(F) {
269 this->os = os;
272 private:
273 std::string Filename;
274 SmallVector<uint32_t, 32> Lines;
278 // Represent a basic block in GCOV. Each block has a unique number in the
279 // function, number of lines belonging to each block, and a set of edges to
280 // other blocks.
281 class GCOVBlock : public GCOVRecord {
282 public:
283 GCOVLines &getFile(StringRef Filename) {
284 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
287 void addEdge(GCOVBlock &Successor) {
288 OutEdges.push_back(&Successor);
291 void writeOut() {
292 uint32_t Len = 3;
293 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
294 for (auto &I : LinesByFile) {
295 Len += I.second.length();
296 SortedLinesByFile.push_back(&I);
299 writeBytes(LinesTag, 4);
300 write(Len);
301 write(Number);
303 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
304 StringMapEntry<GCOVLines> *RHS) {
305 return LHS->getKey() < RHS->getKey();
307 for (auto &I : SortedLinesByFile)
308 I->getValue().writeOut();
309 write(0);
310 write(0);
313 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
314 // Only allow copy before edges and lines have been added. After that,
315 // there are inter-block pointers (eg: edges) that won't take kindly to
316 // blocks being copied or moved around.
317 assert(LinesByFile.empty());
318 assert(OutEdges.empty());
321 private:
322 friend class GCOVFunction;
324 GCOVBlock(uint32_t Number, raw_ostream *os)
325 : Number(Number) {
326 this->os = os;
329 uint32_t Number;
330 StringMap<GCOVLines> LinesByFile;
331 SmallVector<GCOVBlock *, 4> OutEdges;
334 // A function has a unique identifier, a checksum (we leave as zero) and a
335 // set of blocks and a map of edges between blocks. This is the only GCOV
336 // object users can construct, the blocks and lines will be rooted here.
337 class GCOVFunction : public GCOVRecord {
338 public:
339 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
340 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
341 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
342 ReturnBlock(1, os) {
343 this->os = os;
345 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
347 uint32_t i = 0;
348 for (auto &BB : *F) {
349 // Skip index 1 if it's assigned to the ReturnBlock.
350 if (i == 1 && ExitBlockBeforeBody)
351 ++i;
352 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
354 if (!ExitBlockBeforeBody)
355 ReturnBlock.Number = i;
357 std::string FunctionNameAndLine;
358 raw_string_ostream FNLOS(FunctionNameAndLine);
359 FNLOS << getFunctionName(SP) << SP->getLine();
360 FNLOS.flush();
361 FuncChecksum = hash_value(FunctionNameAndLine);
364 GCOVBlock &getBlock(BasicBlock *BB) {
365 return Blocks.find(BB)->second;
368 GCOVBlock &getReturnBlock() {
369 return ReturnBlock;
372 std::string getEdgeDestinations() {
373 std::string EdgeDestinations;
374 raw_string_ostream EDOS(EdgeDestinations);
375 Function *F = Blocks.begin()->first->getParent();
376 for (BasicBlock &I : *F) {
377 GCOVBlock &Block = getBlock(&I);
378 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
379 EDOS << Block.OutEdges[i]->Number;
381 return EdgeDestinations;
384 uint32_t getFuncChecksum() {
385 return FuncChecksum;
388 void setCfgChecksum(uint32_t Checksum) {
389 CfgChecksum = Checksum;
392 void writeOut() {
393 writeBytes(FunctionTag, 4);
394 SmallString<128> Filename = getFilename(SP);
395 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
396 1 + lengthOfGCOVString(Filename) + 1;
397 if (UseCfgChecksum)
398 ++BlockLen;
399 write(BlockLen);
400 write(Ident);
401 write(FuncChecksum);
402 if (UseCfgChecksum)
403 write(CfgChecksum);
404 writeGCOVString(getFunctionName(SP));
405 writeGCOVString(Filename);
406 write(SP->getLine());
408 // Emit count of blocks.
409 writeBytes(BlockTag, 4);
410 write(Blocks.size() + 1);
411 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
412 write(0); // No flags on our blocks.
414 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
416 // Emit edges between blocks.
417 if (Blocks.empty()) return;
418 Function *F = Blocks.begin()->first->getParent();
419 for (BasicBlock &I : *F) {
420 GCOVBlock &Block = getBlock(&I);
421 if (Block.OutEdges.empty()) continue;
423 writeBytes(EdgeTag, 4);
424 write(Block.OutEdges.size() * 2 + 1);
425 write(Block.Number);
426 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
427 LLVM_DEBUG(dbgs() << Block.Number << " -> "
428 << Block.OutEdges[i]->Number << "\n");
429 write(Block.OutEdges[i]->Number);
430 write(0); // no flags
434 // Emit lines for each block.
435 for (BasicBlock &I : *F)
436 getBlock(&I).writeOut();
439 private:
440 const DISubprogram *SP;
441 uint32_t Ident;
442 uint32_t FuncChecksum;
443 bool UseCfgChecksum;
444 uint32_t CfgChecksum;
445 DenseMap<BasicBlock *, GCOVBlock> Blocks;
446 GCOVBlock ReturnBlock;
450 // RegexesStr is a string containing differents regex separated by a semi-colon.
451 // For example "foo\..*$;bar\..*$".
452 std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
453 std::vector<Regex> Regexes;
454 while (!RegexesStr.empty()) {
455 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
456 if (!HeadTail.first.empty()) {
457 Regex Re(HeadTail.first);
458 std::string Err;
459 if (!Re.isValid(Err)) {
460 Ctx->emitError(Twine("Regex ") + HeadTail.first +
461 " is not valid: " + Err);
463 Regexes.emplace_back(std::move(Re));
465 RegexesStr = HeadTail.second;
467 return Regexes;
470 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
471 std::vector<Regex> &Regexes) {
472 for (Regex &Re : Regexes) {
473 if (Re.match(Filename)) {
474 return true;
477 return false;
480 bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
481 if (FilterRe.empty() && ExcludeRe.empty()) {
482 return true;
484 SmallString<128> Filename = getFilename(F.getSubprogram());
485 auto It = InstrumentedFiles.find(Filename);
486 if (It != InstrumentedFiles.end()) {
487 return It->second;
490 SmallString<256> RealPath;
491 StringRef RealFilename;
493 // Path can be
494 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
495 // such a case we must get the real_path.
496 if (sys::fs::real_path(Filename, RealPath)) {
497 // real_path can fail with path like "foo.c".
498 RealFilename = Filename;
499 } else {
500 RealFilename = RealPath;
503 bool ShouldInstrument;
504 if (FilterRe.empty()) {
505 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
506 } else if (ExcludeRe.empty()) {
507 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
508 } else {
509 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
510 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
512 InstrumentedFiles[Filename] = ShouldInstrument;
513 return ShouldInstrument;
516 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
517 GCovFileType OutputType) {
518 bool Notes = OutputType == GCovFileType::GCNO;
520 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
521 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
522 MDNode *N = GCov->getOperand(i);
523 bool ThreeElement = N->getNumOperands() == 3;
524 if (!ThreeElement && N->getNumOperands() != 2)
525 continue;
526 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
527 continue;
529 if (ThreeElement) {
530 // These nodes have no mangling to apply, it's stored mangled in the
531 // bitcode.
532 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
533 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
534 if (!NotesFile || !DataFile)
535 continue;
536 return Notes ? NotesFile->getString() : DataFile->getString();
539 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
540 if (!GCovFile)
541 continue;
543 SmallString<128> Filename = GCovFile->getString();
544 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
545 return Filename.str();
549 SmallString<128> Filename = CU->getFilename();
550 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
551 StringRef FName = sys::path::filename(Filename);
552 SmallString<128> CurPath;
553 if (sys::fs::current_path(CurPath)) return FName;
554 sys::path::append(CurPath, FName);
555 return CurPath.str();
558 bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
559 this->M = &M;
560 this->TLI = &TLI;
561 Ctx = &M.getContext();
563 AddFlushBeforeForkAndExec();
565 FilterRe = createRegexesFromString(Options.Filter);
566 ExcludeRe = createRegexesFromString(Options.Exclude);
568 if (Options.EmitNotes) emitProfileNotes();
569 if (Options.EmitData) return emitProfileArcs();
570 return false;
573 PreservedAnalyses GCOVProfilerPass::run(Module &M,
574 ModuleAnalysisManager &AM) {
576 GCOVProfiler Profiler(GCOVOpts);
578 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
579 if (!Profiler.runOnModule(M, TLI))
580 return PreservedAnalyses::all();
582 return PreservedAnalyses::none();
585 static bool functionHasLines(Function &F) {
586 // Check whether this function actually has any source lines. Not only
587 // do these waste space, they also can crash gcov.
588 for (auto &BB : F) {
589 for (auto &I : BB) {
590 // Debug intrinsic locations correspond to the location of the
591 // declaration, not necessarily any statements or expressions.
592 if (isa<DbgInfoIntrinsic>(&I)) continue;
594 const DebugLoc &Loc = I.getDebugLoc();
595 if (!Loc)
596 continue;
598 // Artificial lines such as calls to the global constructors.
599 if (Loc.getLine() == 0) continue;
601 return true;
604 return false;
607 static bool isUsingScopeBasedEH(Function &F) {
608 if (!F.hasPersonalityFn()) return false;
610 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
611 return isScopedEHPersonality(Personality);
614 static bool shouldKeepInEntry(BasicBlock::iterator It) {
615 if (isa<AllocaInst>(*It)) return true;
616 if (isa<DbgInfoIntrinsic>(*It)) return true;
617 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
618 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
621 return false;
624 void GCOVProfiler::AddFlushBeforeForkAndExec() {
625 SmallVector<Instruction *, 2> ForkAndExecs;
626 for (auto &F : M->functions()) {
627 for (auto &I : instructions(F)) {
628 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
629 if (Function *Callee = CI->getCalledFunction()) {
630 LibFunc LF;
631 if (TLI->getLibFunc(*Callee, LF) &&
632 (LF == LibFunc_fork || LF == LibFunc_execl ||
633 LF == LibFunc_execle || LF == LibFunc_execlp ||
634 LF == LibFunc_execv || LF == LibFunc_execvp ||
635 LF == LibFunc_execve || LF == LibFunc_execvpe ||
636 LF == LibFunc_execvP)) {
637 ForkAndExecs.push_back(&I);
644 // We need to split the block after the fork/exec call
645 // because else the counters for the lines after will be
646 // the same as before the call.
647 for (auto I : ForkAndExecs) {
648 IRBuilder<> Builder(I);
649 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
650 FunctionCallee GCOVFlush = M->getOrInsertFunction("__gcov_flush", FTy);
651 Builder.CreateCall(GCOVFlush);
652 I->getParent()->splitBasicBlock(I);
656 void GCOVProfiler::emitProfileNotes() {
657 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
658 if (!CU_Nodes) return;
660 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
661 // Each compile unit gets its own .gcno file. This means that whether we run
662 // this pass over the original .o's as they're produced, or run it after
663 // LTO, we'll generate the same .gcno files.
665 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
667 // Skip module skeleton (and module) CUs.
668 if (CU->getDWOId())
669 continue;
671 std::error_code EC;
672 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
673 sys::fs::OF_None);
674 if (EC) {
675 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
676 EC.message());
677 continue;
680 std::string EdgeDestinations;
682 unsigned FunctionIdent = 0;
683 for (auto &F : M->functions()) {
684 DISubprogram *SP = F.getSubprogram();
685 if (!SP) continue;
686 if (!functionHasLines(F) || !isFunctionInstrumented(F))
687 continue;
688 // TODO: Functions using scope-based EH are currently not supported.
689 if (isUsingScopeBasedEH(F)) continue;
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.
693 BasicBlock &EntryBlock = F.getEntryBlock();
694 BasicBlock::iterator It = EntryBlock.begin();
695 while (shouldKeepInEntry(It))
696 ++It;
697 EntryBlock.splitBasicBlock(It);
699 Funcs.push_back(std::make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
700 Options.UseCfgChecksum,
701 Options.ExitBlockBeforeBody));
702 GCOVFunction &Func = *Funcs.back();
704 // Add the function line number to the lines of the entry block
705 // to have a counter for the function definition.
706 uint32_t Line = SP->getLine();
707 auto Filename = getFilename(SP);
708 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
710 for (auto &BB : F) {
711 GCOVBlock &Block = Func.getBlock(&BB);
712 Instruction *TI = BB.getTerminator();
713 if (int successors = TI->getNumSuccessors()) {
714 for (int i = 0; i != successors; ++i) {
715 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
717 } else if (isa<ReturnInst>(TI)) {
718 Block.addEdge(Func.getReturnBlock());
721 for (auto &I : BB) {
722 // Debug intrinsic locations correspond to the location of the
723 // declaration, not necessarily any statements or expressions.
724 if (isa<DbgInfoIntrinsic>(&I)) continue;
726 const DebugLoc &Loc = I.getDebugLoc();
727 if (!Loc)
728 continue;
730 // Artificial lines such as calls to the global constructors.
731 if (Loc.getLine() == 0 || Loc.isImplicitCode())
732 continue;
734 if (Line == Loc.getLine()) continue;
735 Line = Loc.getLine();
736 if (SP != getDISubprogram(Loc.getScope()))
737 continue;
739 GCOVLines &Lines = Block.getFile(Filename);
740 Lines.addLine(Loc.getLine());
742 Line = 0;
744 EdgeDestinations += Func.getEdgeDestinations();
747 FileChecksums.push_back(hash_value(EdgeDestinations));
748 out.write("oncg", 4);
749 out.write(ReversedVersion, 4);
750 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
752 for (auto &Func : Funcs) {
753 Func->setCfgChecksum(FileChecksums.back());
754 Func->writeOut();
757 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
758 out.close();
762 bool GCOVProfiler::emitProfileArcs() {
763 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
764 if (!CU_Nodes) return false;
766 bool Result = false;
767 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
768 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
769 for (auto &F : M->functions()) {
770 DISubprogram *SP = F.getSubprogram();
771 if (!SP) continue;
772 if (!functionHasLines(F) || !isFunctionInstrumented(F))
773 continue;
774 // TODO: Functions using scope-based EH are currently not supported.
775 if (isUsingScopeBasedEH(F)) continue;
776 if (!Result) Result = true;
778 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
779 unsigned Edges = 0;
780 for (auto &BB : F) {
781 Instruction *TI = BB.getTerminator();
782 if (isa<ReturnInst>(TI)) {
783 EdgeToCounter[{&BB, nullptr}] = Edges++;
784 } else {
785 for (BasicBlock *Succ : successors(TI)) {
786 EdgeToCounter[{&BB, Succ}] = Edges++;
791 ArrayType *CounterTy =
792 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
793 GlobalVariable *Counters =
794 new GlobalVariable(*M, CounterTy, false,
795 GlobalValue::InternalLinkage,
796 Constant::getNullValue(CounterTy),
797 "__llvm_gcov_ctr");
798 CountersBySP.push_back(std::make_pair(Counters, SP));
800 // If a BB has several predecessors, use a PHINode to select
801 // the correct counter.
802 for (auto &BB : F) {
803 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 = BuilderForPhi.CreateConstInBoundsGEP2_64(
815 Counters->getValueType(), Counters, 0, Edge);
816 Phi->addIncoming(EdgeCounter, Pred);
819 // Skip phis, landingpads.
820 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
821 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
822 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
823 Builder.CreateStore(Count, Phi);
825 Instruction *TI = BB.getTerminator();
826 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 = Builder.CreateConstInBoundsGEP2_64(
831 Counters->getValueType(), Counters, 0, Edge);
832 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
833 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
834 Builder.CreateStore(Count, Counter);
840 Function *WriteoutF = insertCounterWriteout(CountersBySP);
841 Function *FlushF = insertFlush(CountersBySP);
843 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
844 // be executed at exit and the "__llvm_gcov_flush" function to be executed
845 // when "__gcov_flush" is called.
846 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
847 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
848 "__llvm_gcov_init", M);
849 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
850 F->setLinkage(GlobalValue::InternalLinkage);
851 F->addFnAttr(Attribute::NoInline);
852 if (Options.NoRedZone)
853 F->addFnAttr(Attribute::NoRedZone);
855 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
856 IRBuilder<> Builder(BB);
858 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
859 Type *Params[] = {
860 PointerType::get(FTy, 0),
861 PointerType::get(FTy, 0)
863 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
865 // Initialize the environment and register the local writeout and flush
866 // functions.
867 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
868 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
869 Builder.CreateRetVoid();
871 appendToGlobalCtors(*M, F, 0);
874 return Result;
877 FunctionCallee GCOVProfiler::getStartFileFunc() {
878 Type *Args[] = {
879 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
880 Type::getInt8PtrTy(*Ctx), // const char version[4]
881 Type::getInt32Ty(*Ctx), // uint32_t checksum
883 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
884 AttributeList AL;
885 if (auto AK = TLI->getExtAttrForI32Param(false))
886 AL = AL.addParamAttribute(*Ctx, 2, AK);
887 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
888 return Res;
891 FunctionCallee GCOVProfiler::getEmitFunctionFunc() {
892 Type *Args[] = {
893 Type::getInt32Ty(*Ctx), // uint32_t ident
894 Type::getInt8PtrTy(*Ctx), // const char *function_name
895 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
896 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
897 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
899 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
900 AttributeList AL;
901 if (auto AK = TLI->getExtAttrForI32Param(false)) {
902 AL = AL.addParamAttribute(*Ctx, 0, AK);
903 AL = AL.addParamAttribute(*Ctx, 2, AK);
904 AL = AL.addParamAttribute(*Ctx, 3, AK);
905 AL = AL.addParamAttribute(*Ctx, 4, AK);
907 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
910 FunctionCallee GCOVProfiler::getEmitArcsFunc() {
911 Type *Args[] = {
912 Type::getInt32Ty(*Ctx), // uint32_t num_counters
913 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
915 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
916 AttributeList AL;
917 if (auto AK = TLI->getExtAttrForI32Param(false))
918 AL = AL.addParamAttribute(*Ctx, 0, AK);
919 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
922 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
923 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
924 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
927 FunctionCallee GCOVProfiler::getEndFileFunc() {
928 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
929 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
932 Function *GCOVProfiler::insertCounterWriteout(
933 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
934 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
935 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
936 if (!WriteoutF)
937 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
938 "__llvm_gcov_writeout", M);
939 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
940 WriteoutF->addFnAttr(Attribute::NoInline);
941 if (Options.NoRedZone)
942 WriteoutF->addFnAttr(Attribute::NoRedZone);
944 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
945 IRBuilder<> Builder(BB);
947 FunctionCallee StartFile = getStartFileFunc();
948 FunctionCallee EmitFunction = getEmitFunctionFunc();
949 FunctionCallee EmitArcs = getEmitArcsFunc();
950 FunctionCallee SummaryInfo = getSummaryInfoFunc();
951 FunctionCallee EndFile = getEndFileFunc();
953 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
954 if (!CUNodes) {
955 Builder.CreateRetVoid();
956 return WriteoutF;
959 // Collect the relevant data into a large constant data structure that we can
960 // walk to write out everything.
961 StructType *StartFileCallArgsTy = StructType::create(
962 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
963 StructType *EmitFunctionCallArgsTy = StructType::create(
964 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
965 Builder.getInt8Ty(), Builder.getInt32Ty()});
966 StructType *EmitArcsCallArgsTy = StructType::create(
967 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
968 StructType *FileInfoTy =
969 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
970 EmitFunctionCallArgsTy->getPointerTo(),
971 EmitArcsCallArgsTy->getPointerTo()});
973 Constant *Zero32 = Builder.getInt32(0);
974 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
975 Constant *TwoZero32s[] = {Zero32, Zero32};
977 SmallVector<Constant *, 8> FileInfos;
978 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
979 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
981 // Skip module skeleton (and module) CUs.
982 if (CU->getDWOId())
983 continue;
985 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
986 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
987 auto *StartFileCallArgs = ConstantStruct::get(
988 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
989 Builder.CreateGlobalStringPtr(ReversedVersion),
990 Builder.getInt32(CfgChecksum)});
992 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
993 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
994 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
995 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
996 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
997 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
998 EmitFunctionCallArgsTy,
999 {Builder.getInt32(j),
1000 Options.FunctionNamesInData
1001 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
1002 : Constant::getNullValue(Builder.getInt8PtrTy()),
1003 Builder.getInt32(FuncChecksum),
1004 Builder.getInt8(Options.UseCfgChecksum),
1005 Builder.getInt32(CfgChecksum)}));
1007 GlobalVariable *GV = CountersBySP[j].first;
1008 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1009 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1010 EmitArcsCallArgsTy,
1011 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1012 GV->getValueType(), GV, TwoZero32s)}));
1014 // Create global arrays for the two emit calls.
1015 int CountersSize = CountersBySP.size();
1016 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1017 "Mismatched array size!");
1018 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1019 "Mismatched array size!");
1020 auto *EmitFunctionCallArgsArrayTy =
1021 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1022 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1023 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1024 GlobalValue::InternalLinkage,
1025 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1026 EmitFunctionCallArgsArray),
1027 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1028 auto *EmitArcsCallArgsArrayTy =
1029 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1030 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1031 GlobalValue::UnnamedAddr::Global);
1032 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1033 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1034 GlobalValue::InternalLinkage,
1035 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1036 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1037 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1039 FileInfos.push_back(ConstantStruct::get(
1040 FileInfoTy,
1041 {StartFileCallArgs, Builder.getInt32(CountersSize),
1042 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1043 EmitFunctionCallArgsArrayGV,
1044 TwoZero32s),
1045 ConstantExpr::getInBoundsGetElementPtr(
1046 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1049 // If we didn't find anything to actually emit, bail on out.
1050 if (FileInfos.empty()) {
1051 Builder.CreateRetVoid();
1052 return WriteoutF;
1055 // To simplify code, we cap the number of file infos we write out to fit
1056 // easily in a 32-bit signed integer. This gives consistent behavior between
1057 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1058 // operations on 32-bit systems. It also seems unreasonable to try to handle
1059 // more than 2 billion files.
1060 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1061 FileInfos.resize(INT_MAX);
1063 // Create a global for the entire data structure so we can walk it more
1064 // easily.
1065 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1066 auto *FileInfoArrayGV = new GlobalVariable(
1067 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1068 ConstantArray::get(FileInfoArrayTy, FileInfos),
1069 "__llvm_internal_gcov_emit_file_info");
1070 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1072 // Create the CFG for walking this data structure.
1073 auto *FileLoopHeader =
1074 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1075 auto *CounterLoopHeader =
1076 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1077 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1078 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1080 // We always have at least one file, so just branch to the header.
1081 Builder.CreateBr(FileLoopHeader);
1083 // The index into the files structure is our loop induction variable.
1084 Builder.SetInsertPoint(FileLoopHeader);
1085 PHINode *IV =
1086 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1087 IV->addIncoming(Builder.getInt32(0), BB);
1088 auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1089 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1090 auto *StartFileCallArgsPtr =
1091 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1092 auto *StartFileCall = Builder.CreateCall(
1093 StartFile,
1094 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1095 Builder.CreateStructGEP(StartFileCallArgsTy,
1096 StartFileCallArgsPtr, 0)),
1097 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1098 Builder.CreateStructGEP(StartFileCallArgsTy,
1099 StartFileCallArgsPtr, 1)),
1100 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1101 Builder.CreateStructGEP(StartFileCallArgsTy,
1102 StartFileCallArgsPtr, 2))});
1103 if (auto AK = TLI->getExtAttrForI32Param(false))
1104 StartFileCall->addParamAttr(2, AK);
1105 auto *NumCounters =
1106 Builder.CreateLoad(FileInfoTy->getElementType(1),
1107 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1108 auto *EmitFunctionCallArgsArray =
1109 Builder.CreateLoad(FileInfoTy->getElementType(2),
1110 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1111 auto *EmitArcsCallArgsArray =
1112 Builder.CreateLoad(FileInfoTy->getElementType(3),
1113 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1114 auto *EnterCounterLoopCond =
1115 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1116 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1118 Builder.SetInsertPoint(CounterLoopHeader);
1119 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1120 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1121 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1122 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1123 auto *EmitFunctionCall = Builder.CreateCall(
1124 EmitFunction,
1125 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1126 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1127 EmitFunctionCallArgsPtr, 0)),
1128 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1129 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1130 EmitFunctionCallArgsPtr, 1)),
1131 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1132 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1133 EmitFunctionCallArgsPtr, 2)),
1134 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(3),
1135 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1136 EmitFunctionCallArgsPtr, 3)),
1137 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(4),
1138 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1139 EmitFunctionCallArgsPtr,
1140 4))});
1141 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1142 EmitFunctionCall->addParamAttr(0, AK);
1143 EmitFunctionCall->addParamAttr(2, AK);
1144 EmitFunctionCall->addParamAttr(3, AK);
1145 EmitFunctionCall->addParamAttr(4, AK);
1147 auto *EmitArcsCallArgsPtr =
1148 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1149 auto *EmitArcsCall = Builder.CreateCall(
1150 EmitArcs,
1151 {Builder.CreateLoad(
1152 EmitArcsCallArgsTy->getElementType(0),
1153 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1154 Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1155 Builder.CreateStructGEP(EmitArcsCallArgsTy,
1156 EmitArcsCallArgsPtr, 1))});
1157 if (auto AK = TLI->getExtAttrForI32Param(false))
1158 EmitArcsCall->addParamAttr(0, AK);
1159 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1160 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1161 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1162 JV->addIncoming(NextJV, CounterLoopHeader);
1164 Builder.SetInsertPoint(FileLoopLatch);
1165 Builder.CreateCall(SummaryInfo, {});
1166 Builder.CreateCall(EndFile, {});
1167 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1168 auto *FileLoopCond =
1169 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1170 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1171 IV->addIncoming(NextIV, FileLoopLatch);
1173 Builder.SetInsertPoint(ExitBB);
1174 Builder.CreateRetVoid();
1176 return WriteoutF;
1179 Function *GCOVProfiler::
1180 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1181 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1182 Function *FlushF = M->getFunction("__llvm_gcov_flush");
1183 if (!FlushF)
1184 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1185 "__llvm_gcov_flush", M);
1186 else
1187 FlushF->setLinkage(GlobalValue::InternalLinkage);
1188 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1189 FlushF->addFnAttr(Attribute::NoInline);
1190 if (Options.NoRedZone)
1191 FlushF->addFnAttr(Attribute::NoRedZone);
1193 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1195 // Write out the current counters.
1196 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1197 assert(WriteoutF && "Need to create the writeout function first!");
1199 IRBuilder<> Builder(Entry);
1200 Builder.CreateCall(WriteoutF, {});
1202 // Zero out the counters.
1203 for (const auto &I : CountersBySP) {
1204 GlobalVariable *GV = I.first;
1205 Constant *Null = Constant::getNullValue(GV->getValueType());
1206 Builder.CreateStore(Null, GV);
1209 Type *RetTy = FlushF->getReturnType();
1210 if (RetTy == Type::getVoidTy(*Ctx))
1211 Builder.CreateRetVoid();
1212 else if (RetTy->isIntegerTy())
1213 // Used if __llvm_gcov_flush was implicitly declared.
1214 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1215 else
1216 report_fatal_error("invalid return type for __llvm_gcov_flush");
1218 return FlushF;