Function Insertion Error

Hi,
I am trying to insert a function into the LLVM IR. But i get a stack dump exception. My code is as follows.

#include “llvm/Pass.h”
#include “llvm/Function.h”
#include “llvm/Module.h”
#include “llvm/Support/raw_ostream.h”
#include “llvm/ADT/Statistic.h”
#include “llvm/Support/IRBuilder.h”
using namespace llvm;

namespace {
struct FunctionInsert : public ModulePass {
static char ID;
FunctionInsert() : ModulePass(ID) {}

};
virtual bool runOnModule(Module &M) {

FunctionType* ty=FunctionType::get(Type::getInt32Ty(M.getContext()),false);

Function *func = cast(M.getOrInsertFunction(“func”, ty,Type::getInt32Ty(M.getContext()), (Type *)0));
BasicBlock *BB = BasicBlock::Create(M.getContext(), “bb1”, func);
IRBuilder<> builder(BB);
Value *One = builder.getInt32(1);
Argument *ArgX = func->arg_begin();
ArgX->setName(“firstarg”);
Value *Add = builder.CreateAdd(One, ArgX);
builder.CreateRet(Add);
return true;
}
};
}

char FunctionInsert::ID = 0;
static RegisterPass X(“FunctionInsert”, “Function Insertion Pass”);

Most of the above code is from the file examples/HowToUseJIT/HowToUseJIT.cpp.
Thanks:) happy

Hi Rohit,

I am trying to insert a function into the LLVM IR. But i get a stack dump
exception.

you should include the message since it can help us understand what you did
wrong. You built LLVM with assertions enabled, right?

  My code is as follows.

#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/IRBuilder.h"
using namespace llvm;

namespace {
struct FunctionInsert : public ModulePass {
static char ID;
FunctionInsert() : ModulePass(ID) {}

};
virtual bool runOnModule(Module &M) {

FunctionType* ty=FunctionType::get(Type::getInt32Ty(M.getContext()),false);

A function with no parameters that returns an int: int func(void)
However I think you wanted a function that also has an int argument, thus
this should have been

   FunctionType* ty=FunctionType::get(Type::getInt32Ty(M.getContext()),
     Type::getInt32Ty(M.getContext()), false);

which corresponds to: int func(int)

Function *func = cast<Function>(M.getOrInsertFunction("func",
ty,Type::getInt32Ty(M.getContext()), (Type *)0));

Inserting a function that returns type ty and has one argument of type int.
Clearly you don't mean to have your function return a value of function type
(which is what ty is). Probably you meant:

   Function *func = cast<Function>(M.getOrInsertFunction("func", ty));

This will insert a function with type ty, i.e. int func(int)

I didn't look at the rest since this first part needs to be sorted out
before worrying about anything else.

Ciao, Duncan.