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 explained by: example in rules 1.6.4 in
44 // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
46 // This code uses code from the llvm compiler-rt project and the llvm
47 // Kaleidoscope project.
49 //===----------------------------------------------------------------------===//
51 #include "llvm/LLVMContext.h"
52 #include "llvm/DerivedTypes.h"
53 #include "llvm/ExecutionEngine/ExecutionEngine.h"
54 #include "llvm/ExecutionEngine/JIT.h"
55 #include "llvm/IRBuilder.h"
56 #include "llvm/Module.h"
57 #include "llvm/PassManager.h"
58 #include "llvm/Intrinsics.h"
59 #include "llvm/Analysis/Verifier.h"
60 #include "llvm/Target/TargetData.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include "llvm/Support/Dwarf.h"
64 #include "llvm/Support/TargetSelect.h"
66 // FIXME: Although all systems tested with (Linux, OS X), do not need this
67 // header file included. A user on ubuntu reported, undefined symbols
68 // for stderr, and fprintf, and the addition of this include fixed the
69 // issue for them. Given that LLVM's best practices include the goal
70 // of reducing the number of redundant header files included, the
71 // correct solution would be to find out why these symbols are not
72 // defined for the system in question, and fix the issue by finding out
73 // which LLVM header file, if any, would include these symbols.
80 #ifndef USE_GLOBAL_STR_CONSTS
81 #define USE_GLOBAL_STR_CONSTS true
84 // System C++ ABI unwind types from:
85 // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
91 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
92 _URC_FATAL_PHASE2_ERROR = 2,
93 _URC_FATAL_PHASE1_ERROR = 3,
95 _URC_END_OF_STACK = 5,
96 _URC_HANDLER_FOUND = 6,
97 _URC_INSTALL_CONTEXT = 7,
98 _URC_CONTINUE_UNWIND = 8
99 } _Unwind_Reason_Code;
102 _UA_SEARCH_PHASE = 1,
103 _UA_CLEANUP_PHASE = 2,
104 _UA_HANDLER_FRAME = 4,
105 _UA_FORCE_UNWIND = 8,
106 _UA_END_OF_STACK = 16
109 struct _Unwind_Exception;
111 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
112 struct _Unwind_Exception *);
114 struct _Unwind_Exception {
115 uint64_t exception_class;
116 _Unwind_Exception_Cleanup_Fn exception_cleanup;
121 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
122 // Taking that literally does not make much sense generically. Instead
123 // we provide the maximum alignment required by any type for the machine.
124 } __attribute__((__aligned__));
126 struct _Unwind_Context;
127 typedef struct _Unwind_Context *_Unwind_Context_t;
129 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
130 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
131 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
132 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
133 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
134 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
142 /// This is our simplistic type info
143 struct OurExceptionType_t {
149 /// This is our Exception class which relies on a negative offset to calculate
150 /// pointers to its instances from pointers to its unwindException member.
152 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
153 /// on a double word boundary. This is necessary to match the standard:
154 /// http://refspecs.freestandards.org/abi-eh-1.21.html
155 struct OurBaseException_t {
156 struct OurExceptionType_t type;
158 // Note: This is properly aligned in unwind.h
159 struct _Unwind_Exception unwindException;
163 // Note: Not needed since we are C++
164 typedef struct OurBaseException_t OurException;
165 typedef struct _Unwind_Exception OurUnwindException;
168 // Various globals used to support typeinfo and generatted exceptions in
172 static std::map<std::string, llvm::Value*> namedValues;
174 int64_t ourBaseFromUnwindOffset;
176 const unsigned char ourBaseExcpClassChars[] =
177 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
180 static uint64_t ourBaseExceptionClass = 0;
182 static std::vector<std::string> ourTypeInfoNames;
183 static std::map<int, std::string> ourTypeInfoNamesIndex;
185 static llvm::StructType *ourTypeInfoType;
186 static llvm::StructType *ourCaughtResultType;
187 static llvm::StructType *ourExceptionType;
188 static llvm::StructType *ourUnwindExceptionType;
190 static llvm::ConstantInt *ourExceptionNotThrownState;
191 static llvm::ConstantInt *ourExceptionThrownState;
192 static llvm::ConstantInt *ourExceptionCaughtState;
194 typedef std::vector<std::string> ArgNames;
195 typedef std::vector<llvm::Type*> ArgTypes;
198 // Code Generation Utilities
201 /// Utility used to create a function, both declarations and definitions
202 /// @param module for module instance
203 /// @param retType function return type
204 /// @param theArgTypes function's ordered argument types
205 /// @param theArgNames function's ordered arguments needed if use of this
206 /// function corresponds to a function definition. Use empty
207 /// aggregate for function declarations.
208 /// @param functName function name
209 /// @param linkage function linkage
210 /// @param declarationOnly for function declarations
211 /// @param isVarArg function uses vararg arguments
212 /// @returns function instance
213 llvm::Function *createFunction(llvm::Module &module,
215 const ArgTypes &theArgTypes,
216 const ArgNames &theArgNames,
217 const std::string &functName,
218 llvm::GlobalValue::LinkageTypes linkage,
219 bool declarationOnly,
221 llvm::FunctionType *functType =
222 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
223 llvm::Function *ret =
224 llvm::Function::Create(functType, linkage, functName, &module);
225 if (!ret || declarationOnly)
230 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
231 i != theArgNames.size();
234 argIndex->setName(theArgNames[i]);
235 namedValues[theArgNames[i]] = argIndex;
242 /// Create an alloca instruction in the entry block of
243 /// the parent function. This is used for mutable variables etc.
244 /// @param function parent instance
245 /// @param varName stack variable name
246 /// @param type stack variable type
247 /// @param initWith optional constant initialization value
248 /// @returns AllocaInst instance
249 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
250 const std::string &varName,
252 llvm::Constant *initWith = 0) {
253 llvm::BasicBlock &block = function.getEntryBlock();
254 llvm::IRBuilder<> tmp(&block, block.begin());
255 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
258 tmp.CreateStore(initWith, ret);
265 // Code Generation Utilities End
269 // Runtime C Library functions
272 // Note: using an extern "C" block so that static functions can be used
275 // Note: Better ways to decide on bit width
277 /// Prints a 32 bit number, according to the format, to stderr.
278 /// @param intToPrint integer to print
279 /// @param format printf like format to use when printing
280 void print32Int(int intToPrint, const char *format) {
282 // Note: No NULL check
283 fprintf(stderr, format, intToPrint);
286 // Note: No NULL check
287 fprintf(stderr, "::print32Int(...):NULL arg.\n");
292 // Note: Better ways to decide on bit width
294 /// Prints a 64 bit number, according to the format, to stderr.
295 /// @param intToPrint integer to print
296 /// @param format printf like format to use when printing
297 void print64Int(long int intToPrint, const char *format) {
299 // Note: No NULL check
300 fprintf(stderr, format, intToPrint);
303 // Note: No NULL check
304 fprintf(stderr, "::print64Int(...):NULL arg.\n");
309 /// Prints a C string to stderr
310 /// @param toPrint string to print
311 void printStr(char *toPrint) {
313 fprintf(stderr, "%s", toPrint);
316 fprintf(stderr, "::printStr(...):NULL arg.\n");
321 /// Deletes the true previosly allocated exception whose address
322 /// is calculated from the supplied OurBaseException_t::unwindException
323 /// member address. Handles (ignores), NULL pointers.
324 /// @param expToDelete exception to delete
325 void deleteOurException(OurUnwindException *expToDelete) {
328 "deleteOurException(...).\n");
332 (expToDelete->exception_class == ourBaseExceptionClass)) {
334 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
339 /// This function is the struct _Unwind_Exception API mandated delete function
340 /// used by foreign exception handlers when deleting our exception
341 /// (OurException), instances.
342 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
344 /// @param expToDelete exception instance to delete
345 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
346 OurUnwindException *expToDelete) {
349 "deleteFromUnwindOurException(...).\n");
352 deleteOurException(expToDelete);
356 /// Creates (allocates on the heap), an exception (OurException instance),
357 /// of the supplied type info type.
358 /// @param type type info type
359 OurUnwindException *createOurException(int type) {
360 size_t size = sizeof(OurException);
361 OurException *ret = (OurException*) memset(malloc(size), 0, size);
362 (ret->type).type = type;
363 (ret->unwindException).exception_class = ourBaseExceptionClass;
364 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
366 return(&(ret->unwindException));
370 /// Read a uleb128 encoded value and advance pointer
371 /// See Variable Length Data in:
372 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
373 /// @param data reference variable holding memory pointer to decode from
374 /// @returns decoded value
375 static uintptr_t readULEB128(const uint8_t **data) {
376 uintptr_t result = 0;
379 const uint8_t *p = *data;
383 result |= (byte & 0x7f) << shift;
394 /// Read a sleb128 encoded value and advance pointer
395 /// See Variable Length Data in:
396 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
397 /// @param data reference variable holding memory pointer to decode from
398 /// @returns decoded value
399 static uintptr_t readSLEB128(const uint8_t **data) {
400 uintptr_t result = 0;
403 const uint8_t *p = *data;
407 result |= (byte & 0x7f) << shift;
414 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
415 result |= (~0 << shift);
422 /// Read a pointer encoded value and advance pointer
423 /// See Variable Length Data in:
424 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
425 /// @param data reference variable holding memory pointer to decode from
426 /// @param encoding dwarf encoding type
427 /// @returns decoded value
428 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
429 uintptr_t result = 0;
430 const uint8_t *p = *data;
432 if (encoding == llvm::dwarf::DW_EH_PE_omit)
436 switch (encoding & 0x0F) {
437 case llvm::dwarf::DW_EH_PE_absptr:
438 result = *((uintptr_t*)p);
439 p += sizeof(uintptr_t);
441 case llvm::dwarf::DW_EH_PE_uleb128:
442 result = readULEB128(&p);
444 // Note: This case has not been tested
445 case llvm::dwarf::DW_EH_PE_sleb128:
446 result = readSLEB128(&p);
448 case llvm::dwarf::DW_EH_PE_udata2:
449 result = *((uint16_t*)p);
450 p += sizeof(uint16_t);
452 case llvm::dwarf::DW_EH_PE_udata4:
453 result = *((uint32_t*)p);
454 p += sizeof(uint32_t);
456 case llvm::dwarf::DW_EH_PE_udata8:
457 result = *((uint64_t*)p);
458 p += sizeof(uint64_t);
460 case llvm::dwarf::DW_EH_PE_sdata2:
461 result = *((int16_t*)p);
462 p += sizeof(int16_t);
464 case llvm::dwarf::DW_EH_PE_sdata4:
465 result = *((int32_t*)p);
466 p += sizeof(int32_t);
468 case llvm::dwarf::DW_EH_PE_sdata8:
469 result = *((int64_t*)p);
470 p += sizeof(int64_t);
478 // then add relative offset
479 switch (encoding & 0x70) {
480 case llvm::dwarf::DW_EH_PE_absptr:
483 case llvm::dwarf::DW_EH_PE_pcrel:
484 result += (uintptr_t)(*data);
486 case llvm::dwarf::DW_EH_PE_textrel:
487 case llvm::dwarf::DW_EH_PE_datarel:
488 case llvm::dwarf::DW_EH_PE_funcrel:
489 case llvm::dwarf::DW_EH_PE_aligned:
496 // then apply indirection
497 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
498 result = *((uintptr_t*)result);
507 /// Deals with Dwarf actions matching our type infos
508 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
509 /// action matches the supplied exception type. If such a match succeeds,
510 /// the resultAction argument will be set with > 0 index value. Only
511 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
512 /// are supported. Filters are not supported.
513 /// See Variable Length Data in:
514 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
515 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
516 /// @param resultAction reference variable which will be set with result
517 /// @param classInfo our array of type info pointers (to globals)
518 /// @param actionEntry index into above type info array or 0 (clean up).
519 /// We do not support filters.
520 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
521 /// of thrown exception.
522 /// @param exceptionObject thrown _Unwind_Exception instance.
523 /// @returns whether or not a type info was found. False is returned if only
524 /// a cleanup was found
525 static bool handleActionValue(int64_t *resultAction,
526 struct OurExceptionType_t **classInfo,
527 uintptr_t actionEntry,
528 uint64_t exceptionClass,
529 struct _Unwind_Exception *exceptionObject) {
534 (exceptionClass != ourBaseExceptionClass))
537 struct OurBaseException_t *excp = (struct OurBaseException_t*)
538 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
539 struct OurExceptionType_t *excpType = &(excp->type);
540 int type = excpType->type;
544 "handleActionValue(...): exceptionObject = <%p>, "
550 const uint8_t *actionPos = (uint8_t*) actionEntry,
552 int64_t typeOffset = 0,
555 for (int i = 0; true; ++i) {
556 // Each emitted dwarf action corresponds to a 2 tuple of
557 // type info address offset, and action offset to the next
559 typeOffset = readSLEB128(&actionPos);
560 tempActionPos = actionPos;
561 actionOffset = readSLEB128(&tempActionPos);
565 "handleActionValue(...):typeOffset: <%lld>, "
566 "actionOffset: <%lld>.\n",
570 assert((typeOffset >= 0) &&
571 "handleActionValue(...):filters are not supported.");
573 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
574 // argument has been matched.
575 if ((typeOffset > 0) &&
576 (type == (classInfo[-typeOffset])->type)) {
579 "handleActionValue(...):actionValue <%d> found.\n",
582 *resultAction = i + 1;
589 "handleActionValue(...):actionValue not found.\n");
594 actionPos += actionOffset;
601 /// Deals with the Language specific data portion of the emitted dwarf code.
602 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
603 /// @param version unsupported (ignored), unwind version
604 /// @param lsda language specific data area
605 /// @param _Unwind_Action actions minimally supported unwind stage
606 /// (forced specifically not supported)
607 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
608 /// of thrown exception.
609 /// @param exceptionObject thrown _Unwind_Exception instance.
610 /// @param context unwind system context
611 /// @returns minimally supported unwinding control indicator
612 static _Unwind_Reason_Code handleLsda(int version,
614 _Unwind_Action actions,
615 uint64_t exceptionClass,
616 struct _Unwind_Exception *exceptionObject,
617 _Unwind_Context_t context) {
618 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
625 "handleLsda(...):lsda is non-zero.\n");
628 // Get the current instruction pointer and offset it before next
629 // instruction in the current frame which threw the exception.
630 uintptr_t pc = _Unwind_GetIP(context)-1;
632 // Get beginning current frame's code (as defined by the
633 // emitted dwarf code)
634 uintptr_t funcStart = _Unwind_GetRegionStart(context);
635 uintptr_t pcOffset = pc - funcStart;
636 struct OurExceptionType_t **classInfo = NULL;
638 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
641 // Parse LSDA header.
642 uint8_t lpStartEncoding = *lsda++;
644 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
645 readEncodedPointer(&lsda, lpStartEncoding);
648 uint8_t ttypeEncoding = *lsda++;
649 uintptr_t classInfoOffset;
651 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
652 // Calculate type info locations in emitted dwarf code which
653 // were flagged by type info arguments to llvm.eh.selector
655 classInfoOffset = readULEB128(&lsda);
656 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
659 // Walk call-site table looking for range that
660 // includes current PC.
662 uint8_t callSiteEncoding = *lsda++;
663 uint32_t callSiteTableLength = readULEB128(&lsda);
664 const uint8_t *callSiteTableStart = lsda;
665 const uint8_t *callSiteTableEnd = callSiteTableStart +
667 const uint8_t *actionTableStart = callSiteTableEnd;
668 const uint8_t *callSitePtr = callSiteTableStart;
670 bool foreignException = false;
672 while (callSitePtr < callSiteTableEnd) {
673 uintptr_t start = readEncodedPointer(&callSitePtr,
675 uintptr_t length = readEncodedPointer(&callSitePtr,
677 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
680 // Note: Action value
681 uintptr_t actionEntry = readULEB128(&callSitePtr);
683 if (exceptionClass != ourBaseExceptionClass) {
684 // We have been notified of a foreign exception being thrown,
685 // and we therefore need to execute cleanup landing pads
687 foreignException = true;
690 if (landingPad == 0) {
693 "handleLsda(...): No landing pad found.\n");
696 continue; // no landing pad for this entry
700 actionEntry += ((uintptr_t) actionTableStart) - 1;
705 "handleLsda(...):No action table found.\n");
709 bool exceptionMatched = false;
711 if ((start <= pcOffset) && (pcOffset < (start + length))) {
714 "handleLsda(...): Landing pad found.\n");
716 int64_t actionValue = 0;
719 exceptionMatched = handleActionValue(&actionValue,
726 if (!(actions & _UA_SEARCH_PHASE)) {
729 "handleLsda(...): installed landing pad "
733 // Found landing pad for the PC.
734 // Set Instruction Pointer to so we re-enter function
735 // at landing pad. The landing pad is created by the
736 // compiler to take two parameters in registers.
737 _Unwind_SetGR(context,
738 __builtin_eh_return_data_regno(0),
739 (uintptr_t)exceptionObject);
741 // Note: this virtual register directly corresponds
742 // to the return of the llvm.eh.selector intrinsic
743 if (!actionEntry || !exceptionMatched) {
744 // We indicate cleanup only
745 _Unwind_SetGR(context,
746 __builtin_eh_return_data_regno(1),
750 // Matched type info index of llvm.eh.selector intrinsic
752 _Unwind_SetGR(context,
753 __builtin_eh_return_data_regno(1),
757 // To execute landing pad set here
758 _Unwind_SetIP(context, funcStart + landingPad);
759 ret = _URC_INSTALL_CONTEXT;
761 else if (exceptionMatched) {
764 "handleLsda(...): setting handler found.\n");
766 ret = _URC_HANDLER_FOUND;
769 // Note: Only non-clean up handlers are marked as
770 // found. Otherwise the clean up handlers will be
771 // re-found and executed during the clean up
775 "handleLsda(...): cleanup handler found.\n");
787 /// This is the personality function which is embedded (dwarf emitted), in the
788 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
789 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
790 /// @param version unsupported (ignored), unwind version
791 /// @param _Unwind_Action actions minimally supported unwind stage
792 /// (forced specifically not supported)
793 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
794 /// of thrown exception.
795 /// @param exceptionObject thrown _Unwind_Exception instance.
796 /// @param context unwind system context
797 /// @returns minimally supported unwinding control indicator
798 _Unwind_Reason_Code ourPersonality(int version,
799 _Unwind_Action actions,
800 uint64_t exceptionClass,
801 struct _Unwind_Exception *exceptionObject,
802 _Unwind_Context_t context) {
805 "We are in ourPersonality(...):actions is <%d>.\n",
808 if (actions & _UA_SEARCH_PHASE) {
809 fprintf(stderr, "ourPersonality(...):In search phase.\n");
812 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
816 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
820 "ourPersonality(...):lsda = <%p>.\n",
824 // The real work of the personality function is captured here
825 return(handleLsda(version,
834 /// Generates our _Unwind_Exception class from a given character array.
835 /// thereby handling arbitrary lengths (not in standard), and handling
837 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
838 /// @param classChars char array to encode. NULL values not checkedf
839 /// @param classCharsSize number of chars in classChars. Value is not checked.
840 /// @returns class value
841 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
843 uint64_t ret = classChars[0];
845 for (unsigned i = 1; i < classCharsSize; ++i) {
847 ret += classChars[i];
856 // Runtime C Library functions End
860 // Code generation functions
863 /// Generates code to print given constant string
864 /// @param context llvm context
865 /// @param module code for module instance
866 /// @param builder builder instance
867 /// @param toPrint string to print
868 /// @param useGlobal A value of true (default) indicates a GlobalValue is
869 /// generated, and is used to hold the constant string. A value of
870 /// false indicates that the constant string will be stored on the
872 void generateStringPrint(llvm::LLVMContext &context,
873 llvm::Module &module,
874 llvm::IRBuilder<> &builder,
876 bool useGlobal = true) {
877 llvm::Function *printFunct = module.getFunction("printStr");
879 llvm::Value *stringVar;
880 llvm::Constant *stringConstant =
881 llvm::ConstantDataArray::getString(context, toPrint);
884 // Note: Does not work without allocation
886 new llvm::GlobalVariable(module,
887 stringConstant->getType(),
889 llvm::GlobalValue::LinkerPrivateLinkage,
894 stringVar = builder.CreateAlloca(stringConstant->getType());
895 builder.CreateStore(stringConstant, stringVar);
898 llvm::Value *cast = builder.CreatePointerCast(stringVar,
899 builder.getInt8PtrTy());
900 builder.CreateCall(printFunct, cast);
904 /// Generates code to print given runtime integer according to constant
905 /// string format, and a given print function.
906 /// @param context llvm context
907 /// @param module code for module instance
908 /// @param builder builder instance
909 /// @param printFunct function used to "print" integer
910 /// @param toPrint string to print
911 /// @param format printf like formating string for print
912 /// @param useGlobal A value of true (default) indicates a GlobalValue is
913 /// generated, and is used to hold the constant string. A value of
914 /// false indicates that the constant string will be stored on the
916 void generateIntegerPrint(llvm::LLVMContext &context,
917 llvm::Module &module,
918 llvm::IRBuilder<> &builder,
919 llvm::Function &printFunct,
920 llvm::Value &toPrint,
922 bool useGlobal = true) {
923 llvm::Constant *stringConstant =
924 llvm::ConstantDataArray::getString(context, format);
925 llvm::Value *stringVar;
928 // Note: Does not seem to work without allocation
930 new llvm::GlobalVariable(module,
931 stringConstant->getType(),
933 llvm::GlobalValue::LinkerPrivateLinkage,
938 stringVar = builder.CreateAlloca(stringConstant->getType());
939 builder.CreateStore(stringConstant, stringVar);
942 llvm::Value *cast = builder.CreateBitCast(stringVar,
943 builder.getInt8PtrTy());
944 builder.CreateCall2(&printFunct, &toPrint, cast);
948 /// Generates code to handle finally block type semantics: always runs
949 /// regardless of whether a thrown exception is passing through or the
950 /// parent function is simply exiting. In addition to printing some state
951 /// to stderr, this code will resume the exception handling--runs the
952 /// unwind resume block, if the exception has not been previously caught
953 /// by a catch clause, and will otherwise execute the end block (terminator
954 /// block). In addition this function creates the corresponding function's
955 /// stack storage for the exception pointer and catch flag status.
956 /// @param context llvm context
957 /// @param module code for module instance
958 /// @param builder builder instance
959 /// @param toAddTo parent function to add block to
960 /// @param blockName block name of new "finally" block.
961 /// @param functionId output id used for printing
962 /// @param terminatorBlock terminator "end" block
963 /// @param unwindResumeBlock unwind resume block
964 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
965 /// @param exceptionStorage reference to exception pointer storage
966 /// @param caughtResultStorage reference to landingpad result storage
967 /// @returns newly created block
968 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
969 llvm::Module &module,
970 llvm::IRBuilder<> &builder,
971 llvm::Function &toAddTo,
972 std::string &blockName,
973 std::string &functionId,
974 llvm::BasicBlock &terminatorBlock,
975 llvm::BasicBlock &unwindResumeBlock,
976 llvm::Value **exceptionCaughtFlag,
977 llvm::Value **exceptionStorage,
978 llvm::Value **caughtResultStorage) {
979 assert(exceptionCaughtFlag &&
980 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
982 assert(exceptionStorage &&
983 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
985 assert(caughtResultStorage &&
986 "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
989 *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
991 ourExceptionNotThrownState->getType(),
992 ourExceptionNotThrownState);
994 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
995 *exceptionStorage = createEntryBlockAlloca(toAddTo,
997 exceptionStorageType,
998 llvm::ConstantPointerNull::get(
999 exceptionStorageType));
1000 *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1001 "caughtResultStorage",
1002 ourCaughtResultType,
1003 llvm::ConstantAggregateZero::get(
1004 ourCaughtResultType));
1006 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1010 builder.SetInsertPoint(ret);
1012 std::ostringstream bufferToPrint;
1013 bufferToPrint << "Gen: Executing finally block "
1014 << blockName << " in " << functionId << "\n";
1015 generateStringPrint(context,
1018 bufferToPrint.str(),
1019 USE_GLOBAL_STR_CONSTS);
1021 llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1022 *exceptionCaughtFlag),
1025 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1026 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1032 /// Generates catch block semantics which print a string to indicate type of
1033 /// catch executed, sets an exception caught flag, and executes passed in
1034 /// end block (terminator block).
1035 /// @param context llvm context
1036 /// @param module code for module instance
1037 /// @param builder builder instance
1038 /// @param toAddTo parent function to add block to
1039 /// @param blockName block name of new "catch" block.
1040 /// @param functionId output id used for printing
1041 /// @param terminatorBlock terminator "end" block
1042 /// @param exceptionCaughtFlag exception caught/thrown status
1043 /// @returns newly created block
1044 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1045 llvm::Module &module,
1046 llvm::IRBuilder<> &builder,
1047 llvm::Function &toAddTo,
1048 std::string &blockName,
1049 std::string &functionId,
1050 llvm::BasicBlock &terminatorBlock,
1051 llvm::Value &exceptionCaughtFlag) {
1053 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1057 builder.SetInsertPoint(ret);
1059 std::ostringstream bufferToPrint;
1060 bufferToPrint << "Gen: Executing catch block "
1065 generateStringPrint(context,
1068 bufferToPrint.str(),
1069 USE_GLOBAL_STR_CONSTS);
1070 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1071 builder.CreateBr(&terminatorBlock);
1077 /// Generates a function which invokes a function (toInvoke) and, whose
1078 /// unwind block will "catch" the type info types correspondingly held in the
1079 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1080 /// exception which does not match any type info types contained in
1081 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1082 /// with the raised exception. On the other hand the generated code will
1083 /// normally exit if the toInvoke function does not throw an exception.
1084 /// The generated "finally" block is always run regardless of the cause of
1085 /// the generated function exit.
1086 /// The generated function is returned after being verified.
1087 /// @param module code for module instance
1088 /// @param builder builder instance
1089 /// @param fpm a function pass manager holding optional IR to IR
1091 /// @param toInvoke inner function to invoke
1092 /// @param ourId id used to printing purposes
1093 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1094 /// @param exceptionTypesToCatch array of type info types to "catch"
1095 /// @returns generated function
1097 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1098 llvm::IRBuilder<> &builder,
1099 llvm::FunctionPassManager &fpm,
1100 llvm::Function &toInvoke,
1102 unsigned numExceptionsToCatch,
1103 unsigned exceptionTypesToCatch[]) {
1105 llvm::LLVMContext &context = module.getContext();
1106 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1109 argTypes.push_back(builder.getInt32Ty());
1112 argNames.push_back("exceptTypeToThrow");
1114 llvm::Function *ret = createFunction(module,
1115 builder.getVoidTy(),
1119 llvm::Function::ExternalLinkage,
1123 // Block which calls invoke
1124 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1127 // Normal block for invoke
1128 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1131 // Unwind block for invoke
1132 llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
1136 // Block which routes exception to correct catch handler block
1137 llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
1141 // Foreign exception handler
1142 llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
1143 "externalException",
1146 // Block which calls _Unwind_Resume
1147 llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
1151 // Clean up block which delete exception if needed
1152 llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
1154 std::string nextName;
1155 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1156 llvm::Value *exceptionCaughtFlag = NULL;
1157 llvm::Value *exceptionStorage = NULL;
1158 llvm::Value *caughtResultStorage = NULL;
1160 // Finally block which will branch to unwindResumeBlock if
1161 // exception is not caught. Initializes/allocates stack locations.
1162 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1166 nextName = "finally",
1170 &exceptionCaughtFlag,
1172 &caughtResultStorage
1175 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1176 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1178 // One catch block per type info to be caught
1179 catchBlocks[i] = createCatchBlock(context,
1186 *exceptionCaughtFlag);
1191 builder.SetInsertPoint(entryBlock);
1193 std::vector<llvm::Value*> args;
1194 args.push_back(namedValues["exceptTypeToThrow"]);
1195 builder.CreateInvoke(&toInvoke,
1202 builder.SetInsertPoint(endBlock);
1204 generateStringPrint(context,
1207 "Gen: In end block: exiting in " + ourId + ".\n",
1208 USE_GLOBAL_STR_CONSTS);
1209 llvm::Function *deleteOurException = module.getFunction("deleteOurException");
1211 // Note: function handles NULL exceptions
1212 builder.CreateCall(deleteOurException,
1213 builder.CreateLoad(exceptionStorage));
1214 builder.CreateRetVoid();
1218 builder.SetInsertPoint(normalBlock);
1220 generateStringPrint(context,
1223 "Gen: No exception in " + ourId + "!\n",
1224 USE_GLOBAL_STR_CONSTS);
1226 // Finally block is always called
1227 builder.CreateBr(finallyBlock);
1229 // Unwind Resume Block
1231 builder.SetInsertPoint(unwindResumeBlock);
1233 builder.CreateResume(builder.CreateLoad(caughtResultStorage));
1237 builder.SetInsertPoint(exceptionBlock);
1239 llvm::Function *personality = module.getFunction("ourPersonality");
1241 llvm::LandingPadInst *caughtResult =
1242 builder.CreateLandingPad(ourCaughtResultType,
1244 numExceptionsToCatch,
1247 caughtResult->setCleanup(true);
1249 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1250 // Set up type infos to be caught
1251 caughtResult->addClause(module.getGlobalVariable(
1252 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1255 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1256 llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
1258 // FIXME: Redundant storage which, beyond utilizing value of
1259 // caughtResultStore for unwindException storage, may be alleviated
1260 // altogether with a block rearrangement
1261 builder.CreateStore(caughtResult, caughtResultStorage);
1262 builder.CreateStore(unwindException, exceptionStorage);
1263 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
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 = builder.CreatePointerCast(
1304 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 = builder.CreateSwitch(retTypeInfoIndex,
1331 numExceptionsToCatch);
1333 unsigned nextTypeToCatch;
1335 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1336 nextTypeToCatch = i - 1;
1337 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1338 llvm::Type::getInt32Ty(context), i),
1339 catchBlocks[nextTypeToCatch]);
1342 llvm::verifyFunction(*ret);
1349 /// Generates function which throws either an exception matched to a runtime
1350 /// determined type info type (argument to generated function), or if this
1351 /// runtime value matches nativeThrowType, throws a foreign exception by
1352 /// calling nativeThrowFunct.
1353 /// @param module code for module instance
1354 /// @param builder builder instance
1355 /// @param fpm a function pass manager holding optional IR to IR
1357 /// @param ourId id used to printing purposes
1358 /// @param nativeThrowType a runtime argument of this value results in
1359 /// nativeThrowFunct being called to generate/throw exception.
1360 /// @param nativeThrowFunct function which will throw a foreign exception
1361 /// if the above nativeThrowType matches generated function's arg.
1362 /// @returns generated function
1364 llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1365 llvm::IRBuilder<> &builder,
1366 llvm::FunctionPassManager &fpm,
1368 int32_t nativeThrowType,
1369 llvm::Function &nativeThrowFunct) {
1370 llvm::LLVMContext &context = module.getContext();
1371 namedValues.clear();
1372 ArgTypes unwindArgTypes;
1373 unwindArgTypes.push_back(builder.getInt32Ty());
1374 ArgNames unwindArgNames;
1375 unwindArgNames.push_back("exceptTypeToThrow");
1377 llvm::Function *ret = createFunction(module,
1378 builder.getVoidTy(),
1382 llvm::Function::ExternalLinkage,
1386 // Throws either one of our exception or a native C++ exception depending
1387 // on a runtime argument value containing a type info type.
1388 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1391 // Throws a foreign exception
1392 llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1395 // Throws one of our Exceptions
1396 llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1399 // Retrieved runtime type info type to throw
1400 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1402 // nativeThrowBlock block
1404 builder.SetInsertPoint(nativeThrowBlock);
1406 // Throws foreign exception
1407 builder.CreateCall(&nativeThrowFunct, exceptionType);
1408 builder.CreateUnreachable();
1412 builder.SetInsertPoint(entryBlock);
1414 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1415 generateIntegerPrint(context,
1420 "\nGen: About to throw exception type <%d> in " +
1423 USE_GLOBAL_STR_CONSTS);
1425 // Switches on runtime type info type value to determine whether or not
1426 // a foreign exception is thrown. Defaults to throwing one of our
1427 // generated exceptions.
1428 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1429 generatedThrowBlock,
1432 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1436 // generatedThrow block
1438 builder.SetInsertPoint(generatedThrowBlock);
1440 llvm::Function *createOurException = module.getFunction("createOurException");
1441 llvm::Function *raiseOurException = module.getFunction(
1442 "_Unwind_RaiseException");
1444 // Creates exception to throw with runtime type info type.
1445 llvm::Value *exception = builder.CreateCall(createOurException,
1446 namedValues["exceptTypeToThrow"]);
1448 // Throw generated Exception
1449 builder.CreateCall(raiseOurException, exception);
1450 builder.CreateUnreachable();
1452 llvm::verifyFunction(*ret);
1458 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1459 llvm::Module &module,
1460 llvm::IRBuilder<> &builder);
1462 /// Creates test code by generating and organizing these functions into the
1463 /// test case. The test case consists of an outer function setup to invoke
1464 /// an inner function within an environment having multiple catch and single
1465 /// finally blocks. This inner function is also setup to invoke a throw
1466 /// function within an evironment similar in nature to the outer function's
1467 /// catch and finally blocks. Each of these two functions catch mutually
1468 /// exclusive subsets (even or odd) of the type info types configured
1469 /// for this this. All generated functions have a runtime argument which
1470 /// holds a type info type to throw that each function takes and passes it
1471 /// to the inner one if such a inner function exists. This type info type is
1472 /// looked at by the generated throw function to see whether or not it should
1473 /// throw a generated exception with the same type info type, or instead call
1474 /// a supplied a function which in turn will throw a foreign exception.
1475 /// @param module code for module instance
1476 /// @param builder builder instance
1477 /// @param fpm a function pass manager holding optional IR to IR
1479 /// @param nativeThrowFunctName name of external function which will throw
1480 /// a foreign exception
1481 /// @returns outermost generated test function.
1482 llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1483 llvm::IRBuilder<> &builder,
1484 llvm::FunctionPassManager &fpm,
1485 std::string nativeThrowFunctName) {
1486 // Number of type infos to generate
1487 unsigned numTypeInfos = 6;
1489 // Initialze intrisics and external functions to use along with exception
1490 // and type info globals.
1491 createStandardUtilityFunctions(numTypeInfos,
1494 llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
1496 // Create exception throw function using the value ~0 to cause
1497 // foreign exceptions to be thrown.
1498 llvm::Function *throwFunct = createThrowExceptionFunction(module,
1504 // Inner function will catch even type infos
1505 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1506 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1509 // Generate inner function.
1510 llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1515 numExceptionTypesToCatch,
1516 innerExceptionTypesToCatch);
1518 // Outer function will catch odd type infos
1519 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1520 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1523 // Generate outer function
1524 llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1529 numExceptionTypesToCatch,
1530 outerExceptionTypesToCatch);
1532 // Return outer function to run
1533 return(outerCatchFunct);
1537 /// Represents our foreign exceptions
1538 class OurCppRunException : public std::runtime_error {
1540 OurCppRunException(const std::string reason) :
1541 std::runtime_error(reason) {}
1543 OurCppRunException (const OurCppRunException &toCopy) :
1544 std::runtime_error(toCopy) {}
1546 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1547 return(reinterpret_cast<OurCppRunException&>(
1548 std::runtime_error::operator=(toCopy)));
1551 ~OurCppRunException (void) throw () {}
1555 /// Throws foreign C++ exception.
1556 /// @param ignoreIt unused parameter that allows function to match implied
1557 /// generated function contract.
1559 void throwCppException (int32_t ignoreIt) {
1560 throw(OurCppRunException("thrown by throwCppException(...)"));
1563 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1565 /// This is a test harness which runs test by executing generated
1566 /// function with a type info type to throw. Harness wraps the execution
1567 /// of generated function in a C++ try catch clause.
1568 /// @param engine execution engine to use for executing generated function.
1569 /// This demo program expects this to be a JIT instance for demo
1571 /// @param function generated test function to run
1572 /// @param typeToThrow type info type of generated exception to throw, or
1573 /// indicator to cause foreign exception to be thrown.
1575 void runExceptionThrow(llvm::ExecutionEngine *engine,
1576 llvm::Function *function,
1577 int32_t typeToThrow) {
1579 // Find test's function pointer
1580 OurExceptionThrowFunctType functPtr =
1581 reinterpret_cast<OurExceptionThrowFunctType>(
1582 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1586 (*functPtr)(typeToThrow);
1588 catch (OurCppRunException exc) {
1589 // Catch foreign C++ exception
1591 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1592 "with reason: %s.\n",
1596 // Catch all exceptions including our generated ones. This latter
1597 // functionality works according to the example in rules 1.6.4 of
1598 // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22),
1599 // given that these will be exceptions foreign to C++
1600 // (the _Unwind_Exception::exception_class should be different from
1601 // the one used by C++).
1603 "\nrunExceptionThrow(...):In C++ catch all.\n");
1608 // End test functions
1611 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1613 /// This initialization routine creates type info globals and
1614 /// adds external function declarations to module.
1615 /// @param numTypeInfos number of linear type info associated type info types
1616 /// to create as GlobalVariable instances, starting with the value 1.
1617 /// @param module code for module instance
1618 /// @param builder builder instance
1619 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1620 llvm::Module &module,
1621 llvm::IRBuilder<> &builder) {
1623 llvm::LLVMContext &context = module.getContext();
1625 // Exception initializations
1627 // Setup exception catch state
1628 ourExceptionNotThrownState =
1629 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1630 ourExceptionThrownState =
1631 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1632 ourExceptionCaughtState =
1633 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1637 // Create our type info type
1638 ourTypeInfoType = llvm::StructType::get(context,
1639 TypeArray(builder.getInt32Ty()));
1641 llvm::Type *caughtResultFieldTypes[] = {
1642 builder.getInt8PtrTy(),
1643 builder.getInt32Ty()
1646 // Create our landingpad result type
1647 ourCaughtResultType = llvm::StructType::get(context,
1648 TypeArray(caughtResultFieldTypes));
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,
1660 TypeArray(builder.getInt64Ty()));
1662 struct OurBaseException_t dummyException;
1664 // Calculate offset of OurException::unwindException member.
1665 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1666 ((uintptr_t) &(dummyException.unwindException));
1670 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1671 "= %lld, sizeof(struct OurBaseException_t) - "
1672 "sizeof(struct _Unwind_Exception) = %lu.\n",
1673 ourBaseFromUnwindOffset,
1674 sizeof(struct OurBaseException_t) -
1675 sizeof(struct _Unwind_Exception));
1678 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1680 // Create our _Unwind_Exception::exception_class value
1681 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1685 std::string baseStr = "typeInfo", typeInfoName;
1686 std::ostringstream typeInfoNameBuilder;
1687 std::vector<llvm::Constant*> structVals;
1689 llvm::Constant *nextStruct;
1690 llvm::GlobalVariable *nextGlobal = NULL;
1692 // Generate each type info
1694 // Note: First type info is not used.
1695 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1697 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1698 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1700 typeInfoNameBuilder.str("");
1701 typeInfoNameBuilder << baseStr << i;
1702 typeInfoName = typeInfoNameBuilder.str();
1704 // Note: Does not seem to work without allocation
1706 new llvm::GlobalVariable(module,
1709 llvm::GlobalValue::ExternalLinkage,
1713 ourTypeInfoNames.push_back(typeInfoName);
1714 ourTypeInfoNamesIndex[i] = typeInfoName;
1719 llvm::Function *funct = NULL;
1723 llvm::Type *retType = builder.getVoidTy();
1726 argTypes.push_back(builder.getInt32Ty());
1727 argTypes.push_back(builder.getInt8PtrTy());
1731 createFunction(module,
1736 llvm::Function::ExternalLinkage,
1742 retType = builder.getVoidTy();
1745 argTypes.push_back(builder.getInt64Ty());
1746 argTypes.push_back(builder.getInt8PtrTy());
1750 createFunction(module,
1755 llvm::Function::ExternalLinkage,
1761 retType = builder.getVoidTy();
1764 argTypes.push_back(builder.getInt8PtrTy());
1768 createFunction(module,
1773 llvm::Function::ExternalLinkage,
1777 // throwCppException
1779 retType = builder.getVoidTy();
1782 argTypes.push_back(builder.getInt32Ty());
1786 createFunction(module,
1790 "throwCppException",
1791 llvm::Function::ExternalLinkage,
1795 // deleteOurException
1797 retType = builder.getVoidTy();
1800 argTypes.push_back(builder.getInt8PtrTy());
1804 createFunction(module,
1808 "deleteOurException",
1809 llvm::Function::ExternalLinkage,
1813 // createOurException
1815 retType = builder.getInt8PtrTy();
1818 argTypes.push_back(builder.getInt32Ty());
1822 createFunction(module,
1826 "createOurException",
1827 llvm::Function::ExternalLinkage,
1831 // _Unwind_RaiseException
1833 retType = builder.getInt32Ty();
1836 argTypes.push_back(builder.getInt8PtrTy());
1840 funct = createFunction(module,
1844 "_Unwind_RaiseException",
1845 llvm::Function::ExternalLinkage,
1849 funct->addFnAttr(llvm::Attribute::NoReturn);
1853 retType = builder.getInt32Ty();
1856 argTypes.push_back(builder.getInt8PtrTy());
1860 funct = createFunction(module,
1865 llvm::Function::ExternalLinkage,
1869 funct->addFnAttr(llvm::Attribute::NoReturn);
1873 retType = builder.getInt32Ty();
1876 argTypes.push_back(builder.getInt32Ty());
1877 argTypes.push_back(builder.getInt32Ty());
1878 argTypes.push_back(builder.getInt64Ty());
1879 argTypes.push_back(builder.getInt8PtrTy());
1880 argTypes.push_back(builder.getInt8PtrTy());
1884 createFunction(module,
1889 llvm::Function::ExternalLinkage,
1893 // llvm.eh.typeid.for intrinsic
1895 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1899 //===----------------------------------------------------------------------===//
1900 // Main test driver code.
1901 //===----------------------------------------------------------------------===//
1903 /// Demo main routine which takes the type info types to throw. A test will
1904 /// be run for each given type info type. While type info types with the value
1905 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1906 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1907 /// will result in exceptions which pass through to the test harness. All other
1908 /// type info types are not supported and could cause a crash.
1909 int main(int argc, char *argv[]) {
1912 "\nUsage: ExceptionDemo <exception type to throw> "
1913 "[<type 2>...<type n>].\n"
1914 " Each type must have the value of 1 - 6 for "
1915 "generated exceptions to be caught;\n"
1916 " the value -1 for foreign C++ exceptions to be "
1917 "generated and thrown;\n"
1918 " or the values > 6 for exceptions to be ignored.\n"
1919 "\nTry: ExceptionDemo 2 3 7 -1\n"
1920 " for a full test.\n\n");
1924 // If not set, exception handling will not be turned on
1925 llvm::TargetOptions Opts;
1926 Opts.JITExceptionHandling = true;
1928 llvm::InitializeNativeTarget();
1929 llvm::LLVMContext &context = llvm::getGlobalContext();
1930 llvm::IRBuilder<> theBuilder(context);
1932 // Make the module, which holds all the code.
1933 llvm::Module *module = new llvm::Module("my cool jit", context);
1935 // Build engine with JIT
1936 llvm::EngineBuilder factory(module);
1937 factory.setEngineKind(llvm::EngineKind::JIT);
1938 factory.setAllocateGVsWithCode(false);
1939 factory.setTargetOptions(Opts);
1940 llvm::ExecutionEngine *executionEngine = factory.create();
1943 llvm::FunctionPassManager fpm(module);
1945 // Set up the optimizer pipeline.
1946 // Start with registering info about how the
1947 // target lays out data structures.
1948 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1950 // Optimizations turned on
1951 #ifdef ADD_OPT_PASSES
1953 // Basic AliasAnslysis support for GVN.
1954 fpm.add(llvm::createBasicAliasAnalysisPass());
1956 // Promote allocas to registers.
1957 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1959 // Do simple "peephole" optimizations and bit-twiddling optzns.
1960 fpm.add(llvm::createInstructionCombiningPass());
1962 // Reassociate expressions.
1963 fpm.add(llvm::createReassociatePass());
1965 // Eliminate Common SubExpressions.
1966 fpm.add(llvm::createGVNPass());
1968 // Simplify the control flow graph (deleting unreachable
1970 fpm.add(llvm::createCFGSimplificationPass());
1971 #endif // ADD_OPT_PASSES
1973 fpm.doInitialization();
1975 // Generate test code using function throwCppException(...) as
1976 // the function which throws foreign exceptions.
1977 llvm::Function *toRun =
1978 createUnwindExceptionTest(*module,
1981 "throwCppException");
1983 fprintf(stderr, "\nBegin module dump:\n\n");
1987 fprintf(stderr, "\nEnd module dump:\n");
1989 fprintf(stderr, "\n\nBegin Test:\n");
1991 for (int i = 1; i < argc; ++i) {
1992 // Run test for each argument whose value is the exception
1994 runExceptionThrow(executionEngine,
1996 (unsigned) strtoul(argv[i], NULL, 10));
1999 fprintf(stderr, "\nEnd Test:\n\n");
2002 delete executionEngine;