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