LLVM API Documentation
00001 //===- TraceBasicBlocks.cpp - Insert basic-block trace instrumentation ----===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass instruments the specified program with calls into a runtime 00011 // library that cause it to output a trace of basic blocks as a side effect 00012 // of normal execution. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Constants.h" 00017 #include "llvm/DerivedTypes.h" 00018 #include "llvm/Module.h" 00019 #include "llvm/Pass.h" 00020 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00021 #include "llvm/Instructions.h" 00022 #include "ProfilingUtils.h" 00023 #include "llvm/Support/Debug.h" 00024 #include <set> 00025 using namespace llvm; 00026 00027 namespace { 00028 class TraceBasicBlocks : public ModulePass { 00029 bool runOnModule(Module &M); 00030 }; 00031 00032 RegisterOpt<TraceBasicBlocks> X("trace-basic-blocks", 00033 "Insert instrumentation for basic block tracing"); 00034 } 00035 00036 static void InsertInstrumentationCall (BasicBlock *BB, 00037 const std::string FnName, 00038 unsigned BBNumber) { 00039 DEBUG (std::cerr << "InsertInstrumentationCall (\"" << BB->getName () 00040 << "\", \"" << FnName << "\", " << BBNumber << ")\n"); 00041 Module &M = *BB->getParent ()->getParent (); 00042 Function *InstrFn = M.getOrInsertFunction (FnName, Type::VoidTy, 00043 Type::UIntTy, 0); 00044 std::vector<Value*> Args (1); 00045 Args[0] = ConstantUInt::get (Type::UIntTy, BBNumber); 00046 00047 // Insert the call after any alloca or PHI instructions... 00048 BasicBlock::iterator InsertPos = BB->begin(); 00049 while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos)) 00050 ++InsertPos; 00051 00052 Instruction *InstrCall = new CallInst (InstrFn, Args, "", InsertPos); 00053 } 00054 00055 bool TraceBasicBlocks::runOnModule(Module &M) { 00056 Function *Main = M.getMainFunction(); 00057 if (Main == 0) { 00058 std::cerr << "WARNING: cannot insert basic-block trace instrumentation" 00059 << " into a module with no main function!\n"; 00060 return false; // No main, no instrumentation! 00061 } 00062 00063 unsigned BBNumber = 0; 00064 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 00065 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) { 00066 InsertInstrumentationCall (BB, "llvm_trace_basic_block", BBNumber); 00067 ++BBNumber; 00068 } 00069 00070 // Add the initialization call to main. 00071 InsertProfilingInitCall(Main, "llvm_start_basic_block_tracing"); 00072 return true; 00073 } 00074