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/Debug.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Support/InstIterator.h"
35 #include "llvm/Support/PathV2.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 class GCOVProfiler : public ModulePass {
47 : ModulePass(ID), EmitNotes(true), EmitData(true),
48 UseExtraChecksum(false), NoRedZone(false),
49 NoFunctionNamesInData(false) {
50 memcpy(Version, DefaultGCovVersion, 4);
51 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
53 GCOVProfiler(bool EmitNotes, bool EmitData, const char (&Version)[4],
54 bool UseExtraChecksum, bool NoRedZone,
55 bool NoFunctionNamesInData)
56 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
57 UseExtraChecksum(UseExtraChecksum), NoRedZone(NoRedZone),
58 NoFunctionNamesInData(NoFunctionNamesInData) {
59 memcpy(this->Version, Version, 4);
60 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
61 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
63 virtual const char *getPassName() const {
64 return "GCOV Profiler";
67 bool runOnModule(Module &M);
69 // Create the .gcno files for the Module based on DebugInfo.
70 void emitProfileNotes();
72 // Modify the program to track transitions along edges and call into the
73 // profiling runtime to emit .gcda files when run.
74 bool emitProfileArcs();
76 // Get pointers to the functions in the runtime library.
77 Constant *getStartFileFunc();
78 Constant *getIncrementIndirectCounterFunc();
79 Constant *getEmitFunctionFunc();
80 Constant *getEmitArcsFunc();
81 Constant *getEndFileFunc();
83 // Create or retrieve an i32 state value that is used to represent the
84 // pred block number for certain non-trivial edges.
85 GlobalVariable *getEdgeStateValue();
87 // Produce a table of pointers to counters, by predecessor and successor
89 GlobalVariable *buildEdgeLookupTable(Function *F,
90 GlobalVariable *Counter,
91 const UniqueVector<BasicBlock *>&Preds,
92 const UniqueVector<BasicBlock*>&Succs);
94 // Add the function to write out all our counters to the global destructor
96 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
97 void insertIndirectCounterIncrement();
98 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
100 std::string mangleName(DICompileUnit CU, const char *NewStem);
104 char Version[4]; // This is stored in reverse order for direct emission.
105 bool UseExtraChecksum;
107 bool NoFunctionNamesInData;
114 char GCOVProfiler::ID = 0;
115 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
116 "Insert instrumentation for GCOV profiling", false, false)
118 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
119 const char (&Version)[4],
120 bool UseExtraChecksum,
122 bool NoFunctionNamesInData) {
123 return new GCOVProfiler(EmitNotes, EmitData, Version, UseExtraChecksum,
124 NoRedZone, NoFunctionNamesInData);
130 static const char *LinesTag;
131 static const char *FunctionTag;
132 static const char *BlockTag;
133 static const char *EdgeTag;
137 void writeBytes(const char *Bytes, int Size) {
138 os->write(Bytes, Size);
141 void write(uint32_t i) {
142 writeBytes(reinterpret_cast<char*>(&i), 4);
145 // Returns the length measured in 4-byte blocks that will be used to
146 // represent this string in a GCOV file
147 unsigned lengthOfGCOVString(StringRef s) {
148 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
149 // padding out to the next 4-byte word. The length is measured in 4-byte
150 // words including padding, not bytes of actual string.
151 return (s.size() / 4) + 1;
154 void writeGCOVString(StringRef s) {
155 uint32_t Len = lengthOfGCOVString(s);
157 writeBytes(s.data(), s.size());
159 // Write 1 to 4 bytes of NUL padding.
160 assert((unsigned)(4 - (s.size() % 4)) > 0);
161 assert((unsigned)(4 - (s.size() % 4)) <= 4);
162 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
167 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
168 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
169 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
170 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
175 // Constructed only by requesting it from a GCOVBlock, this object stores a
176 // list of line numbers and a single filename, representing lines that belong
178 class GCOVLines : public GCOVRecord {
180 void addLine(uint32_t Line) {
181 Lines.push_back(Line);
185 // Here 2 = 1 for string length + 1 for '0' id#.
186 return lengthOfGCOVString(Filename) + 2 + Lines.size();
191 writeGCOVString(Filename);
192 for (int i = 0, e = Lines.size(); i != e; ++i)
196 GCOVLines(StringRef F, raw_ostream *os)
203 SmallVector<uint32_t, 32> Lines;
206 // Represent a basic block in GCOV. Each block has a unique number in the
207 // function, number of lines belonging to each block, and a set of edges to
209 class GCOVBlock : public GCOVRecord {
211 GCOVLines &getFile(StringRef Filename) {
212 GCOVLines *&Lines = LinesByFile[Filename];
214 Lines = new GCOVLines(Filename, os);
219 void addEdge(GCOVBlock &Successor) {
220 OutEdges.push_back(&Successor);
225 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
226 E = LinesByFile.end(); I != E; ++I) {
227 Len += I->second->length();
230 writeBytes(LinesTag, 4);
233 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
234 E = LinesByFile.end(); I != E; ++I)
235 I->second->writeOut();
241 DeleteContainerSeconds(LinesByFile);
245 friend class GCOVFunction;
247 GCOVBlock(uint32_t Number, raw_ostream *os)
253 StringMap<GCOVLines *> LinesByFile;
254 SmallVector<GCOVBlock *, 4> OutEdges;
257 // A function has a unique identifier, a checksum (we leave as zero) and a
258 // set of blocks and a map of edges between blocks. This is the only GCOV
259 // object users can construct, the blocks and lines will be rooted here.
260 class GCOVFunction : public GCOVRecord {
262 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
263 bool UseExtraChecksum) {
266 Function *F = SP.getFunction();
267 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
269 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
270 Blocks[BB] = new GCOVBlock(i++, os);
272 ReturnBlock = new GCOVBlock(i++, os);
274 writeBytes(FunctionTag, 4);
275 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
276 1 + lengthOfGCOVString(SP.getFilename()) + 1;
277 if (UseExtraChecksum)
281 write(0); // lineno checksum
282 if (UseExtraChecksum)
283 write(0); // cfg checksum
284 writeGCOVString(SP.getName());
285 writeGCOVString(SP.getFilename());
286 write(SP.getLineNumber());
290 DeleteContainerSeconds(Blocks);
294 GCOVBlock &getBlock(BasicBlock *BB) {
298 GCOVBlock &getReturnBlock() {
303 // Emit count of blocks.
304 writeBytes(BlockTag, 4);
305 write(Blocks.size() + 1);
306 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
307 write(0); // No flags on our blocks.
309 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
311 // Emit edges between blocks.
312 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
313 E = Blocks.end(); I != E; ++I) {
314 GCOVBlock &Block = *I->second;
315 if (Block.OutEdges.empty()) continue;
317 writeBytes(EdgeTag, 4);
318 write(Block.OutEdges.size() * 2 + 1);
320 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
321 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
323 write(Block.OutEdges[i]->Number);
324 write(0); // no flags
328 // Emit lines for each block.
329 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
330 E = Blocks.end(); I != E; ++I) {
331 I->second->writeOut();
336 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
337 GCOVBlock *ReturnBlock;
341 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
342 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
343 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
344 MDNode *N = GCov->getOperand(i);
345 if (N->getNumOperands() != 2) continue;
346 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
347 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
348 if (!GCovFile || !CompileUnit) continue;
349 if (CompileUnit == CU) {
350 SmallString<128> Filename = GCovFile->getString();
351 sys::path::replace_extension(Filename, NewStem);
352 return Filename.str();
357 SmallString<128> Filename = CU.getFilename();
358 sys::path::replace_extension(Filename, NewStem);
359 return sys::path::filename(Filename.str());
362 bool GCOVProfiler::runOnModule(Module &M) {
364 Ctx = &M.getContext();
366 if (EmitNotes) emitProfileNotes();
367 if (EmitData) return emitProfileArcs();
371 void GCOVProfiler::emitProfileNotes() {
372 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
373 if (!CU_Nodes) return;
375 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
376 // Each compile unit gets its own .gcno file. This means that whether we run
377 // this pass over the original .o's as they're produced, or run it after
378 // LTO, we'll generate the same .gcno files.
380 DICompileUnit CU(CU_Nodes->getOperand(i));
381 std::string ErrorInfo;
382 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
383 raw_fd_ostream::F_Binary);
384 out.write("oncg", 4);
385 out.write(Version, 4);
386 out.write("MVLL", 4);
388 DIArray SPs = CU.getSubprograms();
389 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
390 DISubprogram SP(SPs.getElement(i));
391 if (!SP.Verify()) continue;
393 Function *F = SP.getFunction();
395 GCOVFunction Func(SP, &out, i, UseExtraChecksum);
397 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
398 GCOVBlock &Block = Func.getBlock(BB);
399 TerminatorInst *TI = BB->getTerminator();
400 if (int successors = TI->getNumSuccessors()) {
401 for (int i = 0; i != successors; ++i) {
402 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
404 } else if (isa<ReturnInst>(TI)) {
405 Block.addEdge(Func.getReturnBlock());
409 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
411 const DebugLoc &Loc = I->getDebugLoc();
412 if (Loc.isUnknown()) continue;
413 if (Line == Loc.getLine()) continue;
414 Line = Loc.getLine();
415 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
417 GCOVLines &Lines = Block.getFile(SP.getFilename());
418 Lines.addLine(Loc.getLine());
423 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
428 bool GCOVProfiler::emitProfileArcs() {
429 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
430 if (!CU_Nodes) return false;
433 bool InsertIndCounterIncrCode = false;
434 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
435 DICompileUnit CU(CU_Nodes->getOperand(i));
436 DIArray SPs = CU.getSubprograms();
437 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
438 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
439 DISubprogram SP(SPs.getElement(i));
440 if (!SP.Verify()) continue;
441 Function *F = SP.getFunction();
443 if (!Result) Result = true;
445 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
446 TerminatorInst *TI = BB->getTerminator();
447 if (isa<ReturnInst>(TI))
450 Edges += TI->getNumSuccessors();
453 ArrayType *CounterTy =
454 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
455 GlobalVariable *Counters =
456 new GlobalVariable(*M, CounterTy, false,
457 GlobalValue::InternalLinkage,
458 Constant::getNullValue(CounterTy),
460 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
462 UniqueVector<BasicBlock *> ComplexEdgePreds;
463 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
466 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
467 TerminatorInst *TI = BB->getTerminator();
468 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
470 IRBuilder<> Builder(TI);
472 if (Successors == 1) {
473 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
475 Value *Count = Builder.CreateLoad(Counter);
476 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
477 Builder.CreateStore(Count, Counter);
478 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
479 Value *Sel = Builder.CreateSelect(BI->getCondition(),
480 Builder.getInt64(Edge),
481 Builder.getInt64(Edge + 1));
482 SmallVector<Value *, 2> Idx;
483 Idx.push_back(Builder.getInt64(0));
485 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
486 Value *Count = Builder.CreateLoad(Counter);
487 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
488 Builder.CreateStore(Count, Counter);
490 ComplexEdgePreds.insert(BB);
491 for (int i = 0; i != Successors; ++i)
492 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
498 if (!ComplexEdgePreds.empty()) {
499 GlobalVariable *EdgeTable =
500 buildEdgeLookupTable(F, Counters,
501 ComplexEdgePreds, ComplexEdgeSuccs);
502 GlobalVariable *EdgeState = getEdgeStateValue();
504 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
505 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
506 Builder.CreateStore(Builder.getInt32(i), EdgeState);
508 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
509 // call runtime to perform increment
510 BasicBlock::iterator InsertPt =
511 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
512 IRBuilder<> Builder(InsertPt);
513 Value *CounterPtrArray =
514 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
515 i * ComplexEdgePreds.size());
517 // Build code to increment the counter.
518 InsertIndCounterIncrCode = true;
519 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
520 EdgeState, CounterPtrArray);
525 insertCounterWriteout(CountersBySP);
526 insertFlush(CountersBySP);
529 if (InsertIndCounterIncrCode)
530 insertIndirectCounterIncrement();
535 // All edges with successors that aren't branches are "complex", because it
536 // requires complex logic to pick which counter to update.
537 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
539 GlobalVariable *Counters,
540 const UniqueVector<BasicBlock *> &Preds,
541 const UniqueVector<BasicBlock *> &Succs) {
542 // TODO: support invoke, threads. We rely on the fact that nothing can modify
543 // the whole-Module pred edge# between the time we set it and the time we next
544 // read it. Threads and invoke make this untrue.
546 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
547 size_t TableSize = Succs.size() * Preds.size();
548 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
549 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
551 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
552 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
553 for (size_t i = 0; i != TableSize; ++i)
554 EdgeTable[i] = NullValue;
557 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
558 TerminatorInst *TI = BB->getTerminator();
559 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
560 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
561 for (int i = 0; i != Successors; ++i) {
562 BasicBlock *Succ = TI->getSuccessor(i);
563 IRBuilder<> Builder(Succ);
564 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
566 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
567 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
573 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
574 GlobalVariable *EdgeTableGV =
576 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
577 ConstantArray::get(EdgeTableTy, V),
578 "__llvm_gcda_edge_table");
579 EdgeTableGV->setUnnamedAddr(true);
583 Constant *GCOVProfiler::getStartFileFunc() {
585 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
586 Type::getInt8PtrTy(*Ctx), // const char version[4]
588 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
589 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
592 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
593 Type *Int32Ty = Type::getInt32Ty(*Ctx);
594 Type *Int64Ty = Type::getInt64Ty(*Ctx);
596 Int32Ty->getPointerTo(), // uint32_t *predecessor
597 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
599 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
600 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
603 Constant *GCOVProfiler::getEmitFunctionFunc() {
605 Type::getInt32Ty(*Ctx), // uint32_t ident
606 Type::getInt8PtrTy(*Ctx), // const char *function_name
607 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
609 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
610 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
613 Constant *GCOVProfiler::getEmitArcsFunc() {
615 Type::getInt32Ty(*Ctx), // uint32_t num_counters
616 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
618 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
619 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
622 Constant *GCOVProfiler::getEndFileFunc() {
623 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
624 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
627 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
628 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
630 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
631 GlobalValue::InternalLinkage,
632 ConstantInt::get(Type::getInt32Ty(*Ctx),
634 "__llvm_gcov_global_state_pred");
635 GV->setUnnamedAddr(true);
640 void GCOVProfiler::insertCounterWriteout(
641 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
642 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
643 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
645 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
646 "__llvm_gcov_writeout", M);
647 WriteoutF->setUnnamedAddr(true);
648 WriteoutF->addFnAttr(Attribute::NoInline);
650 WriteoutF->addFnAttr(Attribute::NoRedZone);
652 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
653 IRBuilder<> Builder(BB);
655 Constant *StartFile = getStartFileFunc();
656 Constant *EmitFunction = getEmitFunctionFunc();
657 Constant *EmitArcs = getEmitArcsFunc();
658 Constant *EndFile = getEndFileFunc();
660 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
662 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
663 DICompileUnit CU(CU_Nodes->getOperand(i));
664 std::string FilenameGcda = mangleName(CU, "gcda");
665 Builder.CreateCall2(StartFile,
666 Builder.CreateGlobalStringPtr(FilenameGcda),
667 Builder.CreateGlobalStringPtr(Version));
668 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
669 DISubprogram SP(CountersBySP[j].second);
670 Builder.CreateCall3(EmitFunction,
672 NoFunctionNamesInData ?
673 Constant::getNullValue(Builder.getInt8PtrTy()) :
674 Builder.CreateGlobalStringPtr(SP.getName()),
675 Builder.getInt8(UseExtraChecksum));
677 GlobalVariable *GV = CountersBySP[j].first;
679 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
680 Builder.CreateCall2(EmitArcs,
681 Builder.getInt32(Arcs),
682 Builder.CreateConstGEP2_64(GV, 0, 0));
684 Builder.CreateCall(EndFile);
687 Builder.CreateRetVoid();
689 // Create a small bit of code that registers the "__llvm_gcov_writeout"
690 // function to be executed at exit.
691 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
692 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
693 "__llvm_gcov_init", M);
694 F->setUnnamedAddr(true);
695 F->setLinkage(GlobalValue::InternalLinkage);
696 F->addFnAttr(Attribute::NoInline);
698 F->addFnAttr(Attribute::NoRedZone);
700 BB = BasicBlock::Create(*Ctx, "entry", F);
701 Builder.SetInsertPoint(BB);
703 FTy = FunctionType::get(Builder.getInt32Ty(),
704 PointerType::get(FTy, 0), false);
705 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
706 Builder.CreateCall(AtExitFn, WriteoutF);
707 Builder.CreateRetVoid();
709 appendToGlobalCtors(*M, F, 0);
712 void GCOVProfiler::insertIndirectCounterIncrement() {
714 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
715 Fn->setUnnamedAddr(true);
716 Fn->setLinkage(GlobalValue::InternalLinkage);
717 Fn->addFnAttr(Attribute::NoInline);
719 Fn->addFnAttr(Attribute::NoRedZone);
721 // Create basic blocks for function.
722 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
723 IRBuilder<> Builder(BB);
725 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
726 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
727 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
729 // uint32_t pred = *predecessor;
730 // if (pred == 0xffffffff) return;
731 Argument *Arg = Fn->arg_begin();
732 Arg->setName("predecessor");
733 Value *Pred = Builder.CreateLoad(Arg, "pred");
734 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
735 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
737 Builder.SetInsertPoint(PredNotNegOne);
739 // uint64_t *counter = counters[pred];
740 // if (!counter) return;
741 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
742 Arg = llvm::next(Fn->arg_begin());
743 Arg->setName("counters");
744 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
745 Value *Counter = Builder.CreateLoad(GEP, "counter");
746 Cond = Builder.CreateICmpEQ(Counter,
747 Constant::getNullValue(
748 Builder.getInt64Ty()->getPointerTo()));
749 Builder.CreateCondBr(Cond, Exit, CounterEnd);
752 Builder.SetInsertPoint(CounterEnd);
753 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
754 Builder.getInt64(1));
755 Builder.CreateStore(Add, Counter);
756 Builder.CreateBr(Exit);
758 // Fill in the exit block.
759 Builder.SetInsertPoint(Exit);
760 Builder.CreateRetVoid();
764 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
765 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
766 Function *FlushF = M->getFunction("__gcov_flush");
768 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
771 FlushF->setLinkage(GlobalValue::InternalLinkage);
772 FlushF->setUnnamedAddr(true);
773 FlushF->addFnAttr(Attribute::NoInline);
775 FlushF->addFnAttr(Attribute::NoRedZone);
777 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
779 // Write out the current counters.
780 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
781 assert(WriteoutF && "Need to create the writeout function first!");
783 IRBuilder<> Builder(Entry);
784 Builder.CreateCall(WriteoutF);
786 // Zero out the counters.
787 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
788 I = CountersBySP.begin(), E = CountersBySP.end();
790 GlobalVariable *GV = I->first;
791 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
792 Builder.CreateStore(Null, GV);
795 Type *RetTy = FlushF->getReturnType();
796 if (RetTy == Type::getVoidTy(*Ctx))
797 Builder.CreateRetVoid();
798 else if (RetTy->isIntegerTy())
799 // Used if __gcov_flush was implicitly declared.
800 Builder.CreateRet(ConstantInt::get(RetTy, 0));
802 report_fatal_error("invalid return type for __gcov_flush");