1
votes

I'm writing a compiler frontend using LLVM. If I create a BasicBlock, add some Instructions to it and finally set the insert point, everything work fine. But when I call SetInsertPoint and THEN add some instruction like this:

    Function * MainFunction = Function::Create( FT, Function::ExternalLinkage, "main", m_Module );
    BasicBlock * BB = BasicBlock::Create( m_Parser->m_Context, "entry", MainFunction );
    m_Builder.SetInsertPoint( BB );
    CallInst * call = m_Builder.CreateCall( m_Module.getFunction( "writeln" ), {ConstantInt::get( m_Context, APInt( INT_SIZE, 1 ) )}, "calltmp" );
    BB->getInstList().push_back( call );
    m_Builder.CreateRet( ConstantInt::get( Type::getInt32Ty( m_Context ), 0 ) );

the program generates LLVM IR correctly, but then at the very end (when calling destructors of LLVM module, context and builder?) it gives segfault. I would really like to do it this way, because then the functions generating the instructions could refer to BB as m_Builder.GetInsertBlock(). And I can't think of any other way how to implement ifs, nested blocks etc.

Why is it generating code properly and crashing at the end? Is there a small problem or am I missing something and it just can't be done like this?

1
I don't use the builder, I build myself, so I cannot answer. But I can comment: Run your code under valgrind, it usually points straight at the source of such problems. - arnt

1 Answers

1
votes
m_Builder.SetInsertPoint( BB );
m_Builder.CreateCall( m_Module.getFunction( "writeln" ), {ConstantInt::get( m_Context, APInt( INT_SIZE, 1 ) )}, "calltmp" );
m_Builder.CreateRet( ConstantInt::get( Type::getInt32Ty( m_Context ), 0 ) );

Try this.