John Galt
John Galt

Reputation: 125

LLVM Insert function call into another function

I am trying to insert function call inside a main function, so then when i run generated binary file, function will be executed automatically. Since language i am trying to "compile" looks like a "scripted" language :

function foo () begin 3 end;
function boo () begin 4 end;

writeln (foo()+boo()) ;
writeln (8) ;
writeln (9) ;

where writeln is a function available by default, and after executing binary i expect to see 7 8 9. Is there a way to insert last function call right before return statement of a main function ? Right now I have

define i32 @main() {
entry:
  ret i32 0
}

and i want to have something like

define i32 @main() {
entry:
  %calltmp = call double @writeln(double 7.000000e+00)
  %calltmp = call double @writeln(double 8.000000e+00)
  %calltmp = call double @writeln(double 9.000000e+00)
  ret i32 0
}

editing IR file manually and compile it afterwards works, but i want to do it in codegen part of my code.

edit

what i generate right now is

define double @__anon_expr() {
entry:
  %main = call double @writeln(double 3.000000e+00)
  ret double %main
}

define i32 @main() {
entry:
  ret i32 0
}

so when i execute binary - nothing happens

Upvotes: 4

Views: 1168

Answers (1)

Atyoum Ustainof
Atyoum Ustainof

Reputation: 394

feel free to source your inspiration from here

Type * returnType = Type::getInt32Ty(TheContext);
std::vector<Type *> argTypes;
FunctionType * functionType = FunctionType::get(returnType, argTypes, false);
Function * function = Function::Create(functionType, Function::ExternalLinkage, "main", TheModule.get());

    BasicBlock * BB = BasicBlock::Create(TheContext, "entry", function);
    Builder.SetInsertPoint(BB);
    vector<Value *> args;
    args.push_back(ConstantFP::get(TheContext, APFloat(4.0)));
    Builder.CreateCall(getFunction("writeln"), args, "call");
    Value * returnValue = Builder.getInt32(0);
    Builder.CreateRet(returnValue);

Upvotes: 6

Related Questions