Fix think-o: emit all 8 bytes of the EOF marker. Also reflow a line in a
[oota-llvm.git] / 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 #define DEBUG_TYPE "insert-gcov-profiling"
18
19 #include "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/Support/IRBuilder.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/UniqueVector.h"
37 #include <string>
38 #include <utility>
39 using namespace llvm;
40
41 namespace {
42   class GCOVProfiler : public ModulePass {
43     bool runOnModule(Module &M);
44   public:
45     static char ID;
46     GCOVProfiler()
47         : ModulePass(ID), EmitNotes(true), EmitData(true) {
48       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49     }
50     GCOVProfiler(bool EmitNotes, bool EmitData)
51         : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData) {
52       assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
53       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
54     }
55     virtual const char *getPassName() const {
56       return "GCOV Profiler";
57     }
58
59   private:
60     // Create the GCNO files for the Module based on DebugInfo.
61     void EmitGCNO(DebugInfoFinder &DIF);
62
63     // Modify the program to track transitions along edges and call into the
64     // profiling runtime to emit .gcda files when run.
65     bool EmitProfileArcs(DebugInfoFinder &DIF);
66
67     // Get pointers to the functions in the runtime library.
68     Constant *getStartFileFunc();
69     Constant *getEmitFunctionFunc();
70     Constant *getEmitArcsFunc();
71     Constant *getEndFileFunc();
72
73     // Add the function to write out all our counters to the global destructor
74     // list.
75     void InsertCounterWriteout(DebugInfoFinder &,
76                                SmallVector<std::pair<GlobalVariable *,
77                                                      uint32_t>, 8> &);
78
79     bool EmitNotes;
80     bool EmitData;
81
82     Module *Mod;
83     LLVMContext *Ctx;
84   };
85 }
86
87 char GCOVProfiler::ID = 0;
88 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
89                 "Insert instrumentation for GCOV profiling", false, false)
90
91 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData) {
92   return new GCOVProfiler(EmitNotes, EmitData);
93 }
94
95 static DISubprogram FindSubprogram(DIScope scope) {
96   while (!scope.isSubprogram()) {
97     assert(scope.isLexicalBlock() &&
98            "Debug location not lexical block or subprogram");
99     scope = DILexicalBlock(scope).getContext();
100   }
101   return DISubprogram(scope);
102 }
103
104 namespace {
105   class GCOVRecord {
106    protected:
107     static const char *lines_tag;
108     static const char *function_tag;
109     static const char *block_tag;
110     static const char *edge_tag;
111
112     GCOVRecord() {}
113
114     void WriteBytes(const char *b, int size) {
115       os->write(b, size);
116     }
117
118     void Write(uint32_t i) {
119       WriteBytes(reinterpret_cast<char*>(&i), 4);
120     }
121
122     // Returns the length measured in 4-byte blocks that will be used to
123     // represent this string in a GCOV file
124     unsigned LengthOfGCOVString(StringRef s) {
125       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
126       // padding out to the next 4-byte word. The length is measured in 4-byte
127       // words including padding, not bytes of actual string.
128       return (s.size() + 5) / 4;
129     }
130
131     void WriteGCOVString(StringRef s) {
132       uint32_t len = LengthOfGCOVString(s);
133       Write(len);
134       WriteBytes(s.data(), s.size());
135
136       // Write 1 to 4 bytes of NUL padding.
137       assert((unsigned)(5 - ((s.size() + 1) % 4)) > 0);
138       assert((unsigned)(5 - ((s.size() + 1) % 4)) <= 4);
139       WriteBytes("\0\0\0\0", 5 - ((s.size() + 1) % 4));
140     }
141
142     raw_ostream *os;
143   };
144   const char *GCOVRecord::lines_tag = "\0\0\x45\x01";
145   const char *GCOVRecord::function_tag = "\0\0\0\1";
146   const char *GCOVRecord::block_tag = "\0\0\x41\x01";
147   const char *GCOVRecord::edge_tag = "\0\0\x43\x01";
148
149   class GCOVFunction;
150   class GCOVBlock;
151
152   // Constructed only by requesting it from a GCOVBlock, this object stores a
153   // list of line numbers and a single filename, representing lines that belong
154   // to the block.
155   class GCOVLines : public GCOVRecord {
156    public:
157     void AddLine(uint32_t line) {
158       lines.push_back(line);
159     }
160
161     uint32_t Length() {
162       return LengthOfGCOVString(filename) + 2 + lines.size();
163     }
164
165    private:
166     friend class GCOVBlock;
167
168     GCOVLines(std::string filename, raw_ostream *os)
169         : filename(filename) {
170       this->os = os;
171     }
172
173     std::string filename;
174     SmallVector<uint32_t, 32> lines;
175   };
176
177   // Represent a basic block in GCOV. Each block has a unique number in the
178   // function, number of lines belonging to each block, and a set of edges to
179   // other blocks.
180   class GCOVBlock : public GCOVRecord {
181    public:
182     GCOVLines &GetFile(std::string filename) {
183       GCOVLines *&lines = lines_by_file[filename];
184       if (!lines) {
185         lines = new GCOVLines(filename, os);
186       }
187       return *lines;
188     }
189
190     void AddEdge(GCOVBlock &successor) {
191       out_edges.push_back(&successor);
192     }
193
194     void WriteOut() {
195       uint32_t len = 3;
196       for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
197                E = lines_by_file.end(); I != E; ++I) {
198         len += I->second->Length();
199       }
200
201       WriteBytes(lines_tag, 4);
202       Write(len);
203       Write(number);
204       for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
205                E = lines_by_file.end(); I != E; ++I) {
206         Write(0);
207         WriteGCOVString(I->second->filename);
208         for (int i = 0, e = I->second->lines.size(); i != e; ++i) {
209           Write(I->second->lines[i]);
210         }
211       }
212       Write(0);
213       Write(0);
214     }
215
216     ~GCOVBlock() {
217       DeleteContainerSeconds(lines_by_file);
218     }
219
220    private:
221     friend class GCOVFunction;
222
223     GCOVBlock(uint32_t number, raw_ostream *os)
224         : number(number) {
225       this->os = os;
226     }
227
228     uint32_t number;
229     BasicBlock *block;
230     StringMap<GCOVLines *> lines_by_file;
231     SmallVector<GCOVBlock *, 4> out_edges;
232   };
233
234   // A function has a unique identifier, a checksum (we leave as zero) and a
235   // set of blocks and a map of edges between blocks. This is the only GCOV
236   // object users can construct, the blocks and lines will be rooted here.
237   class GCOVFunction : public GCOVRecord {
238    public:
239     GCOVFunction(DISubprogram SP, raw_ostream *os) {
240       this->os = os;
241
242       Function *F = SP.getFunction();
243       uint32_t i = 0;
244       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
245         blocks[BB] = new GCOVBlock(i++, os);
246       }
247
248       WriteBytes(function_tag, 4);
249       uint32_t block_len = 1 + 1 + 1 + LengthOfGCOVString(SP.getName()) +
250           1 + LengthOfGCOVString(SP.getFilename()) + 1;
251       Write(block_len);
252       uint32_t ident = reinterpret_cast<intptr_t>((MDNode*)SP);
253       Write(ident);
254       Write(0); // checksum
255       WriteGCOVString(SP.getName());
256       WriteGCOVString(SP.getFilename());
257       Write(SP.getLineNumber());
258     }
259
260     ~GCOVFunction() {
261       DeleteContainerSeconds(blocks);
262     }
263
264     GCOVBlock &GetBlock(BasicBlock *BB) {
265       return *blocks[BB];
266     }
267
268     void WriteOut() {
269       // Emit count of blocks.
270       WriteBytes(block_tag, 4);
271       Write(blocks.size());
272       for (int i = 0, e = blocks.size(); i != e; ++i) {
273         Write(0);  // No flags on our blocks.
274       }
275
276       // Emit edges between blocks.
277       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
278                E = blocks.end(); I != E; ++I) {
279         GCOVBlock &block = *I->second;
280         if (block.out_edges.empty()) continue;
281
282         WriteBytes(edge_tag, 4);
283         Write(block.out_edges.size() * 2 + 1);
284         Write(block.number);
285         for (int i = 0, e = block.out_edges.size(); i != e; ++i) {
286           Write(block.out_edges[i]->number);
287           Write(0);  // no flags
288         }
289       }
290
291       // Emit lines for each block.
292       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
293                E = blocks.end(); I != E; ++I) {
294         I->second->WriteOut();
295       }
296     }
297
298    private:
299     DenseMap<BasicBlock *, GCOVBlock *> blocks;
300   };
301 }
302
303 // Replace the stem of a file, or add one if missing.
304 static std::string ReplaceStem(std::string orig_filename, std::string new_stem){
305   return (sys::path::stem(orig_filename) + "." + new_stem).str();
306 }
307
308 bool GCOVProfiler::runOnModule(Module &M) {
309   Mod = &M;
310   Ctx = &M.getContext();
311
312   DebugInfoFinder DIF;
313   DIF.processModule(*Mod);
314
315   if (EmitNotes) EmitGCNO(DIF);
316   if (EmitData) return EmitProfileArcs(DIF);
317   return false;
318 }
319
320 void GCOVProfiler::EmitGCNO(DebugInfoFinder &DIF) {
321   DenseMap<const MDNode *, raw_fd_ostream *> gcno_files;
322   for (DebugInfoFinder::iterator I = DIF.compile_unit_begin(),
323            E = DIF.compile_unit_end(); I != E; ++I) {
324     // Each compile unit gets its own .gcno file. This means that whether we run
325     // this pass over the original .o's as they're produced, or run it after
326     // LTO, we'll generate the same .gcno files.
327
328     DICompileUnit CU(*I);
329     raw_fd_ostream *&Out = gcno_files[CU];
330     std::string ErrorInfo;
331     Out = new raw_fd_ostream(ReplaceStem(CU.getFilename(), "gcno").c_str(),
332                              ErrorInfo, raw_fd_ostream::F_Binary);
333     Out->write("oncg*404MVLL", 12);
334   }
335
336   for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
337            SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
338     DISubprogram SP(*SPI);
339     raw_fd_ostream *&os = gcno_files[SP.getCompileUnit()];
340
341     GCOVFunction function(SP, os);
342     Function *F = SP.getFunction();
343     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
344       GCOVBlock &block = function.GetBlock(BB);
345       TerminatorInst *TI = BB->getTerminator();
346       if (int successors = TI->getNumSuccessors()) {
347         for (int i = 0; i != successors; ++i) {
348           block.AddEdge(function.GetBlock(TI->getSuccessor(i)));
349         }
350       }
351
352       uint32_t line = 0;
353       for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
354         const DebugLoc &loc = I->getDebugLoc();
355         if (loc.isUnknown()) continue;
356         if (line == loc.getLine()) continue;
357         line = loc.getLine();
358         if (SP != FindSubprogram(DIScope(loc.getScope(*Ctx)))) continue;
359
360         GCOVLines &lines = block.GetFile(SP.getFilename());
361         lines.AddLine(loc.getLine());
362       }
363     }
364     function.WriteOut();
365   }
366
367   for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
368            I = gcno_files.begin(), E = gcno_files.end(); I != E; ++I) {
369     raw_fd_ostream *&Out = I->second;
370     Out->write("\0\0\0\0\0\0\0\0", 8); // EOF
371     Out->close();
372     delete Out;
373   }
374 }
375
376 bool GCOVProfiler::EmitProfileArcs(DebugInfoFinder &DIF) {
377   if (DIF.subprogram_begin() == DIF.subprogram_end())
378     return false;
379
380   SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> counters_by_ident;
381   for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
382            SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
383     DISubprogram SP(*SPI);
384     Function *F = SP.getFunction();
385
386     // TODO: GCOV format requires a distinct unified exit block.
387     unsigned edges = 0;
388     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
389       TerminatorInst *TI = BB->getTerminator();
390       edges += TI->getNumSuccessors();
391     }
392
393     const ArrayType *counter_type =
394         ArrayType::get(Type::getInt64Ty(*Ctx), edges);
395     GlobalVariable *counter =
396         new GlobalVariable(*Mod, counter_type, false,
397                            GlobalValue::InternalLinkage,
398                            Constant::getNullValue(counter_type),
399                            "__llvm_gcov_ctr", 0, false, 0);
400     counters_by_ident.push_back(
401         std::make_pair(counter, reinterpret_cast<intptr_t>((MDNode*)SP)));
402
403     UniqueVector<BasicBlock *> complex_edge_preds;
404     UniqueVector<BasicBlock *> complex_edge_succs;
405
406     unsigned edge_num = 0;
407     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
408       TerminatorInst *TI = BB->getTerminator();
409       if (int successors = TI->getNumSuccessors()) {
410         IRBuilder<> builder(TI);
411
412         if (successors == 1) {
413           Value *ctr = builder.CreateConstInBoundsGEP2_64(counter, 0, edge_num);
414           Value *count = builder.CreateLoad(ctr);
415           count = builder.CreateAdd(count,
416                                     ConstantInt::get(Type::getInt64Ty(*Ctx),1));
417           builder.CreateStore(count, ctr);
418         } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
419           Value *sel = builder.CreateSelect(
420               BI->getCondition(),
421               ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num),
422               ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num + 1));
423           SmallVector<Value *, 2> idx;
424           idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
425           idx.push_back(sel);
426           Value *ctr = builder.CreateInBoundsGEP(counter,
427                                                  idx.begin(), idx.end());
428           Value *count = builder.CreateLoad(ctr);
429           count = builder.CreateAdd(count,
430                                     ConstantInt::get(Type::getInt64Ty(*Ctx),1));
431           builder.CreateStore(count, ctr);
432         } else {
433           complex_edge_preds.insert(BB);
434           for (int i = 0; i != successors; ++i) {
435             complex_edge_succs.insert(TI->getSuccessor(i));
436           }
437         }
438         edge_num += successors;
439       }
440     }
441
442     // TODO: support switch, invoke, indirectbr
443     if (!complex_edge_preds.empty()) {
444       // emit a [preds x [succs x i64*]].
445       for (int i = 0, e = complex_edge_preds.size(); i != e; ++i) {
446         // call runtime to state save
447       }
448       for (int i = 0, e = complex_edge_succs.size(); i != e; ++i) {
449         // call runtime to perform increment
450       }
451     }
452   }
453
454   InsertCounterWriteout(DIF, counters_by_ident);
455
456   return true;
457 }
458
459 Constant *GCOVProfiler::getStartFileFunc() {
460   const Type *Args[1] = { Type::getInt8PtrTy(*Ctx) };
461   const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
462                                               Args, false);
463   return Mod->getOrInsertFunction("llvm_gcda_start_file", FTy);
464 }
465
466 Constant *GCOVProfiler::getEmitFunctionFunc() {
467   const Type *Args[1] = { Type::getInt32Ty(*Ctx) };
468   const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
469                                               Args, false);
470   return Mod->getOrInsertFunction("llvm_gcda_emit_function", FTy);
471 }
472
473 Constant *GCOVProfiler::getEmitArcsFunc() {
474   const Type *Args[] = {
475     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
476     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
477   };
478   const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
479                                               Args, false);
480   return Mod->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
481 }
482
483 Constant *GCOVProfiler::getEndFileFunc() {
484   const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
485   return Mod->getOrInsertFunction("llvm_gcda_end_file", FTy);
486 }
487
488 void GCOVProfiler::InsertCounterWriteout(
489     DebugInfoFinder &DIF,
490     SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> &counters_by_ident) {
491
492   const FunctionType *WriteoutFTy =
493       FunctionType::get(Type::getVoidTy(*Ctx), false);
494   Function *WriteoutF = Function::Create(WriteoutFTy,
495                                          GlobalValue::InternalLinkage,
496                                          "__llvm_gcda_writeout", Mod);
497   WriteoutF->setUnnamedAddr(true);
498   BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
499   IRBuilder<> builder(BB);
500
501   Constant *StartFile = getStartFileFunc();
502   Constant *EmitFunction = getEmitFunctionFunc();
503   Constant *EmitArcs = getEmitArcsFunc();
504   Constant *EndFile = getEndFileFunc();
505
506   for (DebugInfoFinder::iterator CUI = DIF.compile_unit_begin(),
507            CUE = DIF.compile_unit_end(); CUI != CUE; ++CUI) {
508     DICompileUnit compile_unit(*CUI);
509     std::string filename_gcda = ReplaceStem(compile_unit.getFilename(), "gcda");
510     builder.CreateCall(StartFile,
511                        builder.CreateGlobalStringPtr(filename_gcda));
512     for (SmallVector<std::pair<GlobalVariable *, uint32_t>, 8>::iterator
513              I = counters_by_ident.begin(), E = counters_by_ident.end();
514          I != E; ++I) {
515       builder.CreateCall(EmitFunction, ConstantInt::get(Type::getInt32Ty(*Ctx),
516                                                         I->second));
517       GlobalVariable *GV = I->first;
518       unsigned num_arcs =
519           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
520       builder.CreateCall2(
521           EmitArcs,
522           ConstantInt::get(Type::getInt32Ty(*Ctx), num_arcs),
523           builder.CreateConstGEP2_64(GV, 0, 0));
524     }
525     builder.CreateCall(EndFile);
526   }
527   builder.CreateRetVoid();
528
529   InsertProfilingShutdownCall(WriteoutF, Mod);
530 }