Modified demo to use 3.0 resume instruction vs calling _Unwine_Resume.
[oota-llvm.git] / examples / ExceptionDemo / ExceptionDemo.cpp
1 //===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
21 // thrown exception.
22 //
23 // examples:
24 //
25 // ExceptionDemo
26 //
27 //     causes a usage to be printed to stderr
28 // 
29 // ExceptionDemo 2 3 7 -1
30 //
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
40 //
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.
44 //
45 // This code uses code from the llvm compiler-rt project and the llvm 
46 // Kaleidoscope project.
47 //
48 //===----------------------------------------------------------------------===//
49
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/TargetOptions.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Support/IRBuilder.h"
62 #include "llvm/Support/Dwarf.h"
63 #include "llvm/Support/TargetSelect.h"
64
65 #ifdef OLD_EXC_SYSTEM
66 // See use of UpgradeExceptionHandling(...) below                        
67 #include "llvm/AutoUpgrade.h"
68 #endif
69
70 // FIXME: Although all systems tested with (Linux, OS X), do not need this 
71 //        header file included. A user on ubuntu reported, undefined symbols 
72 //        for stderr, and fprintf, and the addition of this include fixed the
73 //        issue for them. Given that LLVM's best practices include the goal 
74 //        of reducing the number of redundant header files included, the 
75 //        correct solution would be to find out why these symbols are not 
76 //        defined for the system in question, and fix the issue by finding out
77 //        which LLVM header file, if any, would include these symbols.
78 #include <cstdio>
79
80 #include <sstream>
81 #include <stdexcept>
82
83
84 #ifndef USE_GLOBAL_STR_CONSTS
85 #define USE_GLOBAL_STR_CONSTS true
86 #endif
87
88 // System C++ ABI unwind types from: 
89 //     http://refspecs.freestandards.org/abi-eh-1.21.html
90
91 extern "C" {
92   
93   typedef enum {
94     _URC_NO_REASON = 0,
95     _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
96     _URC_FATAL_PHASE2_ERROR = 2,
97     _URC_FATAL_PHASE1_ERROR = 3,
98     _URC_NORMAL_STOP = 4,
99     _URC_END_OF_STACK = 5,
100     _URC_HANDLER_FOUND = 6,
101     _URC_INSTALL_CONTEXT = 7,
102     _URC_CONTINUE_UNWIND = 8
103   } _Unwind_Reason_Code;
104   
105   typedef enum {
106     _UA_SEARCH_PHASE = 1,
107     _UA_CLEANUP_PHASE = 2,
108     _UA_HANDLER_FRAME = 4,
109     _UA_FORCE_UNWIND = 8,
110     _UA_END_OF_STACK = 16
111   } _Unwind_Action;
112   
113   struct _Unwind_Exception;
114   
115   typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
116                                                 struct _Unwind_Exception *);
117   
118   struct _Unwind_Exception {
119     uint64_t exception_class;
120     _Unwind_Exception_Cleanup_Fn exception_cleanup;
121     
122     uintptr_t private_1;    
123     uintptr_t private_2;    
124     
125     // @@@ The IA-64 ABI says that this structure must be double-word aligned.
126     //  Taking that literally does not make much sense generically.  Instead 
127     //  we provide the maximum alignment required by any type for the machine.
128   } __attribute__((__aligned__));
129   
130   struct _Unwind_Context;
131   typedef struct _Unwind_Context *_Unwind_Context_t;
132   
133   extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
134   extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
135   extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
136   extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
137   extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
138   extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
139   
140 } // extern "C"
141
142 //
143 // Example types
144 //
145
146 /// This is our simplistic type info
147 struct OurExceptionType_t {
148   /// type info type
149   int type;
150 };
151
152
153 /// This is our Exception class which relies on a negative offset to calculate
154 /// pointers to its instances from pointers to its unwindException member.
155 /// 
156 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
157 ///       on a double word boundary. This is necessary to match the standard:
158 ///       http://refspecs.freestandards.org/abi-eh-1.21.html
159 struct OurBaseException_t {
160   struct OurExceptionType_t type;
161   
162   // Note: This is properly aligned in unwind.h
163   struct _Unwind_Exception unwindException;
164 };
165
166
167 // Note: Not needed since we are C++
168 typedef struct OurBaseException_t OurException;
169 typedef struct _Unwind_Exception OurUnwindException;
170
171 //
172 // Various globals used to support typeinfo and generatted exceptions in 
173 // general
174 //
175
176 static std::map<std::string, llvm::Value*> namedValues;
177
178 int64_t ourBaseFromUnwindOffset;
179
180 const unsigned char ourBaseExcpClassChars[] = 
181 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
182
183
184 static uint64_t ourBaseExceptionClass = 0;
185
186 static std::vector<std::string> ourTypeInfoNames;
187 static std::map<int, std::string> ourTypeInfoNamesIndex;
188
189 static llvm::StructType *ourTypeInfoType;
190 #ifndef OLD_EXC_SYSTEM
191 static llvm::StructType *ourCaughtResultType;
192 #endif
193 static llvm::StructType *ourExceptionType;
194 static llvm::StructType *ourUnwindExceptionType;
195
196 static llvm::ConstantInt *ourExceptionNotThrownState;
197 static llvm::ConstantInt *ourExceptionThrownState;
198 static llvm::ConstantInt *ourExceptionCaughtState;
199
200 typedef std::vector<std::string> ArgNames;
201 typedef std::vector<llvm::Type*> ArgTypes;
202
203 //
204 // Code Generation Utilities
205 //
206
207 /// Utility used to create a function, both declarations and definitions
208 /// @param module for module instance
209 /// @param retType function return type
210 /// @param theArgTypes function's ordered argument types
211 /// @param theArgNames function's ordered arguments needed if use of this
212 ///        function corresponds to a function definition. Use empty 
213 ///        aggregate for function declarations.
214 /// @param functName function name
215 /// @param linkage function linkage
216 /// @param declarationOnly for function declarations
217 /// @param isVarArg function uses vararg arguments
218 /// @returns function instance
219 llvm::Function *createFunction(llvm::Module &module,
220                                llvm::Type *retType,
221                                const ArgTypes &theArgTypes,
222                                const ArgNames &theArgNames,
223                                const std::string &functName,
224                                llvm::GlobalValue::LinkageTypes linkage,
225                                bool declarationOnly,
226                                bool isVarArg) {
227   llvm::FunctionType *functType =
228     llvm::FunctionType::get(retType, theArgTypes, isVarArg);
229   llvm::Function *ret =
230     llvm::Function::Create(functType, linkage, functName, &module);
231   if (!ret || declarationOnly)
232     return(ret);
233   
234   namedValues.clear();
235   unsigned i = 0; 
236   for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
237        i != theArgNames.size();
238        ++argIndex, ++i) {
239     
240     argIndex->setName(theArgNames[i]);
241     namedValues[theArgNames[i]] = argIndex;
242   }
243   
244   return(ret);
245 }
246
247
248 /// Create an alloca instruction in the entry block of
249 /// the parent function.  This is used for mutable variables etc.
250 /// @param function parent instance
251 /// @param varName stack variable name
252 /// @param type stack variable type
253 /// @param initWith optional constant initialization value
254 /// @returns AllocaInst instance
255 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
256                                                 const std::string &varName,
257                                                 llvm::Type *type,
258                                                 llvm::Constant *initWith = 0) {
259   llvm::BasicBlock &block = function.getEntryBlock(); 
260   llvm::IRBuilder<> tmp(&block, block.begin());
261   llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
262   
263   if (initWith) 
264     tmp.CreateStore(initWith, ret);
265   
266   return(ret);
267 }
268
269
270 //
271 // Code Generation Utilities End
272 //
273
274 //
275 // Runtime C Library functions 
276 //
277
278 // Note: using an extern "C" block so that static functions can be used
279 extern "C" {
280
281 // Note: Better ways to decide on bit width
282 //
283 /// Prints a 32 bit number, according to the format, to stderr.
284 /// @param intToPrint integer to print 
285 /// @param format printf like format to use when printing
286 void print32Int(int intToPrint, const char *format) {
287   if (format) {
288     // Note: No NULL check
289     fprintf(stderr, format, intToPrint);
290   }
291   else {
292     // Note: No NULL check
293     fprintf(stderr, "::print32Int(...):NULL arg.\n");
294   }
295 }
296
297
298 // Note: Better ways to decide on bit width
299 //
300 /// Prints a 64 bit number, according to the format, to stderr.
301 /// @param intToPrint integer to print 
302 /// @param format printf like format to use when printing
303 void print64Int(long int intToPrint, const char *format) {
304   if (format) {
305     // Note: No NULL check
306     fprintf(stderr, format, intToPrint);
307   }
308   else {
309     // Note: No NULL check
310     fprintf(stderr, "::print64Int(...):NULL arg.\n");
311   }
312 }
313
314
315 /// Prints a C string to stderr
316 /// @param toPrint string to print
317 void printStr(char *toPrint) {
318   if (toPrint) {
319     fprintf(stderr, "%s", toPrint);
320   }
321   else {
322     fprintf(stderr, "::printStr(...):NULL arg.\n");
323   }
324 }
325
326
327 /// Deletes the true previosly allocated exception whose address
328 /// is calculated from the supplied OurBaseException_t::unwindException
329 /// member address. Handles (ignores), NULL pointers.
330 /// @param expToDelete exception to delete
331 void deleteOurException(OurUnwindException *expToDelete) {
332 #ifdef DEBUG
333   fprintf(stderr,
334           "deleteOurException(...).\n");
335 #endif
336   
337   if (expToDelete &&
338       (expToDelete->exception_class == ourBaseExceptionClass)) {
339     
340     free(((char*) expToDelete) + ourBaseFromUnwindOffset);
341   }
342 }
343
344
345 /// This function is the struct _Unwind_Exception API mandated delete function 
346 /// used by foreign exception handlers when deleting our exception 
347 /// (OurException), instances.
348 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html 
349 /// @unlink
350 /// @param expToDelete exception instance to delete
351 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
352                                   OurUnwindException *expToDelete) {
353 #ifdef DEBUG
354   fprintf(stderr,
355           "deleteFromUnwindOurException(...).\n");
356 #endif
357   
358   deleteOurException(expToDelete);
359 }
360
361
362 /// Creates (allocates on the heap), an exception (OurException instance),
363 /// of the supplied type info type.
364 /// @param type type info type
365 OurUnwindException *createOurException(int type) {
366   size_t size = sizeof(OurException);
367   OurException *ret = (OurException*) memset(malloc(size), 0, size);
368   (ret->type).type = type;
369   (ret->unwindException).exception_class = ourBaseExceptionClass;
370   (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
371   
372   return(&(ret->unwindException));
373 }
374
375
376 /// Read a uleb128 encoded value and advance pointer 
377 /// See Variable Length Data in: 
378 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
379 /// @param data reference variable holding memory pointer to decode from
380 /// @returns decoded value
381 static uintptr_t readULEB128(const uint8_t **data) {
382   uintptr_t result = 0;
383   uintptr_t shift = 0;
384   unsigned char byte;
385   const uint8_t *p = *data;
386   
387   do {
388     byte = *p++;
389     result |= (byte & 0x7f) << shift;
390     shift += 7;
391   } 
392   while (byte & 0x80);
393   
394   *data = p;
395   
396   return result;
397 }
398
399
400 /// Read a sleb128 encoded value and advance pointer 
401 /// See Variable Length Data in: 
402 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
403 /// @param data reference variable holding memory pointer to decode from
404 /// @returns decoded value
405 static uintptr_t readSLEB128(const uint8_t **data) {
406   uintptr_t result = 0;
407   uintptr_t shift = 0;
408   unsigned char byte;
409   const uint8_t *p = *data;
410   
411   do {
412     byte = *p++;
413     result |= (byte & 0x7f) << shift;
414     shift += 7;
415   } 
416   while (byte & 0x80);
417   
418   *data = p;
419   
420   if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
421     result |= (~0 << shift);
422   }
423   
424   return result;
425 }
426
427
428 /// Read a pointer encoded value and advance pointer 
429 /// See Variable Length Data in: 
430 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
431 /// @param data reference variable holding memory pointer to decode from
432 /// @param encoding dwarf encoding type
433 /// @returns decoded value
434 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
435   uintptr_t result = 0;
436   const uint8_t *p = *data;
437   
438   if (encoding == llvm::dwarf::DW_EH_PE_omit) 
439     return(result);
440   
441   // first get value 
442   switch (encoding & 0x0F) {
443     case llvm::dwarf::DW_EH_PE_absptr:
444       result = *((uintptr_t*)p);
445       p += sizeof(uintptr_t);
446       break;
447     case llvm::dwarf::DW_EH_PE_uleb128:
448       result = readULEB128(&p);
449       break;
450       // Note: This case has not been tested
451     case llvm::dwarf::DW_EH_PE_sleb128:
452       result = readSLEB128(&p);
453       break;
454     case llvm::dwarf::DW_EH_PE_udata2:
455       result = *((uint16_t*)p);
456       p += sizeof(uint16_t);
457       break;
458     case llvm::dwarf::DW_EH_PE_udata4:
459       result = *((uint32_t*)p);
460       p += sizeof(uint32_t);
461       break;
462     case llvm::dwarf::DW_EH_PE_udata8:
463       result = *((uint64_t*)p);
464       p += sizeof(uint64_t);
465       break;
466     case llvm::dwarf::DW_EH_PE_sdata2:
467       result = *((int16_t*)p);
468       p += sizeof(int16_t);
469       break;
470     case llvm::dwarf::DW_EH_PE_sdata4:
471       result = *((int32_t*)p);
472       p += sizeof(int32_t);
473       break;
474     case llvm::dwarf::DW_EH_PE_sdata8:
475       result = *((int64_t*)p);
476       p += sizeof(int64_t);
477       break;
478     default:
479       // not supported 
480       abort();
481       break;
482   }
483   
484   // then add relative offset 
485   switch (encoding & 0x70) {
486     case llvm::dwarf::DW_EH_PE_absptr:
487       // do nothing 
488       break;
489     case llvm::dwarf::DW_EH_PE_pcrel:
490       result += (uintptr_t)(*data);
491       break;
492     case llvm::dwarf::DW_EH_PE_textrel:
493     case llvm::dwarf::DW_EH_PE_datarel:
494     case llvm::dwarf::DW_EH_PE_funcrel:
495     case llvm::dwarf::DW_EH_PE_aligned:
496     default:
497       // not supported 
498       abort();
499       break;
500   }
501   
502   // then apply indirection 
503   if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
504     result = *((uintptr_t*)result);
505   }
506   
507   *data = p;
508   
509   return result;
510 }
511
512
513 /// Deals with Dwarf actions matching our type infos 
514 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted 
515 /// action matches the supplied exception type. If such a match succeeds, 
516 /// the resultAction argument will be set with > 0 index value. Only 
517 /// corresponding llvm.eh.selector type info arguments, cleanup arguments 
518 /// are supported. Filters are not supported.
519 /// See Variable Length Data in: 
520 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
521 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
522 /// @param resultAction reference variable which will be set with result
523 /// @param classInfo our array of type info pointers (to globals)
524 /// @param actionEntry index into above type info array or 0 (clean up). 
525 ///        We do not support filters.
526 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
527 ///        of thrown exception.
528 /// @param exceptionObject thrown _Unwind_Exception instance.
529 /// @returns whether or not a type info was found. False is returned if only
530 ///          a cleanup was found
531 static bool handleActionValue(int64_t *resultAction,
532                               struct OurExceptionType_t **classInfo, 
533                               uintptr_t actionEntry, 
534                               uint64_t exceptionClass, 
535                               struct _Unwind_Exception *exceptionObject) {
536   bool ret = false;
537   
538   if (!resultAction || 
539       !exceptionObject || 
540       (exceptionClass != ourBaseExceptionClass))
541     return(ret);
542   
543   struct OurBaseException_t *excp = (struct OurBaseException_t*)
544   (((char*) exceptionObject) + ourBaseFromUnwindOffset);
545   struct OurExceptionType_t *excpType = &(excp->type);
546   int type = excpType->type;
547   
548 #ifdef DEBUG
549   fprintf(stderr,
550           "handleActionValue(...): exceptionObject = <%p>, "
551           "excp = <%p>.\n",
552           exceptionObject,
553           excp);
554 #endif
555   
556   const uint8_t *actionPos = (uint8_t*) actionEntry,
557   *tempActionPos;
558   int64_t typeOffset = 0,
559   actionOffset;
560   
561   for (int i = 0; true; ++i) {
562     // Each emitted dwarf action corresponds to a 2 tuple of
563     // type info address offset, and action offset to the next
564     // emitted action.
565     typeOffset = readSLEB128(&actionPos);
566     tempActionPos = actionPos;
567     actionOffset = readSLEB128(&tempActionPos);
568     
569 #ifdef DEBUG
570     fprintf(stderr,
571             "handleActionValue(...):typeOffset: <%lld>, "
572             "actionOffset: <%lld>.\n",
573             typeOffset,
574             actionOffset);
575 #endif
576     assert((typeOffset >= 0) && 
577            "handleActionValue(...):filters are not supported.");
578     
579     // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
580     //       argument has been matched.
581     if ((typeOffset > 0) &&
582         (type == (classInfo[-typeOffset])->type)) {
583 #ifdef DEBUG
584       fprintf(stderr,
585               "handleActionValue(...):actionValue <%d> found.\n",
586               i);
587 #endif
588       *resultAction = i + 1;
589       ret = true;
590       break;
591     }
592     
593 #ifdef DEBUG
594     fprintf(stderr,
595             "handleActionValue(...):actionValue not found.\n");
596 #endif
597     if (!actionOffset)
598       break;
599     
600     actionPos += actionOffset;
601   }
602   
603   return(ret);
604 }
605
606
607 /// Deals with the Language specific data portion of the emitted dwarf code.
608 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
609 /// @param version unsupported (ignored), unwind version
610 /// @param lsda language specific data area
611 /// @param _Unwind_Action actions minimally supported unwind stage 
612 ///        (forced specifically not supported)
613 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
614 ///        of thrown exception.
615 /// @param exceptionObject thrown _Unwind_Exception instance.
616 /// @param context unwind system context
617 /// @returns minimally supported unwinding control indicator 
618 static _Unwind_Reason_Code handleLsda(int version, 
619                                       const uint8_t *lsda,
620                                       _Unwind_Action actions,
621                                       uint64_t exceptionClass, 
622                                     struct _Unwind_Exception *exceptionObject,
623                                       _Unwind_Context_t context) {
624   _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
625   
626   if (!lsda)
627     return(ret);
628   
629 #ifdef DEBUG
630   fprintf(stderr, 
631           "handleLsda(...):lsda is non-zero.\n");
632 #endif
633   
634   // Get the current instruction pointer and offset it before next
635   // instruction in the current frame which threw the exception.
636   uintptr_t pc = _Unwind_GetIP(context)-1;
637   
638   // Get beginning current frame's code (as defined by the 
639   // emitted dwarf code)
640   uintptr_t funcStart = _Unwind_GetRegionStart(context);
641   uintptr_t pcOffset = pc - funcStart;
642   struct OurExceptionType_t **classInfo = NULL;
643   
644   // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
645   //       dwarf emission
646   
647   // Parse LSDA header.
648   uint8_t lpStartEncoding = *lsda++;
649   
650   if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
651     readEncodedPointer(&lsda, lpStartEncoding); 
652   }
653   
654   uint8_t ttypeEncoding = *lsda++;
655   uintptr_t classInfoOffset;
656   
657   if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
658     // Calculate type info locations in emitted dwarf code which
659     // were flagged by type info arguments to llvm.eh.selector
660     // intrinsic
661     classInfoOffset = readULEB128(&lsda);
662     classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
663   }
664   
665   // Walk call-site table looking for range that 
666   // includes current PC. 
667   
668   uint8_t         callSiteEncoding = *lsda++;
669   uint32_t        callSiteTableLength = readULEB128(&lsda);
670   const uint8_t   *callSiteTableStart = lsda;
671   const uint8_t   *callSiteTableEnd = callSiteTableStart + 
672   callSiteTableLength;
673   const uint8_t   *actionTableStart = callSiteTableEnd;
674   const uint8_t   *callSitePtr = callSiteTableStart;
675   
676   bool foreignException = false;
677   
678   while (callSitePtr < callSiteTableEnd) {
679     uintptr_t start = readEncodedPointer(&callSitePtr, 
680                                          callSiteEncoding);
681     uintptr_t length = readEncodedPointer(&callSitePtr, 
682                                           callSiteEncoding);
683     uintptr_t landingPad = readEncodedPointer(&callSitePtr, 
684                                               callSiteEncoding);
685     
686     // Note: Action value
687     uintptr_t actionEntry = readULEB128(&callSitePtr);
688     
689     if (exceptionClass != ourBaseExceptionClass) {
690       // We have been notified of a foreign exception being thrown,
691       // and we therefore need to execute cleanup landing pads
692       actionEntry = 0;
693       foreignException = true;
694     }
695     
696     if (landingPad == 0) {
697 #ifdef DEBUG
698       fprintf(stderr,
699               "handleLsda(...): No landing pad found.\n");
700 #endif
701       
702       continue; // no landing pad for this entry
703     }
704     
705     if (actionEntry) {
706       actionEntry += ((uintptr_t) actionTableStart) - 1;
707     }
708     else {
709 #ifdef DEBUG
710       fprintf(stderr,
711               "handleLsda(...):No action table found.\n");
712 #endif
713     }
714     
715     bool exceptionMatched = false;
716     
717     if ((start <= pcOffset) && (pcOffset < (start + length))) {
718 #ifdef DEBUG
719       fprintf(stderr,
720               "handleLsda(...): Landing pad found.\n");
721 #endif
722       int64_t actionValue = 0;
723       
724       if (actionEntry) {
725         exceptionMatched = handleActionValue(&actionValue,
726                                              classInfo, 
727                                              actionEntry, 
728                                              exceptionClass, 
729                                              exceptionObject);
730       }
731       
732       if (!(actions & _UA_SEARCH_PHASE)) {
733 #ifdef DEBUG
734         fprintf(stderr,
735                 "handleLsda(...): installed landing pad "
736                 "context.\n");
737 #endif
738         
739         // Found landing pad for the PC.
740         // Set Instruction Pointer to so we re-enter function 
741         // at landing pad. The landing pad is created by the 
742         // compiler to take two parameters in registers.
743         _Unwind_SetGR(context, 
744                       __builtin_eh_return_data_regno(0), 
745                       (uintptr_t)exceptionObject);
746         
747         // Note: this virtual register directly corresponds
748         //       to the return of the llvm.eh.selector intrinsic
749         if (!actionEntry || !exceptionMatched) {
750           // We indicate cleanup only
751           _Unwind_SetGR(context, 
752                         __builtin_eh_return_data_regno(1), 
753                         0);
754         }
755         else {
756           // Matched type info index of llvm.eh.selector intrinsic
757           // passed here.
758           _Unwind_SetGR(context, 
759                         __builtin_eh_return_data_regno(1), 
760                         actionValue);
761         }
762         
763         // To execute landing pad set here
764         _Unwind_SetIP(context, funcStart + landingPad);
765         ret = _URC_INSTALL_CONTEXT;
766       }
767       else if (exceptionMatched) {
768 #ifdef DEBUG
769         fprintf(stderr,
770                 "handleLsda(...): setting handler found.\n");
771 #endif
772         ret = _URC_HANDLER_FOUND;
773       }
774       else {
775         // Note: Only non-clean up handlers are marked as
776         //       found. Otherwise the clean up handlers will be 
777         //       re-found and executed during the clean up 
778         //       phase.
779 #ifdef DEBUG
780         fprintf(stderr,
781                 "handleLsda(...): cleanup handler found.\n");
782 #endif
783       }
784       
785       break;
786     }
787   }
788   
789   return(ret);
790 }
791
792
793 /// This is the personality function which is embedded (dwarf emitted), in the
794 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
795 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
796 /// @param version unsupported (ignored), unwind version
797 /// @param _Unwind_Action actions minimally supported unwind stage 
798 ///        (forced specifically not supported)
799 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
800 ///        of thrown exception.
801 /// @param exceptionObject thrown _Unwind_Exception instance.
802 /// @param context unwind system context
803 /// @returns minimally supported unwinding control indicator 
804 _Unwind_Reason_Code ourPersonality(int version, 
805                                    _Unwind_Action actions,
806                                    uint64_t exceptionClass, 
807                                    struct _Unwind_Exception *exceptionObject,
808                                    _Unwind_Context_t context) {
809 #ifdef DEBUG
810   fprintf(stderr, 
811           "We are in ourPersonality(...):actions is <%d>.\n",
812           actions);
813   
814   if (actions & _UA_SEARCH_PHASE) {
815     fprintf(stderr, "ourPersonality(...):In search phase.\n");
816   }
817   else {
818     fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
819   }
820 #endif
821   
822   const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
823   
824 #ifdef DEBUG
825   fprintf(stderr, 
826           "ourPersonality(...):lsda = <%p>.\n",
827           lsda);
828 #endif
829   
830   // The real work of the personality function is captured here
831   return(handleLsda(version,
832                     lsda,
833                     actions,
834                     exceptionClass,
835                     exceptionObject,
836                     context));
837 }
838
839
840 /// Generates our _Unwind_Exception class from a given character array.
841 /// thereby handling arbitrary lengths (not in standard), and handling
842 /// embedded \0s.
843 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
844 /// @param classChars char array to encode. NULL values not checkedf
845 /// @param classCharsSize number of chars in classChars. Value is not checked.
846 /// @returns class value
847 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
848 {
849   uint64_t ret = classChars[0];
850   
851   for (unsigned i = 1; i < classCharsSize; ++i) {
852     ret <<= 8;
853     ret += classChars[i];
854   }
855   
856   return(ret);
857 }
858
859 } // extern "C"
860
861 //
862 // Runtime C Library functions End
863 //
864
865 //
866 // Code generation functions
867 //
868
869 /// Generates code to print given constant string
870 /// @param context llvm context
871 /// @param module code for module instance
872 /// @param builder builder instance
873 /// @param toPrint string to print
874 /// @param useGlobal A value of true (default) indicates a GlobalValue is 
875 ///        generated, and is used to hold the constant string. A value of 
876 ///        false indicates that the constant string will be stored on the 
877 ///        stack.
878 void generateStringPrint(llvm::LLVMContext &context, 
879                          llvm::Module &module,
880                          llvm::IRBuilder<> &builder, 
881                          std::string toPrint,
882                          bool useGlobal = true) {
883   llvm::Function *printFunct = module.getFunction("printStr");
884   
885   llvm::Value *stringVar;
886   llvm::Constant *stringConstant = 
887   llvm::ConstantArray::get(context, toPrint);
888   
889   if (useGlobal) {
890     // Note: Does not work without allocation
891     stringVar = 
892     new llvm::GlobalVariable(module, 
893                              stringConstant->getType(),
894                              true, 
895                              llvm::GlobalValue::LinkerPrivateLinkage, 
896                              stringConstant, 
897                              "");
898   }
899   else {
900     stringVar = builder.CreateAlloca(stringConstant->getType());
901     builder.CreateStore(stringConstant, stringVar);
902   }
903   
904   llvm::Value *cast = builder.CreatePointerCast(stringVar, 
905                                                 builder.getInt8PtrTy());
906   builder.CreateCall(printFunct, cast);
907 }
908
909
910 /// Generates code to print given runtime integer according to constant
911 /// string format, and a given print function.
912 /// @param context llvm context
913 /// @param module code for module instance
914 /// @param builder builder instance
915 /// @param printFunct function used to "print" integer
916 /// @param toPrint string to print
917 /// @param format printf like formating string for print
918 /// @param useGlobal A value of true (default) indicates a GlobalValue is 
919 ///        generated, and is used to hold the constant string. A value of 
920 ///        false indicates that the constant string will be stored on the 
921 ///        stack.
922 void generateIntegerPrint(llvm::LLVMContext &context, 
923                           llvm::Module &module,
924                           llvm::IRBuilder<> &builder, 
925                           llvm::Function &printFunct,
926                           llvm::Value &toPrint,
927                           std::string format, 
928                           bool useGlobal = true) {
929   llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
930   llvm::Value *stringVar;
931   
932   if (useGlobal) {
933     // Note: Does not seem to work without allocation
934     stringVar = 
935     new llvm::GlobalVariable(module, 
936                              stringConstant->getType(),
937                              true, 
938                              llvm::GlobalValue::LinkerPrivateLinkage, 
939                              stringConstant, 
940                              "");
941   }
942   else {
943     stringVar = builder.CreateAlloca(stringConstant->getType());
944     builder.CreateStore(stringConstant, stringVar);
945   }
946   
947   llvm::Value *cast = builder.CreateBitCast(stringVar, 
948                                             builder.getInt8PtrTy());
949   builder.CreateCall2(&printFunct, &toPrint, cast);
950 }
951
952
953 /// Generates code to handle finally block type semantics: always runs 
954 /// regardless of whether a thrown exception is passing through or the 
955 /// parent function is simply exiting. In addition to printing some state 
956 /// to stderr, this code will resume the exception handling--runs the 
957 /// unwind resume block, if the exception has not been previously caught 
958 /// by a catch clause, and will otherwise execute the end block (terminator 
959 /// block). In addition this function creates the corresponding function's 
960 /// stack storage for the exception pointer and catch flag status.
961 /// @param context llvm context
962 /// @param module code for module instance
963 /// @param builder builder instance
964 /// @param toAddTo parent function to add block to
965 /// @param blockName block name of new "finally" block.
966 /// @param functionId output id used for printing
967 /// @param terminatorBlock terminator "end" block
968 /// @param unwindResumeBlock unwind resume block
969 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
970 /// @param exceptionStorage reference to exception pointer storage
971 #ifndef OLD_EXC_SYSTEM
972 /// @param caughtResultStorage reference to landingpad result storage
973 #endif
974 /// @returns newly created block
975 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context, 
976                                             llvm::Module &module, 
977                                             llvm::IRBuilder<> &builder, 
978                                             llvm::Function &toAddTo,
979                                             std::string &blockName,
980                                             std::string &functionId,
981                                             llvm::BasicBlock &terminatorBlock,
982                                             llvm::BasicBlock &unwindResumeBlock,
983                                             llvm::Value **exceptionCaughtFlag,
984                                             llvm::Value **exceptionStorage
985 #ifndef OLD_EXC_SYSTEM
986                                             ,llvm::Value **caughtResultStorage
987 #endif
988                                             ) {
989   assert(exceptionCaughtFlag && 
990          "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
991          "is NULL");
992   assert(exceptionStorage && 
993          "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
994          "is NULL");
995
996 #ifndef OLD_EXC_SYSTEM
997   assert(caughtResultStorage && 
998          "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
999          "is NULL");
1000 #endif
1001   
1002   *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
1003                                          "exceptionCaught",
1004                                          ourExceptionNotThrownState->getType(),
1005                                          ourExceptionNotThrownState);
1006   
1007   llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
1008   *exceptionStorage = createEntryBlockAlloca(toAddTo,
1009                                              "exceptionStorage",
1010                                              exceptionStorageType,
1011                                              llvm::ConstantPointerNull::get(
1012                                                exceptionStorageType));
1013 #ifndef OLD_EXC_SYSTEM
1014   *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1015                                               "caughtResultStorage",
1016                                               ourCaughtResultType,
1017                                               llvm::ConstantAggregateZero::get(
1018                                                 ourCaughtResultType));
1019 #endif
1020   
1021   llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1022                                                    blockName,
1023                                                    &toAddTo);
1024   
1025   builder.SetInsertPoint(ret);
1026   
1027   std::ostringstream bufferToPrint;
1028   bufferToPrint << "Gen: Executing finally block "
1029     << blockName << " in " << functionId << "\n";
1030   generateStringPrint(context, 
1031                       module, 
1032                       builder, 
1033                       bufferToPrint.str(),
1034                       USE_GLOBAL_STR_CONSTS);
1035   
1036   llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1037                                                        *exceptionCaughtFlag), 
1038                                                      &terminatorBlock,
1039                                                      2);
1040   theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1041   theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1042   
1043   return(ret);
1044 }
1045
1046
1047 /// Generates catch block semantics which print a string to indicate type of
1048 /// catch executed, sets an exception caught flag, and executes passed in 
1049 /// end block (terminator block).
1050 /// @param context llvm context
1051 /// @param module code for module instance
1052 /// @param builder builder instance
1053 /// @param toAddTo parent function to add block to
1054 /// @param blockName block name of new "catch" block.
1055 /// @param functionId output id used for printing
1056 /// @param terminatorBlock terminator "end" block
1057 /// @param exceptionCaughtFlag exception caught/thrown status
1058 /// @returns newly created block
1059 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context, 
1060                                           llvm::Module &module, 
1061                                           llvm::IRBuilder<> &builder, 
1062                                           llvm::Function &toAddTo,
1063                                           std::string &blockName,
1064                                           std::string &functionId,
1065                                           llvm::BasicBlock &terminatorBlock,
1066                                           llvm::Value &exceptionCaughtFlag) {
1067   
1068   llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1069                                                    blockName,
1070                                                    &toAddTo);
1071   
1072   builder.SetInsertPoint(ret);
1073   
1074   std::ostringstream bufferToPrint;
1075   bufferToPrint << "Gen: Executing catch block "
1076   << blockName
1077   << " in "
1078   << functionId
1079   << std::endl;
1080   generateStringPrint(context, 
1081                       module, 
1082                       builder, 
1083                       bufferToPrint.str(),
1084                       USE_GLOBAL_STR_CONSTS);
1085   builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1086   builder.CreateBr(&terminatorBlock);
1087   
1088   return(ret);
1089 }
1090
1091
1092 /// Generates a function which invokes a function (toInvoke) and, whose 
1093 /// unwind block will "catch" the type info types correspondingly held in the 
1094 /// exceptionTypesToCatch argument. If the toInvoke function throws an 
1095 /// exception which does not match any type info types contained in 
1096 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume 
1097 /// with the raised exception. On the other hand the generated code will 
1098 /// normally exit if the toInvoke function does not throw an exception.
1099 /// The generated "finally" block is always run regardless of the cause of 
1100 /// the generated function exit.
1101 /// The generated function is returned after being verified.
1102 /// @param module code for module instance
1103 /// @param builder builder instance
1104 /// @param fpm a function pass manager holding optional IR to IR 
1105 ///        transformations
1106 /// @param toInvoke inner function to invoke
1107 /// @param ourId id used to printing purposes
1108 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1109 /// @param exceptionTypesToCatch array of type info types to "catch"
1110 /// @returns generated function
1111 static
1112 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module, 
1113                                              llvm::IRBuilder<> &builder, 
1114                                              llvm::FunctionPassManager &fpm,
1115                                              llvm::Function &toInvoke,
1116                                              std::string ourId,
1117                                              unsigned numExceptionsToCatch,
1118                                              unsigned exceptionTypesToCatch[]) {
1119   
1120   llvm::LLVMContext &context = module.getContext();
1121   llvm::Function *toPrint32Int = module.getFunction("print32Int");
1122   
1123   ArgTypes argTypes;
1124   argTypes.push_back(builder.getInt32Ty());
1125   
1126   ArgNames argNames;
1127   argNames.push_back("exceptTypeToThrow");
1128   
1129   llvm::Function *ret = createFunction(module, 
1130                                        builder.getVoidTy(),
1131                                        argTypes, 
1132                                        argNames, 
1133                                        ourId,
1134                                        llvm::Function::ExternalLinkage, 
1135                                        false, 
1136                                        false);
1137   
1138   // Block which calls invoke
1139   llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1140                                                           "entry", 
1141                                                           ret);
1142   // Normal block for invoke
1143   llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context, 
1144                                                            "normal", 
1145                                                            ret);
1146   // Unwind block for invoke
1147   llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context, 
1148                                                               "exception", 
1149                                                               ret);
1150   
1151   // Block which routes exception to correct catch handler block
1152   llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context, 
1153                                                              "exceptionRoute", 
1154                                                              ret);
1155   
1156   // Foreign exception handler
1157   llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context, 
1158                                                           "externalException", 
1159                                                           ret);
1160   
1161   // Block which calls _Unwind_Resume
1162   llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context, 
1163                                                                "unwindResume", 
1164                                                                ret);
1165   
1166   // Clean up block which delete exception if needed
1167   llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
1168   
1169   std::string nextName;
1170   std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1171   llvm::Value *exceptionCaughtFlag = NULL;
1172   llvm::Value *exceptionStorage = NULL;
1173 #ifndef OLD_EXC_SYSTEM
1174   llvm::Value *caughtResultStorage = NULL;
1175 #endif
1176   
1177   // Finally block which will branch to unwindResumeBlock if 
1178   // exception is not caught. Initializes/allocates stack locations.
1179   llvm::BasicBlock *finallyBlock = createFinallyBlock(context, 
1180                                                       module, 
1181                                                       builder, 
1182                                                       *ret, 
1183                                                       nextName = "finally", 
1184                                                       ourId,
1185                                                       *endBlock,
1186                                                       *unwindResumeBlock,
1187                                                       &exceptionCaughtFlag,
1188                                                       &exceptionStorage
1189 #ifndef OLD_EXC_SYSTEM
1190                                                       ,&caughtResultStorage
1191 #endif
1192                                                       );
1193   
1194   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1195     nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1196     
1197     // One catch block per type info to be caught
1198     catchBlocks[i] = createCatchBlock(context, 
1199                                       module, 
1200                                       builder, 
1201                                       *ret,
1202                                       nextName, 
1203                                       ourId,
1204                                       *finallyBlock,
1205                                       *exceptionCaughtFlag);
1206   }
1207   
1208   // Entry Block
1209   
1210   builder.SetInsertPoint(entryBlock);
1211   
1212   std::vector<llvm::Value*> args;
1213   args.push_back(namedValues["exceptTypeToThrow"]);
1214   builder.CreateInvoke(&toInvoke, 
1215                        normalBlock, 
1216                        exceptionBlock, 
1217                        args);
1218   
1219   // End Block
1220   
1221   builder.SetInsertPoint(endBlock);
1222   
1223   generateStringPrint(context, 
1224                       module,
1225                       builder, 
1226                       "Gen: In end block: exiting in " + ourId + ".\n",
1227                       USE_GLOBAL_STR_CONSTS);
1228   llvm::Function *deleteOurException = module.getFunction("deleteOurException");
1229   
1230   // Note: function handles NULL exceptions
1231   builder.CreateCall(deleteOurException, 
1232                      builder.CreateLoad(exceptionStorage));
1233   builder.CreateRetVoid();
1234   
1235   // Normal Block
1236   
1237   builder.SetInsertPoint(normalBlock);
1238   
1239   generateStringPrint(context, 
1240                       module,
1241                       builder, 
1242                       "Gen: No exception in " + ourId + "!\n",
1243                       USE_GLOBAL_STR_CONSTS);
1244   
1245   // Finally block is always called
1246   builder.CreateBr(finallyBlock);
1247   
1248   // Unwind Resume Block
1249   
1250   builder.SetInsertPoint(unwindResumeBlock);
1251   
1252   
1253 #ifndef OLD_EXC_SYSTEM
1254   builder.CreateResume(builder.CreateLoad(caughtResultStorage));
1255 #else
1256   llvm::Function *resumeOurException = module.getFunction("_Unwind_Resume");
1257   builder.CreateCall(resumeOurException, 
1258                      builder.CreateLoad(exceptionStorage));
1259   builder.CreateUnreachable();
1260 #endif
1261   
1262   // Exception Block
1263   
1264   builder.SetInsertPoint(exceptionBlock);
1265   
1266   llvm::Function *personality = module.getFunction("ourPersonality");
1267   
1268 #ifndef OLD_EXC_SYSTEM
1269   llvm::LandingPadInst *caughtResult = 
1270     builder.CreateLandingPad(ourCaughtResultType,
1271                              personality,
1272                              numExceptionsToCatch,
1273                              "landingPad");
1274
1275   caughtResult->setCleanup(true);
1276
1277   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1278     // Set up type infos to be caught
1279     caughtResult->addClause(module.getGlobalVariable(
1280                              ourTypeInfoNames[exceptionTypesToCatch[i]]));
1281   }
1282
1283   llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1284   llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
1285
1286   // FIXME: Redundant storage which, beyond utilizing value of 
1287   //        caughtResultStore for unwindException storage, may be alleviated 
1288   //        alltogether with a block rearrangement
1289   builder.CreateStore(caughtResult, caughtResultStorage);
1290   builder.CreateStore(unwindException, exceptionStorage);
1291   builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1292 #else
1293   llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1294
1295   // Retrieve thrown exception
1296   llvm::Value *unwindException = builder.CreateCall(ehException);
1297   
1298   // Store exception and flag
1299   builder.CreateStore(unwindException, exceptionStorage);
1300   builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1301   llvm::Value *functPtr = builder.CreatePointerCast(personality, 
1302                                                     builder.getInt8PtrTy());
1303   
1304   args.clear();
1305   args.push_back(unwindException);
1306   args.push_back(functPtr);
1307   
1308   // Note: Skipping index 0
1309   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1310     // Set up type infos to be caught
1311     args.push_back(module.getGlobalVariable(
1312                                   ourTypeInfoNames[exceptionTypesToCatch[i]]));
1313   }
1314   
1315   args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1316   
1317   llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1318   
1319   // Set up this exeption block as the landing pad which will handle
1320   // given type infos. See case Intrinsic::eh_selector in 
1321   // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1322   // implemented in FunctionLoweringInfo.cpp to see how the implementation
1323   // handles this call. This landing pad (this exception block), will be 
1324   // called either because it nees to cleanup (call finally) or a type 
1325   // info was found which matched the thrown exception.
1326   llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
1327 #endif
1328   
1329   // Retrieve exception_class member from thrown exception 
1330   // (_Unwind_Exception instance). This member tells us whether or not
1331   // the exception is foreign.
1332   llvm::Value *unwindExceptionClass = 
1333     builder.CreateLoad(builder.CreateStructGEP(
1334              builder.CreatePointerCast(unwindException, 
1335                                        ourUnwindExceptionType->getPointerTo()), 
1336                                                0));
1337   
1338   // Branch to the externalExceptionBlock if the exception is foreign or
1339   // to a catch router if not. Either way the finally block will be run.
1340   builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1341                             llvm::ConstantInt::get(builder.getInt64Ty(), 
1342                                                    ourBaseExceptionClass)),
1343                        exceptionRouteBlock,
1344                        externalExceptionBlock);
1345   
1346   // External Exception Block
1347   
1348   builder.SetInsertPoint(externalExceptionBlock);
1349   
1350   generateStringPrint(context, 
1351                       module,
1352                       builder, 
1353                       "Gen: Foreign exception received.\n",
1354                       USE_GLOBAL_STR_CONSTS);
1355   
1356   // Branch to the finally block
1357   builder.CreateBr(finallyBlock);
1358   
1359   // Exception Route Block
1360   
1361   builder.SetInsertPoint(exceptionRouteBlock);
1362   
1363   // Casts exception pointer (_Unwind_Exception instance) to parent 
1364   // (OurException instance).
1365   //
1366   // Note: ourBaseFromUnwindOffset is usually negative
1367   llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1368                                   builder.CreateConstGEP1_64(unwindException,
1369                                                        ourBaseFromUnwindOffset),
1370                                   ourExceptionType->getPointerTo());
1371   
1372   // Retrieve thrown exception type info type
1373   //
1374   // Note: Index is not relative to pointer but instead to structure
1375   //       unlike a true getelementptr (GEP) instruction
1376   typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1377   
1378   llvm::Value *typeInfoThrownType = 
1379   builder.CreateStructGEP(typeInfoThrown, 0);
1380   
1381   generateIntegerPrint(context, 
1382                        module,
1383                        builder, 
1384                        *toPrint32Int, 
1385                        *(builder.CreateLoad(typeInfoThrownType)),
1386                        "Gen: Exception type <%d> received (stack unwound) " 
1387                        " in " + 
1388                        ourId + 
1389                        ".\n",
1390                        USE_GLOBAL_STR_CONSTS);
1391   
1392   // Route to matched type info catch block or run cleanup finally block
1393   llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex, 
1394                                                           finallyBlock, 
1395                                                           numExceptionsToCatch);
1396   
1397   unsigned nextTypeToCatch;
1398   
1399   for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1400     nextTypeToCatch = i - 1;
1401     switchToCatchBlock->addCase(llvm::ConstantInt::get(
1402                                    llvm::Type::getInt32Ty(context), i),
1403                                 catchBlocks[nextTypeToCatch]);
1404   }
1405
1406 #ifdef OLD_EXC_SYSTEM
1407   // Must be run before verifier                                                
1408   UpgradeExceptionHandling(&module);
1409 #endif
1410
1411   
1412   llvm::verifyFunction(*ret);
1413   fpm.run(*ret);
1414   
1415   return(ret);
1416 }
1417
1418
1419 /// Generates function which throws either an exception matched to a runtime
1420 /// determined type info type (argument to generated function), or if this 
1421 /// runtime value matches nativeThrowType, throws a foreign exception by 
1422 /// calling nativeThrowFunct.
1423 /// @param module code for module instance
1424 /// @param builder builder instance
1425 /// @param fpm a function pass manager holding optional IR to IR 
1426 ///        transformations
1427 /// @param ourId id used to printing purposes
1428 /// @param nativeThrowType a runtime argument of this value results in
1429 ///        nativeThrowFunct being called to generate/throw exception.
1430 /// @param nativeThrowFunct function which will throw a foreign exception
1431 ///        if the above nativeThrowType matches generated function's arg.
1432 /// @returns generated function
1433 static
1434 llvm::Function *createThrowExceptionFunction(llvm::Module &module, 
1435                                              llvm::IRBuilder<> &builder, 
1436                                              llvm::FunctionPassManager &fpm,
1437                                              std::string ourId,
1438                                              int32_t nativeThrowType,
1439                                              llvm::Function &nativeThrowFunct) {
1440   llvm::LLVMContext &context = module.getContext();
1441   namedValues.clear();
1442   ArgTypes unwindArgTypes;
1443   unwindArgTypes.push_back(builder.getInt32Ty());
1444   ArgNames unwindArgNames;
1445   unwindArgNames.push_back("exceptTypeToThrow");
1446   
1447   llvm::Function *ret = createFunction(module,
1448                                        builder.getVoidTy(),
1449                                        unwindArgTypes,
1450                                        unwindArgNames,
1451                                        ourId,
1452                                        llvm::Function::ExternalLinkage,
1453                                        false,
1454                                        false);
1455   
1456   // Throws either one of our exception or a native C++ exception depending
1457   // on a runtime argument value containing a type info type.
1458   llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1459                                                           "entry", 
1460                                                           ret);
1461   // Throws a foreign exception
1462   llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1463                                                                 "nativeThrow", 
1464                                                                 ret);
1465   // Throws one of our Exceptions
1466   llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1467                                                              "generatedThrow", 
1468                                                              ret);
1469   // Retrieved runtime type info type to throw
1470   llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1471   
1472   // nativeThrowBlock block
1473   
1474   builder.SetInsertPoint(nativeThrowBlock);
1475   
1476   // Throws foreign exception
1477   builder.CreateCall(&nativeThrowFunct, exceptionType);
1478   builder.CreateUnreachable();
1479   
1480   // entry block
1481   
1482   builder.SetInsertPoint(entryBlock);
1483   
1484   llvm::Function *toPrint32Int = module.getFunction("print32Int");
1485   generateIntegerPrint(context, 
1486                        module,
1487                        builder, 
1488                        *toPrint32Int, 
1489                        *exceptionType, 
1490                        "\nGen: About to throw exception type <%d> in " + 
1491                        ourId + 
1492                        ".\n",
1493                        USE_GLOBAL_STR_CONSTS);
1494   
1495   // Switches on runtime type info type value to determine whether or not
1496   // a foreign exception is thrown. Defaults to throwing one of our 
1497   // generated exceptions.
1498   llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1499                                                      generatedThrowBlock,
1500                                                      1);
1501   
1502   theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context), 
1503                                             nativeThrowType),
1504                      nativeThrowBlock);
1505   
1506   // generatedThrow block
1507   
1508   builder.SetInsertPoint(generatedThrowBlock);
1509   
1510   llvm::Function *createOurException = module.getFunction("createOurException");
1511   llvm::Function *raiseOurException = module.getFunction(
1512                                         "_Unwind_RaiseException");
1513   
1514   // Creates exception to throw with runtime type info type.
1515   llvm::Value *exception = builder.CreateCall(createOurException, 
1516                                               namedValues["exceptTypeToThrow"]);
1517   
1518   // Throw generated Exception
1519   builder.CreateCall(raiseOurException, exception);
1520   builder.CreateUnreachable();
1521   
1522   llvm::verifyFunction(*ret);
1523   fpm.run(*ret);
1524   
1525   return(ret);
1526 }
1527
1528 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1529                                            llvm::Module &module, 
1530                                            llvm::IRBuilder<> &builder);
1531
1532 /// Creates test code by generating and organizing these functions into the 
1533 /// test case. The test case consists of an outer function setup to invoke
1534 /// an inner function within an environment having multiple catch and single 
1535 /// finally blocks. This inner function is also setup to invoke a throw
1536 /// function within an evironment similar in nature to the outer function's 
1537 /// catch and finally blocks. Each of these two functions catch mutually
1538 /// exclusive subsets (even or odd) of the type info types configured
1539 /// for this this. All generated functions have a runtime argument which
1540 /// holds a type info type to throw that each function takes and passes it
1541 /// to the inner one if such a inner function exists. This type info type is
1542 /// looked at by the generated throw function to see whether or not it should
1543 /// throw a generated exception with the same type info type, or instead call
1544 /// a supplied a function which in turn will throw a foreign exception.
1545 /// @param module code for module instance
1546 /// @param builder builder instance
1547 /// @param fpm a function pass manager holding optional IR to IR 
1548 ///        transformations
1549 /// @param nativeThrowFunctName name of external function which will throw
1550 ///        a foreign exception
1551 /// @returns outermost generated test function.
1552 llvm::Function *createUnwindExceptionTest(llvm::Module &module, 
1553                                           llvm::IRBuilder<> &builder, 
1554                                           llvm::FunctionPassManager &fpm,
1555                                           std::string nativeThrowFunctName) {
1556   // Number of type infos to generate
1557   unsigned numTypeInfos = 6;
1558   
1559   // Initialze intrisics and external functions to use along with exception
1560   // and type info globals.
1561   createStandardUtilityFunctions(numTypeInfos,
1562                                  module,
1563                                  builder);
1564   llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
1565   
1566   // Create exception throw function using the value ~0 to cause 
1567   // foreign exceptions to be thrown.
1568   llvm::Function *throwFunct = createThrowExceptionFunction(module,
1569                                                             builder,
1570                                                             fpm,
1571                                                             "throwFunct",
1572                                                             ~0,
1573                                                             *nativeThrowFunct);
1574   // Inner function will catch even type infos
1575   unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1576   size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) / 
1577                                     sizeof(unsigned);
1578   
1579   // Generate inner function.
1580   llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1581                                                     builder,
1582                                                     fpm,
1583                                                     *throwFunct,
1584                                                     "innerCatchFunct",
1585                                                     numExceptionTypesToCatch,
1586                                                     innerExceptionTypesToCatch);
1587   
1588   // Outer function will catch odd type infos
1589   unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1590   numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) / 
1591   sizeof(unsigned);
1592   
1593   // Generate outer function
1594   llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1595                                                     builder,
1596                                                     fpm,
1597                                                     *innerCatchFunct,
1598                                                     "outerCatchFunct",
1599                                                     numExceptionTypesToCatch,
1600                                                     outerExceptionTypesToCatch);
1601   
1602   // Return outer function to run
1603   return(outerCatchFunct);
1604 }
1605
1606
1607 /// Represents our foreign exceptions
1608 class OurCppRunException : public std::runtime_error {
1609 public:
1610   OurCppRunException(const std::string reason) :
1611   std::runtime_error(reason) {}
1612   
1613   OurCppRunException (const OurCppRunException &toCopy) :
1614   std::runtime_error(toCopy) {}
1615   
1616   OurCppRunException &operator = (const OurCppRunException &toCopy) {
1617     return(reinterpret_cast<OurCppRunException&>(
1618                                  std::runtime_error::operator=(toCopy)));
1619   }
1620   
1621   ~OurCppRunException (void) throw () {}
1622 };
1623
1624
1625 /// Throws foreign C++ exception.
1626 /// @param ignoreIt unused parameter that allows function to match implied
1627 ///        generated function contract.
1628 extern "C"
1629 void throwCppException (int32_t ignoreIt) {
1630   throw(OurCppRunException("thrown by throwCppException(...)"));
1631 }
1632
1633 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1634
1635 /// This is a test harness which runs test by executing generated 
1636 /// function with a type info type to throw. Harness wraps the execution
1637 /// of generated function in a C++ try catch clause.
1638 /// @param engine execution engine to use for executing generated function.
1639 ///        This demo program expects this to be a JIT instance for demo
1640 ///        purposes.
1641 /// @param function generated test function to run
1642 /// @param typeToThrow type info type of generated exception to throw, or
1643 ///        indicator to cause foreign exception to be thrown.
1644 static
1645 void runExceptionThrow(llvm::ExecutionEngine *engine, 
1646                        llvm::Function *function, 
1647                        int32_t typeToThrow) {
1648   
1649   // Find test's function pointer
1650   OurExceptionThrowFunctType functPtr = 
1651     reinterpret_cast<OurExceptionThrowFunctType>(
1652        reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1653   
1654   try {
1655     // Run test
1656     (*functPtr)(typeToThrow);
1657   }
1658   catch (OurCppRunException exc) {
1659     // Catch foreign C++ exception
1660     fprintf(stderr,
1661             "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1662             "with reason: %s.\n", 
1663             exc.what());
1664   }
1665   catch (...) {
1666     // Catch all exceptions including our generated ones. I'm not sure
1667     // why this latter functionality should work, as it seems that
1668     // our exceptions should be foreign to C++ (the _Unwind_Exception::
1669     // exception_class should be different from the one used by C++), and
1670     // therefore C++ should ignore the generated exceptions. 
1671     
1672     fprintf(stderr,
1673             "\nrunExceptionThrow(...):In C++ catch all.\n");
1674   }
1675 }
1676
1677 //
1678 // End test functions
1679 //
1680
1681 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1682
1683 /// This initialization routine creates type info globals and 
1684 /// adds external function declarations to module.
1685 /// @param numTypeInfos number of linear type info associated type info types
1686 ///        to create as GlobalVariable instances, starting with the value 1.
1687 /// @param module code for module instance
1688 /// @param builder builder instance
1689 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1690                                            llvm::Module &module, 
1691                                            llvm::IRBuilder<> &builder) {
1692   
1693   llvm::LLVMContext &context = module.getContext();
1694   
1695   // Exception initializations
1696   
1697   // Setup exception catch state
1698   ourExceptionNotThrownState = 
1699     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1700   ourExceptionThrownState = 
1701     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1702   ourExceptionCaughtState = 
1703     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1704   
1705   
1706   
1707   // Create our type info type
1708   ourTypeInfoType = llvm::StructType::get(context, 
1709                                           TypeArray(builder.getInt32Ty()));
1710
1711 #ifndef OLD_EXC_SYSTEM
1712
1713   llvm::Type *caughtResultFieldTypes[] = {
1714     builder.getInt8PtrTy(),
1715     builder.getInt32Ty()
1716   };
1717
1718   // Create our landingpad result type
1719   ourCaughtResultType = llvm::StructType::get(context,
1720                                             TypeArray(caughtResultFieldTypes));
1721
1722 #endif
1723
1724   // Create OurException type
1725   ourExceptionType = llvm::StructType::get(context, 
1726                                            TypeArray(ourTypeInfoType));
1727   
1728   // Create portion of _Unwind_Exception type
1729   //
1730   // Note: Declaring only a portion of the _Unwind_Exception struct.
1731   //       Does this cause problems?
1732   ourUnwindExceptionType =
1733     llvm::StructType::get(context, 
1734                     TypeArray(builder.getInt64Ty()));
1735
1736   struct OurBaseException_t dummyException;
1737   
1738   // Calculate offset of OurException::unwindException member.
1739   ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) - 
1740                             ((uintptr_t) &(dummyException.unwindException));
1741   
1742 #ifdef DEBUG
1743   fprintf(stderr,
1744           "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1745           "= %lld, sizeof(struct OurBaseException_t) - "
1746           "sizeof(struct _Unwind_Exception) = %lu.\n",
1747           ourBaseFromUnwindOffset,
1748           sizeof(struct OurBaseException_t) - 
1749           sizeof(struct _Unwind_Exception));
1750 #endif
1751   
1752   size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1753   
1754   // Create our _Unwind_Exception::exception_class value
1755   ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1756   
1757   // Type infos
1758   
1759   std::string baseStr = "typeInfo", typeInfoName;
1760   std::ostringstream typeInfoNameBuilder;
1761   std::vector<llvm::Constant*> structVals;
1762   
1763   llvm::Constant *nextStruct;
1764   llvm::GlobalVariable *nextGlobal = NULL;
1765   
1766   // Generate each type info
1767   //
1768   // Note: First type info is not used.
1769   for (unsigned i = 0; i <= numTypeInfos; ++i) {
1770     structVals.clear();
1771     structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1772     nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1773     
1774     typeInfoNameBuilder.str("");
1775     typeInfoNameBuilder << baseStr << i;
1776     typeInfoName = typeInfoNameBuilder.str();
1777     
1778     // Note: Does not seem to work without allocation
1779     nextGlobal = 
1780     new llvm::GlobalVariable(module, 
1781                              ourTypeInfoType, 
1782                              true, 
1783                              llvm::GlobalValue::ExternalLinkage, 
1784                              nextStruct, 
1785                              typeInfoName);
1786     
1787     ourTypeInfoNames.push_back(typeInfoName);
1788     ourTypeInfoNamesIndex[i] = typeInfoName;
1789   }
1790   
1791   ArgNames argNames;
1792   ArgTypes argTypes;
1793   llvm::Function *funct = NULL;
1794   
1795   // print32Int
1796   
1797   llvm::Type *retType = builder.getVoidTy();
1798   
1799   argTypes.clear();
1800   argTypes.push_back(builder.getInt32Ty());
1801   argTypes.push_back(builder.getInt8PtrTy());
1802   
1803   argNames.clear();
1804   
1805   createFunction(module, 
1806                  retType, 
1807                  argTypes, 
1808                  argNames, 
1809                  "print32Int", 
1810                  llvm::Function::ExternalLinkage, 
1811                  true, 
1812                  false);
1813   
1814   // print64Int
1815   
1816   retType = builder.getVoidTy();
1817   
1818   argTypes.clear();
1819   argTypes.push_back(builder.getInt64Ty());
1820   argTypes.push_back(builder.getInt8PtrTy());
1821   
1822   argNames.clear();
1823   
1824   createFunction(module, 
1825                  retType, 
1826                  argTypes, 
1827                  argNames, 
1828                  "print64Int", 
1829                  llvm::Function::ExternalLinkage, 
1830                  true, 
1831                  false);
1832   
1833   // printStr
1834   
1835   retType = builder.getVoidTy();
1836   
1837   argTypes.clear();
1838   argTypes.push_back(builder.getInt8PtrTy());
1839   
1840   argNames.clear();
1841   
1842   createFunction(module, 
1843                  retType, 
1844                  argTypes, 
1845                  argNames, 
1846                  "printStr", 
1847                  llvm::Function::ExternalLinkage, 
1848                  true, 
1849                  false);
1850   
1851   // throwCppException
1852   
1853   retType = builder.getVoidTy();
1854   
1855   argTypes.clear();
1856   argTypes.push_back(builder.getInt32Ty());
1857   
1858   argNames.clear();
1859   
1860   createFunction(module, 
1861                  retType, 
1862                  argTypes, 
1863                  argNames, 
1864                  "throwCppException", 
1865                  llvm::Function::ExternalLinkage, 
1866                  true, 
1867                  false);
1868   
1869   // deleteOurException
1870   
1871   retType = builder.getVoidTy();
1872   
1873   argTypes.clear();
1874   argTypes.push_back(builder.getInt8PtrTy());
1875   
1876   argNames.clear();
1877   
1878   createFunction(module, 
1879                  retType, 
1880                  argTypes, 
1881                  argNames, 
1882                  "deleteOurException", 
1883                  llvm::Function::ExternalLinkage, 
1884                  true, 
1885                  false);
1886   
1887   // createOurException
1888   
1889   retType = builder.getInt8PtrTy();
1890   
1891   argTypes.clear();
1892   argTypes.push_back(builder.getInt32Ty());
1893   
1894   argNames.clear();
1895   
1896   createFunction(module, 
1897                  retType, 
1898                  argTypes, 
1899                  argNames, 
1900                  "createOurException", 
1901                  llvm::Function::ExternalLinkage, 
1902                  true, 
1903                  false);
1904   
1905   // _Unwind_RaiseException
1906   
1907   retType = builder.getInt32Ty();
1908   
1909   argTypes.clear();
1910   argTypes.push_back(builder.getInt8PtrTy());
1911   
1912   argNames.clear();
1913   
1914   funct = createFunction(module, 
1915                          retType, 
1916                          argTypes, 
1917                          argNames, 
1918                          "_Unwind_RaiseException", 
1919                          llvm::Function::ExternalLinkage, 
1920                          true, 
1921                          false);
1922   
1923   funct->addFnAttr(llvm::Attribute::NoReturn);
1924   
1925   // _Unwind_Resume
1926   
1927   retType = builder.getInt32Ty();
1928   
1929   argTypes.clear();
1930   argTypes.push_back(builder.getInt8PtrTy());
1931   
1932   argNames.clear();
1933   
1934   funct = createFunction(module, 
1935                          retType, 
1936                          argTypes, 
1937                          argNames, 
1938                          "_Unwind_Resume", 
1939                          llvm::Function::ExternalLinkage, 
1940                          true, 
1941                          false);
1942   
1943   funct->addFnAttr(llvm::Attribute::NoReturn);
1944   
1945   // ourPersonality
1946   
1947   retType = builder.getInt32Ty();
1948   
1949   argTypes.clear();
1950   argTypes.push_back(builder.getInt32Ty());
1951   argTypes.push_back(builder.getInt32Ty());
1952   argTypes.push_back(builder.getInt64Ty());
1953   argTypes.push_back(builder.getInt8PtrTy());
1954   argTypes.push_back(builder.getInt8PtrTy());
1955   
1956   argNames.clear();
1957   
1958   createFunction(module, 
1959                  retType, 
1960                  argTypes, 
1961                  argNames, 
1962                  "ourPersonality", 
1963                  llvm::Function::ExternalLinkage, 
1964                  true, 
1965                  false);
1966   
1967   // llvm.eh.selector intrinsic
1968   
1969   getDeclaration(&module, llvm::Intrinsic::eh_selector);
1970   
1971   // llvm.eh.exception intrinsic
1972   
1973   getDeclaration(&module, llvm::Intrinsic::eh_exception);
1974   
1975   // llvm.eh.typeid.for intrinsic
1976   
1977   getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1978 }
1979
1980
1981 //===----------------------------------------------------------------------===//
1982 // Main test driver code.
1983 //===----------------------------------------------------------------------===//
1984
1985 /// Demo main routine which takes the type info types to throw. A test will
1986 /// be run for each given type info type. While type info types with the value 
1987 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1988 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1989 /// will result in exceptions which pass through to the test harness. All other
1990 /// type info types are not supported and could cause a crash.
1991 int main(int argc, char *argv[]) {
1992   if (argc == 1) {
1993     fprintf(stderr,
1994             "\nUsage: ExceptionDemo <exception type to throw> "
1995             "[<type 2>...<type n>].\n"
1996             "   Each type must have the value of 1 - 6 for "
1997             "generated exceptions to be caught;\n"
1998             "   the value -1 for foreign C++ exceptions to be "
1999             "generated and thrown;\n"
2000             "   or the values > 6 for exceptions to be ignored.\n"
2001             "\nTry: ExceptionDemo 2 3 7 -1\n"
2002             "   for a full test.\n\n");
2003     return(0);
2004   }
2005   
2006   // If not set, exception handling will not be turned on
2007   llvm::JITExceptionHandling = true;
2008   
2009   llvm::InitializeNativeTarget();
2010   llvm::LLVMContext &context = llvm::getGlobalContext();
2011   llvm::IRBuilder<> theBuilder(context);
2012   
2013   // Make the module, which holds all the code.
2014   llvm::Module *module = new llvm::Module("my cool jit", context);
2015   
2016   // Build engine with JIT
2017   llvm::EngineBuilder factory(module);
2018   factory.setEngineKind(llvm::EngineKind::JIT);
2019   factory.setAllocateGVsWithCode(false);
2020   llvm::ExecutionEngine *executionEngine = factory.create();
2021   
2022   {
2023     llvm::FunctionPassManager fpm(module);
2024     
2025     // Set up the optimizer pipeline.  
2026     // Start with registering info about how the
2027     // target lays out data structures.
2028     fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
2029     
2030     // Optimizations turned on
2031 #ifdef ADD_OPT_PASSES
2032     
2033     // Basic AliasAnslysis support for GVN.
2034     fpm.add(llvm::createBasicAliasAnalysisPass());
2035     
2036     // Promote allocas to registers.
2037     fpm.add(llvm::createPromoteMemoryToRegisterPass());
2038     
2039     // Do simple "peephole" optimizations and bit-twiddling optzns.
2040     fpm.add(llvm::createInstructionCombiningPass());
2041     
2042     // Reassociate expressions.
2043     fpm.add(llvm::createReassociatePass());
2044     
2045     // Eliminate Common SubExpressions.
2046     fpm.add(llvm::createGVNPass());
2047     
2048     // Simplify the control flow graph (deleting unreachable 
2049     // blocks, etc).
2050     fpm.add(llvm::createCFGSimplificationPass());
2051 #endif  // ADD_OPT_PASSES
2052     
2053     fpm.doInitialization();
2054     
2055     // Generate test code using function throwCppException(...) as
2056     // the function which throws foreign exceptions.
2057     llvm::Function *toRun = 
2058     createUnwindExceptionTest(*module, 
2059                               theBuilder, 
2060                               fpm,
2061                               "throwCppException");
2062     
2063     fprintf(stderr, "\nBegin module dump:\n\n");
2064     
2065     module->dump();
2066     
2067     fprintf(stderr, "\nEnd module dump:\n");
2068     
2069     fprintf(stderr, "\n\nBegin Test:\n");
2070     
2071     for (int i = 1; i < argc; ++i) {
2072       // Run test for each argument whose value is the exception
2073       // type to throw.
2074       runExceptionThrow(executionEngine, 
2075                         toRun, 
2076                         (unsigned) strtoul(argv[i], NULL, 10));
2077     }
2078     
2079     fprintf(stderr, "\nEnd Test:\n\n");
2080   } 
2081   
2082   delete executionEngine;
2083   
2084   return 0;
2085 }
2086