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