1 //===-- EmitFunctions.cpp - interface to insert instrumentation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This inserts a global constant table with function pointers all along
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Support/CFG.h"
27 struct EmitFunctionTable : public Pass {
31 RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
34 char doDFS(BasicBlock * node,std::map<BasicBlock *, Color > &color){
37 for(succ_iterator vl = succ_begin(node), ve = succ_end(node); vl != ve; ++vl){
41 if(color[BB]!=GREY && color[BB]!=BLACK){
42 if(!doDFS(BB, color)){
48 else if(color[BB]==GREY)
57 char hasBackEdge(Function *F){
58 std::map<BasicBlock *, Color > color;
59 return doDFS(F->begin(), color);
62 // Per Module pass for inserting function table
63 bool EmitFunctionTable::run(Module &M){
64 std::vector<const Type*> vType;
66 std::vector<Constant *> vConsts;
67 std::vector<Constant *> sBCons;
69 unsigned int counter = 0;
70 for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
71 if (!MI->isExternal()) {
72 vType.push_back(MI->getType());
76 vConsts.push_back(ConstantPointerRef::get(MI));
77 sBCons.push_back(ConstantInt::get(Type::SByteTy, hasBackEdge(MI)));
82 StructType *sttype = StructType::get(vType);
83 ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
85 GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
86 GlobalValue::ExternalLinkage,
87 cstruct, "llvmFunctionTable");
88 M.getGlobalList().push_back(gb);
90 ConstantArray *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
94 GlobalVariable *funcArray = new GlobalVariable(constArray->getType(), true,
95 GlobalValue::ExternalLinkage,
96 constArray, "llvmSimpleFunction");
98 M.getGlobalList().push_back(funcArray);
100 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
101 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
102 GlobalValue::ExternalLinkage,
103 cnst, "llvmFunctionCount");
104 M.getGlobalList().push_back(fnCount);
105 return true; // Always modifies program