在llvm上写一个简单的清理着陆垫

时间:2012-10-31 19:58:55

标签: c++ exception-handling llvm

我创建了一个基本函数Foo1,通过调用调用另一个函数Bar2。展开清理基本块中的第一条指令必须是着陆点:

void bar2()
{ 
  throw;
}
llvm::Function* Bar2Fn = llvm::Function::Create( voidSig , &bar2);
engine->addGlobalMapping( Bar2Fn, (void*)&bar2 );
llvm::InvokeInst* inv = builder.CreateInvoke( Bar2Fn , continueBlock, unwindBlock, llvmArgValues , "invoke");
builder.CreateBr(continueBlock);
builder.SetInsertPoint(unwindBlock);
llvm::LandingPadInst* landPadInst = builder.CreateLandingPad(...);
//add some cleanup code? where??

我真的不知道我需要在CreateLandingPad的参数之间放置什么才能获得一个基本的登陆平台,它可以调用当前Foo1堆栈对象的自定义清理代码。 Bar2可能通过调用自己抛出(或重新抛出现有异常)的c ++函数来抛出

1 个答案:

答案 0 :(得分:6)

我承认我在这里没什么经验,但你看过异常演示代码示例了吗?它似乎包含了您希望找到的那种序列。

基本上,你首先要设置个性,就像在C ++中一样:

llvm::Function *personality = module.getFunction("__gxx_personality_v0");

然后,您创建具有该个性的登录牌并定义其类型:

llvm::LandingPadInst *caughtResult = 
  builder.CreateLandingPad(ourCaughtResultType,
                           personality,
                           numExceptionsToCatch,
                           "landingPad");

设置要捕获的类型:

for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
  // Set up type infos to be caught
  caughtResult->addClause(module.getGlobalVariable(
                          ourTypeInfoNames[exceptionTypesToCatch[i]]));
}

并表示它是一个清理处理程序:

caughtResult->setCleanup(true);

我相信这就是它;现在你可以自己获得例外:

llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);

从中获取这些代码段的ExceptionDemo.cpp文件包含更完整的序列;具体来说,它显示了如何检查捕获的异常的类型根,并在匹配某些内容时分支到特定的块 - 清理代码:

llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);

// FIXME: Redundant storage which, beyond utilizing value of
//        caughtResultStore for unwindException storage, may be alleviated
//        altogether with a block rearrangement
builder.CreateStore(caughtResult, caughtResultStorage);
builder.CreateStore(unwindException, exceptionStorage);
builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);

// Retrieve exception_class member from thrown exception
// (_Unwind_Exception instance). This member tells us whether or not
// the exception is foreign.
llvm::Value *unwindExceptionClass =
  builder.CreateLoad(builder.CreateStructGEP(
           builder.CreatePointerCast(unwindException,
                                     ourUnwindExceptionType->getPointerTo()),
                                             0));

// Branch to the externalExceptionBlock if the exception is foreign or
// to a catch router if not. Either way the finally block will be run.
builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
                          llvm::ConstantInt::get(builder.getInt64Ty(),
                                                 ourBaseExceptionClass)),
                     exceptionRouteBlock,
                     externalExceptionBlock);

最后,还提供了另一个示例以及解释on the blog post that introduced the new exception handling mechanism