1 //===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Demo program which implements an example LLVM exception implementation, and
11 // shows several test cases including the handling of foreign exceptions.
12 // It is run with type info types arguments to throw. A test will
13 // be run for each given type info type. While type info types with the value
14 // of -1 will trigger a foreign C++ exception to be thrown; type info types
15 // <= 6 and >= 1 will cause the associated generated exceptions to be thrown
16 // and caught by generated test functions; and type info types > 6
17 // will result in exceptions which pass through to the test harness. All other
18 // type info types are not supported and could cause a crash. In all cases,
19 // the "finally" blocks of every generated test functions will executed
20 // regardless of whether or not that test function ignores or catches the
27 // causes a usage to be printed to stderr
29 // ExceptionDemo 2 3 7 -1
31 // results in the following cases:
32 // - Value 2 causes an exception with a type info type of 2 to be
33 // thrown and caught by an inner generated test function.
34 // - Value 3 causes an exception with a type info type of 3 to be
35 // thrown and caught by an outer generated test function.
36 // - Value 7 causes an exception with a type info type of 7 to be
37 // thrown and NOT be caught by any generated function.
38 // - Value -1 causes a foreign C++ exception to be thrown and not be
39 // caught by any generated function
41 // Cases -1 and 7 are caught by a C++ test harness where the validity of
42 // of a C++ catch(...) clause catching a generated exception with a
43 // type info type of 7 is questionable.
45 // This code uses code from the llvm compiler-rt project and the llvm
46 // Kaleidoscope project.
48 //===----------------------------------------------------------------------===//
50 #include "llvm/LLVMContext.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/ExecutionEngine/ExecutionEngine.h"
53 #include "llvm/ExecutionEngine/JIT.h"
54 #include "llvm/Module.h"
55 #include "llvm/PassManager.h"
56 #include "llvm/Intrinsics.h"
57 #include "llvm/Analysis/Verifier.h"
58 #include "llvm/Target/TargetData.h"
59 #include "llvm/Target/TargetSelect.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Support/IRBuilder.h"
63 #include "llvm/Support/Dwarf.h"
65 // Note: Some systems seem to have a problem finding
66 // the symbols like stderr, and fprintf when this
67 // header file is not included
74 #ifndef USE_GLOBAL_STR_CONSTS
75 #define USE_GLOBAL_STR_CONSTS true
78 // System C++ ABI unwind types from:
79 // http://refspecs.freestandards.org/abi-eh-1.21.html
85 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
86 _URC_FATAL_PHASE2_ERROR = 2,
87 _URC_FATAL_PHASE1_ERROR = 3,
89 _URC_END_OF_STACK = 5,
90 _URC_HANDLER_FOUND = 6,
91 _URC_INSTALL_CONTEXT = 7,
92 _URC_CONTINUE_UNWIND = 8
93 } _Unwind_Reason_Code;
97 _UA_CLEANUP_PHASE = 2,
98 _UA_HANDLER_FRAME = 4,
100 _UA_END_OF_STACK = 16
103 struct _Unwind_Exception;
105 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
106 struct _Unwind_Exception *);
108 struct _Unwind_Exception {
109 uint64_t exception_class;
110 _Unwind_Exception_Cleanup_Fn exception_cleanup;
115 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
116 // Taking that literally does not make much sense generically. Instead
117 // we provide the maximum alignment required by any type for the machine.
118 } __attribute__((__aligned__));
120 struct _Unwind_Context;
121 typedef struct _Unwind_Context *_Unwind_Context_t;
123 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
124 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
125 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
126 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
127 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
128 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
136 /// This is our simplistic type info
137 struct OurExceptionType_t {
143 /// This is our Exception class which relies on a negative offset to calculate
144 /// pointers to its instances from pointers to its unwindException member.
146 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
147 /// on a double word boundary. This is necessary to match the standard:
148 /// http://refspecs.freestandards.org/abi-eh-1.21.html
149 struct OurBaseException_t {
150 struct OurExceptionType_t type;
152 // Note: This is properly aligned in unwind.h
153 struct _Unwind_Exception unwindException;
157 // Note: Not needed since we are C++
158 typedef struct OurBaseException_t OurException;
159 typedef struct _Unwind_Exception OurUnwindException;
162 // Various globals used to support typeinfo and generatted exceptions in
166 static std::map<std::string, llvm::Value*> namedValues;
168 int64_t ourBaseFromUnwindOffset;
170 const unsigned char ourBaseExcpClassChars[] =
171 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
174 static uint64_t ourBaseExceptionClass = 0;
176 static std::vector<std::string> ourTypeInfoNames;
177 static std::map<int, std::string> ourTypeInfoNamesIndex;
179 static llvm::StructType *ourTypeInfoType;
180 static llvm::StructType *ourExceptionType;
181 static llvm::StructType *ourUnwindExceptionType;
183 static llvm::ConstantInt *ourExceptionNotThrownState;
184 static llvm::ConstantInt *ourExceptionThrownState;
185 static llvm::ConstantInt *ourExceptionCaughtState;
187 typedef std::vector<std::string> ArgNames;
188 typedef std::vector<const llvm::Type*> ArgTypes;
191 // Code Generation Utilities
194 /// Utility used to create a function, both declarations and definitions
195 /// @param module for module instance
196 /// @param retType function return type
197 /// @param theArgTypes function's ordered argument types
198 /// @param theArgNames function's ordered arguments needed if use of this
199 /// function corresponds to a function definition. Use empty
200 /// aggregate for function declarations.
201 /// @param functName function name
202 /// @param linkage function linkage
203 /// @param declarationOnly for function declarations
204 /// @param isVarArg function uses vararg arguments
205 /// @returns function instance
206 llvm::Function *createFunction(llvm::Module &module,
207 const llvm::Type *retType,
208 const ArgTypes &theArgTypes,
209 const ArgNames &theArgNames,
210 const std::string &functName,
211 llvm::GlobalValue::LinkageTypes linkage,
212 bool declarationOnly,
214 llvm::FunctionType *functType =
215 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
216 llvm::Function *ret =
217 llvm::Function::Create(functType, linkage, functName, &module);
218 if (!ret || declarationOnly)
223 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
224 i != theArgNames.size();
227 argIndex->setName(theArgNames[i]);
228 namedValues[theArgNames[i]] = argIndex;
235 /// Create an alloca instruction in the entry block of
236 /// the parent function. This is used for mutable variables etc.
237 /// @param function parent instance
238 /// @param varName stack variable name
239 /// @param type stack variable type
240 /// @param initWith optional constant initialization value
241 /// @returns AllocaInst instance
242 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
243 const std::string &varName,
244 const llvm::Type *type,
245 llvm::Constant *initWith = 0) {
246 llvm::BasicBlock &block = function.getEntryBlock();
247 llvm::IRBuilder<> tmp(&block, block.begin());
248 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
251 tmp.CreateStore(initWith, ret);
258 // Code Generation Utilities End
262 // Runtime C Library functions
265 // Note: using an extern "C" block so that static functions can be used
268 // Note: Better ways to decide on bit width
270 /// Prints a 32 bit number, according to the format, to stderr.
271 /// @param intToPrint integer to print
272 /// @param format printf like format to use when printing
273 void print32Int(int intToPrint, const char *format) {
275 // Note: No NULL check
276 fprintf(stderr, format, intToPrint);
279 // Note: No NULL check
280 fprintf(stderr, "::print32Int(...):NULL arg.\n");
285 // Note: Better ways to decide on bit width
287 /// Prints a 64 bit number, according to the format, to stderr.
288 /// @param intToPrint integer to print
289 /// @param format printf like format to use when printing
290 void print64Int(long int intToPrint, const char *format) {
292 // Note: No NULL check
293 fprintf(stderr, format, intToPrint);
296 // Note: No NULL check
297 fprintf(stderr, "::print64Int(...):NULL arg.\n");
302 /// Prints a C string to stderr
303 /// @param toPrint string to print
304 void printStr(char *toPrint) {
306 fprintf(stderr, "%s", toPrint);
309 fprintf(stderr, "::printStr(...):NULL arg.\n");
314 /// Deletes the true previosly allocated exception whose address
315 /// is calculated from the supplied OurBaseException_t::unwindException
316 /// member address. Handles (ignores), NULL pointers.
317 /// @param expToDelete exception to delete
318 void deleteOurException(OurUnwindException *expToDelete) {
321 "deleteOurException(...).\n");
325 (expToDelete->exception_class == ourBaseExceptionClass)) {
327 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
332 /// This function is the struct _Unwind_Exception API mandated delete function
333 /// used by foreign exception handlers when deleting our exception
334 /// (OurException), instances.
335 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
337 /// @param expToDelete exception instance to delete
338 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
339 OurUnwindException *expToDelete) {
342 "deleteFromUnwindOurException(...).\n");
345 deleteOurException(expToDelete);
349 /// Creates (allocates on the heap), an exception (OurException instance),
350 /// of the supplied type info type.
351 /// @param type type info type
352 OurUnwindException *createOurException(int type) {
353 size_t size = sizeof(OurException);
354 OurException *ret = (OurException*) memset(malloc(size), 0, size);
355 (ret->type).type = type;
356 (ret->unwindException).exception_class = ourBaseExceptionClass;
357 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
359 return(&(ret->unwindException));
363 /// Read a uleb128 encoded value and advance pointer
364 /// See Variable Length Data in:
365 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
366 /// @param data reference variable holding memory pointer to decode from
367 /// @returns decoded value
368 static uintptr_t readULEB128(const uint8_t **data) {
369 uintptr_t result = 0;
372 const uint8_t *p = *data;
376 result |= (byte & 0x7f) << shift;
387 /// Read a sleb128 encoded value and advance pointer
388 /// See Variable Length Data in:
389 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
390 /// @param data reference variable holding memory pointer to decode from
391 /// @returns decoded value
392 static uintptr_t readSLEB128(const uint8_t **data) {
393 uintptr_t result = 0;
396 const uint8_t *p = *data;
400 result |= (byte & 0x7f) << shift;
407 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
408 result |= (~0 << shift);
415 /// Read a pointer encoded value and advance pointer
416 /// See Variable Length Data in:
417 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
418 /// @param data reference variable holding memory pointer to decode from
419 /// @param encoding dwarf encoding type
420 /// @returns decoded value
421 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
422 uintptr_t result = 0;
423 const uint8_t *p = *data;
425 if (encoding == llvm::dwarf::DW_EH_PE_omit)
429 switch (encoding & 0x0F) {
430 case llvm::dwarf::DW_EH_PE_absptr:
431 result = *((uintptr_t*)p);
432 p += sizeof(uintptr_t);
434 case llvm::dwarf::DW_EH_PE_uleb128:
435 result = readULEB128(&p);
437 // Note: This case has not been tested
438 case llvm::dwarf::DW_EH_PE_sleb128:
439 result = readSLEB128(&p);
441 case llvm::dwarf::DW_EH_PE_udata2:
442 result = *((uint16_t*)p);
443 p += sizeof(uint16_t);
445 case llvm::dwarf::DW_EH_PE_udata4:
446 result = *((uint32_t*)p);
447 p += sizeof(uint32_t);
449 case llvm::dwarf::DW_EH_PE_udata8:
450 result = *((uint64_t*)p);
451 p += sizeof(uint64_t);
453 case llvm::dwarf::DW_EH_PE_sdata2:
454 result = *((int16_t*)p);
455 p += sizeof(int16_t);
457 case llvm::dwarf::DW_EH_PE_sdata4:
458 result = *((int32_t*)p);
459 p += sizeof(int32_t);
461 case llvm::dwarf::DW_EH_PE_sdata8:
462 result = *((int64_t*)p);
463 p += sizeof(int64_t);
471 // then add relative offset
472 switch (encoding & 0x70) {
473 case llvm::dwarf::DW_EH_PE_absptr:
476 case llvm::dwarf::DW_EH_PE_pcrel:
477 result += (uintptr_t)(*data);
479 case llvm::dwarf::DW_EH_PE_textrel:
480 case llvm::dwarf::DW_EH_PE_datarel:
481 case llvm::dwarf::DW_EH_PE_funcrel:
482 case llvm::dwarf::DW_EH_PE_aligned:
489 // then apply indirection
490 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
491 result = *((uintptr_t*)result);
500 /// Deals with Dwarf actions matching our type infos
501 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
502 /// action matches the supplied exception type. If such a match succeeds,
503 /// the resultAction argument will be set with > 0 index value. Only
504 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
505 /// are supported. Filters are not supported.
506 /// See Variable Length Data in:
507 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
508 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
509 /// @param resultAction reference variable which will be set with result
510 /// @param classInfo our array of type info pointers (to globals)
511 /// @param actionEntry index into above type info array or 0 (clean up).
512 /// We do not support filters.
513 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
514 /// of thrown exception.
515 /// @param exceptionObject thrown _Unwind_Exception instance.
516 /// @returns whether or not a type info was found. False is returned if only
517 /// a cleanup was found
518 static bool handleActionValue(int64_t *resultAction,
519 struct OurExceptionType_t **classInfo,
520 uintptr_t actionEntry,
521 uint64_t exceptionClass,
522 struct _Unwind_Exception *exceptionObject) {
527 (exceptionClass != ourBaseExceptionClass))
530 struct OurBaseException_t *excp = (struct OurBaseException_t*)
531 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
532 struct OurExceptionType_t *excpType = &(excp->type);
533 int type = excpType->type;
537 "handleActionValue(...): exceptionObject = <%p>, "
543 const uint8_t *actionPos = (uint8_t*) actionEntry,
545 int64_t typeOffset = 0,
548 for (int i = 0; true; ++i) {
549 // Each emitted dwarf action corresponds to a 2 tuple of
550 // type info address offset, and action offset to the next
552 typeOffset = readSLEB128(&actionPos);
553 tempActionPos = actionPos;
554 actionOffset = readSLEB128(&tempActionPos);
558 "handleActionValue(...):typeOffset: <%lld>, "
559 "actionOffset: <%lld>.\n",
563 assert((typeOffset >= 0) &&
564 "handleActionValue(...):filters are not supported.");
566 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
567 // argument has been matched.
568 if ((typeOffset > 0) &&
569 (type == (classInfo[-typeOffset])->type)) {
572 "handleActionValue(...):actionValue <%d> found.\n",
575 *resultAction = i + 1;
582 "handleActionValue(...):actionValue not found.\n");
587 actionPos += actionOffset;
594 /// Deals with the Language specific data portion of the emitted dwarf code.
595 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
596 /// @param version unsupported (ignored), unwind version
597 /// @param lsda language specific data area
598 /// @param _Unwind_Action actions minimally supported unwind stage
599 /// (forced specifically not supported)
600 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
601 /// of thrown exception.
602 /// @param exceptionObject thrown _Unwind_Exception instance.
603 /// @param context unwind system context
604 /// @returns minimally supported unwinding control indicator
605 static _Unwind_Reason_Code handleLsda(int version,
607 _Unwind_Action actions,
608 uint64_t exceptionClass,
609 struct _Unwind_Exception *exceptionObject,
610 _Unwind_Context_t context) {
611 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
618 "handleLsda(...):lsda is non-zero.\n");
621 // Get the current instruction pointer and offset it before next
622 // instruction in the current frame which threw the exception.
623 uintptr_t pc = _Unwind_GetIP(context)-1;
625 // Get beginning current frame's code (as defined by the
626 // emitted dwarf code)
627 uintptr_t funcStart = _Unwind_GetRegionStart(context);
628 uintptr_t pcOffset = pc - funcStart;
629 struct OurExceptionType_t **classInfo = NULL;
631 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
634 // Parse LSDA header.
635 uint8_t lpStartEncoding = *lsda++;
637 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
638 readEncodedPointer(&lsda, lpStartEncoding);
641 uint8_t ttypeEncoding = *lsda++;
642 uintptr_t classInfoOffset;
644 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
645 // Calculate type info locations in emitted dwarf code which
646 // were flagged by type info arguments to llvm.eh.selector
648 classInfoOffset = readULEB128(&lsda);
649 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
652 // Walk call-site table looking for range that
653 // includes current PC.
655 uint8_t callSiteEncoding = *lsda++;
656 uint32_t callSiteTableLength = readULEB128(&lsda);
657 const uint8_t *callSiteTableStart = lsda;
658 const uint8_t *callSiteTableEnd = callSiteTableStart +
660 const uint8_t *actionTableStart = callSiteTableEnd;
661 const uint8_t *callSitePtr = callSiteTableStart;
663 bool foreignException = false;
665 while (callSitePtr < callSiteTableEnd) {
666 uintptr_t start = readEncodedPointer(&callSitePtr,
668 uintptr_t length = readEncodedPointer(&callSitePtr,
670 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
673 // Note: Action value
674 uintptr_t actionEntry = readULEB128(&callSitePtr);
676 if (exceptionClass != ourBaseExceptionClass) {
677 // We have been notified of a foreign exception being thrown,
678 // and we therefore need to execute cleanup landing pads
680 foreignException = true;
683 if (landingPad == 0) {
686 "handleLsda(...): No landing pad found.\n");
689 continue; // no landing pad for this entry
693 actionEntry += ((uintptr_t) actionTableStart) - 1;
698 "handleLsda(...):No action table found.\n");
702 bool exceptionMatched = false;
704 if ((start <= pcOffset) && (pcOffset < (start + length))) {
707 "handleLsda(...): Landing pad found.\n");
709 int64_t actionValue = 0;
712 exceptionMatched = handleActionValue(&actionValue,
719 if (!(actions & _UA_SEARCH_PHASE)) {
722 "handleLsda(...): installed landing pad "
726 // Found landing pad for the PC.
727 // Set Instruction Pointer to so we re-enter function
728 // at landing pad. The landing pad is created by the
729 // compiler to take two parameters in registers.
730 _Unwind_SetGR(context,
731 __builtin_eh_return_data_regno(0),
732 (uintptr_t)exceptionObject);
734 // Note: this virtual register directly corresponds
735 // to the return of the llvm.eh.selector intrinsic
736 if (!actionEntry || !exceptionMatched) {
737 // We indicate cleanup only
738 _Unwind_SetGR(context,
739 __builtin_eh_return_data_regno(1),
743 // Matched type info index of llvm.eh.selector intrinsic
745 _Unwind_SetGR(context,
746 __builtin_eh_return_data_regno(1),
750 // To execute landing pad set here
751 _Unwind_SetIP(context, funcStart + landingPad);
752 ret = _URC_INSTALL_CONTEXT;
754 else if (exceptionMatched) {
757 "handleLsda(...): setting handler found.\n");
759 ret = _URC_HANDLER_FOUND;
762 // Note: Only non-clean up handlers are marked as
763 // found. Otherwise the clean up handlers will be
764 // re-found and executed during the clean up
768 "handleLsda(...): cleanup handler found.\n");
780 /// This is the personality function which is embedded (dwarf emitted), in the
781 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
782 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
783 /// @param version unsupported (ignored), unwind version
784 /// @param _Unwind_Action actions minimally supported unwind stage
785 /// (forced specifically not supported)
786 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
787 /// of thrown exception.
788 /// @param exceptionObject thrown _Unwind_Exception instance.
789 /// @param context unwind system context
790 /// @returns minimally supported unwinding control indicator
791 _Unwind_Reason_Code ourPersonality(int version,
792 _Unwind_Action actions,
793 uint64_t exceptionClass,
794 struct _Unwind_Exception *exceptionObject,
795 _Unwind_Context_t context) {
798 "We are in ourPersonality(...):actions is <%d>.\n",
801 if (actions & _UA_SEARCH_PHASE) {
802 fprintf(stderr, "ourPersonality(...):In search phase.\n");
805 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
809 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
813 "ourPersonality(...):lsda = <%p>.\n",
817 // The real work of the personality function is captured here
818 return(handleLsda(version,
827 /// Generates our _Unwind_Exception class from a given character array.
828 /// thereby handling arbitrary lengths (not in standard), and handling
830 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
831 /// @param classChars char array to encode. NULL values not checkedf
832 /// @param classCharsSize number of chars in classChars. Value is not checked.
833 /// @returns class value
834 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
836 uint64_t ret = classChars[0];
838 for (unsigned i = 1; i < classCharsSize; ++i) {
840 ret += classChars[i];
849 // Runtime C Library functions End
853 // Code generation functions
856 /// Generates code to print given constant string
857 /// @param context llvm context
858 /// @param module code for module instance
859 /// @param builder builder instance
860 /// @param toPrint string to print
861 /// @param useGlobal A value of true (default) indicates a GlobalValue is
862 /// generated, and is used to hold the constant string. A value of
863 /// false indicates that the constant string will be stored on the
865 void generateStringPrint(llvm::LLVMContext &context,
866 llvm::Module &module,
867 llvm::IRBuilder<> &builder,
869 bool useGlobal = true) {
870 llvm::Function *printFunct = module.getFunction("printStr");
872 llvm::Value *stringVar;
873 llvm::Constant *stringConstant =
874 llvm::ConstantArray::get(context, toPrint);
877 // Note: Does not work without allocation
879 new llvm::GlobalVariable(module,
880 stringConstant->getType(),
882 llvm::GlobalValue::LinkerPrivateLinkage,
887 stringVar = builder.CreateAlloca(stringConstant->getType());
888 builder.CreateStore(stringConstant, stringVar);
892 builder.CreatePointerCast(stringVar,
893 builder.getInt8Ty()->getPointerTo());
894 builder.CreateCall(printFunct, cast);
898 /// Generates code to print given runtime integer according to constant
899 /// string format, and a given print function.
900 /// @param context llvm context
901 /// @param module code for module instance
902 /// @param builder builder instance
903 /// @param printFunct function used to "print" integer
904 /// @param toPrint string to print
905 /// @param format printf like formating string for print
906 /// @param useGlobal A value of true (default) indicates a GlobalValue is
907 /// generated, and is used to hold the constant string. A value of
908 /// false indicates that the constant string will be stored on the
910 void generateIntegerPrint(llvm::LLVMContext &context,
911 llvm::Module &module,
912 llvm::IRBuilder<> &builder,
913 llvm::Function &printFunct,
914 llvm::Value &toPrint,
916 bool useGlobal = true) {
917 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
918 llvm::Value *stringVar;
921 // Note: Does not seem to work without allocation
923 new llvm::GlobalVariable(module,
924 stringConstant->getType(),
926 llvm::GlobalValue::LinkerPrivateLinkage,
931 stringVar = builder.CreateAlloca(stringConstant->getType());
932 builder.CreateStore(stringConstant, stringVar);
936 builder.CreateBitCast(stringVar,
937 builder.getInt8Ty()->getPointerTo());
938 builder.CreateCall2(&printFunct, &toPrint, cast);
942 /// Generates code to handle finally block type semantics: always runs
943 /// regardless of whether a thrown exception is passing through or the
944 /// parent function is simply exiting. In addition to printing some state
945 /// to stderr, this code will resume the exception handling--runs the
946 /// unwind resume block, if the exception has not been previously caught
947 /// by a catch clause, and will otherwise execute the end block (terminator
948 /// block). In addition this function creates the corresponding function's
949 /// stack storage for the exception pointer and catch flag status.
950 /// @param context llvm context
951 /// @param module code for module instance
952 /// @param builder builder instance
953 /// @param toAddTo parent function to add block to
954 /// @param blockName block name of new "finally" block.
955 /// @param functionId output id used for printing
956 /// @param terminatorBlock terminator "end" block
957 /// @param unwindResumeBlock unwind resume block
958 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
959 /// @param exceptionStorage reference to exception pointer storage
960 /// @returns newly created block
961 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
962 llvm::Module &module,
963 llvm::IRBuilder<> &builder,
964 llvm::Function &toAddTo,
965 std::string &blockName,
966 std::string &functionId,
967 llvm::BasicBlock &terminatorBlock,
968 llvm::BasicBlock &unwindResumeBlock,
969 llvm::Value **exceptionCaughtFlag,
970 llvm::Value **exceptionStorage) {
971 assert(exceptionCaughtFlag &&
972 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
974 assert(exceptionStorage &&
975 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
978 *exceptionCaughtFlag =
979 createEntryBlockAlloca(toAddTo,
981 ourExceptionNotThrownState->getType(),
982 ourExceptionNotThrownState);
984 const llvm::PointerType *exceptionStorageType =
985 builder.getInt8Ty()->getPointerTo();
987 createEntryBlockAlloca(toAddTo,
989 exceptionStorageType,
990 llvm::ConstantPointerNull::get(
991 exceptionStorageType));
993 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
997 builder.SetInsertPoint(ret);
999 std::ostringstream bufferToPrint;
1000 bufferToPrint << "Gen: Executing finally block "
1001 << blockName << " in " << functionId << "\n";
1002 generateStringPrint(context,
1005 bufferToPrint.str(),
1006 USE_GLOBAL_STR_CONSTS);
1008 llvm::SwitchInst *theSwitch =
1009 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1012 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1013 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1019 /// Generates catch block semantics which print a string to indicate type of
1020 /// catch executed, sets an exception caught flag, and executes passed in
1021 /// end block (terminator block).
1022 /// @param context llvm context
1023 /// @param module code for module instance
1024 /// @param builder builder instance
1025 /// @param toAddTo parent function to add block to
1026 /// @param blockName block name of new "catch" block.
1027 /// @param functionId output id used for printing
1028 /// @param terminatorBlock terminator "end" block
1029 /// @param exceptionCaughtFlag exception caught/thrown status
1030 /// @returns newly created block
1031 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1032 llvm::Module &module,
1033 llvm::IRBuilder<> &builder,
1034 llvm::Function &toAddTo,
1035 std::string &blockName,
1036 std::string &functionId,
1037 llvm::BasicBlock &terminatorBlock,
1038 llvm::Value &exceptionCaughtFlag) {
1040 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1044 builder.SetInsertPoint(ret);
1046 std::ostringstream bufferToPrint;
1047 bufferToPrint << "Gen: Executing catch block "
1052 generateStringPrint(context,
1055 bufferToPrint.str(),
1056 USE_GLOBAL_STR_CONSTS);
1057 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1058 builder.CreateBr(&terminatorBlock);
1064 /// Generates a function which invokes a function (toInvoke) and, whose
1065 /// unwind block will "catch" the type info types correspondingly held in the
1066 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1067 /// exception which does not match any type info types contained in
1068 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1069 /// with the raised exception. On the other hand the generated code will
1070 /// normally exit if the toInvoke function does not throw an exception.
1071 /// The generated "finally" block is always run regardless of the cause of
1072 /// the generated function exit.
1073 /// The generated function is returned after being verified.
1074 /// @param module code for module instance
1075 /// @param builder builder instance
1076 /// @param fpm a function pass manager holding optional IR to IR
1078 /// @param toInvoke inner function to invoke
1079 /// @param ourId id used to printing purposes
1080 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1081 /// @param exceptionTypesToCatch array of type info types to "catch"
1082 /// @returns generated function
1084 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1085 llvm::IRBuilder<> &builder,
1086 llvm::FunctionPassManager &fpm,
1087 llvm::Function &toInvoke,
1089 unsigned numExceptionsToCatch,
1090 unsigned exceptionTypesToCatch[]) {
1092 llvm::LLVMContext &context = module.getContext();
1093 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1096 argTypes.push_back(builder.getInt32Ty());
1099 argNames.push_back("exceptTypeToThrow");
1101 llvm::Function *ret = createFunction(module,
1102 builder.getVoidTy(),
1106 llvm::Function::ExternalLinkage,
1110 // Block which calls invoke
1111 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1114 // Normal block for invoke
1115 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1118 // Unwind block for invoke
1119 llvm::BasicBlock *exceptionBlock =
1120 llvm::BasicBlock::Create(context, "exception", ret);
1122 // Block which routes exception to correct catch handler block
1123 llvm::BasicBlock *exceptionRouteBlock =
1124 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1126 // Foreign exception handler
1127 llvm::BasicBlock *externalExceptionBlock =
1128 llvm::BasicBlock::Create(context, "externalException", ret);
1130 // Block which calls _Unwind_Resume
1131 llvm::BasicBlock *unwindResumeBlock =
1132 llvm::BasicBlock::Create(context, "unwindResume", ret);
1134 // Clean up block which delete exception if needed
1135 llvm::BasicBlock *endBlock =
1136 llvm::BasicBlock::Create(context, "end", ret);
1138 std::string nextName;
1139 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1140 llvm::Value *exceptionCaughtFlag = NULL;
1141 llvm::Value *exceptionStorage = NULL;
1143 // Finally block which will branch to unwindResumeBlock if
1144 // exception is not caught. Initializes/allocates stack locations.
1145 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1149 nextName = "finally",
1153 &exceptionCaughtFlag,
1156 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1157 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1159 // One catch block per type info to be caught
1160 catchBlocks[i] = createCatchBlock(context,
1167 *exceptionCaughtFlag);
1172 builder.SetInsertPoint(entryBlock);
1174 std::vector<llvm::Value*> args;
1175 args.push_back(namedValues["exceptTypeToThrow"]);
1176 builder.CreateInvoke(&toInvoke,
1184 builder.SetInsertPoint(endBlock);
1186 generateStringPrint(context,
1189 "Gen: In end block: exiting in " + ourId + ".\n",
1190 USE_GLOBAL_STR_CONSTS);
1191 llvm::Function *deleteOurException =
1192 module.getFunction("deleteOurException");
1194 // Note: function handles NULL exceptions
1195 builder.CreateCall(deleteOurException,
1196 builder.CreateLoad(exceptionStorage));
1197 builder.CreateRetVoid();
1201 builder.SetInsertPoint(normalBlock);
1203 generateStringPrint(context,
1206 "Gen: No exception in " + ourId + "!\n",
1207 USE_GLOBAL_STR_CONSTS);
1209 // Finally block is always called
1210 builder.CreateBr(finallyBlock);
1212 // Unwind Resume Block
1214 builder.SetInsertPoint(unwindResumeBlock);
1216 llvm::Function *resumeOurException =
1217 module.getFunction("_Unwind_Resume");
1218 builder.CreateCall(resumeOurException,
1219 builder.CreateLoad(exceptionStorage));
1220 builder.CreateUnreachable();
1224 builder.SetInsertPoint(exceptionBlock);
1226 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1228 // Retrieve thrown exception
1229 llvm::Value *unwindException = builder.CreateCall(ehException);
1231 // Store exception and flag
1232 builder.CreateStore(unwindException, exceptionStorage);
1233 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1234 llvm::Function *personality = module.getFunction("ourPersonality");
1235 llvm::Value *functPtr =
1236 builder.CreatePointerCast(personality,
1237 builder.getInt8Ty()->getPointerTo());
1240 args.push_back(unwindException);
1241 args.push_back(functPtr);
1243 // Note: Skipping index 0
1244 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1245 // Set up type infos to be caught
1246 args.push_back(module.getGlobalVariable(
1247 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1250 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1252 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1254 // Set up this exeption block as the landing pad which will handle
1255 // given type infos. See case Intrinsic::eh_selector in
1256 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1257 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1258 // handles this call. This landing pad (this exception block), will be
1259 // called either because it nees to cleanup (call finally) or a type
1260 // info was found which matched the thrown exception.
1261 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector,
1265 // Retrieve exception_class member from thrown exception
1266 // (_Unwind_Exception instance). This member tells us whether or not
1267 // the exception is foreign.
1268 llvm::Value *unwindExceptionClass =
1269 builder.CreateLoad(builder.CreateStructGEP(
1270 builder.CreatePointerCast(unwindException,
1271 ourUnwindExceptionType->getPointerTo()),
1274 // Branch to the externalExceptionBlock if the exception is foreign or
1275 // to a catch router if not. Either way the finally block will be run.
1276 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1277 llvm::ConstantInt::get(builder.getInt64Ty(),
1278 ourBaseExceptionClass)),
1279 exceptionRouteBlock,
1280 externalExceptionBlock);
1282 // External Exception Block
1284 builder.SetInsertPoint(externalExceptionBlock);
1286 generateStringPrint(context,
1289 "Gen: Foreign exception received.\n",
1290 USE_GLOBAL_STR_CONSTS);
1292 // Branch to the finally block
1293 builder.CreateBr(finallyBlock);
1295 // Exception Route Block
1297 builder.SetInsertPoint(exceptionRouteBlock);
1299 // Casts exception pointer (_Unwind_Exception instance) to parent
1300 // (OurException instance).
1302 // Note: ourBaseFromUnwindOffset is usually negative
1303 llvm::Value *typeInfoThrown =
1304 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1305 ourBaseFromUnwindOffset),
1306 ourExceptionType->getPointerTo());
1308 // Retrieve thrown exception type info type
1310 // Note: Index is not relative to pointer but instead to structure
1311 // unlike a true getelementptr (GEP) instruction
1312 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1314 llvm::Value *typeInfoThrownType =
1315 builder.CreateStructGEP(typeInfoThrown, 0);
1317 generateIntegerPrint(context,
1321 *(builder.CreateLoad(typeInfoThrownType)),
1322 "Gen: Exception type <%d> received (stack unwound) "
1326 USE_GLOBAL_STR_CONSTS);
1328 // Route to matched type info catch block or run cleanup finally block
1329 llvm::SwitchInst *switchToCatchBlock =
1330 builder.CreateSwitch(retTypeInfoIndex,
1332 numExceptionsToCatch);
1334 unsigned nextTypeToCatch;
1336 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1337 nextTypeToCatch = i - 1;
1338 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1339 llvm::Type::getInt32Ty(context), i),
1340 catchBlocks[nextTypeToCatch]);
1343 llvm::verifyFunction(*ret);
1350 /// Generates function which throws either an exception matched to a runtime
1351 /// determined type info type (argument to generated function), or if this
1352 /// runtime value matches nativeThrowType, throws a foreign exception by
1353 /// calling nativeThrowFunct.
1354 /// @param module code for module instance
1355 /// @param builder builder instance
1356 /// @param fpm a function pass manager holding optional IR to IR
1358 /// @param ourId id used to printing purposes
1359 /// @param nativeThrowType a runtime argument of this value results in
1360 /// nativeThrowFunct being called to generate/throw exception.
1361 /// @param nativeThrowFunct function which will throw a foreign exception
1362 /// if the above nativeThrowType matches generated function's arg.
1363 /// @returns generated function
1365 llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1366 llvm::IRBuilder<> &builder,
1367 llvm::FunctionPassManager &fpm,
1369 int32_t nativeThrowType,
1370 llvm::Function &nativeThrowFunct) {
1371 llvm::LLVMContext &context = module.getContext();
1372 namedValues.clear();
1373 ArgTypes unwindArgTypes;
1374 unwindArgTypes.push_back(builder.getInt32Ty());
1375 ArgNames unwindArgNames;
1376 unwindArgNames.push_back("exceptTypeToThrow");
1378 llvm::Function *ret = createFunction(module,
1379 builder.getVoidTy(),
1383 llvm::Function::ExternalLinkage,
1387 // Throws either one of our exception or a native C++ exception depending
1388 // on a runtime argument value containing a type info type.
1389 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1392 // Throws a foreign exception
1393 llvm::BasicBlock *nativeThrowBlock =
1394 llvm::BasicBlock::Create(context,
1397 // Throws one of our Exceptions
1398 llvm::BasicBlock *generatedThrowBlock =
1399 llvm::BasicBlock::Create(context,
1402 // Retrieved runtime type info type to throw
1403 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1405 // nativeThrowBlock block
1407 builder.SetInsertPoint(nativeThrowBlock);
1409 // Throws foreign exception
1410 builder.CreateCall(&nativeThrowFunct, exceptionType);
1411 builder.CreateUnreachable();
1415 builder.SetInsertPoint(entryBlock);
1417 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1418 generateIntegerPrint(context,
1423 "\nGen: About to throw exception type <%d> in " +
1426 USE_GLOBAL_STR_CONSTS);
1428 // Switches on runtime type info type value to determine whether or not
1429 // a foreign exception is thrown. Defaults to throwing one of our
1430 // generated exceptions.
1431 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1432 generatedThrowBlock,
1435 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1439 // generatedThrow block
1441 builder.SetInsertPoint(generatedThrowBlock);
1443 llvm::Function *createOurException =
1444 module.getFunction("createOurException");
1445 llvm::Function *raiseOurException =
1446 module.getFunction("_Unwind_RaiseException");
1448 // Creates exception to throw with runtime type info type.
1449 llvm::Value *exception =
1450 builder.CreateCall(createOurException,
1451 namedValues["exceptTypeToThrow"]);
1453 // Throw generated Exception
1454 builder.CreateCall(raiseOurException, exception);
1455 builder.CreateUnreachable();
1457 llvm::verifyFunction(*ret);
1463 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1464 llvm::Module &module,
1465 llvm::IRBuilder<> &builder);
1467 /// Creates test code by generating and organizing these functions into the
1468 /// test case. The test case consists of an outer function setup to invoke
1469 /// an inner function within an environment having multiple catch and single
1470 /// finally blocks. This inner function is also setup to invoke a throw
1471 /// function within an evironment similar in nature to the outer function's
1472 /// catch and finally blocks. Each of these two functions catch mutually
1473 /// exclusive subsets (even or odd) of the type info types configured
1474 /// for this this. All generated functions have a runtime argument which
1475 /// holds a type info type to throw that each function takes and passes it
1476 /// to the inner one if such a inner function exists. This type info type is
1477 /// looked at by the generated throw function to see whether or not it should
1478 /// throw a generated exception with the same type info type, or instead call
1479 /// a supplied a function which in turn will throw a foreign exception.
1480 /// @param module code for module instance
1481 /// @param builder builder instance
1482 /// @param fpm a function pass manager holding optional IR to IR
1484 /// @param nativeThrowFunctName name of external function which will throw
1485 /// a foreign exception
1486 /// @returns outermost generated test function.
1487 llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1488 llvm::IRBuilder<> &builder,
1489 llvm::FunctionPassManager &fpm,
1490 std::string nativeThrowFunctName) {
1491 // Number of type infos to generate
1492 unsigned numTypeInfos = 6;
1494 // Initialze intrisics and external functions to use along with exception
1495 // and type info globals.
1496 createStandardUtilityFunctions(numTypeInfos,
1499 llvm::Function *nativeThrowFunct =
1500 module.getFunction(nativeThrowFunctName);
1502 // Create exception throw function using the value ~0 to cause
1503 // foreign exceptions to be thrown.
1504 llvm::Function *throwFunct =
1505 createThrowExceptionFunction(module,
1511 // Inner function will catch even type infos
1512 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1513 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1516 // Generate inner function.
1517 llvm::Function *innerCatchFunct =
1518 createCatchWrappedInvokeFunction(module,
1523 numExceptionTypesToCatch,
1524 innerExceptionTypesToCatch);
1526 // Outer function will catch odd type infos
1527 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1528 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1531 // Generate outer function
1532 llvm::Function *outerCatchFunct =
1533 createCatchWrappedInvokeFunction(module,
1538 numExceptionTypesToCatch,
1539 outerExceptionTypesToCatch);
1541 // Return outer function to run
1542 return(outerCatchFunct);
1546 /// Represents our foreign exceptions
1547 class OurCppRunException : public std::runtime_error {
1549 OurCppRunException(const std::string reason) :
1550 std::runtime_error(reason) {}
1552 OurCppRunException (const OurCppRunException &toCopy) :
1553 std::runtime_error(toCopy) {}
1555 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1556 return(reinterpret_cast<OurCppRunException&>(
1557 std::runtime_error::operator=(toCopy)));
1560 ~OurCppRunException (void) throw () {}
1564 /// Throws foreign C++ exception.
1565 /// @param ignoreIt unused parameter that allows function to match implied
1566 /// generated function contract.
1568 void throwCppException (int32_t ignoreIt) {
1569 throw(OurCppRunException("thrown by throwCppException(...)"));
1572 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1574 /// This is a test harness which runs test by executing generated
1575 /// function with a type info type to throw. Harness wraps the excecution
1576 /// of generated function in a C++ try catch clause.
1577 /// @param engine execution engine to use for executing generated function.
1578 /// This demo program expects this to be a JIT instance for demo
1580 /// @param function generated test function to run
1581 /// @param typeToThrow type info type of generated exception to throw, or
1582 /// indicator to cause foreign exception to be thrown.
1584 void runExceptionThrow(llvm::ExecutionEngine *engine,
1585 llvm::Function *function,
1586 int32_t typeToThrow) {
1588 // Find test's function pointer
1589 OurExceptionThrowFunctType functPtr =
1590 reinterpret_cast<OurExceptionThrowFunctType>(
1591 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1595 (*functPtr)(typeToThrow);
1597 catch (OurCppRunException exc) {
1598 // Catch foreign C++ exception
1600 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1601 "with reason: %s.\n",
1605 // Catch all exceptions including our generated ones. I'm not sure
1606 // why this latter functionality should work, as it seems that
1607 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1608 // exception_class should be different from the one used by C++), and
1609 // therefore C++ should ignore the generated exceptions.
1612 "\nrunExceptionThrow(...):In C++ catch all.\n");
1617 // End test functions
1620 typedef llvm::ArrayRef<const llvm::Type*> TypeArray;
1622 /// This initialization routine creates type info globals and
1623 /// adds external function declarations to module.
1624 /// @param numTypeInfos number of linear type info associated type info types
1625 /// to create as GlobalVariable instances, starting with the value 1.
1626 /// @param module code for module instance
1627 /// @param builder builder instance
1628 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1629 llvm::Module &module,
1630 llvm::IRBuilder<> &builder) {
1632 llvm::LLVMContext &context = module.getContext();
1634 // Exception initializations
1636 // Setup exception catch state
1637 ourExceptionNotThrownState =
1638 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1639 ourExceptionThrownState =
1640 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1641 ourExceptionCaughtState =
1642 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1646 // Create our type info type
1647 ourTypeInfoType = llvm::StructType::get(context,
1648 TypeArray(builder.getInt32Ty()));
1650 // Create OurException type
1651 ourExceptionType = llvm::StructType::get(context,
1652 TypeArray(ourTypeInfoType));
1654 // Create portion of _Unwind_Exception type
1656 // Note: Declaring only a portion of the _Unwind_Exception struct.
1657 // Does this cause problems?
1658 ourUnwindExceptionType =
1659 llvm::StructType::get(context, TypeArray(builder.getInt64Ty()));
1660 struct OurBaseException_t dummyException;
1662 // Calculate offset of OurException::unwindException member.
1663 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1664 ((uintptr_t) &(dummyException.unwindException));
1668 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1669 "= %lld, sizeof(struct OurBaseException_t) - "
1670 "sizeof(struct _Unwind_Exception) = %lu.\n",
1671 ourBaseFromUnwindOffset,
1672 sizeof(struct OurBaseException_t) -
1673 sizeof(struct _Unwind_Exception));
1676 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1678 // Create our _Unwind_Exception::exception_class value
1679 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1683 std::string baseStr = "typeInfo", typeInfoName;
1684 std::ostringstream typeInfoNameBuilder;
1685 std::vector<llvm::Constant*> structVals;
1687 llvm::Constant *nextStruct;
1688 llvm::GlobalVariable *nextGlobal = NULL;
1690 // Generate each type info
1692 // Note: First type info is not used.
1693 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1695 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1696 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1698 typeInfoNameBuilder.str("");
1699 typeInfoNameBuilder << baseStr << i;
1700 typeInfoName = typeInfoNameBuilder.str();
1702 // Note: Does not seem to work without allocation
1704 new llvm::GlobalVariable(module,
1707 llvm::GlobalValue::ExternalLinkage,
1711 ourTypeInfoNames.push_back(typeInfoName);
1712 ourTypeInfoNamesIndex[i] = typeInfoName;
1717 llvm::Function *funct = NULL;
1721 const llvm::Type *retType = builder.getVoidTy();
1724 argTypes.push_back(builder.getInt32Ty());
1725 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1729 createFunction(module,
1734 llvm::Function::ExternalLinkage,
1740 retType = builder.getVoidTy();
1743 argTypes.push_back(builder.getInt64Ty());
1744 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1748 createFunction(module,
1753 llvm::Function::ExternalLinkage,
1759 retType = builder.getVoidTy();
1762 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1766 createFunction(module,
1771 llvm::Function::ExternalLinkage,
1775 // throwCppException
1777 retType = builder.getVoidTy();
1780 argTypes.push_back(builder.getInt32Ty());
1784 createFunction(module,
1788 "throwCppException",
1789 llvm::Function::ExternalLinkage,
1793 // deleteOurException
1795 retType = builder.getVoidTy();
1798 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1802 createFunction(module,
1806 "deleteOurException",
1807 llvm::Function::ExternalLinkage,
1811 // createOurException
1813 retType = builder.getInt8Ty()->getPointerTo();
1816 argTypes.push_back(builder.getInt32Ty());
1820 createFunction(module,
1824 "createOurException",
1825 llvm::Function::ExternalLinkage,
1829 // _Unwind_RaiseException
1831 retType = builder.getInt32Ty();
1834 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1838 funct = createFunction(module,
1842 "_Unwind_RaiseException",
1843 llvm::Function::ExternalLinkage,
1847 funct->addFnAttr(llvm::Attribute::NoReturn);
1851 retType = builder.getInt32Ty();
1854 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1858 funct = createFunction(module,
1863 llvm::Function::ExternalLinkage,
1867 funct->addFnAttr(llvm::Attribute::NoReturn);
1871 retType = builder.getInt32Ty();
1874 argTypes.push_back(builder.getInt32Ty());
1875 argTypes.push_back(builder.getInt32Ty());
1876 argTypes.push_back(builder.getInt64Ty());
1877 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1878 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1882 createFunction(module,
1887 llvm::Function::ExternalLinkage,
1891 // llvm.eh.selector intrinsic
1893 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1895 // llvm.eh.exception intrinsic
1897 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1899 // llvm.eh.typeid.for intrinsic
1901 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1905 //===----------------------------------------------------------------------===//
1906 // Main test driver code.
1907 //===----------------------------------------------------------------------===//
1909 /// Demo main routine which takes the type info types to throw. A test will
1910 /// be run for each given type info type. While type info types with the value
1911 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1912 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1913 /// will result in exceptions which pass through to the test harness. All other
1914 /// type info types are not supported and could cause a crash.
1915 int main(int argc, char *argv[]) {
1918 "\nUsage: ExceptionDemo <exception type to throw> "
1919 "[<type 2>...<type n>].\n"
1920 " Each type must have the value of 1 - 6 for "
1921 "generated exceptions to be caught;\n"
1922 " the value -1 for foreign C++ exceptions to be "
1923 "generated and thrown;\n"
1924 " or the values > 6 for exceptions to be ignored.\n"
1925 "\nTry: ExceptionDemo 2 3 7 -1\n"
1926 " for a full test.\n\n");
1930 // If not set, exception handling will not be turned on
1931 llvm::JITExceptionHandling = true;
1933 llvm::InitializeNativeTarget();
1934 llvm::LLVMContext &context = llvm::getGlobalContext();
1935 llvm::IRBuilder<> theBuilder(context);
1937 // Make the module, which holds all the code.
1938 llvm::Module *module = new llvm::Module("my cool jit", context);
1940 // Build engine with JIT
1941 llvm::EngineBuilder factory(module);
1942 factory.setEngineKind(llvm::EngineKind::JIT);
1943 factory.setAllocateGVsWithCode(false);
1944 llvm::ExecutionEngine *executionEngine = factory.create();
1947 llvm::FunctionPassManager fpm(module);
1949 // Set up the optimizer pipeline.
1950 // Start with registering info about how the
1951 // target lays out data structures.
1952 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1954 // Optimizations turned on
1955 #ifdef ADD_OPT_PASSES
1957 // Basic AliasAnslysis support for GVN.
1958 fpm.add(llvm::createBasicAliasAnalysisPass());
1960 // Promote allocas to registers.
1961 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1963 // Do simple "peephole" optimizations and bit-twiddling optzns.
1964 fpm.add(llvm::createInstructionCombiningPass());
1966 // Reassociate expressions.
1967 fpm.add(llvm::createReassociatePass());
1969 // Eliminate Common SubExpressions.
1970 fpm.add(llvm::createGVNPass());
1972 // Simplify the control flow graph (deleting unreachable
1974 fpm.add(llvm::createCFGSimplificationPass());
1975 #endif // ADD_OPT_PASSES
1977 fpm.doInitialization();
1979 // Generate test code using function throwCppException(...) as
1980 // the function which throws foreign exceptions.
1981 llvm::Function *toRun =
1982 createUnwindExceptionTest(*module,
1985 "throwCppException");
1987 fprintf(stderr, "\nBegin module dump:\n\n");
1991 fprintf(stderr, "\nEnd module dump:\n");
1993 fprintf(stderr, "\n\nBegin Test:\n");
1995 for (int i = 1; i < argc; ++i) {
1996 // Run test for each argument whose value is the exception
1998 runExceptionThrow(executionEngine,
2000 (unsigned) strtoul(argv[i], NULL, 10));
2003 fprintf(stderr, "\nEnd Test:\n\n");
2006 delete executionEngine;