]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
Merge ^/head r327150 through r327164.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Instrumentation / GCOVProfiling.cpp
1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
13 // file on exit.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/UniqueVector.h"
24 #include "llvm/Analysis/EHPersonalities.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/GCOVProfiler.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/ModuleUtils.h"
41 #include <algorithm>
42 #include <memory>
43 #include <string>
44 #include <utility>
45 using namespace llvm;
46
47 #define DEBUG_TYPE "insert-gcov-profiling"
48
49 static cl::opt<std::string>
50 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
51                    cl::ValueRequired);
52 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
53                                                 cl::init(false), cl::Hidden);
54
55 GCOVOptions GCOVOptions::getDefault() {
56   GCOVOptions Options;
57   Options.EmitNotes = true;
58   Options.EmitData = true;
59   Options.UseCfgChecksum = false;
60   Options.NoRedZone = false;
61   Options.FunctionNamesInData = true;
62   Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
63
64   if (DefaultGCOVVersion.size() != 4) {
65     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
66                              DefaultGCOVVersion);
67   }
68   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
69   return Options;
70 }
71
72 namespace {
73 class GCOVFunction;
74
75 class GCOVProfiler {
76 public:
77   GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
78   GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
79     assert((Options.EmitNotes || Options.EmitData) &&
80            "GCOVProfiler asked to do nothing?");
81     ReversedVersion[0] = Options.Version[3];
82     ReversedVersion[1] = Options.Version[2];
83     ReversedVersion[2] = Options.Version[1];
84     ReversedVersion[3] = Options.Version[0];
85     ReversedVersion[4] = '\0';
86   }
87   bool runOnModule(Module &M);
88
89 private:
90   // Create the .gcno files for the Module based on DebugInfo.
91   void emitProfileNotes();
92
93   // Modify the program to track transitions along edges and call into the
94   // profiling runtime to emit .gcda files when run.
95   bool emitProfileArcs();
96
97   // Get pointers to the functions in the runtime library.
98   Constant *getStartFileFunc();
99   Constant *getIncrementIndirectCounterFunc();
100   Constant *getEmitFunctionFunc();
101   Constant *getEmitArcsFunc();
102   Constant *getSummaryInfoFunc();
103   Constant *getEndFileFunc();
104
105   // Create or retrieve an i32 state value that is used to represent the
106   // pred block number for certain non-trivial edges.
107   GlobalVariable *getEdgeStateValue();
108
109   // Produce a table of pointers to counters, by predecessor and successor
110   // block number.
111   GlobalVariable *buildEdgeLookupTable(Function *F, GlobalVariable *Counter,
112                                        const UniqueVector<BasicBlock *> &Preds,
113                                        const UniqueVector<BasicBlock *> &Succs);
114
115   // Add the function to write out all our counters to the global destructor
116   // list.
117   Function *
118   insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119   Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
120   void insertIndirectCounterIncrement();
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;
133   LLVMContext *Ctx;
134   SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
135 };
136
137 class GCOVProfilerLegacyPass : public ModulePass {
138 public:
139   static char ID;
140   GCOVProfilerLegacyPass()
141       : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
142   GCOVProfilerLegacyPass(const GCOVOptions &Opts)
143       : ModulePass(ID), Profiler(Opts) {
144     initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
145   }
146   StringRef getPassName() const override { return "GCOV Profiler"; }
147
148   bool runOnModule(Module &M) override { return Profiler.runOnModule(M); }
149
150 private:
151   GCOVProfiler Profiler;
152 };
153 }
154
155 char GCOVProfilerLegacyPass::ID = 0;
156 INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling",
157                 "Insert instrumentation for GCOV profiling", false, false)
158
159 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
160   return new GCOVProfilerLegacyPass(Options);
161 }
162
163 static StringRef getFunctionName(const DISubprogram *SP) {
164   if (!SP->getLinkageName().empty())
165     return SP->getLinkageName();
166   return SP->getName();
167 }
168
169 namespace {
170   class GCOVRecord {
171    protected:
172     static const char *const LinesTag;
173     static const char *const FunctionTag;
174     static const char *const BlockTag;
175     static const char *const EdgeTag;
176
177     GCOVRecord() = default;
178
179     void writeBytes(const char *Bytes, int Size) {
180       os->write(Bytes, Size);
181     }
182
183     void write(uint32_t i) {
184       writeBytes(reinterpret_cast<char*>(&i), 4);
185     }
186
187     // Returns the length measured in 4-byte blocks that will be used to
188     // represent this string in a GCOV file
189     static unsigned lengthOfGCOVString(StringRef s) {
190       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
191       // padding out to the next 4-byte word. The length is measured in 4-byte
192       // words including padding, not bytes of actual string.
193       return (s.size() / 4) + 1;
194     }
195
196     void writeGCOVString(StringRef s) {
197       uint32_t Len = lengthOfGCOVString(s);
198       write(Len);
199       writeBytes(s.data(), s.size());
200
201       // Write 1 to 4 bytes of NUL padding.
202       assert((unsigned)(4 - (s.size() % 4)) > 0);
203       assert((unsigned)(4 - (s.size() % 4)) <= 4);
204       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
205     }
206
207     raw_ostream *os;
208   };
209   const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
210   const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
211   const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
212   const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
213
214   class GCOVFunction;
215   class GCOVBlock;
216
217   // Constructed only by requesting it from a GCOVBlock, this object stores a
218   // list of line numbers and a single filename, representing lines that belong
219   // to the block.
220   class GCOVLines : public GCOVRecord {
221    public:
222     void addLine(uint32_t Line) {
223       assert(Line != 0 && "Line zero is not a valid real line number.");
224       Lines.push_back(Line);
225     }
226
227     uint32_t length() const {
228       // Here 2 = 1 for string length + 1 for '0' id#.
229       return lengthOfGCOVString(Filename) + 2 + Lines.size();
230     }
231
232     void writeOut() {
233       write(0);
234       writeGCOVString(Filename);
235       for (int i = 0, e = Lines.size(); i != e; ++i)
236         write(Lines[i]);
237     }
238
239     GCOVLines(StringRef F, raw_ostream *os)
240       : Filename(F) {
241       this->os = os;
242     }
243
244    private:
245     StringRef Filename;
246     SmallVector<uint32_t, 32> Lines;
247   };
248
249
250   // Represent a basic block in GCOV. Each block has a unique number in the
251   // function, number of lines belonging to each block, and a set of edges to
252   // other blocks.
253   class GCOVBlock : public GCOVRecord {
254    public:
255     GCOVLines &getFile(StringRef Filename) {
256       return LinesByFile.try_emplace(Filename, Filename, os).first->second;
257     }
258
259     void addEdge(GCOVBlock &Successor) {
260       OutEdges.push_back(&Successor);
261     }
262
263     void writeOut() {
264       uint32_t Len = 3;
265       SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
266       for (auto &I : LinesByFile) {
267         Len += I.second.length();
268         SortedLinesByFile.push_back(&I);
269       }
270
271       writeBytes(LinesTag, 4);
272       write(Len);
273       write(Number);
274
275       std::sort(
276           SortedLinesByFile.begin(), SortedLinesByFile.end(),
277           [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
278             return LHS->getKey() < RHS->getKey();
279           });
280       for (auto &I : SortedLinesByFile)
281         I->getValue().writeOut();
282       write(0);
283       write(0);
284     }
285
286     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
287       // Only allow copy before edges and lines have been added. After that,
288       // there are inter-block pointers (eg: edges) that won't take kindly to
289       // blocks being copied or moved around.
290       assert(LinesByFile.empty());
291       assert(OutEdges.empty());
292     }
293
294    private:
295     friend class GCOVFunction;
296
297     GCOVBlock(uint32_t Number, raw_ostream *os)
298         : Number(Number) {
299       this->os = os;
300     }
301
302     uint32_t Number;
303     StringMap<GCOVLines> LinesByFile;
304     SmallVector<GCOVBlock *, 4> OutEdges;
305   };
306
307   // A function has a unique identifier, a checksum (we leave as zero) and a
308   // set of blocks and a map of edges between blocks. This is the only GCOV
309   // object users can construct, the blocks and lines will be rooted here.
310   class GCOVFunction : public GCOVRecord {
311    public:
312      GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
313                   uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
314          : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
315            ReturnBlock(1, os) {
316       this->os = os;
317
318       DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
319
320       uint32_t i = 0;
321       for (auto &BB : *F) {
322         // Skip index 1 if it's assigned to the ReturnBlock.
323         if (i == 1 && ExitBlockBeforeBody)
324           ++i;
325         Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
326       }
327       if (!ExitBlockBeforeBody)
328         ReturnBlock.Number = i;
329
330       std::string FunctionNameAndLine;
331       raw_string_ostream FNLOS(FunctionNameAndLine);
332       FNLOS << getFunctionName(SP) << SP->getLine();
333       FNLOS.flush();
334       FuncChecksum = hash_value(FunctionNameAndLine);
335     }
336
337     GCOVBlock &getBlock(BasicBlock *BB) {
338       return Blocks.find(BB)->second;
339     }
340
341     GCOVBlock &getReturnBlock() {
342       return ReturnBlock;
343     }
344
345     std::string getEdgeDestinations() {
346       std::string EdgeDestinations;
347       raw_string_ostream EDOS(EdgeDestinations);
348       Function *F = Blocks.begin()->first->getParent();
349       for (BasicBlock &I : *F) {
350         GCOVBlock &Block = getBlock(&I);
351         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
352           EDOS << Block.OutEdges[i]->Number;
353       }
354       return EdgeDestinations;
355     }
356
357     uint32_t getFuncChecksum() {
358       return FuncChecksum;
359     }
360
361     void setCfgChecksum(uint32_t Checksum) {
362       CfgChecksum = Checksum;
363     }
364
365     void writeOut() {
366       writeBytes(FunctionTag, 4);
367       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
368                           1 + lengthOfGCOVString(SP->getFilename()) + 1;
369       if (UseCfgChecksum)
370         ++BlockLen;
371       write(BlockLen);
372       write(Ident);
373       write(FuncChecksum);
374       if (UseCfgChecksum)
375         write(CfgChecksum);
376       writeGCOVString(getFunctionName(SP));
377       writeGCOVString(SP->getFilename());
378       write(SP->getLine());
379
380       // Emit count of blocks.
381       writeBytes(BlockTag, 4);
382       write(Blocks.size() + 1);
383       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
384         write(0);  // No flags on our blocks.
385       }
386       DEBUG(dbgs() << Blocks.size() << " blocks.\n");
387
388       // Emit edges between blocks.
389       if (Blocks.empty()) return;
390       Function *F = Blocks.begin()->first->getParent();
391       for (BasicBlock &I : *F) {
392         GCOVBlock &Block = getBlock(&I);
393         if (Block.OutEdges.empty()) continue;
394
395         writeBytes(EdgeTag, 4);
396         write(Block.OutEdges.size() * 2 + 1);
397         write(Block.Number);
398         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
399           DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
400                        << "\n");
401           write(Block.OutEdges[i]->Number);
402           write(0);  // no flags
403         }
404       }
405
406       // Emit lines for each block.
407       for (BasicBlock &I : *F)
408         getBlock(&I).writeOut();
409     }
410
411    private:
412      const DISubprogram *SP;
413     uint32_t Ident;
414     uint32_t FuncChecksum;
415     bool UseCfgChecksum;
416     uint32_t CfgChecksum;
417     DenseMap<BasicBlock *, GCOVBlock> Blocks;
418     GCOVBlock ReturnBlock;
419   };
420 }
421
422 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
423                                      GCovFileType OutputType) {
424   bool Notes = OutputType == GCovFileType::GCNO;
425
426   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
427     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
428       MDNode *N = GCov->getOperand(i);
429       bool ThreeElement = N->getNumOperands() == 3;
430       if (!ThreeElement && N->getNumOperands() != 2)
431         continue;
432       if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
433         continue;
434
435       if (ThreeElement) {
436         // These nodes have no mangling to apply, it's stored mangled in the
437         // bitcode.
438         MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
439         MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
440         if (!NotesFile || !DataFile)
441           continue;
442         return Notes ? NotesFile->getString() : DataFile->getString();
443       }
444
445       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
446       if (!GCovFile)
447         continue;
448
449       SmallString<128> Filename = GCovFile->getString();
450       sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
451       return Filename.str();
452     }
453   }
454
455   SmallString<128> Filename = CU->getFilename();
456   sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
457   StringRef FName = sys::path::filename(Filename);
458   SmallString<128> CurPath;
459   if (sys::fs::current_path(CurPath)) return FName;
460   sys::path::append(CurPath, FName);
461   return CurPath.str();
462 }
463
464 bool GCOVProfiler::runOnModule(Module &M) {
465   this->M = &M;
466   Ctx = &M.getContext();
467
468   if (Options.EmitNotes) emitProfileNotes();
469   if (Options.EmitData) return emitProfileArcs();
470   return false;
471 }
472
473 PreservedAnalyses GCOVProfilerPass::run(Module &M,
474                                         ModuleAnalysisManager &AM) {
475
476   GCOVProfiler Profiler(GCOVOpts);
477
478   if (!Profiler.runOnModule(M))
479     return PreservedAnalyses::all();
480
481   return PreservedAnalyses::none();
482 }
483
484 static bool functionHasLines(Function &F) {
485   // Check whether this function actually has any source lines. Not only
486   // do these waste space, they also can crash gcov.
487   for (auto &BB : F) {
488     for (auto &I : BB) {
489       // Debug intrinsic locations correspond to the location of the
490       // declaration, not necessarily any statements or expressions.
491       if (isa<DbgInfoIntrinsic>(&I)) continue;
492
493       const DebugLoc &Loc = I.getDebugLoc();
494       if (!Loc)
495         continue;
496
497       // Artificial lines such as calls to the global constructors.
498       if (Loc.getLine() == 0) continue;
499
500       return true;
501     }
502   }
503   return false;
504 }
505
506 static bool isUsingFuncletBasedEH(Function &F) {
507   if (!F.hasPersonalityFn()) return false;
508
509   EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
510   return isFuncletEHPersonality(Personality);
511 }
512
513 static bool shouldKeepInEntry(BasicBlock::iterator It) {
514         if (isa<AllocaInst>(*It)) return true;
515         if (isa<DbgInfoIntrinsic>(*It)) return true;
516         if (auto *II = dyn_cast<IntrinsicInst>(It)) {
517                 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
518         }
519
520         return false;
521 }
522
523 void GCOVProfiler::emitProfileNotes() {
524   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
525   if (!CU_Nodes) return;
526
527   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
528     // Each compile unit gets its own .gcno file. This means that whether we run
529     // this pass over the original .o's as they're produced, or run it after
530     // LTO, we'll generate the same .gcno files.
531
532     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
533
534     // Skip module skeleton (and module) CUs.
535     if (CU->getDWOId())
536       continue;
537
538     std::error_code EC;
539     raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
540     if (EC) {
541       Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
542                      EC.message());
543       continue;
544     }
545
546     std::string EdgeDestinations;
547
548     unsigned FunctionIdent = 0;
549     for (auto &F : M->functions()) {
550       DISubprogram *SP = F.getSubprogram();
551       if (!SP) continue;
552       if (!functionHasLines(F)) continue;
553       // TODO: Functions using funclet-based EH are currently not supported.
554       if (isUsingFuncletBasedEH(F)) continue;
555
556       // gcov expects every function to start with an entry block that has a
557       // single successor, so split the entry block to make sure of that.
558       BasicBlock &EntryBlock = F.getEntryBlock();
559       BasicBlock::iterator It = EntryBlock.begin();
560       while (shouldKeepInEntry(It))
561         ++It;
562       EntryBlock.splitBasicBlock(It);
563
564       Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
565                                                 Options.UseCfgChecksum,
566                                                 Options.ExitBlockBeforeBody));
567       GCOVFunction &Func = *Funcs.back();
568
569       for (auto &BB : F) {
570         GCOVBlock &Block = Func.getBlock(&BB);
571         TerminatorInst *TI = BB.getTerminator();
572         if (int successors = TI->getNumSuccessors()) {
573           for (int i = 0; i != successors; ++i) {
574             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
575           }
576         } else if (isa<ReturnInst>(TI)) {
577           Block.addEdge(Func.getReturnBlock());
578         }
579
580         uint32_t Line = 0;
581         for (auto &I : BB) {
582           // Debug intrinsic locations correspond to the location of the
583           // declaration, not necessarily any statements or expressions.
584           if (isa<DbgInfoIntrinsic>(&I)) continue;
585
586           const DebugLoc &Loc = I.getDebugLoc();
587           if (!Loc)
588             continue;
589
590           // Artificial lines such as calls to the global constructors.
591           if (Loc.getLine() == 0) continue;
592
593           if (Line == Loc.getLine()) continue;
594           Line = Loc.getLine();
595           if (SP != getDISubprogram(Loc.getScope()))
596             continue;
597
598           GCOVLines &Lines = Block.getFile(SP->getFilename());
599           Lines.addLine(Loc.getLine());
600         }
601       }
602       EdgeDestinations += Func.getEdgeDestinations();
603     }
604
605     FileChecksums.push_back(hash_value(EdgeDestinations));
606     out.write("oncg", 4);
607     out.write(ReversedVersion, 4);
608     out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
609
610     for (auto &Func : Funcs) {
611       Func->setCfgChecksum(FileChecksums.back());
612       Func->writeOut();
613     }
614
615     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
616     out.close();
617   }
618 }
619
620 bool GCOVProfiler::emitProfileArcs() {
621   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
622   if (!CU_Nodes) return false;
623
624   bool Result = false;
625   bool InsertIndCounterIncrCode = false;
626   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
627     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
628     for (auto &F : M->functions()) {
629       DISubprogram *SP = F.getSubprogram();
630       if (!SP) continue;
631       if (!functionHasLines(F)) continue;
632       // TODO: Functions using funclet-based EH are currently not supported.
633       if (isUsingFuncletBasedEH(F)) continue;
634       if (!Result) Result = true;
635
636       unsigned Edges = 0;
637       for (auto &BB : F) {
638         TerminatorInst *TI = BB.getTerminator();
639         if (isa<ReturnInst>(TI))
640           ++Edges;
641         else
642           Edges += TI->getNumSuccessors();
643       }
644
645       ArrayType *CounterTy =
646         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
647       GlobalVariable *Counters =
648         new GlobalVariable(*M, CounterTy, false,
649                            GlobalValue::InternalLinkage,
650                            Constant::getNullValue(CounterTy),
651                            "__llvm_gcov_ctr");
652       CountersBySP.push_back(std::make_pair(Counters, SP));
653
654       UniqueVector<BasicBlock *> ComplexEdgePreds;
655       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
656
657       unsigned Edge = 0;
658       for (auto &BB : F) {
659         TerminatorInst *TI = BB.getTerminator();
660         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
661         if (Successors) {
662           if (Successors == 1) {
663             IRBuilder<> Builder(&*BB.getFirstInsertionPt());
664             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
665                                                                 Edge);
666             Value *Count = Builder.CreateLoad(Counter);
667             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
668             Builder.CreateStore(Count, Counter);
669           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
670             IRBuilder<> Builder(BI);
671             Value *Sel = Builder.CreateSelect(BI->getCondition(),
672                                               Builder.getInt64(Edge),
673                                               Builder.getInt64(Edge + 1));
674             Value *Counter = Builder.CreateInBoundsGEP(
675                 Counters->getValueType(), Counters, {Builder.getInt64(0), Sel});
676             Value *Count = Builder.CreateLoad(Counter);
677             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
678             Builder.CreateStore(Count, Counter);
679           } else {
680             ComplexEdgePreds.insert(&BB);
681             for (int i = 0; i != Successors; ++i)
682               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
683           }
684
685           Edge += Successors;
686         }
687       }
688
689       if (!ComplexEdgePreds.empty()) {
690         GlobalVariable *EdgeTable =
691           buildEdgeLookupTable(&F, Counters,
692                                ComplexEdgePreds, ComplexEdgeSuccs);
693         GlobalVariable *EdgeState = getEdgeStateValue();
694
695         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
696           IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
697           Builder.CreateStore(Builder.getInt32(i), EdgeState);
698         }
699
700         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
701           // Call runtime to perform increment.
702           IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
703           Value *CounterPtrArray =
704             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
705                                                i * ComplexEdgePreds.size());
706
707           // Build code to increment the counter.
708           InsertIndCounterIncrCode = true;
709           Builder.CreateCall(getIncrementIndirectCounterFunc(),
710                              {EdgeState, CounterPtrArray});
711         }
712       }
713     }
714
715     Function *WriteoutF = insertCounterWriteout(CountersBySP);
716     Function *FlushF = insertFlush(CountersBySP);
717
718     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
719     // be executed at exit and the "__llvm_gcov_flush" function to be executed
720     // when "__gcov_flush" is called.
721     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
722     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
723                                    "__llvm_gcov_init", M);
724     F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
725     F->setLinkage(GlobalValue::InternalLinkage);
726     F->addFnAttr(Attribute::NoInline);
727     if (Options.NoRedZone)
728       F->addFnAttr(Attribute::NoRedZone);
729
730     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
731     IRBuilder<> Builder(BB);
732
733     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
734     Type *Params[] = {
735       PointerType::get(FTy, 0),
736       PointerType::get(FTy, 0)
737     };
738     FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
739
740     // Initialize the environment and register the local writeout and flush
741     // functions.
742     Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
743     Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
744     Builder.CreateRetVoid();
745
746     appendToGlobalCtors(*M, F, 0);
747   }
748
749   if (InsertIndCounterIncrCode)
750     insertIndirectCounterIncrement();
751
752   return Result;
753 }
754
755 // All edges with successors that aren't branches are "complex", because it
756 // requires complex logic to pick which counter to update.
757 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
758     Function *F,
759     GlobalVariable *Counters,
760     const UniqueVector<BasicBlock *> &Preds,
761     const UniqueVector<BasicBlock *> &Succs) {
762   // TODO: support invoke, threads. We rely on the fact that nothing can modify
763   // the whole-Module pred edge# between the time we set it and the time we next
764   // read it. Threads and invoke make this untrue.
765
766   // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
767   size_t TableSize = Succs.size() * Preds.size();
768   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
769   ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
770
771   std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
772   Constant *NullValue = Constant::getNullValue(Int64PtrTy);
773   for (size_t i = 0; i != TableSize; ++i)
774     EdgeTable[i] = NullValue;
775
776   unsigned Edge = 0;
777   for (BasicBlock &BB : *F) {
778     TerminatorInst *TI = BB.getTerminator();
779     int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
780     if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
781       for (int i = 0; i != Successors; ++i) {
782         BasicBlock *Succ = TI->getSuccessor(i);
783         IRBuilder<> Builder(Succ);
784         Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
785                                                             Edge + i);
786         EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
787                   (Preds.idFor(&BB) - 1)] = cast<Constant>(Counter);
788       }
789     }
790     Edge += Successors;
791   }
792
793   GlobalVariable *EdgeTableGV =
794       new GlobalVariable(
795           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
796           ConstantArray::get(EdgeTableTy,
797                              makeArrayRef(&EdgeTable[0],TableSize)),
798           "__llvm_gcda_edge_table");
799   EdgeTableGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
800   return EdgeTableGV;
801 }
802
803 Constant *GCOVProfiler::getStartFileFunc() {
804   Type *Args[] = {
805     Type::getInt8PtrTy(*Ctx),  // const char *orig_filename
806     Type::getInt8PtrTy(*Ctx),  // const char version[4]
807     Type::getInt32Ty(*Ctx),    // uint32_t checksum
808   };
809   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
810   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
811 }
812
813 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
814   Type *Int32Ty = Type::getInt32Ty(*Ctx);
815   Type *Int64Ty = Type::getInt64Ty(*Ctx);
816   Type *Args[] = {
817     Int32Ty->getPointerTo(),                // uint32_t *predecessor
818     Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
819   };
820   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
821   return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
822 }
823
824 Constant *GCOVProfiler::getEmitFunctionFunc() {
825   Type *Args[] = {
826     Type::getInt32Ty(*Ctx),    // uint32_t ident
827     Type::getInt8PtrTy(*Ctx),  // const char *function_name
828     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
829     Type::getInt8Ty(*Ctx),     // uint8_t use_extra_checksum
830     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
831   };
832   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
833   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
834 }
835
836 Constant *GCOVProfiler::getEmitArcsFunc() {
837   Type *Args[] = {
838     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
839     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
840   };
841   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
842   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
843 }
844
845 Constant *GCOVProfiler::getSummaryInfoFunc() {
846   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
847   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
848 }
849
850 Constant *GCOVProfiler::getEndFileFunc() {
851   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
852   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
853 }
854
855 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
856   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
857   if (!GV) {
858     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
859                             GlobalValue::InternalLinkage,
860                             ConstantInt::get(Type::getInt32Ty(*Ctx),
861                                              0xffffffff),
862                             "__llvm_gcov_global_state_pred");
863     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
864   }
865   return GV;
866 }
867
868 Function *GCOVProfiler::insertCounterWriteout(
869     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
870   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
871   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
872   if (!WriteoutF)
873     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
874                                  "__llvm_gcov_writeout", M);
875   WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
876   WriteoutF->addFnAttr(Attribute::NoInline);
877   if (Options.NoRedZone)
878     WriteoutF->addFnAttr(Attribute::NoRedZone);
879
880   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
881   IRBuilder<> Builder(BB);
882
883   Constant *StartFile = getStartFileFunc();
884   Constant *EmitFunction = getEmitFunctionFunc();
885   Constant *EmitArcs = getEmitArcsFunc();
886   Constant *SummaryInfo = getSummaryInfoFunc();
887   Constant *EndFile = getEndFileFunc();
888
889   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
890   if (CU_Nodes) {
891     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
892       auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
893
894       // Skip module skeleton (and module) CUs.
895       if (CU->getDWOId())
896         continue;
897
898       std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
899       uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
900       Builder.CreateCall(StartFile,
901                          {Builder.CreateGlobalStringPtr(FilenameGcda),
902                           Builder.CreateGlobalStringPtr(ReversedVersion),
903                           Builder.getInt32(CfgChecksum)});
904       for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
905         auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
906         uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
907         Builder.CreateCall(
908             EmitFunction,
909             {Builder.getInt32(j),
910              Options.FunctionNamesInData
911                  ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
912                  : Constant::getNullValue(Builder.getInt8PtrTy()),
913              Builder.getInt32(FuncChecksum),
914              Builder.getInt8(Options.UseCfgChecksum),
915              Builder.getInt32(CfgChecksum)});
916
917         GlobalVariable *GV = CountersBySP[j].first;
918         unsigned Arcs =
919           cast<ArrayType>(GV->getValueType())->getNumElements();
920         Builder.CreateCall(EmitArcs, {Builder.getInt32(Arcs),
921                                       Builder.CreateConstGEP2_64(GV, 0, 0)});
922       }
923       Builder.CreateCall(SummaryInfo, {});
924       Builder.CreateCall(EndFile, {});
925     }
926   }
927
928   Builder.CreateRetVoid();
929   return WriteoutF;
930 }
931
932 void GCOVProfiler::insertIndirectCounterIncrement() {
933   Function *Fn =
934     cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
935   Fn->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
936   Fn->setLinkage(GlobalValue::InternalLinkage);
937   Fn->addFnAttr(Attribute::NoInline);
938   if (Options.NoRedZone)
939     Fn->addFnAttr(Attribute::NoRedZone);
940
941   // Create basic blocks for function.
942   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
943   IRBuilder<> Builder(BB);
944
945   BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
946   BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
947   BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
948
949   // uint32_t pred = *predecessor;
950   // if (pred == 0xffffffff) return;
951   Argument *Arg = &*Fn->arg_begin();
952   Arg->setName("predecessor");
953   Value *Pred = Builder.CreateLoad(Arg, "pred");
954   Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
955   BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
956
957   Builder.SetInsertPoint(PredNotNegOne);
958
959   // uint64_t *counter = counters[pred];
960   // if (!counter) return;
961   Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
962   Arg = &*std::next(Fn->arg_begin());
963   Arg->setName("counters");
964   Value *GEP = Builder.CreateGEP(Type::getInt64PtrTy(*Ctx), Arg, ZExtPred);
965   Value *Counter = Builder.CreateLoad(GEP, "counter");
966   Cond = Builder.CreateICmpEQ(Counter,
967                               Constant::getNullValue(
968                                   Builder.getInt64Ty()->getPointerTo()));
969   Builder.CreateCondBr(Cond, Exit, CounterEnd);
970
971   // ++*counter;
972   Builder.SetInsertPoint(CounterEnd);
973   Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
974                                  Builder.getInt64(1));
975   Builder.CreateStore(Add, Counter);
976   Builder.CreateBr(Exit);
977
978   // Fill in the exit block.
979   Builder.SetInsertPoint(Exit);
980   Builder.CreateRetVoid();
981 }
982
983 Function *GCOVProfiler::
984 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
985   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
986   Function *FlushF = M->getFunction("__llvm_gcov_flush");
987   if (!FlushF)
988     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
989                               "__llvm_gcov_flush", M);
990   else
991     FlushF->setLinkage(GlobalValue::InternalLinkage);
992   FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
993   FlushF->addFnAttr(Attribute::NoInline);
994   if (Options.NoRedZone)
995     FlushF->addFnAttr(Attribute::NoRedZone);
996
997   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
998
999   // Write out the current counters.
1000   Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1001   assert(WriteoutF && "Need to create the writeout function first!");
1002
1003   IRBuilder<> Builder(Entry);
1004   Builder.CreateCall(WriteoutF, {});
1005
1006   // Zero out the counters.
1007   for (const auto &I : CountersBySP) {
1008     GlobalVariable *GV = I.first;
1009     Constant *Null = Constant::getNullValue(GV->getValueType());
1010     Builder.CreateStore(Null, GV);
1011   }
1012
1013   Type *RetTy = FlushF->getReturnType();
1014   if (RetTy == Type::getVoidTy(*Ctx))
1015     Builder.CreateRetVoid();
1016   else if (RetTy->isIntegerTy())
1017     // Used if __llvm_gcov_flush was implicitly declared.
1018     Builder.CreateRet(ConstantInt::get(RetTy, 0));
1019   else
1020     report_fatal_error("invalid return type for __llvm_gcov_flush");
1021
1022   return FlushF;
1023 }