1 //===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
3 // This inserts a global constant table with function pointers all along
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/Module.h"
10 #include "llvm/Pass.h"
11 #include "llvm/Support/CFG.h"
20 struct EmitFunctionTable : public Pass {
24 RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
27 char doDFS(BasicBlock * node,std::map<BasicBlock *, Color > &color){
30 for(BasicBlock::succ_iterator vl = succ_begin(node),
31 ve = succ_end(node); vl != ve; ++vl){
35 if(color[BB]!=GREY && color[BB]!=BLACK){
36 if(!doDFS(BB, color)){
42 else if(color[BB]==GREY)
51 char hasBackEdge(Function *F){
52 std::map<BasicBlock *, Color > color;
53 return doDFS(F->begin(), color);
56 // Per Module pass for inserting function table
57 bool EmitFunctionTable::run(Module &M){
58 std::vector<const Type*> vType;
60 std::vector<Constant *> vConsts;
61 std::vector<Constant *> sBCons;
63 unsigned int counter = 0;
64 for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
65 if (!MI->isExternal()) {
66 vType.push_back(MI->getType());
70 vConsts.push_back(ConstantPointerRef::get(MI));
71 sBCons.push_back(ConstantInt::get(Type::SByteTy, hasBackEdge(MI)));
76 StructType *sttype = StructType::get(vType);
77 ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
79 GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
80 GlobalValue::ExternalLinkage,
81 cstruct, "llvmFunctionTable");
82 M.getGlobalList().push_back(gb);
84 ConstantArray *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
88 GlobalVariable *funcArray = new GlobalVariable(constArray->getType(), true,
89 GlobalValue::ExternalLinkage,
90 constArray, "llvmSimpleFunction");
92 M.getGlobalList().push_back(funcArray);
94 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
95 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
96 GlobalValue::ExternalLinkage,
97 cnst, "llvmFunctionCount");
98 M.getGlobalList().push_back(fnCount);
99 return true; // Always modifies program