blob: c2e012c32a25e5b2463fb9c9e45d75504f1be796 [file] [log] [blame]
Chris Lattner626ab1c2011-04-08 18:02:51 +00001//===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002//
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//
Chris Lattner626ab1c2011-04-08 18:02:51 +00008//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00009//
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
Garrison Venn113aa862011-09-28 10:53:56 +000043// type info type of 7 is explained by: example in rules 1.6.4 in
44// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
Garrison Venna2c2f1a2010-02-09 23:22:43 +000045//
46// This code uses code from the llvm compiler-rt project and the llvm
47// Kaleidoscope project.
48//
Chris Lattner626ab1c2011-04-08 18:02:51 +000049//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +000050
51#include "llvm/LLVMContext.h"
52#include "llvm/DerivedTypes.h"
53#include "llvm/ExecutionEngine/ExecutionEngine.h"
54#include "llvm/ExecutionEngine/JIT.h"
55#include "llvm/Module.h"
56#include "llvm/PassManager.h"
57#include "llvm/Intrinsics.h"
58#include "llvm/Analysis/Verifier.h"
59#include "llvm/Target/TargetData.h"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000060#include "llvm/Target/TargetOptions.h"
61#include "llvm/Transforms/Scalar.h"
62#include "llvm/Support/IRBuilder.h"
63#include "llvm/Support/Dwarf.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000064#include "llvm/Support/TargetSelect.h"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000065
Garrison Venn18bba842011-04-12 12:30:10 +000066// FIXME: Although all systems tested with (Linux, OS X), do not need this
67// header file included. A user on ubuntu reported, undefined symbols
68// for stderr, and fprintf, and the addition of this include fixed the
69// issue for them. Given that LLVM's best practices include the goal
70// of reducing the number of redundant header files included, the
71// correct solution would be to find out why these symbols are not
72// defined for the system in question, and fix the issue by finding out
73// which LLVM header file, if any, would include these symbols.
Garrison Venn2a7d4ad2011-04-11 19:52:49 +000074#include <cstdio>
Garrison Venn18bba842011-04-12 12:30:10 +000075
Garrison Venna2c2f1a2010-02-09 23:22:43 +000076#include <sstream>
Garrison Venna2c2f1a2010-02-09 23:22:43 +000077#include <stdexcept>
78
79
80#ifndef USE_GLOBAL_STR_CONSTS
81#define USE_GLOBAL_STR_CONSTS true
82#endif
83
84// System C++ ABI unwind types from:
Garrison Venn113aa862011-09-28 10:53:56 +000085// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
Garrison Venna2c2f1a2010-02-09 23:22:43 +000086
87extern "C" {
Chris Lattner626ab1c2011-04-08 18:02:51 +000088
89 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +000090 _URC_NO_REASON = 0,
91 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
92 _URC_FATAL_PHASE2_ERROR = 2,
93 _URC_FATAL_PHASE1_ERROR = 3,
94 _URC_NORMAL_STOP = 4,
95 _URC_END_OF_STACK = 5,
96 _URC_HANDLER_FOUND = 6,
97 _URC_INSTALL_CONTEXT = 7,
98 _URC_CONTINUE_UNWIND = 8
Chris Lattner626ab1c2011-04-08 18:02:51 +000099 } _Unwind_Reason_Code;
100
101 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000102 _UA_SEARCH_PHASE = 1,
103 _UA_CLEANUP_PHASE = 2,
104 _UA_HANDLER_FRAME = 4,
105 _UA_FORCE_UNWIND = 8,
106 _UA_END_OF_STACK = 16
Chris Lattner626ab1c2011-04-08 18:02:51 +0000107 } _Unwind_Action;
108
109 struct _Unwind_Exception;
110
111 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
112 struct _Unwind_Exception *);
113
114 struct _Unwind_Exception {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000115 uint64_t exception_class;
116 _Unwind_Exception_Cleanup_Fn exception_cleanup;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000117
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000118 uintptr_t private_1;
119 uintptr_t private_2;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000120
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000121 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
122 // Taking that literally does not make much sense generically. Instead
123 // we provide the maximum alignment required by any type for the machine.
Chris Lattner626ab1c2011-04-08 18:02:51 +0000124 } __attribute__((__aligned__));
125
126 struct _Unwind_Context;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000127 typedef struct _Unwind_Context *_Unwind_Context_t;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000128
Garrison Venn64cfcef2011-04-10 14:06:52 +0000129 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000130 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
131 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
132 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
133 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
134 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
135
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000136} // extern "C"
137
138//
139// Example types
140//
141
142/// This is our simplistic type info
143struct OurExceptionType_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000144 /// type info type
145 int type;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000146};
147
148
149/// This is our Exception class which relies on a negative offset to calculate
150/// pointers to its instances from pointers to its unwindException member.
151///
152/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
153/// on a double word boundary. This is necessary to match the standard:
154/// http://refspecs.freestandards.org/abi-eh-1.21.html
155struct OurBaseException_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000156 struct OurExceptionType_t type;
157
158 // Note: This is properly aligned in unwind.h
159 struct _Unwind_Exception unwindException;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000160};
161
162
163// Note: Not needed since we are C++
164typedef struct OurBaseException_t OurException;
165typedef struct _Unwind_Exception OurUnwindException;
166
167//
168// Various globals used to support typeinfo and generatted exceptions in
169// general
170//
171
172static std::map<std::string, llvm::Value*> namedValues;
173
174int64_t ourBaseFromUnwindOffset;
175
176const unsigned char ourBaseExcpClassChars[] =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000177{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000178
179
180static uint64_t ourBaseExceptionClass = 0;
181
182static std::vector<std::string> ourTypeInfoNames;
183static std::map<int, std::string> ourTypeInfoNamesIndex;
184
Garrison Venn64cfcef2011-04-10 14:06:52 +0000185static llvm::StructType *ourTypeInfoType;
Garrison Venn85500712011-09-22 15:45:14 +0000186static llvm::StructType *ourCaughtResultType;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000187static llvm::StructType *ourExceptionType;
188static llvm::StructType *ourUnwindExceptionType;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000189
Garrison Venn64cfcef2011-04-10 14:06:52 +0000190static llvm::ConstantInt *ourExceptionNotThrownState;
191static llvm::ConstantInt *ourExceptionThrownState;
192static llvm::ConstantInt *ourExceptionCaughtState;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000193
194typedef std::vector<std::string> ArgNames;
Garrison Venn6e6cdd02011-07-11 16:31:53 +0000195typedef std::vector<llvm::Type*> ArgTypes;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000196
197//
198// Code Generation Utilities
199//
200
201/// Utility used to create a function, both declarations and definitions
202/// @param module for module instance
203/// @param retType function return type
204/// @param theArgTypes function's ordered argument types
205/// @param theArgNames function's ordered arguments needed if use of this
206/// function corresponds to a function definition. Use empty
207/// aggregate for function declarations.
208/// @param functName function name
209/// @param linkage function linkage
210/// @param declarationOnly for function declarations
211/// @param isVarArg function uses vararg arguments
212/// @returns function instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000213llvm::Function *createFunction(llvm::Module &module,
Chris Lattner77613d42011-07-18 04:52:09 +0000214 llvm::Type *retType,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000215 const ArgTypes &theArgTypes,
216 const ArgNames &theArgNames,
217 const std::string &functName,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000218 llvm::GlobalValue::LinkageTypes linkage,
219 bool declarationOnly,
220 bool isVarArg) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000221 llvm::FunctionType *functType =
222 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
223 llvm::Function *ret =
224 llvm::Function::Create(functType, linkage, functName, &module);
225 if (!ret || declarationOnly)
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000226 return(ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000227
228 namedValues.clear();
229 unsigned i = 0;
230 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
231 i != theArgNames.size();
232 ++argIndex, ++i) {
233
234 argIndex->setName(theArgNames[i]);
235 namedValues[theArgNames[i]] = argIndex;
236 }
237
238 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000239}
240
241
242/// Create an alloca instruction in the entry block of
243/// the parent function. This is used for mutable variables etc.
244/// @param function parent instance
245/// @param varName stack variable name
246/// @param type stack variable type
247/// @param initWith optional constant initialization value
248/// @returns AllocaInst instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000249static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000250 const std::string &varName,
Chris Lattner77613d42011-07-18 04:52:09 +0000251 llvm::Type *type,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000252 llvm::Constant *initWith = 0) {
253 llvm::BasicBlock &block = function.getEntryBlock();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000254 llvm::IRBuilder<> tmp(&block, block.begin());
Garrison Venn64cfcef2011-04-10 14:06:52 +0000255 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000256
257 if (initWith)
258 tmp.CreateStore(initWith, ret);
259
260 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000261}
262
263
264//
265// Code Generation Utilities End
266//
267
268//
269// Runtime C Library functions
270//
271
272// Note: using an extern "C" block so that static functions can be used
273extern "C" {
274
275// Note: Better ways to decide on bit width
276//
277/// Prints a 32 bit number, according to the format, to stderr.
278/// @param intToPrint integer to print
279/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000280void print32Int(int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000281 if (format) {
282 // Note: No NULL check
283 fprintf(stderr, format, intToPrint);
284 }
285 else {
286 // Note: No NULL check
287 fprintf(stderr, "::print32Int(...):NULL arg.\n");
288 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000289}
290
291
292// Note: Better ways to decide on bit width
293//
294/// Prints a 64 bit number, according to the format, to stderr.
295/// @param intToPrint integer to print
296/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000297void print64Int(long int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000298 if (format) {
299 // Note: No NULL check
300 fprintf(stderr, format, intToPrint);
301 }
302 else {
303 // Note: No NULL check
304 fprintf(stderr, "::print64Int(...):NULL arg.\n");
305 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000306}
307
308
309/// Prints a C string to stderr
310/// @param toPrint string to print
Garrison Venn64cfcef2011-04-10 14:06:52 +0000311void printStr(char *toPrint) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000312 if (toPrint) {
313 fprintf(stderr, "%s", toPrint);
314 }
315 else {
316 fprintf(stderr, "::printStr(...):NULL arg.\n");
317 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000318}
319
320
321/// Deletes the true previosly allocated exception whose address
322/// is calculated from the supplied OurBaseException_t::unwindException
323/// member address. Handles (ignores), NULL pointers.
324/// @param expToDelete exception to delete
Garrison Venn64cfcef2011-04-10 14:06:52 +0000325void deleteOurException(OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000326#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000327 fprintf(stderr,
328 "deleteOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000329#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000330
331 if (expToDelete &&
332 (expToDelete->exception_class == ourBaseExceptionClass)) {
333
334 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
335 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000336}
337
338
339/// This function is the struct _Unwind_Exception API mandated delete function
340/// used by foreign exception handlers when deleting our exception
341/// (OurException), instances.
342/// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
343/// @unlink
344/// @param expToDelete exception instance to delete
345void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000346 OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000347#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000348 fprintf(stderr,
349 "deleteFromUnwindOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000350#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000351
352 deleteOurException(expToDelete);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000353}
354
355
356/// Creates (allocates on the heap), an exception (OurException instance),
357/// of the supplied type info type.
358/// @param type type info type
Garrison Venn64cfcef2011-04-10 14:06:52 +0000359OurUnwindException *createOurException(int type) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000360 size_t size = sizeof(OurException);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000361 OurException *ret = (OurException*) memset(malloc(size), 0, size);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000362 (ret->type).type = type;
363 (ret->unwindException).exception_class = ourBaseExceptionClass;
364 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
365
366 return(&(ret->unwindException));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000367}
368
369
370/// Read a uleb128 encoded value and advance pointer
371/// See Variable Length Data in:
372/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
373/// @param data reference variable holding memory pointer to decode from
374/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000375static uintptr_t readULEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000376 uintptr_t result = 0;
377 uintptr_t shift = 0;
378 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000379 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000380
381 do {
382 byte = *p++;
383 result |= (byte & 0x7f) << shift;
384 shift += 7;
385 }
386 while (byte & 0x80);
387
388 *data = p;
389
390 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000391}
392
393
394/// Read a sleb128 encoded value and advance pointer
395/// See Variable Length Data in:
396/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
397/// @param data reference variable holding memory pointer to decode from
398/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000399static uintptr_t readSLEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000400 uintptr_t result = 0;
401 uintptr_t shift = 0;
402 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000403 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000404
405 do {
406 byte = *p++;
407 result |= (byte & 0x7f) << shift;
408 shift += 7;
409 }
410 while (byte & 0x80);
411
412 *data = p;
413
414 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
415 result |= (~0 << shift);
416 }
417
418 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000419}
420
421
422/// Read a pointer encoded value and advance pointer
423/// See Variable Length Data in:
424/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
425/// @param data reference variable holding memory pointer to decode from
426/// @param encoding dwarf encoding type
427/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000428static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000429 uintptr_t result = 0;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000430 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000431
432 if (encoding == llvm::dwarf::DW_EH_PE_omit)
433 return(result);
434
435 // first get value
436 switch (encoding & 0x0F) {
437 case llvm::dwarf::DW_EH_PE_absptr:
438 result = *((uintptr_t*)p);
439 p += sizeof(uintptr_t);
440 break;
441 case llvm::dwarf::DW_EH_PE_uleb128:
442 result = readULEB128(&p);
443 break;
444 // Note: This case has not been tested
445 case llvm::dwarf::DW_EH_PE_sleb128:
446 result = readSLEB128(&p);
447 break;
448 case llvm::dwarf::DW_EH_PE_udata2:
449 result = *((uint16_t*)p);
450 p += sizeof(uint16_t);
451 break;
452 case llvm::dwarf::DW_EH_PE_udata4:
453 result = *((uint32_t*)p);
454 p += sizeof(uint32_t);
455 break;
456 case llvm::dwarf::DW_EH_PE_udata8:
457 result = *((uint64_t*)p);
458 p += sizeof(uint64_t);
459 break;
460 case llvm::dwarf::DW_EH_PE_sdata2:
461 result = *((int16_t*)p);
462 p += sizeof(int16_t);
463 break;
464 case llvm::dwarf::DW_EH_PE_sdata4:
465 result = *((int32_t*)p);
466 p += sizeof(int32_t);
467 break;
468 case llvm::dwarf::DW_EH_PE_sdata8:
469 result = *((int64_t*)p);
470 p += sizeof(int64_t);
471 break;
472 default:
473 // not supported
474 abort();
475 break;
476 }
477
478 // then add relative offset
479 switch (encoding & 0x70) {
480 case llvm::dwarf::DW_EH_PE_absptr:
481 // do nothing
482 break;
483 case llvm::dwarf::DW_EH_PE_pcrel:
484 result += (uintptr_t)(*data);
485 break;
486 case llvm::dwarf::DW_EH_PE_textrel:
487 case llvm::dwarf::DW_EH_PE_datarel:
488 case llvm::dwarf::DW_EH_PE_funcrel:
489 case llvm::dwarf::DW_EH_PE_aligned:
490 default:
491 // not supported
492 abort();
493 break;
494 }
495
496 // then apply indirection
497 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
498 result = *((uintptr_t*)result);
499 }
500
501 *data = p;
502
503 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000504}
505
506
507/// Deals with Dwarf actions matching our type infos
508/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
509/// action matches the supplied exception type. If such a match succeeds,
510/// the resultAction argument will be set with > 0 index value. Only
511/// corresponding llvm.eh.selector type info arguments, cleanup arguments
512/// are supported. Filters are not supported.
513/// See Variable Length Data in:
514/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
515/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
516/// @param resultAction reference variable which will be set with result
517/// @param classInfo our array of type info pointers (to globals)
518/// @param actionEntry index into above type info array or 0 (clean up).
519/// We do not support filters.
520/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
521/// of thrown exception.
522/// @param exceptionObject thrown _Unwind_Exception instance.
523/// @returns whether or not a type info was found. False is returned if only
524/// a cleanup was found
525static bool handleActionValue(int64_t *resultAction,
526 struct OurExceptionType_t **classInfo,
527 uintptr_t actionEntry,
528 uint64_t exceptionClass,
529 struct _Unwind_Exception *exceptionObject) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000530 bool ret = false;
531
532 if (!resultAction ||
533 !exceptionObject ||
534 (exceptionClass != ourBaseExceptionClass))
535 return(ret);
536
Garrison Venn64cfcef2011-04-10 14:06:52 +0000537 struct OurBaseException_t *excp = (struct OurBaseException_t*)
Chris Lattner626ab1c2011-04-08 18:02:51 +0000538 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
539 struct OurExceptionType_t *excpType = &(excp->type);
540 int type = excpType->type;
541
542#ifdef DEBUG
543 fprintf(stderr,
544 "handleActionValue(...): exceptionObject = <%p>, "
545 "excp = <%p>.\n",
546 exceptionObject,
547 excp);
548#endif
549
550 const uint8_t *actionPos = (uint8_t*) actionEntry,
551 *tempActionPos;
552 int64_t typeOffset = 0,
553 actionOffset;
554
555 for (int i = 0; true; ++i) {
556 // Each emitted dwarf action corresponds to a 2 tuple of
557 // type info address offset, and action offset to the next
558 // emitted action.
559 typeOffset = readSLEB128(&actionPos);
560 tempActionPos = actionPos;
561 actionOffset = readSLEB128(&tempActionPos);
562
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000563#ifdef DEBUG
564 fprintf(stderr,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000565 "handleActionValue(...):typeOffset: <%lld>, "
566 "actionOffset: <%lld>.\n",
567 typeOffset,
568 actionOffset);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000569#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000570 assert((typeOffset >= 0) &&
571 "handleActionValue(...):filters are not supported.");
572
573 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
574 // argument has been matched.
575 if ((typeOffset > 0) &&
576 (type == (classInfo[-typeOffset])->type)) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000577#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000578 fprintf(stderr,
579 "handleActionValue(...):actionValue <%d> found.\n",
580 i);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000581#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000582 *resultAction = i + 1;
583 ret = true;
584 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000585 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000586
587#ifdef DEBUG
588 fprintf(stderr,
589 "handleActionValue(...):actionValue not found.\n");
590#endif
591 if (!actionOffset)
592 break;
593
594 actionPos += actionOffset;
595 }
596
597 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000598}
599
600
601/// Deals with the Language specific data portion of the emitted dwarf code.
602/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
603/// @param version unsupported (ignored), unwind version
604/// @param lsda language specific data area
605/// @param _Unwind_Action actions minimally supported unwind stage
606/// (forced specifically not supported)
607/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
608/// of thrown exception.
609/// @param exceptionObject thrown _Unwind_Exception instance.
610/// @param context unwind system context
611/// @returns minimally supported unwinding control indicator
612static _Unwind_Reason_Code handleLsda(int version,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000613 const uint8_t *lsda,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000614 _Unwind_Action actions,
615 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000616 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000617 _Unwind_Context_t context) {
618 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
619
620 if (!lsda)
621 return(ret);
622
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000623#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000624 fprintf(stderr,
625 "handleLsda(...):lsda is non-zero.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000626#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000627
628 // Get the current instruction pointer and offset it before next
629 // instruction in the current frame which threw the exception.
630 uintptr_t pc = _Unwind_GetIP(context)-1;
631
632 // Get beginning current frame's code (as defined by the
633 // emitted dwarf code)
634 uintptr_t funcStart = _Unwind_GetRegionStart(context);
635 uintptr_t pcOffset = pc - funcStart;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000636 struct OurExceptionType_t **classInfo = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000637
638 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
639 // dwarf emission
640
641 // Parse LSDA header.
642 uint8_t lpStartEncoding = *lsda++;
643
644 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
645 readEncodedPointer(&lsda, lpStartEncoding);
646 }
647
648 uint8_t ttypeEncoding = *lsda++;
649 uintptr_t classInfoOffset;
650
651 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
652 // Calculate type info locations in emitted dwarf code which
653 // were flagged by type info arguments to llvm.eh.selector
654 // intrinsic
655 classInfoOffset = readULEB128(&lsda);
656 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
657 }
658
659 // Walk call-site table looking for range that
660 // includes current PC.
661
662 uint8_t callSiteEncoding = *lsda++;
663 uint32_t callSiteTableLength = readULEB128(&lsda);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000664 const uint8_t *callSiteTableStart = lsda;
665 const uint8_t *callSiteTableEnd = callSiteTableStart +
Chris Lattner626ab1c2011-04-08 18:02:51 +0000666 callSiteTableLength;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000667 const uint8_t *actionTableStart = callSiteTableEnd;
668 const uint8_t *callSitePtr = callSiteTableStart;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000669
670 bool foreignException = false;
671
672 while (callSitePtr < callSiteTableEnd) {
673 uintptr_t start = readEncodedPointer(&callSitePtr,
674 callSiteEncoding);
675 uintptr_t length = readEncodedPointer(&callSitePtr,
676 callSiteEncoding);
677 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000678 callSiteEncoding);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000679
680 // Note: Action value
681 uintptr_t actionEntry = readULEB128(&callSitePtr);
682
683 if (exceptionClass != ourBaseExceptionClass) {
684 // We have been notified of a foreign exception being thrown,
685 // and we therefore need to execute cleanup landing pads
686 actionEntry = 0;
687 foreignException = true;
688 }
689
690 if (landingPad == 0) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000691#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000692 fprintf(stderr,
693 "handleLsda(...): No landing pad found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000694#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000695
696 continue; // no landing pad for this entry
697 }
698
699 if (actionEntry) {
700 actionEntry += ((uintptr_t) actionTableStart) - 1;
701 }
702 else {
703#ifdef DEBUG
704 fprintf(stderr,
705 "handleLsda(...):No action table found.\n");
706#endif
707 }
708
709 bool exceptionMatched = false;
710
711 if ((start <= pcOffset) && (pcOffset < (start + length))) {
712#ifdef DEBUG
713 fprintf(stderr,
714 "handleLsda(...): Landing pad found.\n");
715#endif
716 int64_t actionValue = 0;
717
718 if (actionEntry) {
Garrison Venn64cfcef2011-04-10 14:06:52 +0000719 exceptionMatched = handleActionValue(&actionValue,
720 classInfo,
721 actionEntry,
722 exceptionClass,
723 exceptionObject);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000724 }
725
726 if (!(actions & _UA_SEARCH_PHASE)) {
727#ifdef DEBUG
728 fprintf(stderr,
729 "handleLsda(...): installed landing pad "
730 "context.\n");
731#endif
732
733 // Found landing pad for the PC.
734 // Set Instruction Pointer to so we re-enter function
735 // at landing pad. The landing pad is created by the
736 // compiler to take two parameters in registers.
737 _Unwind_SetGR(context,
738 __builtin_eh_return_data_regno(0),
739 (uintptr_t)exceptionObject);
740
741 // Note: this virtual register directly corresponds
742 // to the return of the llvm.eh.selector intrinsic
743 if (!actionEntry || !exceptionMatched) {
744 // We indicate cleanup only
745 _Unwind_SetGR(context,
746 __builtin_eh_return_data_regno(1),
747 0);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000748 }
749 else {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000750 // Matched type info index of llvm.eh.selector intrinsic
751 // passed here.
752 _Unwind_SetGR(context,
753 __builtin_eh_return_data_regno(1),
754 actionValue);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000755 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000756
757 // To execute landing pad set here
758 _Unwind_SetIP(context, funcStart + landingPad);
759 ret = _URC_INSTALL_CONTEXT;
760 }
761 else if (exceptionMatched) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000762#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000763 fprintf(stderr,
764 "handleLsda(...): setting handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000765#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000766 ret = _URC_HANDLER_FOUND;
767 }
768 else {
769 // Note: Only non-clean up handlers are marked as
770 // found. Otherwise the clean up handlers will be
771 // re-found and executed during the clean up
772 // phase.
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000773#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000774 fprintf(stderr,
775 "handleLsda(...): cleanup handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000776#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000777 }
778
779 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000780 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000781 }
782
783 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000784}
785
786
787/// This is the personality function which is embedded (dwarf emitted), in the
788/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
789/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
790/// @param version unsupported (ignored), unwind version
791/// @param _Unwind_Action actions minimally supported unwind stage
792/// (forced specifically not supported)
793/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
794/// of thrown exception.
795/// @param exceptionObject thrown _Unwind_Exception instance.
796/// @param context unwind system context
797/// @returns minimally supported unwinding control indicator
798_Unwind_Reason_Code ourPersonality(int version,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000799 _Unwind_Action actions,
800 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000801 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000802 _Unwind_Context_t context) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000803#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000804 fprintf(stderr,
805 "We are in ourPersonality(...):actions is <%d>.\n",
806 actions);
807
808 if (actions & _UA_SEARCH_PHASE) {
809 fprintf(stderr, "ourPersonality(...):In search phase.\n");
810 }
811 else {
812 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
813 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000814#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000815
Garrison Venn64cfcef2011-04-10 14:06:52 +0000816 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000817
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000818#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000819 fprintf(stderr,
820 "ourPersonality(...):lsda = <%p>.\n",
821 lsda);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000822#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000823
824 // The real work of the personality function is captured here
825 return(handleLsda(version,
826 lsda,
827 actions,
828 exceptionClass,
829 exceptionObject,
830 context));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000831}
832
833
834/// Generates our _Unwind_Exception class from a given character array.
835/// thereby handling arbitrary lengths (not in standard), and handling
836/// embedded \0s.
837/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
838/// @param classChars char array to encode. NULL values not checkedf
839/// @param classCharsSize number of chars in classChars. Value is not checked.
840/// @returns class value
841uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
842{
Chris Lattner626ab1c2011-04-08 18:02:51 +0000843 uint64_t ret = classChars[0];
844
845 for (unsigned i = 1; i < classCharsSize; ++i) {
846 ret <<= 8;
847 ret += classChars[i];
848 }
849
850 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000851}
852
853} // extern "C"
854
855//
856// Runtime C Library functions End
857//
858
859//
860// Code generation functions
861//
862
863/// Generates code to print given constant string
864/// @param context llvm context
865/// @param module code for module instance
866/// @param builder builder instance
867/// @param toPrint string to print
868/// @param useGlobal A value of true (default) indicates a GlobalValue is
869/// generated, and is used to hold the constant string. A value of
870/// false indicates that the constant string will be stored on the
871/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000872void generateStringPrint(llvm::LLVMContext &context,
873 llvm::Module &module,
874 llvm::IRBuilder<> &builder,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000875 std::string toPrint,
876 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000877 llvm::Function *printFunct = module.getFunction("printStr");
878
879 llvm::Value *stringVar;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000880 llvm::Constant *stringConstant =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000881 llvm::ConstantArray::get(context, toPrint);
882
883 if (useGlobal) {
884 // Note: Does not work without allocation
885 stringVar =
886 new llvm::GlobalVariable(module,
887 stringConstant->getType(),
888 true,
889 llvm::GlobalValue::LinkerPrivateLinkage,
890 stringConstant,
891 "");
892 }
893 else {
894 stringVar = builder.CreateAlloca(stringConstant->getType());
895 builder.CreateStore(stringConstant, stringVar);
896 }
897
Garrison Venn9cb50862011-09-23 14:45:10 +0000898 llvm::Value *cast = builder.CreatePointerCast(stringVar,
899 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000900 builder.CreateCall(printFunct, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000901}
902
903
904/// Generates code to print given runtime integer according to constant
905/// string format, and a given print function.
906/// @param context llvm context
907/// @param module code for module instance
908/// @param builder builder instance
909/// @param printFunct function used to "print" integer
910/// @param toPrint string to print
911/// @param format printf like formating string for print
912/// @param useGlobal A value of true (default) indicates a GlobalValue is
913/// generated, and is used to hold the constant string. A value of
914/// false indicates that the constant string will be stored on the
915/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000916void generateIntegerPrint(llvm::LLVMContext &context,
917 llvm::Module &module,
918 llvm::IRBuilder<> &builder,
919 llvm::Function &printFunct,
920 llvm::Value &toPrint,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000921 std::string format,
922 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000923 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
924 llvm::Value *stringVar;
925
926 if (useGlobal) {
927 // Note: Does not seem to work without allocation
928 stringVar =
929 new llvm::GlobalVariable(module,
930 stringConstant->getType(),
931 true,
932 llvm::GlobalValue::LinkerPrivateLinkage,
933 stringConstant,
934 "");
935 }
936 else {
937 stringVar = builder.CreateAlloca(stringConstant->getType());
938 builder.CreateStore(stringConstant, stringVar);
939 }
940
Garrison Venn9cb50862011-09-23 14:45:10 +0000941 llvm::Value *cast = builder.CreateBitCast(stringVar,
942 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000943 builder.CreateCall2(&printFunct, &toPrint, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000944}
945
946
947/// Generates code to handle finally block type semantics: always runs
948/// regardless of whether a thrown exception is passing through or the
949/// parent function is simply exiting. In addition to printing some state
950/// to stderr, this code will resume the exception handling--runs the
951/// unwind resume block, if the exception has not been previously caught
952/// by a catch clause, and will otherwise execute the end block (terminator
953/// block). In addition this function creates the corresponding function's
954/// stack storage for the exception pointer and catch flag status.
955/// @param context llvm context
956/// @param module code for module instance
957/// @param builder builder instance
958/// @param toAddTo parent function to add block to
959/// @param blockName block name of new "finally" block.
960/// @param functionId output id used for printing
961/// @param terminatorBlock terminator "end" block
962/// @param unwindResumeBlock unwind resume block
963/// @param exceptionCaughtFlag reference exception caught/thrown status storage
964/// @param exceptionStorage reference to exception pointer storage
Garrison Venn9cb50862011-09-23 14:45:10 +0000965/// @param caughtResultStorage reference to landingpad result storage
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000966/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +0000967static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
968 llvm::Module &module,
969 llvm::IRBuilder<> &builder,
970 llvm::Function &toAddTo,
971 std::string &blockName,
972 std::string &functionId,
973 llvm::BasicBlock &terminatorBlock,
974 llvm::BasicBlock &unwindResumeBlock,
975 llvm::Value **exceptionCaughtFlag,
Bill Wendling08e8db42012-02-04 00:29:12 +0000976 llvm::Value **exceptionStorage,
977 llvm::Value **caughtResultStorage) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000978 assert(exceptionCaughtFlag &&
979 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
980 "is NULL");
981 assert(exceptionStorage &&
982 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
983 "is NULL");
Garrison Venn9cb50862011-09-23 14:45:10 +0000984 assert(caughtResultStorage &&
985 "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
986 "is NULL");
Chris Lattner626ab1c2011-04-08 18:02:51 +0000987
Garrison Venn9cb50862011-09-23 14:45:10 +0000988 *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
989 "exceptionCaught",
990 ourExceptionNotThrownState->getType(),
991 ourExceptionNotThrownState);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000992
Chris Lattner77613d42011-07-18 04:52:09 +0000993 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
Garrison Venn9cb50862011-09-23 14:45:10 +0000994 *exceptionStorage = createEntryBlockAlloca(toAddTo,
995 "exceptionStorage",
996 exceptionStorageType,
997 llvm::ConstantPointerNull::get(
998 exceptionStorageType));
Garrison Venn9cb50862011-09-23 14:45:10 +0000999 *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1000 "caughtResultStorage",
1001 ourCaughtResultType,
1002 llvm::ConstantAggregateZero::get(
1003 ourCaughtResultType));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001004
1005 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1006 blockName,
1007 &toAddTo);
1008
1009 builder.SetInsertPoint(ret);
1010
1011 std::ostringstream bufferToPrint;
1012 bufferToPrint << "Gen: Executing finally block "
1013 << blockName << " in " << functionId << "\n";
1014 generateStringPrint(context,
1015 module,
1016 builder,
1017 bufferToPrint.str(),
1018 USE_GLOBAL_STR_CONSTS);
1019
Garrison Venn9cb50862011-09-23 14:45:10 +00001020 llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1021 *exceptionCaughtFlag),
1022 &terminatorBlock,
1023 2);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001024 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1025 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1026
1027 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001028}
1029
1030
1031/// Generates catch block semantics which print a string to indicate type of
1032/// catch executed, sets an exception caught flag, and executes passed in
1033/// end block (terminator block).
1034/// @param context llvm context
1035/// @param module code for module instance
1036/// @param builder builder instance
1037/// @param toAddTo parent function to add block to
1038/// @param blockName block name of new "catch" block.
1039/// @param functionId output id used for printing
1040/// @param terminatorBlock terminator "end" block
1041/// @param exceptionCaughtFlag exception caught/thrown status
1042/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001043static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1044 llvm::Module &module,
1045 llvm::IRBuilder<> &builder,
1046 llvm::Function &toAddTo,
1047 std::string &blockName,
1048 std::string &functionId,
1049 llvm::BasicBlock &terminatorBlock,
1050 llvm::Value &exceptionCaughtFlag) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001051
1052 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1053 blockName,
1054 &toAddTo);
1055
1056 builder.SetInsertPoint(ret);
1057
1058 std::ostringstream bufferToPrint;
1059 bufferToPrint << "Gen: Executing catch block "
1060 << blockName
1061 << " in "
1062 << functionId
1063 << std::endl;
1064 generateStringPrint(context,
1065 module,
1066 builder,
1067 bufferToPrint.str(),
1068 USE_GLOBAL_STR_CONSTS);
1069 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1070 builder.CreateBr(&terminatorBlock);
1071
1072 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001073}
1074
1075
1076/// Generates a function which invokes a function (toInvoke) and, whose
1077/// unwind block will "catch" the type info types correspondingly held in the
1078/// exceptionTypesToCatch argument. If the toInvoke function throws an
1079/// exception which does not match any type info types contained in
1080/// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1081/// with the raised exception. On the other hand the generated code will
1082/// normally exit if the toInvoke function does not throw an exception.
1083/// The generated "finally" block is always run regardless of the cause of
1084/// the generated function exit.
1085/// The generated function is returned after being verified.
1086/// @param module code for module instance
1087/// @param builder builder instance
1088/// @param fpm a function pass manager holding optional IR to IR
1089/// transformations
1090/// @param toInvoke inner function to invoke
1091/// @param ourId id used to printing purposes
1092/// @param numExceptionsToCatch length of exceptionTypesToCatch array
1093/// @param exceptionTypesToCatch array of type info types to "catch"
1094/// @returns generated function
1095static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001096llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1097 llvm::IRBuilder<> &builder,
1098 llvm::FunctionPassManager &fpm,
1099 llvm::Function &toInvoke,
1100 std::string ourId,
1101 unsigned numExceptionsToCatch,
1102 unsigned exceptionTypesToCatch[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001103
Garrison Venn64cfcef2011-04-10 14:06:52 +00001104 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001105 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1106
1107 ArgTypes argTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001108 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001109
1110 ArgNames argNames;
1111 argNames.push_back("exceptTypeToThrow");
1112
Garrison Venn64cfcef2011-04-10 14:06:52 +00001113 llvm::Function *ret = createFunction(module,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001114 builder.getVoidTy(),
1115 argTypes,
1116 argNames,
1117 ourId,
1118 llvm::Function::ExternalLinkage,
1119 false,
1120 false);
1121
1122 // Block which calls invoke
1123 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1124 "entry",
1125 ret);
1126 // Normal block for invoke
1127 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1128 "normal",
1129 ret);
1130 // Unwind block for invoke
Garrison Venn9cb50862011-09-23 14:45:10 +00001131 llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
1132 "exception",
1133 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001134
1135 // Block which routes exception to correct catch handler block
Garrison Venn9cb50862011-09-23 14:45:10 +00001136 llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
1137 "exceptionRoute",
1138 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001139
1140 // Foreign exception handler
Garrison Venn9cb50862011-09-23 14:45:10 +00001141 llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
1142 "externalException",
1143 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001144
1145 // Block which calls _Unwind_Resume
Garrison Venn9cb50862011-09-23 14:45:10 +00001146 llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
1147 "unwindResume",
1148 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001149
1150 // Clean up block which delete exception if needed
Garrison Venn9cb50862011-09-23 14:45:10 +00001151 llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001152
1153 std::string nextName;
1154 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001155 llvm::Value *exceptionCaughtFlag = NULL;
1156 llvm::Value *exceptionStorage = NULL;
Garrison Venn9cb50862011-09-23 14:45:10 +00001157 llvm::Value *caughtResultStorage = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001158
1159 // Finally block which will branch to unwindResumeBlock if
1160 // exception is not caught. Initializes/allocates stack locations.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001161 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001162 module,
1163 builder,
1164 *ret,
1165 nextName = "finally",
1166 ourId,
1167 *endBlock,
1168 *unwindResumeBlock,
1169 &exceptionCaughtFlag,
Bill Wendling08e8db42012-02-04 00:29:12 +00001170 &exceptionStorage,
1171 &caughtResultStorage
Garrison Venn9cb50862011-09-23 14:45:10 +00001172 );
Chris Lattner626ab1c2011-04-08 18:02:51 +00001173
1174 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1175 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1176
1177 // One catch block per type info to be caught
1178 catchBlocks[i] = createCatchBlock(context,
1179 module,
1180 builder,
1181 *ret,
1182 nextName,
1183 ourId,
1184 *finallyBlock,
1185 *exceptionCaughtFlag);
1186 }
1187
1188 // Entry Block
1189
1190 builder.SetInsertPoint(entryBlock);
1191
1192 std::vector<llvm::Value*> args;
1193 args.push_back(namedValues["exceptTypeToThrow"]);
1194 builder.CreateInvoke(&toInvoke,
1195 normalBlock,
1196 exceptionBlock,
Chris Lattner77613d42011-07-18 04:52:09 +00001197 args);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001198
1199 // End Block
1200
1201 builder.SetInsertPoint(endBlock);
1202
1203 generateStringPrint(context,
1204 module,
1205 builder,
1206 "Gen: In end block: exiting in " + ourId + ".\n",
1207 USE_GLOBAL_STR_CONSTS);
Garrison Venn9cb50862011-09-23 14:45:10 +00001208 llvm::Function *deleteOurException = module.getFunction("deleteOurException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001209
1210 // Note: function handles NULL exceptions
1211 builder.CreateCall(deleteOurException,
1212 builder.CreateLoad(exceptionStorage));
1213 builder.CreateRetVoid();
1214
1215 // Normal Block
1216
1217 builder.SetInsertPoint(normalBlock);
1218
1219 generateStringPrint(context,
1220 module,
1221 builder,
1222 "Gen: No exception in " + ourId + "!\n",
1223 USE_GLOBAL_STR_CONSTS);
1224
1225 // Finally block is always called
1226 builder.CreateBr(finallyBlock);
1227
1228 // Unwind Resume Block
1229
1230 builder.SetInsertPoint(unwindResumeBlock);
1231
Garrison Venn9cb50862011-09-23 14:45:10 +00001232 builder.CreateResume(builder.CreateLoad(caughtResultStorage));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001233
1234 // Exception Block
1235
1236 builder.SetInsertPoint(exceptionBlock);
1237
Garrison Venn85500712011-09-22 15:45:14 +00001238 llvm::Function *personality = module.getFunction("ourPersonality");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001239
Garrison Venn85500712011-09-22 15:45:14 +00001240 llvm::LandingPadInst *caughtResult =
1241 builder.CreateLandingPad(ourCaughtResultType,
1242 personality,
1243 numExceptionsToCatch,
1244 "landingPad");
1245
1246 caughtResult->setCleanup(true);
1247
1248 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1249 // Set up type infos to be caught
1250 caughtResult->addClause(module.getGlobalVariable(
1251 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1252 }
1253
1254 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
Garrison Venn9cb50862011-09-23 14:45:10 +00001255 llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
Garrison Venn85500712011-09-22 15:45:14 +00001256
Garrison Venn9cb50862011-09-23 14:45:10 +00001257 // FIXME: Redundant storage which, beyond utilizing value of
1258 // caughtResultStore for unwindException storage, may be alleviated
1259 // alltogether with a block rearrangement
1260 builder.CreateStore(caughtResult, caughtResultStorage);
Garrison Venn85500712011-09-22 15:45:14 +00001261 builder.CreateStore(unwindException, exceptionStorage);
1262 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001263
1264 // Retrieve exception_class member from thrown exception
1265 // (_Unwind_Exception instance). This member tells us whether or not
1266 // the exception is foreign.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001267 llvm::Value *unwindExceptionClass =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001268 builder.CreateLoad(builder.CreateStructGEP(
1269 builder.CreatePointerCast(unwindException,
1270 ourUnwindExceptionType->getPointerTo()),
1271 0));
1272
1273 // Branch to the externalExceptionBlock if the exception is foreign or
1274 // to a catch router if not. Either way the finally block will be run.
1275 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1276 llvm::ConstantInt::get(builder.getInt64Ty(),
1277 ourBaseExceptionClass)),
1278 exceptionRouteBlock,
1279 externalExceptionBlock);
1280
1281 // External Exception Block
1282
1283 builder.SetInsertPoint(externalExceptionBlock);
1284
1285 generateStringPrint(context,
1286 module,
1287 builder,
1288 "Gen: Foreign exception received.\n",
1289 USE_GLOBAL_STR_CONSTS);
1290
1291 // Branch to the finally block
1292 builder.CreateBr(finallyBlock);
1293
1294 // Exception Route Block
1295
1296 builder.SetInsertPoint(exceptionRouteBlock);
1297
1298 // Casts exception pointer (_Unwind_Exception instance) to parent
1299 // (OurException instance).
1300 //
1301 // Note: ourBaseFromUnwindOffset is usually negative
Garrison Venn9cb50862011-09-23 14:45:10 +00001302 llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1303 builder.CreateConstGEP1_64(unwindException,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001304 ourBaseFromUnwindOffset),
Garrison Venn9cb50862011-09-23 14:45:10 +00001305 ourExceptionType->getPointerTo());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001306
1307 // Retrieve thrown exception type info type
1308 //
1309 // Note: Index is not relative to pointer but instead to structure
1310 // unlike a true getelementptr (GEP) instruction
1311 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1312
Garrison Venn64cfcef2011-04-10 14:06:52 +00001313 llvm::Value *typeInfoThrownType =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001314 builder.CreateStructGEP(typeInfoThrown, 0);
1315
1316 generateIntegerPrint(context,
1317 module,
1318 builder,
1319 *toPrint32Int,
1320 *(builder.CreateLoad(typeInfoThrownType)),
1321 "Gen: Exception type <%d> received (stack unwound) "
1322 " in " +
1323 ourId +
1324 ".\n",
1325 USE_GLOBAL_STR_CONSTS);
1326
1327 // Route to matched type info catch block or run cleanup finally block
Garrison Venn9cb50862011-09-23 14:45:10 +00001328 llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
1329 finallyBlock,
1330 numExceptionsToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001331
1332 unsigned nextTypeToCatch;
1333
1334 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1335 nextTypeToCatch = i - 1;
1336 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1337 llvm::Type::getInt32Ty(context), i),
1338 catchBlocks[nextTypeToCatch]);
1339 }
Garrison Vennaae66fa2011-09-22 14:07:50 +00001340
Chris Lattner626ab1c2011-04-08 18:02:51 +00001341 llvm::verifyFunction(*ret);
1342 fpm.run(*ret);
1343
1344 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001345}
1346
1347
1348/// Generates function which throws either an exception matched to a runtime
1349/// determined type info type (argument to generated function), or if this
1350/// runtime value matches nativeThrowType, throws a foreign exception by
1351/// calling nativeThrowFunct.
1352/// @param module code for module instance
1353/// @param builder builder instance
1354/// @param fpm a function pass manager holding optional IR to IR
1355/// transformations
1356/// @param ourId id used to printing purposes
1357/// @param nativeThrowType a runtime argument of this value results in
1358/// nativeThrowFunct being called to generate/throw exception.
1359/// @param nativeThrowFunct function which will throw a foreign exception
1360/// if the above nativeThrowType matches generated function's arg.
1361/// @returns generated function
1362static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001363llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1364 llvm::IRBuilder<> &builder,
1365 llvm::FunctionPassManager &fpm,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001366 std::string ourId,
1367 int32_t nativeThrowType,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001368 llvm::Function &nativeThrowFunct) {
1369 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001370 namedValues.clear();
1371 ArgTypes unwindArgTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001372 unwindArgTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001373 ArgNames unwindArgNames;
1374 unwindArgNames.push_back("exceptTypeToThrow");
1375
1376 llvm::Function *ret = createFunction(module,
1377 builder.getVoidTy(),
1378 unwindArgTypes,
1379 unwindArgNames,
1380 ourId,
1381 llvm::Function::ExternalLinkage,
1382 false,
1383 false);
1384
1385 // Throws either one of our exception or a native C++ exception depending
1386 // on a runtime argument value containing a type info type.
1387 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1388 "entry",
1389 ret);
1390 // Throws a foreign exception
Garrison Venn9cb50862011-09-23 14:45:10 +00001391 llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1392 "nativeThrow",
1393 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001394 // Throws one of our Exceptions
Garrison Venn9cb50862011-09-23 14:45:10 +00001395 llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1396 "generatedThrow",
1397 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001398 // Retrieved runtime type info type to throw
Garrison Venn64cfcef2011-04-10 14:06:52 +00001399 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
Chris Lattner626ab1c2011-04-08 18:02:51 +00001400
1401 // nativeThrowBlock block
1402
1403 builder.SetInsertPoint(nativeThrowBlock);
1404
1405 // Throws foreign exception
1406 builder.CreateCall(&nativeThrowFunct, exceptionType);
1407 builder.CreateUnreachable();
1408
1409 // entry block
1410
1411 builder.SetInsertPoint(entryBlock);
1412
1413 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1414 generateIntegerPrint(context,
1415 module,
1416 builder,
1417 *toPrint32Int,
1418 *exceptionType,
1419 "\nGen: About to throw exception type <%d> in " +
1420 ourId +
1421 ".\n",
1422 USE_GLOBAL_STR_CONSTS);
1423
1424 // Switches on runtime type info type value to determine whether or not
1425 // a foreign exception is thrown. Defaults to throwing one of our
1426 // generated exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001427 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001428 generatedThrowBlock,
1429 1);
1430
1431 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1432 nativeThrowType),
1433 nativeThrowBlock);
1434
1435 // generatedThrow block
1436
1437 builder.SetInsertPoint(generatedThrowBlock);
1438
Garrison Venn9cb50862011-09-23 14:45:10 +00001439 llvm::Function *createOurException = module.getFunction("createOurException");
1440 llvm::Function *raiseOurException = module.getFunction(
1441 "_Unwind_RaiseException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001442
1443 // Creates exception to throw with runtime type info type.
Garrison Venn9cb50862011-09-23 14:45:10 +00001444 llvm::Value *exception = builder.CreateCall(createOurException,
1445 namedValues["exceptTypeToThrow"]);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001446
1447 // Throw generated Exception
1448 builder.CreateCall(raiseOurException, exception);
1449 builder.CreateUnreachable();
1450
1451 llvm::verifyFunction(*ret);
1452 fpm.run(*ret);
1453
1454 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001455}
1456
1457static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001458 llvm::Module &module,
1459 llvm::IRBuilder<> &builder);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001460
1461/// Creates test code by generating and organizing these functions into the
1462/// test case. The test case consists of an outer function setup to invoke
1463/// an inner function within an environment having multiple catch and single
1464/// finally blocks. This inner function is also setup to invoke a throw
1465/// function within an evironment similar in nature to the outer function's
1466/// catch and finally blocks. Each of these two functions catch mutually
1467/// exclusive subsets (even or odd) of the type info types configured
1468/// for this this. All generated functions have a runtime argument which
1469/// holds a type info type to throw that each function takes and passes it
1470/// to the inner one if such a inner function exists. This type info type is
1471/// looked at by the generated throw function to see whether or not it should
1472/// throw a generated exception with the same type info type, or instead call
1473/// a supplied a function which in turn will throw a foreign exception.
1474/// @param module code for module instance
1475/// @param builder builder instance
1476/// @param fpm a function pass manager holding optional IR to IR
1477/// transformations
1478/// @param nativeThrowFunctName name of external function which will throw
1479/// a foreign exception
1480/// @returns outermost generated test function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001481llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1482 llvm::IRBuilder<> &builder,
1483 llvm::FunctionPassManager &fpm,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001484 std::string nativeThrowFunctName) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001485 // Number of type infos to generate
1486 unsigned numTypeInfos = 6;
1487
1488 // Initialze intrisics and external functions to use along with exception
1489 // and type info globals.
1490 createStandardUtilityFunctions(numTypeInfos,
1491 module,
1492 builder);
Garrison Venn9cb50862011-09-23 14:45:10 +00001493 llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001494
1495 // Create exception throw function using the value ~0 to cause
1496 // foreign exceptions to be thrown.
Garrison Venn9cb50862011-09-23 14:45:10 +00001497 llvm::Function *throwFunct = createThrowExceptionFunction(module,
1498 builder,
1499 fpm,
1500 "throwFunct",
1501 ~0,
1502 *nativeThrowFunct);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001503 // Inner function will catch even type infos
1504 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1505 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
Garrison Venn9cb50862011-09-23 14:45:10 +00001506 sizeof(unsigned);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001507
1508 // Generate inner function.
Garrison Venn9cb50862011-09-23 14:45:10 +00001509 llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1510 builder,
1511 fpm,
1512 *throwFunct,
1513 "innerCatchFunct",
1514 numExceptionTypesToCatch,
1515 innerExceptionTypesToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001516
1517 // Outer function will catch odd type infos
1518 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1519 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1520 sizeof(unsigned);
1521
1522 // Generate outer function
Garrison Venn9cb50862011-09-23 14:45:10 +00001523 llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1524 builder,
1525 fpm,
1526 *innerCatchFunct,
1527 "outerCatchFunct",
1528 numExceptionTypesToCatch,
1529 outerExceptionTypesToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001530
1531 // Return outer function to run
1532 return(outerCatchFunct);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001533}
1534
1535
1536/// Represents our foreign exceptions
1537class OurCppRunException : public std::runtime_error {
1538public:
Chris Lattner626ab1c2011-04-08 18:02:51 +00001539 OurCppRunException(const std::string reason) :
1540 std::runtime_error(reason) {}
1541
Garrison Venn64cfcef2011-04-10 14:06:52 +00001542 OurCppRunException (const OurCppRunException &toCopy) :
Chris Lattner626ab1c2011-04-08 18:02:51 +00001543 std::runtime_error(toCopy) {}
1544
Garrison Venn64cfcef2011-04-10 14:06:52 +00001545 OurCppRunException &operator = (const OurCppRunException &toCopy) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001546 return(reinterpret_cast<OurCppRunException&>(
1547 std::runtime_error::operator=(toCopy)));
1548 }
1549
1550 ~OurCppRunException (void) throw () {}
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001551};
1552
1553
1554/// Throws foreign C++ exception.
1555/// @param ignoreIt unused parameter that allows function to match implied
1556/// generated function contract.
1557extern "C"
1558void throwCppException (int32_t ignoreIt) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001559 throw(OurCppRunException("thrown by throwCppException(...)"));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001560}
1561
1562typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1563
1564/// This is a test harness which runs test by executing generated
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001565/// function with a type info type to throw. Harness wraps the execution
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001566/// of generated function in a C++ try catch clause.
1567/// @param engine execution engine to use for executing generated function.
1568/// This demo program expects this to be a JIT instance for demo
1569/// purposes.
1570/// @param function generated test function to run
1571/// @param typeToThrow type info type of generated exception to throw, or
1572/// indicator to cause foreign exception to be thrown.
1573static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001574void runExceptionThrow(llvm::ExecutionEngine *engine,
1575 llvm::Function *function,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001576 int32_t typeToThrow) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001577
1578 // Find test's function pointer
1579 OurExceptionThrowFunctType functPtr =
1580 reinterpret_cast<OurExceptionThrowFunctType>(
1581 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1582
1583 try {
1584 // Run test
1585 (*functPtr)(typeToThrow);
1586 }
1587 catch (OurCppRunException exc) {
1588 // Catch foreign C++ exception
1589 fprintf(stderr,
1590 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1591 "with reason: %s.\n",
1592 exc.what());
1593 }
1594 catch (...) {
Garrison Venn113aa862011-09-28 10:53:56 +00001595 // Catch all exceptions including our generated ones. This latter
1596 // functionality works according to the example in rules 1.6.4 of
1597 // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22),
1598 // given that these will be exceptions foreign to C++
1599 // (the _Unwind_Exception::exception_class should be different from
1600 // the one used by C++).
Chris Lattner626ab1c2011-04-08 18:02:51 +00001601 fprintf(stderr,
1602 "\nrunExceptionThrow(...):In C++ catch all.\n");
1603 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001604}
1605
1606//
1607// End test functions
1608//
1609
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001610typedef llvm::ArrayRef<llvm::Type*> TypeArray;
Chris Lattnercad3f772011-04-08 17:56:47 +00001611
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001612/// This initialization routine creates type info globals and
1613/// adds external function declarations to module.
1614/// @param numTypeInfos number of linear type info associated type info types
1615/// to create as GlobalVariable instances, starting with the value 1.
1616/// @param module code for module instance
1617/// @param builder builder instance
1618static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001619 llvm::Module &module,
1620 llvm::IRBuilder<> &builder) {
Chris Lattnercad3f772011-04-08 17:56:47 +00001621
Garrison Venn64cfcef2011-04-10 14:06:52 +00001622 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001623
1624 // Exception initializations
1625
1626 // Setup exception catch state
1627 ourExceptionNotThrownState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001628 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001629 ourExceptionThrownState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001630 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001631 ourExceptionCaughtState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001632 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001633
1634
1635
1636 // Create our type info type
1637 ourTypeInfoType = llvm::StructType::get(context,
Garrison Venn9cb50862011-09-23 14:45:10 +00001638 TypeArray(builder.getInt32Ty()));
Garrison Venn85500712011-09-22 15:45:14 +00001639
Garrison Venn85500712011-09-22 15:45:14 +00001640 llvm::Type *caughtResultFieldTypes[] = {
1641 builder.getInt8PtrTy(),
1642 builder.getInt32Ty()
1643 };
1644
1645 // Create our landingpad result type
1646 ourCaughtResultType = llvm::StructType::get(context,
1647 TypeArray(caughtResultFieldTypes));
1648
Chris Lattner626ab1c2011-04-08 18:02:51 +00001649 // Create OurException type
1650 ourExceptionType = llvm::StructType::get(context,
1651 TypeArray(ourTypeInfoType));
1652
1653 // Create portion of _Unwind_Exception type
1654 //
1655 // Note: Declaring only a portion of the _Unwind_Exception struct.
1656 // Does this cause problems?
1657 ourUnwindExceptionType =
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001658 llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001659 TypeArray(builder.getInt64Ty()));
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001660
Chris Lattner626ab1c2011-04-08 18:02:51 +00001661 struct OurBaseException_t dummyException;
1662
1663 // Calculate offset of OurException::unwindException member.
1664 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
Garrison Venn9cb50862011-09-23 14:45:10 +00001665 ((uintptr_t) &(dummyException.unwindException));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001666
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001667#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +00001668 fprintf(stderr,
1669 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1670 "= %lld, sizeof(struct OurBaseException_t) - "
1671 "sizeof(struct _Unwind_Exception) = %lu.\n",
1672 ourBaseFromUnwindOffset,
1673 sizeof(struct OurBaseException_t) -
1674 sizeof(struct _Unwind_Exception));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001675#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +00001676
1677 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1678
1679 // Create our _Unwind_Exception::exception_class value
1680 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1681
1682 // Type infos
1683
1684 std::string baseStr = "typeInfo", typeInfoName;
1685 std::ostringstream typeInfoNameBuilder;
1686 std::vector<llvm::Constant*> structVals;
1687
1688 llvm::Constant *nextStruct;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001689 llvm::GlobalVariable *nextGlobal = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001690
1691 // Generate each type info
1692 //
1693 // Note: First type info is not used.
1694 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1695 structVals.clear();
1696 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1697 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001698
Chris Lattner626ab1c2011-04-08 18:02:51 +00001699 typeInfoNameBuilder.str("");
1700 typeInfoNameBuilder << baseStr << i;
1701 typeInfoName = typeInfoNameBuilder.str();
1702
1703 // Note: Does not seem to work without allocation
1704 nextGlobal =
1705 new llvm::GlobalVariable(module,
1706 ourTypeInfoType,
1707 true,
1708 llvm::GlobalValue::ExternalLinkage,
1709 nextStruct,
1710 typeInfoName);
1711
1712 ourTypeInfoNames.push_back(typeInfoName);
1713 ourTypeInfoNamesIndex[i] = typeInfoName;
1714 }
1715
1716 ArgNames argNames;
1717 ArgTypes argTypes;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001718 llvm::Function *funct = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001719
1720 // print32Int
1721
Chris Lattner77613d42011-07-18 04:52:09 +00001722 llvm::Type *retType = builder.getVoidTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001723
1724 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001725 argTypes.push_back(builder.getInt32Ty());
1726 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001727
1728 argNames.clear();
1729
1730 createFunction(module,
1731 retType,
1732 argTypes,
1733 argNames,
1734 "print32Int",
1735 llvm::Function::ExternalLinkage,
1736 true,
1737 false);
1738
1739 // print64Int
1740
1741 retType = builder.getVoidTy();
1742
1743 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001744 argTypes.push_back(builder.getInt64Ty());
1745 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001746
1747 argNames.clear();
1748
1749 createFunction(module,
1750 retType,
1751 argTypes,
1752 argNames,
1753 "print64Int",
1754 llvm::Function::ExternalLinkage,
1755 true,
1756 false);
1757
1758 // printStr
1759
1760 retType = builder.getVoidTy();
1761
1762 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001763 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001764
1765 argNames.clear();
1766
1767 createFunction(module,
1768 retType,
1769 argTypes,
1770 argNames,
1771 "printStr",
1772 llvm::Function::ExternalLinkage,
1773 true,
1774 false);
1775
1776 // throwCppException
1777
1778 retType = builder.getVoidTy();
1779
1780 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001781 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001782
1783 argNames.clear();
1784
1785 createFunction(module,
1786 retType,
1787 argTypes,
1788 argNames,
1789 "throwCppException",
1790 llvm::Function::ExternalLinkage,
1791 true,
1792 false);
1793
1794 // deleteOurException
1795
1796 retType = builder.getVoidTy();
1797
1798 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001799 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001800
1801 argNames.clear();
1802
1803 createFunction(module,
1804 retType,
1805 argTypes,
1806 argNames,
1807 "deleteOurException",
1808 llvm::Function::ExternalLinkage,
1809 true,
1810 false);
1811
1812 // createOurException
1813
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001814 retType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001815
1816 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001817 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001818
1819 argNames.clear();
1820
1821 createFunction(module,
1822 retType,
1823 argTypes,
1824 argNames,
1825 "createOurException",
1826 llvm::Function::ExternalLinkage,
1827 true,
1828 false);
1829
1830 // _Unwind_RaiseException
1831
1832 retType = builder.getInt32Ty();
1833
1834 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001835 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001836
1837 argNames.clear();
1838
1839 funct = createFunction(module,
1840 retType,
1841 argTypes,
1842 argNames,
1843 "_Unwind_RaiseException",
1844 llvm::Function::ExternalLinkage,
1845 true,
1846 false);
1847
1848 funct->addFnAttr(llvm::Attribute::NoReturn);
1849
1850 // _Unwind_Resume
1851
1852 retType = builder.getInt32Ty();
1853
1854 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001855 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001856
1857 argNames.clear();
1858
1859 funct = createFunction(module,
1860 retType,
1861 argTypes,
1862 argNames,
1863 "_Unwind_Resume",
1864 llvm::Function::ExternalLinkage,
1865 true,
1866 false);
1867
1868 funct->addFnAttr(llvm::Attribute::NoReturn);
1869
1870 // ourPersonality
1871
1872 retType = builder.getInt32Ty();
1873
1874 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001875 argTypes.push_back(builder.getInt32Ty());
1876 argTypes.push_back(builder.getInt32Ty());
1877 argTypes.push_back(builder.getInt64Ty());
1878 argTypes.push_back(builder.getInt8PtrTy());
1879 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001880
1881 argNames.clear();
1882
1883 createFunction(module,
1884 retType,
1885 argTypes,
1886 argNames,
1887 "ourPersonality",
1888 llvm::Function::ExternalLinkage,
1889 true,
1890 false);
1891
Chris Lattner626ab1c2011-04-08 18:02:51 +00001892 // llvm.eh.typeid.for intrinsic
1893
1894 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001895}
1896
1897
Chris Lattner626ab1c2011-04-08 18:02:51 +00001898//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001899// Main test driver code.
Chris Lattner626ab1c2011-04-08 18:02:51 +00001900//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001901
1902/// Demo main routine which takes the type info types to throw. A test will
1903/// be run for each given type info type. While type info types with the value
1904/// of -1 will trigger a foreign C++ exception to be thrown; type info types
1905/// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1906/// will result in exceptions which pass through to the test harness. All other
1907/// type info types are not supported and could cause a crash.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001908int main(int argc, char *argv[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001909 if (argc == 1) {
1910 fprintf(stderr,
1911 "\nUsage: ExceptionDemo <exception type to throw> "
1912 "[<type 2>...<type n>].\n"
1913 " Each type must have the value of 1 - 6 for "
1914 "generated exceptions to be caught;\n"
1915 " the value -1 for foreign C++ exceptions to be "
1916 "generated and thrown;\n"
1917 " or the values > 6 for exceptions to be ignored.\n"
1918 "\nTry: ExceptionDemo 2 3 7 -1\n"
1919 " for a full test.\n\n");
1920 return(0);
1921 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001922
Chris Lattner626ab1c2011-04-08 18:02:51 +00001923 // If not set, exception handling will not be turned on
Peter Collingbourned40e1032011-12-07 23:58:57 +00001924 llvm::TargetOptions Opts;
1925 Opts.JITExceptionHandling = true;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001926
1927 llvm::InitializeNativeTarget();
Garrison Venn64cfcef2011-04-10 14:06:52 +00001928 llvm::LLVMContext &context = llvm::getGlobalContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001929 llvm::IRBuilder<> theBuilder(context);
1930
1931 // Make the module, which holds all the code.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001932 llvm::Module *module = new llvm::Module("my cool jit", context);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001933
1934 // Build engine with JIT
1935 llvm::EngineBuilder factory(module);
1936 factory.setEngineKind(llvm::EngineKind::JIT);
1937 factory.setAllocateGVsWithCode(false);
Peter Collingbourned40e1032011-12-07 23:58:57 +00001938 factory.setTargetOptions(Opts);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001939 llvm::ExecutionEngine *executionEngine = factory.create();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001940
1941 {
1942 llvm::FunctionPassManager fpm(module);
1943
1944 // Set up the optimizer pipeline.
1945 // Start with registering info about how the
1946 // target lays out data structures.
1947 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1948
1949 // Optimizations turned on
1950#ifdef ADD_OPT_PASSES
1951
1952 // Basic AliasAnslysis support for GVN.
1953 fpm.add(llvm::createBasicAliasAnalysisPass());
1954
1955 // Promote allocas to registers.
1956 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1957
1958 // Do simple "peephole" optimizations and bit-twiddling optzns.
1959 fpm.add(llvm::createInstructionCombiningPass());
1960
1961 // Reassociate expressions.
1962 fpm.add(llvm::createReassociatePass());
1963
1964 // Eliminate Common SubExpressions.
1965 fpm.add(llvm::createGVNPass());
1966
1967 // Simplify the control flow graph (deleting unreachable
1968 // blocks, etc).
1969 fpm.add(llvm::createCFGSimplificationPass());
1970#endif // ADD_OPT_PASSES
1971
1972 fpm.doInitialization();
1973
1974 // Generate test code using function throwCppException(...) as
1975 // the function which throws foreign exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001976 llvm::Function *toRun =
Garrison Venn85500712011-09-22 15:45:14 +00001977 createUnwindExceptionTest(*module,
1978 theBuilder,
1979 fpm,
1980 "throwCppException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001981
1982 fprintf(stderr, "\nBegin module dump:\n\n");
1983
1984 module->dump();
1985
1986 fprintf(stderr, "\nEnd module dump:\n");
1987
1988 fprintf(stderr, "\n\nBegin Test:\n");
1989
1990 for (int i = 1; i < argc; ++i) {
1991 // Run test for each argument whose value is the exception
1992 // type to throw.
1993 runExceptionThrow(executionEngine,
1994 toRun,
1995 (unsigned) strtoul(argv[i], NULL, 10));
1996 }
1997
1998 fprintf(stderr, "\nEnd Test:\n\n");
1999 }
2000
2001 delete executionEngine;
2002
2003 return 0;
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002004}
2005