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 "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/DebugInfo.h"
22 #include "llvm/IRBuilder.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/UniqueVector.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), Use402Format(false),
48 UseExtraChecksum(false) {
49 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
51 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
52 bool useExtraChecksum = false)
53 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
54 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
55 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
56 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
58 virtual const char *getPassName() const {
59 return "GCOV Profiler";
62 bool runOnModule(Module &M);
64 // Create the GCNO files for the Module based on DebugInfo.
67 // Modify the program to track transitions along edges and call into the
68 // profiling runtime to emit .gcda files when run.
69 bool emitProfileArcs();
71 // Get pointers to the functions in the runtime library.
72 Constant *getStartFileFunc();
73 Constant *getIncrementIndirectCounterFunc();
74 Constant *getEmitFunctionFunc();
75 Constant *getEmitArcsFunc();
76 Constant *getEndFileFunc();
78 // Create or retrieve an i32 state value that is used to represent the
79 // pred block number for certain non-trivial edges.
80 GlobalVariable *getEdgeStateValue();
82 // Produce a table of pointers to counters, by predecessor and successor
84 GlobalVariable *buildEdgeLookupTable(Function *F,
85 GlobalVariable *Counter,
86 const UniqueVector<BasicBlock *> &Preds,
87 const UniqueVector<BasicBlock *> &Succs);
89 // Add the function to write out all our counters to the global destructor
91 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
92 void insertIndirectCounterIncrement();
94 std::string mangleName(DICompileUnit CU, std::string NewStem);
99 bool UseExtraChecksum;
106 char GCOVProfiler::ID = 0;
107 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
108 "Insert instrumentation for GCOV profiling", false, false)
110 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
112 bool UseExtraChecksum) {
113 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
119 static const char *LinesTag;
120 static const char *FunctionTag;
121 static const char *BlockTag;
122 static const char *EdgeTag;
126 void writeBytes(const char *Bytes, int Size) {
127 os->write(Bytes, Size);
130 void write(uint32_t i) {
131 writeBytes(reinterpret_cast<char*>(&i), 4);
134 // Returns the length measured in 4-byte blocks that will be used to
135 // represent this string in a GCOV file
136 unsigned lengthOfGCOVString(StringRef s) {
137 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
138 // padding out to the next 4-byte word. The length is measured in 4-byte
139 // words including padding, not bytes of actual string.
140 return (s.size() / 4) + 1;
143 void writeGCOVString(StringRef s) {
144 uint32_t Len = lengthOfGCOVString(s);
146 writeBytes(s.data(), s.size());
148 // Write 1 to 4 bytes of NUL padding.
149 assert((unsigned)(4 - (s.size() % 4)) > 0);
150 assert((unsigned)(4 - (s.size() % 4)) <= 4);
151 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
156 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
157 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
158 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
159 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
164 // Constructed only by requesting it from a GCOVBlock, this object stores a
165 // list of line numbers and a single filename, representing lines that belong
167 class GCOVLines : public GCOVRecord {
169 void addLine(uint32_t Line) {
170 Lines.push_back(Line);
174 // Here 2 = 1 for string length + 1 for '0' id#.
175 return lengthOfGCOVString(Filename) + 2 + Lines.size();
180 writeGCOVString(Filename);
181 for (int i = 0, e = Lines.size(); i != e; ++i)
185 GCOVLines(StringRef F, raw_ostream *os)
192 SmallVector<uint32_t, 32> Lines;
195 // Represent a basic block in GCOV. Each block has a unique number in the
196 // function, number of lines belonging to each block, and a set of edges to
198 class GCOVBlock : public GCOVRecord {
200 GCOVLines &getFile(StringRef Filename) {
201 GCOVLines *&Lines = LinesByFile[Filename];
203 Lines = new GCOVLines(Filename, os);
208 void addEdge(GCOVBlock &Successor) {
209 OutEdges.push_back(&Successor);
214 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
215 E = LinesByFile.end(); I != E; ++I) {
216 Len += I->second->length();
219 writeBytes(LinesTag, 4);
222 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
223 E = LinesByFile.end(); I != E; ++I)
224 I->second->writeOut();
230 DeleteContainerSeconds(LinesByFile);
234 friend class GCOVFunction;
236 GCOVBlock(uint32_t Number, raw_ostream *os)
242 StringMap<GCOVLines *> LinesByFile;
243 SmallVector<GCOVBlock *, 4> OutEdges;
246 // A function has a unique identifier, a checksum (we leave as zero) and a
247 // set of blocks and a map of edges between blocks. This is the only GCOV
248 // object users can construct, the blocks and lines will be rooted here.
249 class GCOVFunction : public GCOVRecord {
251 GCOVFunction(DISubprogram SP, raw_ostream *os,
252 bool Use402Format, bool UseExtraChecksum) {
255 Function *F = SP.getFunction();
256 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
258 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
259 Blocks[BB] = new GCOVBlock(i++, os);
261 ReturnBlock = new GCOVBlock(i++, os);
263 writeBytes(FunctionTag, 4);
264 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
265 1 + lengthOfGCOVString(SP.getFilename()) + 1;
266 if (UseExtraChecksum)
269 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
271 write(0); // lineno checksum
272 if (UseExtraChecksum)
273 write(0); // cfg checksum
274 writeGCOVString(SP.getName());
275 writeGCOVString(SP.getFilename());
276 write(SP.getLineNumber());
280 DeleteContainerSeconds(Blocks);
284 GCOVBlock &getBlock(BasicBlock *BB) {
288 GCOVBlock &getReturnBlock() {
293 // Emit count of blocks.
294 writeBytes(BlockTag, 4);
295 write(Blocks.size() + 1);
296 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
297 write(0); // No flags on our blocks.
299 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
301 // Emit edges between blocks.
302 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
303 E = Blocks.end(); I != E; ++I) {
304 GCOVBlock &Block = *I->second;
305 if (Block.OutEdges.empty()) continue;
307 writeBytes(EdgeTag, 4);
308 write(Block.OutEdges.size() * 2 + 1);
310 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
311 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
313 write(Block.OutEdges[i]->Number);
314 write(0); // no flags
318 // Emit lines for each block.
319 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
320 E = Blocks.end(); I != E; ++I) {
321 I->second->writeOut();
326 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
327 GCOVBlock *ReturnBlock;
331 std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
332 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
333 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
334 MDNode *N = GCov->getOperand(i);
335 if (N->getNumOperands() != 2) continue;
336 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
337 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
338 if (!GCovFile || !CompileUnit) continue;
339 if (CompileUnit == CU) {
340 SmallString<128> Filename = GCovFile->getString();
341 sys::path::replace_extension(Filename, NewStem);
342 return Filename.str();
347 SmallString<128> Filename = CU.getFilename();
348 sys::path::replace_extension(Filename, NewStem);
349 return sys::path::filename(Filename.str());
352 bool GCOVProfiler::runOnModule(Module &M) {
354 Ctx = &M.getContext();
356 if (EmitNotes) emitGCNO();
357 if (EmitData) return emitProfileArcs();
361 void GCOVProfiler::emitGCNO() {
362 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
363 if (!CU_Nodes) return;
365 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
366 // Each compile unit gets its own .gcno file. This means that whether we run
367 // this pass over the original .o's as they're produced, or run it after
368 // LTO, we'll generate the same .gcno files.
370 DICompileUnit CU(CU_Nodes->getOperand(i));
371 std::string ErrorInfo;
372 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
373 raw_fd_ostream::F_Binary);
375 out.write("oncg*404MVLL", 12);
377 out.write("oncg*204MVLL", 12);
379 DIArray SPs = CU.getSubprograms();
380 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
381 DISubprogram SP(SPs.getElement(i));
382 if (!SP.Verify()) continue;
384 Function *F = SP.getFunction();
386 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
388 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
389 GCOVBlock &Block = Func.getBlock(BB);
390 TerminatorInst *TI = BB->getTerminator();
391 if (int successors = TI->getNumSuccessors()) {
392 for (int i = 0; i != successors; ++i) {
393 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
395 } else if (isa<ReturnInst>(TI)) {
396 Block.addEdge(Func.getReturnBlock());
400 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
402 const DebugLoc &Loc = I->getDebugLoc();
403 if (Loc.isUnknown()) continue;
404 if (Line == Loc.getLine()) continue;
405 Line = Loc.getLine();
406 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
408 GCOVLines &Lines = Block.getFile(SP.getFilename());
409 Lines.addLine(Loc.getLine());
414 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
419 bool GCOVProfiler::emitProfileArcs() {
420 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
421 if (!CU_Nodes) return false;
424 bool InsertIndCounterIncrCode = false;
425 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
426 DICompileUnit CU(CU_Nodes->getOperand(i));
427 DIArray SPs = CU.getSubprograms();
428 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
429 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
430 DISubprogram SP(SPs.getElement(i));
431 if (!SP.Verify()) continue;
432 Function *F = SP.getFunction();
434 if (!Result) Result = true;
436 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
437 TerminatorInst *TI = BB->getTerminator();
438 if (isa<ReturnInst>(TI))
441 Edges += TI->getNumSuccessors();
444 ArrayType *CounterTy =
445 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
446 GlobalVariable *Counters =
447 new GlobalVariable(*M, CounterTy, false,
448 GlobalValue::InternalLinkage,
449 Constant::getNullValue(CounterTy),
451 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
453 UniqueVector<BasicBlock *> ComplexEdgePreds;
454 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
457 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
458 TerminatorInst *TI = BB->getTerminator();
459 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
461 IRBuilder<> Builder(TI);
463 if (Successors == 1) {
464 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
466 Value *Count = Builder.CreateLoad(Counter);
467 Count = Builder.CreateAdd(Count,
468 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
469 Builder.CreateStore(Count, Counter);
470 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
471 Value *Sel = Builder.CreateSelect(
473 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
474 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
475 SmallVector<Value *, 2> Idx;
476 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
478 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
479 Value *Count = Builder.CreateLoad(Counter);
480 Count = Builder.CreateAdd(Count,
481 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
482 Builder.CreateStore(Count, Counter);
484 ComplexEdgePreds.insert(BB);
485 for (int i = 0; i != Successors; ++i)
486 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
492 if (!ComplexEdgePreds.empty()) {
493 GlobalVariable *EdgeTable =
494 buildEdgeLookupTable(F, Counters,
495 ComplexEdgePreds, ComplexEdgeSuccs);
496 GlobalVariable *EdgeState = getEdgeStateValue();
498 Type *Int32Ty = Type::getInt32Ty(*Ctx);
499 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
500 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
501 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
503 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
504 // call runtime to perform increment
505 BasicBlock::iterator InsertPt =
506 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
507 IRBuilder<> Builder(InsertPt);
508 Value *CounterPtrArray =
509 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
510 i * ComplexEdgePreds.size());
512 // Build code to increment the counter.
513 InsertIndCounterIncrCode = true;
514 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
515 EdgeState, CounterPtrArray);
520 insertCounterWriteout(CountersBySP);
523 if (InsertIndCounterIncrCode)
524 insertIndirectCounterIncrement();
529 // All edges with successors that aren't branches are "complex", because it
530 // requires complex logic to pick which counter to update.
531 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
533 GlobalVariable *Counters,
534 const UniqueVector<BasicBlock *> &Preds,
535 const UniqueVector<BasicBlock *> &Succs) {
536 // TODO: support invoke, threads. We rely on the fact that nothing can modify
537 // the whole-Module pred edge# between the time we set it and the time we next
538 // read it. Threads and invoke make this untrue.
540 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
541 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
542 ArrayType *EdgeTableTy = ArrayType::get(
543 Int64PtrTy, Succs.size() * Preds.size());
545 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
546 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
547 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
548 EdgeTable[i] = NullValue;
551 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
552 TerminatorInst *TI = BB->getTerminator();
553 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
554 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
555 for (int i = 0; i != Successors; ++i) {
556 BasicBlock *Succ = TI->getSuccessor(i);
557 IRBuilder<> builder(Succ);
558 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
560 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
561 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
567 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
568 GlobalVariable *EdgeTableGV =
570 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
571 ConstantArray::get(EdgeTableTy, V),
572 "__llvm_gcda_edge_table");
573 EdgeTableGV->setUnnamedAddr(true);
577 Constant *GCOVProfiler::getStartFileFunc() {
578 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
579 Type::getInt8PtrTy(*Ctx), false);
580 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
583 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
584 Type *Int32Ty = Type::getInt32Ty(*Ctx);
585 Type *Int64Ty = Type::getInt64Ty(*Ctx);
587 Int32Ty->getPointerTo(), // uint32_t *predecessor
588 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
590 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
591 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
594 Constant *GCOVProfiler::getEmitFunctionFunc() {
596 Type::getInt32Ty(*Ctx), // uint32_t ident
597 Type::getInt8PtrTy(*Ctx), // const char *function_name
599 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
600 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
603 Constant *GCOVProfiler::getEmitArcsFunc() {
605 Type::getInt32Ty(*Ctx), // uint32_t num_counters
606 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
608 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
610 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
613 Constant *GCOVProfiler::getEndFileFunc() {
614 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
615 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
618 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
619 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
621 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
622 GlobalValue::InternalLinkage,
623 ConstantInt::get(Type::getInt32Ty(*Ctx),
625 "__llvm_gcov_global_state_pred");
626 GV->setUnnamedAddr(true);
631 void GCOVProfiler::insertCounterWriteout(
632 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
633 FunctionType *WriteoutFTy =
634 FunctionType::get(Type::getVoidTy(*Ctx), false);
635 Function *WriteoutF = Function::Create(WriteoutFTy,
636 GlobalValue::InternalLinkage,
637 "__llvm_gcov_writeout", M);
638 WriteoutF->setUnnamedAddr(true);
639 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
640 IRBuilder<> Builder(BB);
642 Constant *StartFile = getStartFileFunc();
643 Constant *EmitFunction = getEmitFunctionFunc();
644 Constant *EmitArcs = getEmitArcsFunc();
645 Constant *EndFile = getEndFileFunc();
647 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
649 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
650 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
651 std::string FilenameGcda = mangleName(compile_unit, "gcda");
652 Builder.CreateCall(StartFile,
653 Builder.CreateGlobalStringPtr(FilenameGcda));
654 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
655 I = CountersBySP.begin(), E = CountersBySP.end();
657 DISubprogram SP(I->second);
658 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
659 Builder.CreateCall2(EmitFunction,
660 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
661 Builder.CreateGlobalStringPtr(SP.getName()));
663 GlobalVariable *GV = I->first;
665 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
666 Builder.CreateCall2(EmitArcs,
667 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
668 Builder.CreateConstGEP2_64(GV, 0, 0));
670 Builder.CreateCall(EndFile);
673 Builder.CreateRetVoid();
675 // Create a small bit of code that registers the "__llvm_gcov_writeout"
676 // function to be executed at exit.
677 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
678 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
679 "__llvm_gcov_init", M);
680 F->setUnnamedAddr(true);
681 F->setLinkage(GlobalValue::InternalLinkage);
682 F->addFnAttr(Attribute::NoInline);
684 BB = BasicBlock::Create(*Ctx, "entry", F);
685 Builder.SetInsertPoint(BB);
687 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
688 PointerType::get(FTy, 0), false);
689 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
690 Builder.CreateCall(AtExitFn, WriteoutF);
691 Builder.CreateRetVoid();
693 appendToGlobalCtors(*M, F, 0);
696 void GCOVProfiler::insertIndirectCounterIncrement() {
698 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
699 Fn->setUnnamedAddr(true);
700 Fn->setLinkage(GlobalValue::InternalLinkage);
701 Fn->addFnAttr(Attribute::NoInline);
703 Type *Int32Ty = Type::getInt32Ty(*Ctx);
704 Type *Int64Ty = Type::getInt64Ty(*Ctx);
705 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
707 // Create basic blocks for function.
708 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
709 IRBuilder<> Builder(BB);
711 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
712 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
713 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
715 // uint32_t pred = *predecessor;
716 // if (pred == 0xffffffff) return;
717 Argument *Arg = Fn->arg_begin();
718 Arg->setName("predecessor");
719 Value *Pred = Builder.CreateLoad(Arg, "pred");
720 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
721 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
723 Builder.SetInsertPoint(PredNotNegOne);
725 // uint64_t *counter = counters[pred];
726 // if (!counter) return;
727 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
728 Arg = llvm::next(Fn->arg_begin());
729 Arg->setName("counters");
730 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
731 Value *Counter = Builder.CreateLoad(GEP, "counter");
732 Cond = Builder.CreateICmpEQ(Counter,
733 Constant::getNullValue(Int64Ty->getPointerTo()));
734 Builder.CreateCondBr(Cond, Exit, CounterEnd);
737 Builder.SetInsertPoint(CounterEnd);
738 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
739 ConstantInt::get(Int64Ty, 1));
740 Builder.CreateStore(Add, Counter);
741 Builder.CreateBr(Exit);
743 // Fill in the exit block.
744 Builder.SetInsertPoint(Exit);
745 Builder.CreateRetVoid();