#include "llvm/ADT/STLExtras.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
#include <cstdio>
#include <sstream>
#include <stdexcept>
#include <inttypes.h>
#include <unwind.h>
#ifndef USE_GLOBAL_STR_CONSTS
#define USE_GLOBAL_STR_CONSTS true
#endif
struct OurExceptionType_t {
int type;
};
struct OurBaseException_t {
struct OurExceptionType_t type;
struct _Unwind_Exception unwindException;
};
typedef struct OurBaseException_t OurException;
typedef struct _Unwind_Exception OurUnwindException;
static std::map<std::string, llvm::Value*> namedValues;
int64_t ourBaseFromUnwindOffset;
const unsigned char ourBaseExcpClassChars[] =
{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
static uint64_t ourBaseExceptionClass = 0;
static std::vector<std::string> ourTypeInfoNames;
static std::map<int, std::string> ourTypeInfoNamesIndex;
static llvm::StructType *ourTypeInfoType;
static llvm::StructType *ourCaughtResultType;
static llvm::StructType *ourExceptionType;
static llvm::StructType *ourUnwindExceptionType;
static llvm::ConstantInt *ourExceptionNotThrownState;
static llvm::ConstantInt *ourExceptionThrownState;
static llvm::ConstantInt *ourExceptionCaughtState;
typedef std::vector<std::string> ArgNames;
typedef std::vector<llvm::Type*> ArgTypes;
llvm::Function *createFunction(llvm::Module &module,
llvm::Type *retType,
const ArgTypes &theArgTypes,
const ArgNames &theArgNames,
const std::string &functName,
llvm::GlobalValue::LinkageTypes linkage,
bool declarationOnly,
bool isVarArg) {
llvm::FunctionType *functType =
llvm::FunctionType::get(retType, theArgTypes, isVarArg);
llvm::Function *ret =
llvm::Function::Create(functType, linkage, functName, &module);
if (!ret || declarationOnly)
return(ret);
namedValues.clear();
unsigned i = 0;
for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
i != theArgNames.size();
++argIndex, ++i) {
argIndex->setName(theArgNames[i]);
namedValues[theArgNames[i]] = argIndex;
}
return(ret);
}
static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
const std::string &varName,
llvm::Type *type,
llvm::Constant *initWith = 0) {
llvm::BasicBlock &block = function.getEntryBlock();
llvm::IRBuilder<> tmp(&block, block.begin());
llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName);
if (initWith)
tmp.CreateStore(initWith, ret);
return(ret);
}
namespace {
template <typename Type_>
uintptr_t ReadType(const uint8_t *&p) {
Type_ value;
memcpy(&value, p, sizeof(Type_));
p += sizeof(Type_);
return static_cast<uintptr_t>(value);
}
}
extern "C" {
void print32Int(int intToPrint, const char *format) {
if (format) {
fprintf(stderr, format, intToPrint);
}
else {
fprintf(stderr, "::print32Int(...):NULL arg.\n");
}
}
void print64Int(long int intToPrint, const char *format) {
if (format) {
fprintf(stderr, format, intToPrint);
}
else {
fprintf(stderr, "::print64Int(...):NULL arg.\n");
}
}
void printStr(char *toPrint) {
if (toPrint) {
fprintf(stderr, "%s", toPrint);
}
else {
fprintf(stderr, "::printStr(...):NULL arg.\n");
}
}
void deleteOurException(OurUnwindException *expToDelete) {
#ifdef DEBUG
fprintf(stderr,
"deleteOurException(...).\n");
#endif
if (expToDelete &&
(expToDelete->exception_class == ourBaseExceptionClass)) {
free(((char*) expToDelete) + ourBaseFromUnwindOffset);
}
}
void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
OurUnwindException *expToDelete) {
#ifdef DEBUG
fprintf(stderr,
"deleteFromUnwindOurException(...).\n");
#endif
deleteOurException(expToDelete);
}
OurUnwindException *createOurException(int type) {
size_t size = sizeof(OurException);
OurException *ret = (OurException*) memset(malloc(size), 0, size);
(ret->type).type = type;
(ret->unwindException).exception_class = ourBaseExceptionClass;
(ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
return(&(ret->unwindException));
}
static uintptr_t readULEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
return result;
}
static uintptr_t readSLEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
result |= (~0 << shift);
}
return result;
}
unsigned getEncodingSize(uint8_t Encoding) {
if (Encoding == llvm::dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
return sizeof(uintptr_t);
case llvm::dwarf::DW_EH_PE_udata2:
return sizeof(uint16_t);
case llvm::dwarf::DW_EH_PE_udata4:
return sizeof(uint32_t);
case llvm::dwarf::DW_EH_PE_udata8:
return sizeof(uint64_t);
case llvm::dwarf::DW_EH_PE_sdata2:
return sizeof(int16_t);
case llvm::dwarf::DW_EH_PE_sdata4:
return sizeof(int32_t);
case llvm::dwarf::DW_EH_PE_sdata8:
return sizeof(int64_t);
default:
abort();
}
}
static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
uintptr_t result = 0;
const uint8_t *p = *data;
if (encoding == llvm::dwarf::DW_EH_PE_omit)
return(result);
switch (encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
result = ReadType<uintptr_t>(p);
break;
case llvm::dwarf::DW_EH_PE_uleb128:
result = readULEB128(&p);
break;
case llvm::dwarf::DW_EH_PE_sleb128:
result = readSLEB128(&p);
break;
case llvm::dwarf::DW_EH_PE_udata2:
result = ReadType<uint16_t>(p);
break;
case llvm::dwarf::DW_EH_PE_udata4:
result = ReadType<uint32_t>(p);
break;
case llvm::dwarf::DW_EH_PE_udata8:
result = ReadType<uint64_t>(p);
break;
case llvm::dwarf::DW_EH_PE_sdata2:
result = ReadType<int16_t>(p);
break;
case llvm::dwarf::DW_EH_PE_sdata4:
result = ReadType<int32_t>(p);
break;
case llvm::dwarf::DW_EH_PE_sdata8:
result = ReadType<int64_t>(p);
break;
default:
abort();
break;
}
switch (encoding & 0x70) {
case llvm::dwarf::DW_EH_PE_absptr:
break;
case llvm::dwarf::DW_EH_PE_pcrel:
result += (uintptr_t)(*data);
break;
case llvm::dwarf::DW_EH_PE_textrel:
case llvm::dwarf::DW_EH_PE_datarel:
case llvm::dwarf::DW_EH_PE_funcrel:
case llvm::dwarf::DW_EH_PE_aligned:
default:
abort();
break;
}
if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
result = *((uintptr_t*)result);
}
*data = p;
return result;
}
static bool handleActionValue(int64_t *resultAction,
uint8_t TTypeEncoding,
const uint8_t *ClassInfo,
uintptr_t actionEntry,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject) {
bool ret = false;
if (!resultAction ||
!exceptionObject ||
(exceptionClass != ourBaseExceptionClass))
return(ret);
struct OurBaseException_t *excp = (struct OurBaseException_t*)
(((char*) exceptionObject) + ourBaseFromUnwindOffset);
struct OurExceptionType_t *excpType = &(excp->type);
int type = excpType->type;
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...): exceptionObject = <%p>, "
"excp = <%p>.\n",
(void*)exceptionObject,
(void*)excp);
#endif
const uint8_t *actionPos = (uint8_t*) actionEntry,
*tempActionPos;
int64_t typeOffset = 0,
actionOffset;
for (int i = 0; true; ++i) {
typeOffset = readSLEB128(&actionPos);
tempActionPos = actionPos;
actionOffset = readSLEB128(&tempActionPos);
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):typeOffset: <%" PRIi64 ">, "
"actionOffset: <%" PRIi64 ">.\n",
typeOffset,
actionOffset);
#endif
assert((typeOffset >= 0) &&
"handleActionValue(...):filters are not supported.");
if (typeOffset > 0) {
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue <%d> found.\n",
i);
#endif
unsigned EncSize = getEncodingSize(TTypeEncoding);
const uint8_t *EntryP = ClassInfo - typeOffset * EncSize;
uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
struct OurExceptionType_t *ThisClassInfo =
reinterpret_cast<struct OurExceptionType_t *>(P);
if (ThisClassInfo->type == type) {
*resultAction = i + 1;
ret = true;
break;
}
}
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue not found.\n");
#endif
if (!actionOffset)
break;
actionPos += actionOffset;
}
return(ret);
}
static _Unwind_Reason_Code handleLsda(int version, const uint8_t *lsda,
_Unwind_Action actions,
_Unwind_Exception_Class exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context) {
_Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
if (!lsda)
return(ret);
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):lsda is non-zero.\n");
#endif
uintptr_t pc = _Unwind_GetIP(context)-1;
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t pcOffset = pc - funcStart;
const uint8_t *ClassInfo = NULL;
uint8_t lpStartEncoding = *lsda++;
if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
readEncodedPointer(&lsda, lpStartEncoding);
}
uint8_t ttypeEncoding = *lsda++;
uintptr_t classInfoOffset;
if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
classInfoOffset = readULEB128(&lsda);
ClassInfo = lsda + classInfoOffset;
}
uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t *callSiteTableStart = lsda;
const uint8_t *callSiteTableEnd = callSiteTableStart +
callSiteTableLength;
const uint8_t *actionTableStart = callSiteTableEnd;
const uint8_t *callSitePtr = callSiteTableStart;
while (callSitePtr < callSiteTableEnd) {
uintptr_t start = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t landingPad = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t actionEntry = readULEB128(&callSitePtr);
if (exceptionClass != ourBaseExceptionClass) {
actionEntry = 0;
}
if (landingPad == 0) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): No landing pad found.\n");
#endif
continue; }
if (actionEntry) {
actionEntry += ((uintptr_t) actionTableStart) - 1;
}
else {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):No action table found.\n");
#endif
}
bool exceptionMatched = false;
if ((start <= pcOffset) && (pcOffset < (start + length))) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): Landing pad found.\n");
#endif
int64_t actionValue = 0;
if (actionEntry) {
exceptionMatched = handleActionValue(&actionValue,
ttypeEncoding,
ClassInfo,
actionEntry,
exceptionClass,
exceptionObject);
}
if (!(actions & _UA_SEARCH_PHASE)) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): installed landing pad "
"context.\n");
#endif
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(0),
(uintptr_t)exceptionObject);
if (!actionEntry || !exceptionMatched) {
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
0);
}
else {
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
actionValue);
}
_Unwind_SetIP(context, funcStart + landingPad);
ret = _URC_INSTALL_CONTEXT;
}
else if (exceptionMatched) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): setting handler found.\n");
#endif
ret = _URC_HANDLER_FOUND;
}
else {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): cleanup handler found.\n");
#endif
}
break;
}
}
return(ret);
}
_Unwind_Reason_Code ourPersonality(int version, _Unwind_Action actions,
_Unwind_Exception_Class exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context) {
#ifdef DEBUG
fprintf(stderr,
"We are in ourPersonality(...):actions is <%d>.\n",
actions);
if (actions & _UA_SEARCH_PHASE) {
fprintf(stderr, "ourPersonality(...):In search phase.\n");
}
else {
fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
}
#endif
const uint8_t *lsda = (const uint8_t *)_Unwind_GetLanguageSpecificData(context);
#ifdef DEBUG
fprintf(stderr,
"ourPersonality(...):lsda = <%p>.\n",
(void*)lsda);
#endif
return(handleLsda(version,
lsda,
actions,
exceptionClass,
exceptionObject,
context));
}
uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
{
uint64_t ret = classChars[0];
for (unsigned i = 1; i < classCharsSize; ++i) {
ret <<= 8;
ret += classChars[i];
}
return(ret);
}
}
void generateStringPrint(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
std::string toPrint,
bool useGlobal = true) {
llvm::Function *printFunct = module.getFunction("printStr");
llvm::Value *stringVar;
llvm::Constant *stringConstant =
llvm::ConstantDataArray::getString(context, toPrint);
if (useGlobal) {
stringVar =
new llvm::GlobalVariable(module,
stringConstant->getType(),
true,
llvm::GlobalValue::PrivateLinkage,
stringConstant,
"");
}
else {
stringVar = builder.CreateAlloca(stringConstant->getType());
builder.CreateStore(stringConstant, stringVar);
}
llvm::Value *cast = builder.CreatePointerCast(stringVar,
builder.getInt8PtrTy());
builder.CreateCall(printFunct, cast);
}
void generateIntegerPrint(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
llvm::Function &printFunct,
llvm::Value &toPrint,
std::string format,
bool useGlobal = true) {
llvm::Constant *stringConstant =
llvm::ConstantDataArray::getString(context, format);
llvm::Value *stringVar;
if (useGlobal) {
stringVar =
new llvm::GlobalVariable(module,
stringConstant->getType(),
true,
llvm::GlobalValue::PrivateLinkage,
stringConstant,
"");
}
else {
stringVar = builder.CreateAlloca(stringConstant->getType());
builder.CreateStore(stringConstant, stringVar);
}
llvm::Value *cast = builder.CreateBitCast(stringVar,
builder.getInt8PtrTy());
builder.CreateCall(&printFunct, {&toPrint, cast});
}
static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
llvm::Function &toAddTo,
std::string &blockName,
std::string &functionId,
llvm::BasicBlock &terminatorBlock,
llvm::BasicBlock &unwindResumeBlock,
llvm::Value **exceptionCaughtFlag,
llvm::Value **exceptionStorage,
llvm::Value **caughtResultStorage) {
assert(exceptionCaughtFlag &&
"ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
"is NULL");
assert(exceptionStorage &&
"ExceptionDemo::createFinallyBlock(...):exceptionStorage "
"is NULL");
assert(caughtResultStorage &&
"ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
"is NULL");
*exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
"exceptionCaught",
ourExceptionNotThrownState->getType(),
ourExceptionNotThrownState);
llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
*exceptionStorage = createEntryBlockAlloca(toAddTo,
"exceptionStorage",
exceptionStorageType,
llvm::ConstantPointerNull::get(
exceptionStorageType));
*caughtResultStorage = createEntryBlockAlloca(toAddTo,
"caughtResultStorage",
ourCaughtResultType,
llvm::ConstantAggregateZero::get(
ourCaughtResultType));
llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
blockName,
&toAddTo);
builder.SetInsertPoint(ret);
std::ostringstream bufferToPrint;
bufferToPrint << "Gen: Executing finally block "
<< blockName << " in " << functionId << "\n";
generateStringPrint(context,
module,
builder,
bufferToPrint.str(),
USE_GLOBAL_STR_CONSTS);
llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
*exceptionCaughtFlag),
&terminatorBlock,
2);
theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
return(ret);
}
static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
llvm::Function &toAddTo,
std::string &blockName,
std::string &functionId,
llvm::BasicBlock &terminatorBlock,
llvm::Value &exceptionCaughtFlag) {
llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
blockName,
&toAddTo);
builder.SetInsertPoint(ret);
std::ostringstream bufferToPrint;
bufferToPrint << "Gen: Executing catch block "
<< blockName
<< " in "
<< functionId
<< std::endl;
generateStringPrint(context,
module,
builder,
bufferToPrint.str(),
USE_GLOBAL_STR_CONSTS);
builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
builder.CreateBr(&terminatorBlock);
return(ret);
}
static llvm::Function *createCatchWrappedInvokeFunction(
llvm::Module &module, llvm::IRBuilder<> &builder,
llvm::legacy::FunctionPassManager &fpm, llvm::Function &toInvoke,
std::string ourId, unsigned numExceptionsToCatch,
unsigned exceptionTypesToCatch[]) {
llvm::LLVMContext &context = module.getContext();
llvm::Function *toPrint32Int = module.getFunction("print32Int");
ArgTypes argTypes;
argTypes.push_back(builder.getInt32Ty());
ArgNames argNames;
argNames.push_back("exceptTypeToThrow");
llvm::Function *ret = createFunction(module,
builder.getVoidTy(),
argTypes,
argNames,
ourId,
llvm::Function::ExternalLinkage,
false,
false);
llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
"entry",
ret);
llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
"normal",
ret);
llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
"exception",
ret);
llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
"exceptionRoute",
ret);
llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
"externalException",
ret);
llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
"unwindResume",
ret);
llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
std::string nextName;
std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
llvm::Value *exceptionCaughtFlag = NULL;
llvm::Value *exceptionStorage = NULL;
llvm::Value *caughtResultStorage = NULL;
llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
module,
builder,
*ret,
nextName = "finally",
ourId,
*endBlock,
*unwindResumeBlock,
&exceptionCaughtFlag,
&exceptionStorage,
&caughtResultStorage
);
for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
catchBlocks[i] = createCatchBlock(context,
module,
builder,
*ret,
nextName,
ourId,
*finallyBlock,
*exceptionCaughtFlag);
}
builder.SetInsertPoint(entryBlock);
std::vector<llvm::Value*> args;
args.push_back(namedValues["exceptTypeToThrow"]);
builder.CreateInvoke(&toInvoke,
normalBlock,
exceptionBlock,
args);
builder.SetInsertPoint(endBlock);
generateStringPrint(context,
module,
builder,
"Gen: In end block: exiting in " + ourId + ".\n",
USE_GLOBAL_STR_CONSTS);
llvm::Function *deleteOurException = module.getFunction("deleteOurException");
builder.CreateCall(deleteOurException,
builder.CreateLoad(exceptionStorage));
builder.CreateRetVoid();
builder.SetInsertPoint(normalBlock);
generateStringPrint(context,
module,
builder,
"Gen: No exception in " + ourId + "!\n",
USE_GLOBAL_STR_CONSTS);
builder.CreateBr(finallyBlock);
builder.SetInsertPoint(unwindResumeBlock);
builder.CreateResume(builder.CreateLoad(caughtResultStorage));
builder.SetInsertPoint(exceptionBlock);
llvm::Function *personality = module.getFunction("ourPersonality");
ret->setPersonalityFn(personality);
llvm::LandingPadInst *caughtResult =
builder.CreateLandingPad(ourCaughtResultType,
numExceptionsToCatch,
"landingPad");
caughtResult->setCleanup(true);
for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
caughtResult->addClause(module.getGlobalVariable(
ourTypeInfoNames[exceptionTypesToCatch[i]]));
}
llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
builder.CreateStore(caughtResult, caughtResultStorage);
builder.CreateStore(unwindException, exceptionStorage);
builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
llvm::Value *unwindExceptionClass =
builder.CreateLoad(builder.CreateStructGEP(
ourUnwindExceptionType,
builder.CreatePointerCast(unwindException,
ourUnwindExceptionType->getPointerTo()),
0));
builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
llvm::ConstantInt::get(builder.getInt64Ty(),
ourBaseExceptionClass)),
exceptionRouteBlock,
externalExceptionBlock);
builder.SetInsertPoint(externalExceptionBlock);
generateStringPrint(context,
module,
builder,
"Gen: Foreign exception received.\n",
USE_GLOBAL_STR_CONSTS);
builder.CreateBr(finallyBlock);
builder.SetInsertPoint(exceptionRouteBlock);
llvm::Value *typeInfoThrown = builder.CreatePointerCast(
builder.CreateConstGEP1_64(unwindException,
ourBaseFromUnwindOffset),
ourExceptionType->getPointerTo());
typeInfoThrown = builder.CreateStructGEP(ourExceptionType, typeInfoThrown, 0);
llvm::Value *typeInfoThrownType =
builder.CreateStructGEP(builder.getInt8PtrTy(), typeInfoThrown, 0);
generateIntegerPrint(context,
module,
builder,
*toPrint32Int,
*(builder.CreateLoad(typeInfoThrownType)),
"Gen: Exception type <%d> received (stack unwound) "
" in " +
ourId +
".\n",
USE_GLOBAL_STR_CONSTS);
llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
finallyBlock,
numExceptionsToCatch);
unsigned nextTypeToCatch;
for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
nextTypeToCatch = i - 1;
switchToCatchBlock->addCase(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(context), i),
catchBlocks[nextTypeToCatch]);
}
llvm::verifyFunction(*ret);
fpm.run(*ret);
return(ret);
}
static llvm::Function *
createThrowExceptionFunction(llvm::Module &module, llvm::IRBuilder<> &builder,
llvm::legacy::FunctionPassManager &fpm,
std::string ourId, int32_t nativeThrowType,
llvm::Function &nativeThrowFunct) {
llvm::LLVMContext &context = module.getContext();
namedValues.clear();
ArgTypes unwindArgTypes;
unwindArgTypes.push_back(builder.getInt32Ty());
ArgNames unwindArgNames;
unwindArgNames.push_back("exceptTypeToThrow");
llvm::Function *ret = createFunction(module,
builder.getVoidTy(),
unwindArgTypes,
unwindArgNames,
ourId,
llvm::Function::ExternalLinkage,
false,
false);
llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
"entry",
ret);
llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
"nativeThrow",
ret);
llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
"generatedThrow",
ret);
llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
builder.SetInsertPoint(nativeThrowBlock);
builder.CreateCall(&nativeThrowFunct, exceptionType);
builder.CreateUnreachable();
builder.SetInsertPoint(entryBlock);
llvm::Function *toPrint32Int = module.getFunction("print32Int");
generateIntegerPrint(context,
module,
builder,
*toPrint32Int,
*exceptionType,
"\nGen: About to throw exception type <%d> in " +
ourId +
".\n",
USE_GLOBAL_STR_CONSTS);
llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
generatedThrowBlock,
1);
theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
nativeThrowType),
nativeThrowBlock);
builder.SetInsertPoint(generatedThrowBlock);
llvm::Function *createOurException = module.getFunction("createOurException");
llvm::Function *raiseOurException = module.getFunction(
"_Unwind_RaiseException");
llvm::Value *exception = builder.CreateCall(createOurException,
namedValues["exceptTypeToThrow"]);
builder.CreateCall(raiseOurException, exception);
builder.CreateUnreachable();
llvm::verifyFunction(*ret);
fpm.run(*ret);
return(ret);
}
static void createStandardUtilityFunctions(unsigned numTypeInfos,
llvm::Module &module,
llvm::IRBuilder<> &builder);
llvm::Function *
createUnwindExceptionTest(llvm::Module &module, llvm::IRBuilder<> &builder,
llvm::legacy::FunctionPassManager &fpm,
std::string nativeThrowFunctName) {
unsigned numTypeInfos = 6;
createStandardUtilityFunctions(numTypeInfos,
module,
builder);
llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
llvm::Function *throwFunct = createThrowExceptionFunction(module,
builder,
fpm,
"throwFunct",
~0,
*nativeThrowFunct);
unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
sizeof(unsigned);
llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
builder,
fpm,
*throwFunct,
"innerCatchFunct",
numExceptionTypesToCatch,
innerExceptionTypesToCatch);
unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
sizeof(unsigned);
llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
builder,
fpm,
*innerCatchFunct,
"outerCatchFunct",
numExceptionTypesToCatch,
outerExceptionTypesToCatch);
return(outerCatchFunct);
}
namespace {
class OurCppRunException : public std::runtime_error {
public:
OurCppRunException(const std::string reason) :
std::runtime_error(reason) {}
OurCppRunException (const OurCppRunException &toCopy) :
std::runtime_error(toCopy) {}
OurCppRunException &operator = (const OurCppRunException &toCopy) {
return(reinterpret_cast<OurCppRunException&>(
std::runtime_error::operator=(toCopy)));
}
~OurCppRunException(void) throw() override {}
};
}
extern "C"
void throwCppException (int32_t ignoreIt) {
throw(OurCppRunException("thrown by throwCppException(...)"));
}
typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
static
void runExceptionThrow(llvm::ExecutionEngine *engine,
llvm::Function *function,
int32_t typeToThrow) {
OurExceptionThrowFunctType functPtr =
reinterpret_cast<OurExceptionThrowFunctType>(
reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
try {
(*functPtr)(typeToThrow);
}
catch (OurCppRunException exc) {
fprintf(stderr,
"\nrunExceptionThrow(...):In C++ catch OurCppRunException "
"with reason: %s.\n",
exc.what());
}
catch (...) {
fprintf(stderr,
"\nrunExceptionThrow(...):In C++ catch all.\n");
}
}
typedef llvm::ArrayRef<llvm::Type*> TypeArray;
static void createStandardUtilityFunctions(unsigned numTypeInfos,
llvm::Module &module,
llvm::IRBuilder<> &builder) {
llvm::LLVMContext &context = module.getContext();
ourExceptionNotThrownState =
llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
ourExceptionThrownState =
llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
ourExceptionCaughtState =
llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
ourTypeInfoType = llvm::StructType::get(context,
TypeArray(builder.getInt32Ty()));
llvm::Type *caughtResultFieldTypes[] = {
builder.getInt8PtrTy(),
builder.getInt32Ty()
};
ourCaughtResultType = llvm::StructType::get(context,
TypeArray(caughtResultFieldTypes));
ourExceptionType = llvm::StructType::get(context,
TypeArray(ourTypeInfoType));
ourUnwindExceptionType =
llvm::StructType::get(context,
TypeArray(builder.getInt64Ty()));
struct OurBaseException_t dummyException;
ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
((uintptr_t) &(dummyException.unwindException));
#ifdef DEBUG
fprintf(stderr,
"createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
"= %" PRIi64 ", sizeof(struct OurBaseException_t) - "
"sizeof(struct _Unwind_Exception) = %lu.\n",
ourBaseFromUnwindOffset,
sizeof(struct OurBaseException_t) -
sizeof(struct _Unwind_Exception));
#endif
size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
std::string baseStr = "typeInfo", typeInfoName;
std::ostringstream typeInfoNameBuilder;
std::vector<llvm::Constant*> structVals;
llvm::Constant *nextStruct;
for (unsigned i = 0; i <= numTypeInfos; ++i) {
structVals.clear();
structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
typeInfoNameBuilder.str("");
typeInfoNameBuilder << baseStr << i;
typeInfoName = typeInfoNameBuilder.str();
new llvm::GlobalVariable(module,
ourTypeInfoType,
true,
llvm::GlobalValue::ExternalLinkage,
nextStruct,
typeInfoName);
ourTypeInfoNames.push_back(typeInfoName);
ourTypeInfoNamesIndex[i] = typeInfoName;
}
ArgNames argNames;
ArgTypes argTypes;
llvm::Function *funct = NULL;
llvm::Type *retType = builder.getVoidTy();
argTypes.clear();
argTypes.push_back(builder.getInt32Ty());
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"print32Int",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getVoidTy();
argTypes.clear();
argTypes.push_back(builder.getInt64Ty());
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"print64Int",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getVoidTy();
argTypes.clear();
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"printStr",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getVoidTy();
argTypes.clear();
argTypes.push_back(builder.getInt32Ty());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"throwCppException",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getVoidTy();
argTypes.clear();
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"deleteOurException",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getInt8PtrTy();
argTypes.clear();
argTypes.push_back(builder.getInt32Ty());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"createOurException",
llvm::Function::ExternalLinkage,
true,
false);
retType = builder.getInt32Ty();
argTypes.clear();
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
funct = createFunction(module,
retType,
argTypes,
argNames,
"_Unwind_RaiseException",
llvm::Function::ExternalLinkage,
true,
false);
funct->setDoesNotReturn();
retType = builder.getInt32Ty();
argTypes.clear();
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
funct = createFunction(module,
retType,
argTypes,
argNames,
"_Unwind_Resume",
llvm::Function::ExternalLinkage,
true,
false);
funct->setDoesNotReturn();
retType = builder.getInt32Ty();
argTypes.clear();
argTypes.push_back(builder.getInt32Ty());
argTypes.push_back(builder.getInt32Ty());
argTypes.push_back(builder.getInt64Ty());
argTypes.push_back(builder.getInt8PtrTy());
argTypes.push_back(builder.getInt8PtrTy());
argNames.clear();
createFunction(module,
retType,
argTypes,
argNames,
"ourPersonality",
llvm::Function::ExternalLinkage,
true,
false);
getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
fprintf(stderr,
"\nUsage: ExceptionDemo <exception type to throw> "
"[<type 2>...<type n>].\n"
" Each type must have the value of 1 - 6 for "
"generated exceptions to be caught;\n"
" the value -1 for foreign C++ exceptions to be "
"generated and thrown;\n"
" or the values > 6 for exceptions to be ignored.\n"
"\nTry: ExceptionDemo 2 3 7 -1\n"
" for a full test.\n\n");
return(0);
}
llvm::TargetOptions Opts;
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::LLVMContext Context;
llvm::IRBuilder<> theBuilder(Context);
std::unique_ptr<llvm::Module> Owner =
std::make_unique<llvm::Module>("my cool jit", Context);
llvm::Module *module = Owner.get();
std::unique_ptr<llvm::RTDyldMemoryManager> MemMgr(new llvm::SectionMemoryManager());
llvm::EngineBuilder factory(std::move(Owner));
factory.setEngineKind(llvm::EngineKind::JIT);
factory.setTargetOptions(Opts);
factory.setMCJITMemoryManager(std::move(MemMgr));
llvm::ExecutionEngine *executionEngine = factory.create();
{
llvm::legacy::FunctionPassManager fpm(module);
module->setDataLayout(executionEngine->getDataLayout());
#ifdef ADD_OPT_PASSES
fpm.add(llvm::createBasicAliasAnalysisPass());
fpm.add(llvm::createPromoteMemoryToRegisterPass());
fpm.add(llvm::createInstructionCombiningPass());
fpm.add(llvm::createReassociatePass());
fpm.add(llvm::createGVNPass());
fpm.add(llvm::createCFGSimplificationPass());
#endif
fpm.doInitialization();
llvm::Function *toRun =
createUnwindExceptionTest(*module,
theBuilder,
fpm,
"throwCppException");
executionEngine->finalizeObject();
#ifndef NDEBUG
fprintf(stderr, "\nBegin module dump:\n\n");
module->dump();
fprintf(stderr, "\nEnd module dump:\n");
#endif
fprintf(stderr, "\n\nBegin Test:\n");
for (int i = 1; i < argc; ++i) {
runExceptionThrow(executionEngine,
toRun,
(unsigned) strtoul(argv[i], NULL, 10));
}
fprintf(stderr, "\nEnd Test:\n\n");
}
delete executionEngine;
return 0;
}