1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "insert-gcov-profiling"
19 #include "llvm/Transforms/Instrumentation.h"
20 #include "ProfilingUtils.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/UniqueVector.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/DebugLoc.h"
35 #include "llvm/Support/InstIterator.h"
36 #include "llvm/Support/PathV2.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 static cl::opt<std::string>
44 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
47 GCOVOptions GCOVOptions::getDefault() {
49 Options.EmitNotes = true;
50 Options.EmitData = true;
51 Options.UseCfgChecksum = false;
52 Options.NoRedZone = false;
53 Options.FunctionNamesInData = true;
55 if (DefaultGCOVVersion.size() != 4) {
56 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
59 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
64 class GCOVProfiler : public ModulePass {
67 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
68 ReversedVersion[0] = Options.Version[3];
69 ReversedVersion[1] = Options.Version[2];
70 ReversedVersion[2] = Options.Version[1];
71 ReversedVersion[3] = Options.Version[0];
72 ReversedVersion[4] = '\0';
73 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
75 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
78 ReversedVersion[0] = Options.Version[3];
79 ReversedVersion[1] = Options.Version[2];
80 ReversedVersion[2] = Options.Version[1];
81 ReversedVersion[3] = Options.Version[0];
82 ReversedVersion[4] = '\0';
83 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
85 virtual const char *getPassName() const {
86 return "GCOV Profiler";
90 bool runOnModule(Module &M);
92 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
95 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
97 bool emitProfileArcs();
99 // Get pointers to the functions in the runtime library.
100 Constant *getStartFileFunc();
101 Constant *getIncrementIndirectCounterFunc();
102 Constant *getEmitFunctionFunc();
103 Constant *getEmitArcsFunc();
104 Constant *getEndFileFunc();
106 // Create or retrieve an i32 state value that is used to represent the
107 // pred block number for certain non-trivial edges.
108 GlobalVariable *getEdgeStateValue();
110 // Produce a table of pointers to counters, by predecessor and successor
112 GlobalVariable *buildEdgeLookupTable(Function *F,
113 GlobalVariable *Counter,
114 const UniqueVector<BasicBlock *>&Preds,
115 const UniqueVector<BasicBlock*>&Succs);
117 // Add the function to write out all our counters to the global destructor
119 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
120 void insertIndirectCounterIncrement();
121 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
123 std::string mangleName(DICompileUnit CU, const char *NewStem);
127 // Reversed, NUL-terminated copy of Options.Version.
128 char ReversedVersion[5];
135 char GCOVProfiler::ID = 0;
136 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
137 "Insert instrumentation for GCOV profiling", false, false)
139 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
140 return new GCOVProfiler(Options);
146 static const char *LinesTag;
147 static const char *FunctionTag;
148 static const char *BlockTag;
149 static const char *EdgeTag;
153 void writeBytes(const char *Bytes, int Size) {
154 os->write(Bytes, Size);
157 void write(uint32_t i) {
158 writeBytes(reinterpret_cast<char*>(&i), 4);
161 // Returns the length measured in 4-byte blocks that will be used to
162 // represent this string in a GCOV file
163 unsigned lengthOfGCOVString(StringRef s) {
164 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
165 // padding out to the next 4-byte word. The length is measured in 4-byte
166 // words including padding, not bytes of actual string.
167 return (s.size() / 4) + 1;
170 void writeGCOVString(StringRef s) {
171 uint32_t Len = lengthOfGCOVString(s);
173 writeBytes(s.data(), s.size());
175 // Write 1 to 4 bytes of NUL padding.
176 assert((unsigned)(4 - (s.size() % 4)) > 0);
177 assert((unsigned)(4 - (s.size() % 4)) <= 4);
178 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
183 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
184 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
185 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
186 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
191 // Constructed only by requesting it from a GCOVBlock, this object stores a
192 // list of line numbers and a single filename, representing lines that belong
194 class GCOVLines : public GCOVRecord {
196 void addLine(uint32_t Line) {
197 Lines.push_back(Line);
201 // Here 2 = 1 for string length + 1 for '0' id#.
202 return lengthOfGCOVString(Filename) + 2 + Lines.size();
207 writeGCOVString(Filename);
208 for (int i = 0, e = Lines.size(); i != e; ++i)
212 GCOVLines(StringRef F, raw_ostream *os)
219 SmallVector<uint32_t, 32> Lines;
222 // Represent a basic block in GCOV. Each block has a unique number in the
223 // function, number of lines belonging to each block, and a set of edges to
225 class GCOVBlock : public GCOVRecord {
227 GCOVLines &getFile(StringRef Filename) {
228 GCOVLines *&Lines = LinesByFile[Filename];
230 Lines = new GCOVLines(Filename, os);
235 void addEdge(GCOVBlock &Successor) {
236 OutEdges.push_back(&Successor);
241 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
242 E = LinesByFile.end(); I != E; ++I) {
243 Len += I->second->length();
246 writeBytes(LinesTag, 4);
249 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
250 E = LinesByFile.end(); I != E; ++I)
251 I->second->writeOut();
257 DeleteContainerSeconds(LinesByFile);
261 friend class GCOVFunction;
263 GCOVBlock(uint32_t Number, raw_ostream *os)
269 StringMap<GCOVLines *> LinesByFile;
270 SmallVector<GCOVBlock *, 4> OutEdges;
273 // A function has a unique identifier, a checksum (we leave as zero) and a
274 // set of blocks and a map of edges between blocks. This is the only GCOV
275 // object users can construct, the blocks and lines will be rooted here.
276 class GCOVFunction : public GCOVRecord {
278 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
279 bool UseCfgChecksum) {
282 Function *F = SP.getFunction();
283 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
285 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
286 Blocks[BB] = new GCOVBlock(i++, os);
288 ReturnBlock = new GCOVBlock(i++, os);
290 writeBytes(FunctionTag, 4);
291 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
292 1 + lengthOfGCOVString(SP.getFilename()) + 1;
297 write(0); // lineno checksum
299 write(0); // cfg checksum
300 writeGCOVString(SP.getName());
301 writeGCOVString(SP.getFilename());
302 write(SP.getLineNumber());
306 DeleteContainerSeconds(Blocks);
310 GCOVBlock &getBlock(BasicBlock *BB) {
314 GCOVBlock &getReturnBlock() {
319 // Emit count of blocks.
320 writeBytes(BlockTag, 4);
321 write(Blocks.size() + 1);
322 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
323 write(0); // No flags on our blocks.
325 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
327 // Emit edges between blocks.
328 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
329 E = Blocks.end(); I != E; ++I) {
330 GCOVBlock &Block = *I->second;
331 if (Block.OutEdges.empty()) continue;
333 writeBytes(EdgeTag, 4);
334 write(Block.OutEdges.size() * 2 + 1);
336 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
337 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
339 write(Block.OutEdges[i]->Number);
340 write(0); // no flags
344 // Emit lines for each block.
345 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
346 E = Blocks.end(); I != E; ++I) {
347 I->second->writeOut();
352 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
353 GCOVBlock *ReturnBlock;
357 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
358 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
359 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
360 MDNode *N = GCov->getOperand(i);
361 if (N->getNumOperands() != 2) continue;
362 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
363 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
364 if (!GCovFile || !CompileUnit) continue;
365 if (CompileUnit == CU) {
366 SmallString<128> Filename = GCovFile->getString();
367 sys::path::replace_extension(Filename, NewStem);
368 return Filename.str();
373 SmallString<128> Filename = CU.getFilename();
374 sys::path::replace_extension(Filename, NewStem);
375 return sys::path::filename(Filename.str());
378 bool GCOVProfiler::runOnModule(Module &M) {
380 Ctx = &M.getContext();
382 if (Options.EmitNotes) emitProfileNotes();
383 if (Options.EmitData) return emitProfileArcs();
387 void GCOVProfiler::emitProfileNotes() {
388 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
389 if (!CU_Nodes) return;
391 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
392 // Each compile unit gets its own .gcno file. This means that whether we run
393 // this pass over the original .o's as they're produced, or run it after
394 // LTO, we'll generate the same .gcno files.
396 DICompileUnit CU(CU_Nodes->getOperand(i));
397 std::string ErrorInfo;
398 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
399 raw_fd_ostream::F_Binary);
400 out.write("oncg", 4);
401 out.write(ReversedVersion, 4);
402 out.write("MVLL", 4);
404 DIArray SPs = CU.getSubprograms();
405 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
406 DISubprogram SP(SPs.getElement(i));
407 if (!SP.Verify()) continue;
409 Function *F = SP.getFunction();
411 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
413 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
414 GCOVBlock &Block = Func.getBlock(BB);
415 TerminatorInst *TI = BB->getTerminator();
416 if (int successors = TI->getNumSuccessors()) {
417 for (int i = 0; i != successors; ++i) {
418 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
420 } else if (isa<ReturnInst>(TI)) {
421 Block.addEdge(Func.getReturnBlock());
425 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
427 const DebugLoc &Loc = I->getDebugLoc();
428 if (Loc.isUnknown()) continue;
429 if (Line == Loc.getLine()) continue;
430 Line = Loc.getLine();
431 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
433 GCOVLines &Lines = Block.getFile(SP.getFilename());
434 Lines.addLine(Loc.getLine());
439 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
444 bool GCOVProfiler::emitProfileArcs() {
445 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
446 if (!CU_Nodes) return false;
449 bool InsertIndCounterIncrCode = false;
450 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
451 DICompileUnit CU(CU_Nodes->getOperand(i));
452 DIArray SPs = CU.getSubprograms();
453 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
454 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
455 DISubprogram SP(SPs.getElement(i));
456 if (!SP.Verify()) continue;
457 Function *F = SP.getFunction();
459 if (!Result) Result = true;
461 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
462 TerminatorInst *TI = BB->getTerminator();
463 if (isa<ReturnInst>(TI))
466 Edges += TI->getNumSuccessors();
469 ArrayType *CounterTy =
470 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
471 GlobalVariable *Counters =
472 new GlobalVariable(*M, CounterTy, false,
473 GlobalValue::InternalLinkage,
474 Constant::getNullValue(CounterTy),
476 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
478 UniqueVector<BasicBlock *> ComplexEdgePreds;
479 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
482 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
483 TerminatorInst *TI = BB->getTerminator();
484 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
486 IRBuilder<> Builder(TI);
488 if (Successors == 1) {
489 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
491 Value *Count = Builder.CreateLoad(Counter);
492 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
493 Builder.CreateStore(Count, Counter);
494 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
495 Value *Sel = Builder.CreateSelect(BI->getCondition(),
496 Builder.getInt64(Edge),
497 Builder.getInt64(Edge + 1));
498 SmallVector<Value *, 2> Idx;
499 Idx.push_back(Builder.getInt64(0));
501 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
502 Value *Count = Builder.CreateLoad(Counter);
503 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
504 Builder.CreateStore(Count, Counter);
506 ComplexEdgePreds.insert(BB);
507 for (int i = 0; i != Successors; ++i)
508 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
514 if (!ComplexEdgePreds.empty()) {
515 GlobalVariable *EdgeTable =
516 buildEdgeLookupTable(F, Counters,
517 ComplexEdgePreds, ComplexEdgeSuccs);
518 GlobalVariable *EdgeState = getEdgeStateValue();
520 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
521 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
522 Builder.CreateStore(Builder.getInt32(i), EdgeState);
524 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
525 // call runtime to perform increment
526 BasicBlock::iterator InsertPt =
527 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
528 IRBuilder<> Builder(InsertPt);
529 Value *CounterPtrArray =
530 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
531 i * ComplexEdgePreds.size());
533 // Build code to increment the counter.
534 InsertIndCounterIncrCode = true;
535 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
536 EdgeState, CounterPtrArray);
541 insertCounterWriteout(CountersBySP);
542 insertFlush(CountersBySP);
545 if (InsertIndCounterIncrCode)
546 insertIndirectCounterIncrement();
551 // All edges with successors that aren't branches are "complex", because it
552 // requires complex logic to pick which counter to update.
553 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
555 GlobalVariable *Counters,
556 const UniqueVector<BasicBlock *> &Preds,
557 const UniqueVector<BasicBlock *> &Succs) {
558 // TODO: support invoke, threads. We rely on the fact that nothing can modify
559 // the whole-Module pred edge# between the time we set it and the time we next
560 // read it. Threads and invoke make this untrue.
562 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
563 size_t TableSize = Succs.size() * Preds.size();
564 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
565 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
567 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
568 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
569 for (size_t i = 0; i != TableSize; ++i)
570 EdgeTable[i] = NullValue;
573 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
574 TerminatorInst *TI = BB->getTerminator();
575 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
576 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
577 for (int i = 0; i != Successors; ++i) {
578 BasicBlock *Succ = TI->getSuccessor(i);
579 IRBuilder<> Builder(Succ);
580 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
582 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
583 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
589 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
590 GlobalVariable *EdgeTableGV =
592 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
593 ConstantArray::get(EdgeTableTy, V),
594 "__llvm_gcda_edge_table");
595 EdgeTableGV->setUnnamedAddr(true);
599 Constant *GCOVProfiler::getStartFileFunc() {
601 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
602 Type::getInt8PtrTy(*Ctx), // const char version[4]
604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
605 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
608 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
609 Type *Int32Ty = Type::getInt32Ty(*Ctx);
610 Type *Int64Ty = Type::getInt64Ty(*Ctx);
612 Int32Ty->getPointerTo(), // uint32_t *predecessor
613 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
615 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
616 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
619 Constant *GCOVProfiler::getEmitFunctionFunc() {
621 Type::getInt32Ty(*Ctx), // uint32_t ident
622 Type::getInt8PtrTy(*Ctx), // const char *function_name
623 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
625 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
626 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
629 Constant *GCOVProfiler::getEmitArcsFunc() {
631 Type::getInt32Ty(*Ctx), // uint32_t num_counters
632 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
634 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
635 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
638 Constant *GCOVProfiler::getEndFileFunc() {
639 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
640 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
643 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
644 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
646 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
647 GlobalValue::InternalLinkage,
648 ConstantInt::get(Type::getInt32Ty(*Ctx),
650 "__llvm_gcov_global_state_pred");
651 GV->setUnnamedAddr(true);
656 void GCOVProfiler::insertCounterWriteout(
657 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
658 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
659 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
661 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
662 "__llvm_gcov_writeout", M);
663 WriteoutF->setUnnamedAddr(true);
664 WriteoutF->addFnAttr(Attribute::NoInline);
665 if (Options.NoRedZone)
666 WriteoutF->addFnAttr(Attribute::NoRedZone);
668 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
669 IRBuilder<> Builder(BB);
671 Constant *StartFile = getStartFileFunc();
672 Constant *EmitFunction = getEmitFunctionFunc();
673 Constant *EmitArcs = getEmitArcsFunc();
674 Constant *EndFile = getEndFileFunc();
676 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
678 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
679 DICompileUnit CU(CU_Nodes->getOperand(i));
680 std::string FilenameGcda = mangleName(CU, "gcda");
681 Builder.CreateCall2(StartFile,
682 Builder.CreateGlobalStringPtr(FilenameGcda),
683 Builder.CreateGlobalStringPtr(ReversedVersion));
684 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
685 DISubprogram SP(CountersBySP[j].second);
686 Builder.CreateCall3(EmitFunction,
688 Options.FunctionNamesInData ?
689 Builder.CreateGlobalStringPtr(SP.getName()) :
690 Constant::getNullValue(Builder.getInt8PtrTy()),
691 Builder.getInt8(Options.UseCfgChecksum));
693 GlobalVariable *GV = CountersBySP[j].first;
695 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
696 Builder.CreateCall2(EmitArcs,
697 Builder.getInt32(Arcs),
698 Builder.CreateConstGEP2_64(GV, 0, 0));
700 Builder.CreateCall(EndFile);
703 Builder.CreateRetVoid();
705 // Create a small bit of code that registers the "__llvm_gcov_writeout"
706 // function to be executed at exit.
707 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
708 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
709 "__llvm_gcov_init", M);
710 F->setUnnamedAddr(true);
711 F->setLinkage(GlobalValue::InternalLinkage);
712 F->addFnAttr(Attribute::NoInline);
713 if (Options.NoRedZone)
714 F->addFnAttr(Attribute::NoRedZone);
716 BB = BasicBlock::Create(*Ctx, "entry", F);
717 Builder.SetInsertPoint(BB);
719 FTy = FunctionType::get(Builder.getInt32Ty(),
720 PointerType::get(FTy, 0), false);
721 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
722 Builder.CreateCall(AtExitFn, WriteoutF);
723 Builder.CreateRetVoid();
725 appendToGlobalCtors(*M, F, 0);
728 void GCOVProfiler::insertIndirectCounterIncrement() {
730 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
731 Fn->setUnnamedAddr(true);
732 Fn->setLinkage(GlobalValue::InternalLinkage);
733 Fn->addFnAttr(Attribute::NoInline);
734 if (Options.NoRedZone)
735 Fn->addFnAttr(Attribute::NoRedZone);
737 // Create basic blocks for function.
738 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
739 IRBuilder<> Builder(BB);
741 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
742 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
743 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
745 // uint32_t pred = *predecessor;
746 // if (pred == 0xffffffff) return;
747 Argument *Arg = Fn->arg_begin();
748 Arg->setName("predecessor");
749 Value *Pred = Builder.CreateLoad(Arg, "pred");
750 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
751 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
753 Builder.SetInsertPoint(PredNotNegOne);
755 // uint64_t *counter = counters[pred];
756 // if (!counter) return;
757 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
758 Arg = llvm::next(Fn->arg_begin());
759 Arg->setName("counters");
760 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
761 Value *Counter = Builder.CreateLoad(GEP, "counter");
762 Cond = Builder.CreateICmpEQ(Counter,
763 Constant::getNullValue(
764 Builder.getInt64Ty()->getPointerTo()));
765 Builder.CreateCondBr(Cond, Exit, CounterEnd);
768 Builder.SetInsertPoint(CounterEnd);
769 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
770 Builder.getInt64(1));
771 Builder.CreateStore(Add, Counter);
772 Builder.CreateBr(Exit);
774 // Fill in the exit block.
775 Builder.SetInsertPoint(Exit);
776 Builder.CreateRetVoid();
780 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
781 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
782 Function *FlushF = M->getFunction("__gcov_flush");
784 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
787 FlushF->setLinkage(GlobalValue::InternalLinkage);
788 FlushF->setUnnamedAddr(true);
789 FlushF->addFnAttr(Attribute::NoInline);
790 if (Options.NoRedZone)
791 FlushF->addFnAttr(Attribute::NoRedZone);
793 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
795 // Write out the current counters.
796 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
797 assert(WriteoutF && "Need to create the writeout function first!");
799 IRBuilder<> Builder(Entry);
800 Builder.CreateCall(WriteoutF);
802 // Zero out the counters.
803 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
804 I = CountersBySP.begin(), E = CountersBySP.end();
806 GlobalVariable *GV = I->first;
807 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
808 Builder.CreateStore(Null, GV);
811 Type *RetTy = FlushF->getReturnType();
812 if (RetTy == Type::getVoidTy(*Ctx))
813 Builder.CreateRetVoid();
814 else if (RetTy->isIntegerTy())
815 // Used if __gcov_flush was implicitly declared.
816 Builder.CreateRet(ConstantInt::get(RetTy, 0));
818 report_fatal_error("invalid return type for __gcov_flush");