second32
second32

Reputation: 83

LLVM - setting insert point of BasicBlock after adding instructions causes segfault

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?

Upvotes: 1

Views: 1135

Answers (1)

harry
harry

Reputation: 1095

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.

Upvotes: 1

Related Questions