CGException.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. //===--- CGException.cpp - Emit LLVM Code for C++ 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. // This contains code dealing with C++ exception related code generation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGCleanup.h"
  15. #include "CGObjCRuntime.h"
  16. #include "TargetInfo.h"
  17. #include "clang/AST/StmtCXX.h"
  18. #include "llvm/Intrinsics.h"
  19. #include "llvm/Support/CallSite.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
  23. // void *__cxa_allocate_exception(size_t thrown_size);
  24. llvm::FunctionType *FTy =
  25. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
  26. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
  27. }
  28. static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
  29. // void __cxa_free_exception(void *thrown_exception);
  30. llvm::FunctionType *FTy =
  31. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  32. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
  33. }
  34. static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
  35. // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
  36. // void (*dest) (void *));
  37. llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
  38. llvm::FunctionType *FTy =
  39. llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
  40. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
  41. }
  42. static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
  43. // void __cxa_rethrow();
  44. llvm::FunctionType *FTy =
  45. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  46. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
  47. }
  48. static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
  49. // void *__cxa_get_exception_ptr(void*);
  50. llvm::FunctionType *FTy =
  51. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  52. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
  53. }
  54. static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
  55. // void *__cxa_begin_catch(void*);
  56. llvm::FunctionType *FTy =
  57. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  58. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
  59. }
  60. static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
  61. // void __cxa_end_catch();
  62. llvm::FunctionType *FTy =
  63. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  64. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
  65. }
  66. static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
  67. // void __cxa_call_unexepcted(void *thrown_exception);
  68. llvm::FunctionType *FTy =
  69. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  70. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
  71. }
  72. llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
  73. llvm::FunctionType *FTy =
  74. llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
  75. if (CGM.getLangOptions().SjLjExceptions)
  76. return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
  77. return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
  78. }
  79. llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
  80. llvm::FunctionType *FTy =
  81. llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
  82. if (CGM.getLangOptions().SjLjExceptions)
  83. return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
  84. return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
  85. }
  86. static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
  87. // void __terminate();
  88. llvm::FunctionType *FTy =
  89. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  90. StringRef name;
  91. // In C++, use std::terminate().
  92. if (CGF.getLangOptions().CPlusPlus)
  93. name = "_ZSt9terminatev"; // FIXME: mangling!
  94. else if (CGF.getLangOptions().ObjC1 &&
  95. CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
  96. name = "objc_terminate";
  97. else
  98. name = "abort";
  99. return CGF.CGM.CreateRuntimeFunction(FTy, name);
  100. }
  101. static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
  102. StringRef Name) {
  103. llvm::FunctionType *FTy =
  104. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  105. return CGF.CGM.CreateRuntimeFunction(FTy, Name);
  106. }
  107. namespace {
  108. /// The exceptions personality for a function.
  109. struct EHPersonality {
  110. const char *PersonalityFn;
  111. // If this is non-null, this personality requires a non-standard
  112. // function for rethrowing an exception after a catchall cleanup.
  113. // This function must have prototype void(void*).
  114. const char *CatchallRethrowFn;
  115. static const EHPersonality &get(const LangOptions &Lang);
  116. static const EHPersonality GNU_C;
  117. static const EHPersonality GNU_C_SJLJ;
  118. static const EHPersonality GNU_ObjC;
  119. static const EHPersonality GNU_ObjCXX;
  120. static const EHPersonality NeXT_ObjC;
  121. static const EHPersonality GNU_CPlusPlus;
  122. static const EHPersonality GNU_CPlusPlus_SJLJ;
  123. };
  124. }
  125. const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
  126. const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
  127. const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
  128. const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
  129. const EHPersonality
  130. EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
  131. const EHPersonality
  132. EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
  133. const EHPersonality
  134. EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
  135. static const EHPersonality &getCPersonality(const LangOptions &L) {
  136. if (L.SjLjExceptions)
  137. return EHPersonality::GNU_C_SJLJ;
  138. return EHPersonality::GNU_C;
  139. }
  140. static const EHPersonality &getObjCPersonality(const LangOptions &L) {
  141. if (L.NeXTRuntime) {
  142. if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
  143. else return getCPersonality(L);
  144. } else {
  145. return EHPersonality::GNU_ObjC;
  146. }
  147. }
  148. static const EHPersonality &getCXXPersonality(const LangOptions &L) {
  149. if (L.SjLjExceptions)
  150. return EHPersonality::GNU_CPlusPlus_SJLJ;
  151. else
  152. return EHPersonality::GNU_CPlusPlus;
  153. }
  154. /// Determines the personality function to use when both C++
  155. /// and Objective-C exceptions are being caught.
  156. static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
  157. // The ObjC personality defers to the C++ personality for non-ObjC
  158. // handlers. Unlike the C++ case, we use the same personality
  159. // function on targets using (backend-driven) SJLJ EH.
  160. if (L.NeXTRuntime) {
  161. if (L.ObjCNonFragileABI)
  162. return EHPersonality::NeXT_ObjC;
  163. // In the fragile ABI, just use C++ exception handling and hope
  164. // they're not doing crazy exception mixing.
  165. else
  166. return getCXXPersonality(L);
  167. }
  168. // The GNU runtime's personality function inherently doesn't support
  169. // mixed EH. Use the C++ personality just to avoid returning null.
  170. return EHPersonality::GNU_ObjCXX;
  171. }
  172. const EHPersonality &EHPersonality::get(const LangOptions &L) {
  173. if (L.CPlusPlus && L.ObjC1)
  174. return getObjCXXPersonality(L);
  175. else if (L.CPlusPlus)
  176. return getCXXPersonality(L);
  177. else if (L.ObjC1)
  178. return getObjCPersonality(L);
  179. else
  180. return getCPersonality(L);
  181. }
  182. static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
  183. const EHPersonality &Personality) {
  184. llvm::Constant *Fn =
  185. CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
  186. Personality.PersonalityFn);
  187. return Fn;
  188. }
  189. static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
  190. const EHPersonality &Personality) {
  191. llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
  192. return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  193. }
  194. /// Check whether a personality function could reasonably be swapped
  195. /// for a C++ personality function.
  196. static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
  197. for (llvm::Constant::use_iterator
  198. I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
  199. llvm::User *User = *I;
  200. // Conditionally white-list bitcasts.
  201. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
  202. if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
  203. if (!PersonalityHasOnlyCXXUses(CE))
  204. return false;
  205. continue;
  206. }
  207. // Otherwise, it has to be a landingpad instruction.
  208. llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
  209. if (!LPI) return false;
  210. for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
  211. // Look for something that would've been returned by the ObjC
  212. // runtime's GetEHType() method.
  213. llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
  214. if (LPI->isCatch(I)) {
  215. // Check if the catch value has the ObjC prefix.
  216. if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
  217. // ObjC EH selector entries are always global variables with
  218. // names starting like this.
  219. if (GV->getName().startswith("OBJC_EHTYPE"))
  220. return false;
  221. } else {
  222. // Check if any of the filter values have the ObjC prefix.
  223. llvm::Constant *CVal = cast<llvm::Constant>(Val);
  224. for (llvm::User::op_iterator
  225. II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
  226. if (llvm::GlobalVariable *GV =
  227. cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
  228. // ObjC EH selector entries are always global variables with
  229. // names starting like this.
  230. if (GV->getName().startswith("OBJC_EHTYPE"))
  231. return false;
  232. }
  233. }
  234. }
  235. }
  236. return true;
  237. }
  238. /// Try to use the C++ personality function in ObjC++. Not doing this
  239. /// can cause some incompatibilities with gcc, which is more
  240. /// aggressive about only using the ObjC++ personality in a function
  241. /// when it really needs it.
  242. void CodeGenModule::SimplifyPersonality() {
  243. // For now, this is really a Darwin-specific operation.
  244. if (!Context.getTargetInfo().getTriple().isOSDarwin())
  245. return;
  246. // If we're not in ObjC++ -fexceptions, there's nothing to do.
  247. if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
  248. return;
  249. const EHPersonality &ObjCXX = EHPersonality::get(Features);
  250. const EHPersonality &CXX = getCXXPersonality(Features);
  251. if (&ObjCXX == &CXX)
  252. return;
  253. assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
  254. "Different EHPersonalities using the same personality function.");
  255. llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
  256. // Nothing to do if it's unused.
  257. if (!Fn || Fn->use_empty()) return;
  258. // Can't do the optimization if it has non-C++ uses.
  259. if (!PersonalityHasOnlyCXXUses(Fn)) return;
  260. // Create the C++ personality function and kill off the old
  261. // function.
  262. llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
  263. // This can happen if the user is screwing with us.
  264. if (Fn->getType() != CXXFn->getType()) return;
  265. Fn->replaceAllUsesWith(CXXFn);
  266. Fn->eraseFromParent();
  267. }
  268. /// Returns the value to inject into a selector to indicate the
  269. /// presence of a catch-all.
  270. static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
  271. // Possibly we should use @llvm.eh.catch.all.value here.
  272. return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  273. }
  274. namespace {
  275. /// A cleanup to free the exception object if its initialization
  276. /// throws.
  277. struct FreeException : EHScopeStack::Cleanup {
  278. llvm::Value *exn;
  279. FreeException(llvm::Value *exn) : exn(exn) {}
  280. void Emit(CodeGenFunction &CGF, Flags flags) {
  281. CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
  282. ->setDoesNotThrow();
  283. }
  284. };
  285. }
  286. // Emits an exception expression into the given location. This
  287. // differs from EmitAnyExprToMem only in that, if a final copy-ctor
  288. // call is required, an exception within that copy ctor causes
  289. // std::terminate to be invoked.
  290. static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
  291. llvm::Value *addr) {
  292. // Make sure the exception object is cleaned up if there's an
  293. // exception during initialization.
  294. CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
  295. EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
  296. // __cxa_allocate_exception returns a void*; we need to cast this
  297. // to the appropriate type for the object.
  298. llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
  299. llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
  300. // FIXME: this isn't quite right! If there's a final unelided call
  301. // to a copy constructor, then according to [except.terminate]p1 we
  302. // must call std::terminate() if that constructor throws, because
  303. // technically that copy occurs after the exception expression is
  304. // evaluated but before the exception is caught. But the best way
  305. // to handle that is to teach EmitAggExpr to do the final copy
  306. // differently if it can't be elided.
  307. CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
  308. /*IsInit*/ true);
  309. // Deactivate the cleanup block.
  310. CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
  311. }
  312. llvm::Value *CodeGenFunction::getExceptionSlot() {
  313. if (!ExceptionSlot)
  314. ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
  315. return ExceptionSlot;
  316. }
  317. llvm::Value *CodeGenFunction::getEHSelectorSlot() {
  318. if (!EHSelectorSlot)
  319. EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
  320. return EHSelectorSlot;
  321. }
  322. llvm::Value *CodeGenFunction::getExceptionFromSlot() {
  323. return Builder.CreateLoad(getExceptionSlot(), "exn");
  324. }
  325. llvm::Value *CodeGenFunction::getSelectorFromSlot() {
  326. return Builder.CreateLoad(getEHSelectorSlot(), "sel");
  327. }
  328. void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
  329. if (!E->getSubExpr()) {
  330. if (getInvokeDest()) {
  331. Builder.CreateInvoke(getReThrowFn(*this),
  332. getUnreachableBlock(),
  333. getInvokeDest())
  334. ->setDoesNotReturn();
  335. } else {
  336. Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
  337. Builder.CreateUnreachable();
  338. }
  339. // throw is an expression, and the expression emitters expect us
  340. // to leave ourselves at a valid insertion point.
  341. EmitBlock(createBasicBlock("throw.cont"));
  342. return;
  343. }
  344. QualType ThrowType = E->getSubExpr()->getType();
  345. // Now allocate the exception object.
  346. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  347. uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
  348. llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
  349. llvm::CallInst *ExceptionPtr =
  350. Builder.CreateCall(AllocExceptionFn,
  351. llvm::ConstantInt::get(SizeTy, TypeSize),
  352. "exception");
  353. ExceptionPtr->setDoesNotThrow();
  354. EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
  355. // Now throw the exception.
  356. llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
  357. /*ForEH=*/true);
  358. // The address of the destructor. If the exception type has a
  359. // trivial destructor (or isn't a record), we just pass null.
  360. llvm::Constant *Dtor = 0;
  361. if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
  362. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
  363. if (!Record->hasTrivialDestructor()) {
  364. CXXDestructorDecl *DtorD = Record->getDestructor();
  365. Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
  366. Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
  367. }
  368. }
  369. if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
  370. if (getInvokeDest()) {
  371. llvm::InvokeInst *ThrowCall =
  372. Builder.CreateInvoke3(getThrowFn(*this),
  373. getUnreachableBlock(), getInvokeDest(),
  374. ExceptionPtr, TypeInfo, Dtor);
  375. ThrowCall->setDoesNotReturn();
  376. } else {
  377. llvm::CallInst *ThrowCall =
  378. Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
  379. ThrowCall->setDoesNotReturn();
  380. Builder.CreateUnreachable();
  381. }
  382. // throw is an expression, and the expression emitters expect us
  383. // to leave ourselves at a valid insertion point.
  384. EmitBlock(createBasicBlock("throw.cont"));
  385. }
  386. void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
  387. if (!CGM.getLangOptions().CXXExceptions)
  388. return;
  389. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  390. if (FD == 0)
  391. return;
  392. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  393. if (Proto == 0)
  394. return;
  395. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  396. if (isNoexceptExceptionSpec(EST)) {
  397. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  398. // noexcept functions are simple terminate scopes.
  399. EHStack.pushTerminate();
  400. }
  401. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  402. unsigned NumExceptions = Proto->getNumExceptions();
  403. EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
  404. for (unsigned I = 0; I != NumExceptions; ++I) {
  405. QualType Ty = Proto->getExceptionType(I);
  406. QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
  407. llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
  408. /*ForEH=*/true);
  409. Filter->setFilter(I, EHType);
  410. }
  411. }
  412. }
  413. /// Emit the dispatch block for a filter scope if necessary.
  414. static void emitFilterDispatchBlock(CodeGenFunction &CGF,
  415. EHFilterScope &filterScope) {
  416. llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
  417. if (!dispatchBlock) return;
  418. if (dispatchBlock->use_empty()) {
  419. delete dispatchBlock;
  420. return;
  421. }
  422. CGF.EmitBlockAfterUses(dispatchBlock);
  423. // If this isn't a catch-all filter, we need to check whether we got
  424. // here because the filter triggered.
  425. if (filterScope.getNumFilters()) {
  426. // Load the selector value.
  427. llvm::Value *selector = CGF.getSelectorFromSlot();
  428. llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
  429. llvm::Value *zero = CGF.Builder.getInt32(0);
  430. llvm::Value *failsFilter =
  431. CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
  432. CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
  433. CGF.EmitBlock(unexpectedBB);
  434. }
  435. // Call __cxa_call_unexpected. This doesn't need to be an invoke
  436. // because __cxa_call_unexpected magically filters exceptions
  437. // according to the last landing pad the exception was thrown
  438. // into. Seriously.
  439. llvm::Value *exn = CGF.getExceptionFromSlot();
  440. CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
  441. ->setDoesNotReturn();
  442. CGF.Builder.CreateUnreachable();
  443. }
  444. void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
  445. if (!CGM.getLangOptions().CXXExceptions)
  446. return;
  447. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  448. if (FD == 0)
  449. return;
  450. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  451. if (Proto == 0)
  452. return;
  453. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  454. if (isNoexceptExceptionSpec(EST)) {
  455. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  456. EHStack.popTerminate();
  457. }
  458. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  459. EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
  460. emitFilterDispatchBlock(*this, filterScope);
  461. EHStack.popFilter();
  462. }
  463. }
  464. void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
  465. EnterCXXTryStmt(S);
  466. EmitStmt(S.getTryBlock());
  467. ExitCXXTryStmt(S);
  468. }
  469. void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  470. unsigned NumHandlers = S.getNumHandlers();
  471. EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
  472. for (unsigned I = 0; I != NumHandlers; ++I) {
  473. const CXXCatchStmt *C = S.getHandler(I);
  474. llvm::BasicBlock *Handler = createBasicBlock("catch");
  475. if (C->getExceptionDecl()) {
  476. // FIXME: Dropping the reference type on the type into makes it
  477. // impossible to correctly implement catch-by-reference
  478. // semantics for pointers. Unfortunately, this is what all
  479. // existing compilers do, and it's not clear that the standard
  480. // personality routine is capable of doing this right. See C++ DR 388:
  481. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
  482. QualType CaughtType = C->getCaughtType();
  483. CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
  484. llvm::Value *TypeInfo = 0;
  485. if (CaughtType->isObjCObjectPointerType())
  486. TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
  487. else
  488. TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
  489. CatchScope->setHandler(I, TypeInfo, Handler);
  490. } else {
  491. // No exception decl indicates '...', a catch-all.
  492. CatchScope->setCatchAllHandler(I, Handler);
  493. }
  494. }
  495. }
  496. llvm::BasicBlock *
  497. CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
  498. // The dispatch block for the end of the scope chain is a block that
  499. // just resumes unwinding.
  500. if (si == EHStack.stable_end())
  501. return getEHResumeBlock();
  502. // Otherwise, we should look at the actual scope.
  503. EHScope &scope = *EHStack.find(si);
  504. llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
  505. if (!dispatchBlock) {
  506. switch (scope.getKind()) {
  507. case EHScope::Catch: {
  508. // Apply a special case to a single catch-all.
  509. EHCatchScope &catchScope = cast<EHCatchScope>(scope);
  510. if (catchScope.getNumHandlers() == 1 &&
  511. catchScope.getHandler(0).isCatchAll()) {
  512. dispatchBlock = catchScope.getHandler(0).Block;
  513. // Otherwise, make a dispatch block.
  514. } else {
  515. dispatchBlock = createBasicBlock("catch.dispatch");
  516. }
  517. break;
  518. }
  519. case EHScope::Cleanup:
  520. dispatchBlock = createBasicBlock("ehcleanup");
  521. break;
  522. case EHScope::Filter:
  523. dispatchBlock = createBasicBlock("filter.dispatch");
  524. break;
  525. case EHScope::Terminate:
  526. dispatchBlock = getTerminateHandler();
  527. break;
  528. }
  529. scope.setCachedEHDispatchBlock(dispatchBlock);
  530. }
  531. return dispatchBlock;
  532. }
  533. /// Check whether this is a non-EH scope, i.e. a scope which doesn't
  534. /// affect exception handling. Currently, the only non-EH scopes are
  535. /// normal-only cleanup scopes.
  536. static bool isNonEHScope(const EHScope &S) {
  537. switch (S.getKind()) {
  538. case EHScope::Cleanup:
  539. return !cast<EHCleanupScope>(S).isEHCleanup();
  540. case EHScope::Filter:
  541. case EHScope::Catch:
  542. case EHScope::Terminate:
  543. return false;
  544. }
  545. llvm_unreachable("Invalid EHScope Kind!");
  546. }
  547. llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
  548. assert(EHStack.requiresLandingPad());
  549. assert(!EHStack.empty());
  550. if (!CGM.getLangOptions().Exceptions)
  551. return 0;
  552. // Check the innermost scope for a cached landing pad. If this is
  553. // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
  554. llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
  555. if (LP) return LP;
  556. // Build the landing pad for this scope.
  557. LP = EmitLandingPad();
  558. assert(LP);
  559. // Cache the landing pad on the innermost scope. If this is a
  560. // non-EH scope, cache the landing pad on the enclosing scope, too.
  561. for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
  562. ir->setCachedLandingPad(LP);
  563. if (!isNonEHScope(*ir)) break;
  564. }
  565. return LP;
  566. }
  567. // This code contains a hack to work around a design flaw in
  568. // LLVM's EH IR which breaks semantics after inlining. This same
  569. // hack is implemented in llvm-gcc.
  570. //
  571. // The LLVM EH abstraction is basically a thin veneer over the
  572. // traditional GCC zero-cost design: for each range of instructions
  573. // in the function, there is (at most) one "landing pad" with an
  574. // associated chain of EH actions. A language-specific personality
  575. // function interprets this chain of actions and (1) decides whether
  576. // or not to resume execution at the landing pad and (2) if so,
  577. // provides an integer indicating why it's stopping. In LLVM IR,
  578. // the association of a landing pad with a range of instructions is
  579. // achieved via an invoke instruction, the chain of actions becomes
  580. // the arguments to the @llvm.eh.selector call, and the selector
  581. // call returns the integer indicator. Other than the required
  582. // presence of two intrinsic function calls in the landing pad,
  583. // the IR exactly describes the layout of the output code.
  584. //
  585. // A principal advantage of this design is that it is completely
  586. // language-agnostic; in theory, the LLVM optimizers can treat
  587. // landing pads neutrally, and targets need only know how to lower
  588. // the intrinsics to have a functioning exceptions system (assuming
  589. // that platform exceptions follow something approximately like the
  590. // GCC design). Unfortunately, landing pads cannot be combined in a
  591. // language-agnostic way: given selectors A and B, there is no way
  592. // to make a single landing pad which faithfully represents the
  593. // semantics of propagating an exception first through A, then
  594. // through B, without knowing how the personality will interpret the
  595. // (lowered form of the) selectors. This means that inlining has no
  596. // choice but to crudely chain invokes (i.e., to ignore invokes in
  597. // the inlined function, but to turn all unwindable calls into
  598. // invokes), which is only semantically valid if every unwind stops
  599. // at every landing pad.
  600. //
  601. // Therefore, the invoke-inline hack is to guarantee that every
  602. // landing pad has a catch-all.
  603. enum CleanupHackLevel_t {
  604. /// A level of hack that requires that all landing pads have
  605. /// catch-alls.
  606. CHL_MandatoryCatchall,
  607. /// A level of hack that requires that all landing pads handle
  608. /// cleanups.
  609. CHL_MandatoryCleanup,
  610. /// No hacks at all; ideal IR generation.
  611. CHL_Ideal
  612. };
  613. const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
  614. llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
  615. assert(EHStack.requiresLandingPad());
  616. EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
  617. switch (innermostEHScope.getKind()) {
  618. case EHScope::Terminate:
  619. return getTerminateLandingPad();
  620. case EHScope::Catch:
  621. case EHScope::Cleanup:
  622. case EHScope::Filter:
  623. if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
  624. return lpad;
  625. }
  626. // Save the current IR generation state.
  627. CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
  628. const EHPersonality &personality = EHPersonality::get(getLangOptions());
  629. // Create and configure the landing pad.
  630. llvm::BasicBlock *lpad = createBasicBlock("lpad");
  631. EmitBlock(lpad);
  632. llvm::LandingPadInst *LPadInst =
  633. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
  634. getOpaquePersonalityFn(CGM, personality), 0);
  635. llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
  636. Builder.CreateStore(LPadExn, getExceptionSlot());
  637. llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
  638. Builder.CreateStore(LPadSel, getEHSelectorSlot());
  639. // Save the exception pointer. It's safe to use a single exception
  640. // pointer per function because EH cleanups can never have nested
  641. // try/catches.
  642. // Build the landingpad instruction.
  643. // Accumulate all the handlers in scope.
  644. bool hasCatchAll = false;
  645. bool hasCleanup = false;
  646. bool hasFilter = false;
  647. SmallVector<llvm::Value*, 4> filterTypes;
  648. llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
  649. for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
  650. I != E; ++I) {
  651. switch (I->getKind()) {
  652. case EHScope::Cleanup:
  653. // If we have a cleanup, remember that.
  654. hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
  655. continue;
  656. case EHScope::Filter: {
  657. assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
  658. assert(!hasCatchAll && "EH filter reached after catch-all");
  659. // Filter scopes get added to the landingpad in weird ways.
  660. EHFilterScope &filter = cast<EHFilterScope>(*I);
  661. hasFilter = true;
  662. // Add all the filter values.
  663. for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
  664. filterTypes.push_back(filter.getFilter(i));
  665. goto done;
  666. }
  667. case EHScope::Terminate:
  668. // Terminate scopes are basically catch-alls.
  669. assert(!hasCatchAll);
  670. hasCatchAll = true;
  671. goto done;
  672. case EHScope::Catch:
  673. break;
  674. }
  675. EHCatchScope &catchScope = cast<EHCatchScope>(*I);
  676. for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
  677. EHCatchScope::Handler handler = catchScope.getHandler(hi);
  678. // If this is a catch-all, register that and abort.
  679. if (!handler.Type) {
  680. assert(!hasCatchAll);
  681. hasCatchAll = true;
  682. goto done;
  683. }
  684. // Check whether we already have a handler for this type.
  685. if (catchTypes.insert(handler.Type))
  686. // If not, add it directly to the landingpad.
  687. LPadInst->addClause(handler.Type);
  688. }
  689. }
  690. done:
  691. // If we have a catch-all, add null to the landingpad.
  692. assert(!(hasCatchAll && hasFilter));
  693. if (hasCatchAll) {
  694. LPadInst->addClause(getCatchAllValue(*this));
  695. // If we have an EH filter, we need to add those handlers in the
  696. // right place in the landingpad, which is to say, at the end.
  697. } else if (hasFilter) {
  698. // Create a filter expression: a constant array indicating which filter
  699. // types there are. The personality routine only lands here if the filter
  700. // doesn't match.
  701. llvm::SmallVector<llvm::Constant*, 8> Filters;
  702. llvm::ArrayType *AType =
  703. llvm::ArrayType::get(!filterTypes.empty() ?
  704. filterTypes[0]->getType() : Int8PtrTy,
  705. filterTypes.size());
  706. for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
  707. Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
  708. llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
  709. LPadInst->addClause(FilterArray);
  710. // Also check whether we need a cleanup.
  711. if (hasCleanup)
  712. LPadInst->setCleanup(true);
  713. // Otherwise, signal that we at least have cleanups.
  714. } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
  715. if (CleanupHackLevel == CHL_MandatoryCatchall)
  716. LPadInst->addClause(getCatchAllValue(*this));
  717. else
  718. LPadInst->setCleanup(true);
  719. }
  720. assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
  721. "landingpad instruction has no clauses!");
  722. // Tell the backend how to generate the landing pad.
  723. Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
  724. // Restore the old IR generation state.
  725. Builder.restoreIP(savedIP);
  726. return lpad;
  727. }
  728. namespace {
  729. /// A cleanup to call __cxa_end_catch. In many cases, the caught
  730. /// exception type lets us state definitively that the thrown exception
  731. /// type does not have a destructor. In particular:
  732. /// - Catch-alls tell us nothing, so we have to conservatively
  733. /// assume that the thrown exception might have a destructor.
  734. /// - Catches by reference behave according to their base types.
  735. /// - Catches of non-record types will only trigger for exceptions
  736. /// of non-record types, which never have destructors.
  737. /// - Catches of record types can trigger for arbitrary subclasses
  738. /// of the caught type, so we have to assume the actual thrown
  739. /// exception type might have a throwing destructor, even if the
  740. /// caught type's destructor is trivial or nothrow.
  741. struct CallEndCatch : EHScopeStack::Cleanup {
  742. CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
  743. bool MightThrow;
  744. void Emit(CodeGenFunction &CGF, Flags flags) {
  745. if (!MightThrow) {
  746. CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
  747. return;
  748. }
  749. CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
  750. }
  751. };
  752. }
  753. /// Emits a call to __cxa_begin_catch and enters a cleanup to call
  754. /// __cxa_end_catch.
  755. ///
  756. /// \param EndMightThrow - true if __cxa_end_catch might throw
  757. static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
  758. llvm::Value *Exn,
  759. bool EndMightThrow) {
  760. llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
  761. Call->setDoesNotThrow();
  762. CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
  763. return Call;
  764. }
  765. /// A "special initializer" callback for initializing a catch
  766. /// parameter during catch initialization.
  767. static void InitCatchParam(CodeGenFunction &CGF,
  768. const VarDecl &CatchParam,
  769. llvm::Value *ParamAddr) {
  770. // Load the exception from where the landing pad saved it.
  771. llvm::Value *Exn = CGF.getExceptionFromSlot();
  772. CanQualType CatchType =
  773. CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
  774. llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
  775. // If we're catching by reference, we can just cast the object
  776. // pointer to the appropriate pointer.
  777. if (isa<ReferenceType>(CatchType)) {
  778. QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
  779. bool EndCatchMightThrow = CaughtType->isRecordType();
  780. // __cxa_begin_catch returns the adjusted object pointer.
  781. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
  782. // We have no way to tell the personality function that we're
  783. // catching by reference, so if we're catching a pointer,
  784. // __cxa_begin_catch will actually return that pointer by value.
  785. if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
  786. QualType PointeeType = PT->getPointeeType();
  787. // When catching by reference, generally we should just ignore
  788. // this by-value pointer and use the exception object instead.
  789. if (!PointeeType->isRecordType()) {
  790. // Exn points to the struct _Unwind_Exception header, which
  791. // we have to skip past in order to reach the exception data.
  792. unsigned HeaderSize =
  793. CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
  794. AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
  795. // However, if we're catching a pointer-to-record type that won't
  796. // work, because the personality function might have adjusted
  797. // the pointer. There's actually no way for us to fully satisfy
  798. // the language/ABI contract here: we can't use Exn because it
  799. // might have the wrong adjustment, but we can't use the by-value
  800. // pointer because it's off by a level of abstraction.
  801. //
  802. // The current solution is to dump the adjusted pointer into an
  803. // alloca, which breaks language semantics (because changing the
  804. // pointer doesn't change the exception) but at least works.
  805. // The better solution would be to filter out non-exact matches
  806. // and rethrow them, but this is tricky because the rethrow
  807. // really needs to be catchable by other sites at this landing
  808. // pad. The best solution is to fix the personality function.
  809. } else {
  810. // Pull the pointer for the reference type off.
  811. llvm::Type *PtrTy =
  812. cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
  813. // Create the temporary and write the adjusted pointer into it.
  814. llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
  815. llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  816. CGF.Builder.CreateStore(Casted, ExnPtrTmp);
  817. // Bind the reference to the temporary.
  818. AdjustedExn = ExnPtrTmp;
  819. }
  820. }
  821. llvm::Value *ExnCast =
  822. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
  823. CGF.Builder.CreateStore(ExnCast, ParamAddr);
  824. return;
  825. }
  826. // Non-aggregates (plus complexes).
  827. bool IsComplex = false;
  828. if (!CGF.hasAggregateLLVMType(CatchType) ||
  829. (IsComplex = CatchType->isAnyComplexType())) {
  830. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
  831. // If the catch type is a pointer type, __cxa_begin_catch returns
  832. // the pointer by value.
  833. if (CatchType->hasPointerRepresentation()) {
  834. llvm::Value *CastExn =
  835. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
  836. switch (CatchType.getQualifiers().getObjCLifetime()) {
  837. case Qualifiers::OCL_Strong:
  838. CastExn = CGF.EmitARCRetainNonBlock(CastExn);
  839. // fallthrough
  840. case Qualifiers::OCL_None:
  841. case Qualifiers::OCL_ExplicitNone:
  842. case Qualifiers::OCL_Autoreleasing:
  843. CGF.Builder.CreateStore(CastExn, ParamAddr);
  844. return;
  845. case Qualifiers::OCL_Weak:
  846. CGF.EmitARCInitWeak(ParamAddr, CastExn);
  847. return;
  848. }
  849. llvm_unreachable("bad ownership qualifier!");
  850. }
  851. // Otherwise, it returns a pointer into the exception object.
  852. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  853. llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  854. if (IsComplex) {
  855. CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
  856. ParamAddr, /*volatile*/ false);
  857. } else {
  858. unsigned Alignment =
  859. CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
  860. llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
  861. CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
  862. CatchType);
  863. }
  864. return;
  865. }
  866. assert(isa<RecordType>(CatchType) && "unexpected catch type!");
  867. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  868. // Check for a copy expression. If we don't have a copy expression,
  869. // that means a trivial copy is okay.
  870. const Expr *copyExpr = CatchParam.getInit();
  871. if (!copyExpr) {
  872. llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
  873. llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
  874. CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
  875. return;
  876. }
  877. // We have to call __cxa_get_exception_ptr to get the adjusted
  878. // pointer before copying.
  879. llvm::CallInst *rawAdjustedExn =
  880. CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
  881. rawAdjustedExn->setDoesNotThrow();
  882. // Cast that to the appropriate type.
  883. llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
  884. // The copy expression is defined in terms of an OpaqueValueExpr.
  885. // Find it and map it to the adjusted expression.
  886. CodeGenFunction::OpaqueValueMapping
  887. opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
  888. CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
  889. // Call the copy ctor in a terminate scope.
  890. CGF.EHStack.pushTerminate();
  891. // Perform the copy construction.
  892. CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
  893. CGF.EmitAggExpr(copyExpr,
  894. AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
  895. AggValueSlot::IsNotDestructed,
  896. AggValueSlot::DoesNotNeedGCBarriers,
  897. AggValueSlot::IsNotAliased));
  898. // Leave the terminate scope.
  899. CGF.EHStack.popTerminate();
  900. // Undo the opaque value mapping.
  901. opaque.pop();
  902. // Finally we can call __cxa_begin_catch.
  903. CallBeginCatch(CGF, Exn, true);
  904. }
  905. /// Begins a catch statement by initializing the catch variable and
  906. /// calling __cxa_begin_catch.
  907. static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
  908. // We have to be very careful with the ordering of cleanups here:
  909. // C++ [except.throw]p4:
  910. // The destruction [of the exception temporary] occurs
  911. // immediately after the destruction of the object declared in
  912. // the exception-declaration in the handler.
  913. //
  914. // So the precise ordering is:
  915. // 1. Construct catch variable.
  916. // 2. __cxa_begin_catch
  917. // 3. Enter __cxa_end_catch cleanup
  918. // 4. Enter dtor cleanup
  919. //
  920. // We do this by using a slightly abnormal initialization process.
  921. // Delegation sequence:
  922. // - ExitCXXTryStmt opens a RunCleanupsScope
  923. // - EmitAutoVarAlloca creates the variable and debug info
  924. // - InitCatchParam initializes the variable from the exception
  925. // - CallBeginCatch calls __cxa_begin_catch
  926. // - CallBeginCatch enters the __cxa_end_catch cleanup
  927. // - EmitAutoVarCleanups enters the variable destructor cleanup
  928. // - EmitCXXTryStmt emits the code for the catch body
  929. // - EmitCXXTryStmt close the RunCleanupsScope
  930. VarDecl *CatchParam = S->getExceptionDecl();
  931. if (!CatchParam) {
  932. llvm::Value *Exn = CGF.getExceptionFromSlot();
  933. CallBeginCatch(CGF, Exn, true);
  934. return;
  935. }
  936. // Emit the local.
  937. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  938. InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
  939. CGF.EmitAutoVarCleanups(var);
  940. }
  941. namespace {
  942. struct CallRethrow : EHScopeStack::Cleanup {
  943. void Emit(CodeGenFunction &CGF, Flags flags) {
  944. CGF.EmitCallOrInvoke(getReThrowFn(CGF));
  945. }
  946. };
  947. }
  948. /// Emit the structure of the dispatch block for the given catch scope.
  949. /// It is an invariant that the dispatch block already exists.
  950. static void emitCatchDispatchBlock(CodeGenFunction &CGF,
  951. EHCatchScope &catchScope) {
  952. llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
  953. assert(dispatchBlock);
  954. // If there's only a single catch-all, getEHDispatchBlock returned
  955. // that catch-all as the dispatch block.
  956. if (catchScope.getNumHandlers() == 1 &&
  957. catchScope.getHandler(0).isCatchAll()) {
  958. assert(dispatchBlock == catchScope.getHandler(0).Block);
  959. return;
  960. }
  961. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
  962. CGF.EmitBlockAfterUses(dispatchBlock);
  963. // Select the right handler.
  964. llvm::Value *llvm_eh_typeid_for =
  965. CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
  966. // Load the selector value.
  967. llvm::Value *selector = CGF.getSelectorFromSlot();
  968. // Test against each of the exception types we claim to catch.
  969. for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
  970. assert(i < e && "ran off end of handlers!");
  971. const EHCatchScope::Handler &handler = catchScope.getHandler(i);
  972. llvm::Value *typeValue = handler.Type;
  973. assert(typeValue && "fell into catch-all case!");
  974. typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
  975. // Figure out the next block.
  976. bool nextIsEnd;
  977. llvm::BasicBlock *nextBlock;
  978. // If this is the last handler, we're at the end, and the next
  979. // block is the block for the enclosing EH scope.
  980. if (i + 1 == e) {
  981. nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
  982. nextIsEnd = true;
  983. // If the next handler is a catch-all, we're at the end, and the
  984. // next block is that handler.
  985. } else if (catchScope.getHandler(i+1).isCatchAll()) {
  986. nextBlock = catchScope.getHandler(i+1).Block;
  987. nextIsEnd = true;
  988. // Otherwise, we're not at the end and we need a new block.
  989. } else {
  990. nextBlock = CGF.createBasicBlock("catch.fallthrough");
  991. nextIsEnd = false;
  992. }
  993. // Figure out the catch type's index in the LSDA's type table.
  994. llvm::CallInst *typeIndex =
  995. CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
  996. typeIndex->setDoesNotThrow();
  997. llvm::Value *matchesTypeIndex =
  998. CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
  999. CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
  1000. // If the next handler is a catch-all, we're completely done.
  1001. if (nextIsEnd) {
  1002. CGF.Builder.restoreIP(savedIP);
  1003. return;
  1004. // Otherwise we need to emit and continue at that block.
  1005. } else {
  1006. CGF.EmitBlock(nextBlock);
  1007. }
  1008. }
  1009. llvm_unreachable("fell out of loop!");
  1010. }
  1011. void CodeGenFunction::popCatchScope() {
  1012. EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
  1013. if (catchScope.hasEHBranches())
  1014. emitCatchDispatchBlock(*this, catchScope);
  1015. EHStack.popCatch();
  1016. }
  1017. void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  1018. unsigned NumHandlers = S.getNumHandlers();
  1019. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1020. assert(CatchScope.getNumHandlers() == NumHandlers);
  1021. // If the catch was not required, bail out now.
  1022. if (!CatchScope.hasEHBranches()) {
  1023. EHStack.popCatch();
  1024. return;
  1025. }
  1026. // Emit the structure of the EH dispatch for this catch.
  1027. emitCatchDispatchBlock(*this, CatchScope);
  1028. // Copy the handler blocks off before we pop the EH stack. Emitting
  1029. // the handlers might scribble on this memory.
  1030. SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
  1031. memcpy(Handlers.data(), CatchScope.begin(),
  1032. NumHandlers * sizeof(EHCatchScope::Handler));
  1033. EHStack.popCatch();
  1034. // The fall-through block.
  1035. llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
  1036. // We just emitted the body of the try; jump to the continue block.
  1037. if (HaveInsertPoint())
  1038. Builder.CreateBr(ContBB);
  1039. // Determine if we need an implicit rethrow for all these catch handlers.
  1040. bool ImplicitRethrow = false;
  1041. if (IsFnTryBlock)
  1042. ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
  1043. isa<CXXConstructorDecl>(CurCodeDecl);
  1044. // Perversely, we emit the handlers backwards precisely because we
  1045. // want them to appear in source order. In all of these cases, the
  1046. // catch block will have exactly one predecessor, which will be a
  1047. // particular block in the catch dispatch. However, in the case of
  1048. // a catch-all, one of the dispatch blocks will branch to two
  1049. // different handlers, and EmitBlockAfterUses will cause the second
  1050. // handler to be moved before the first.
  1051. for (unsigned I = NumHandlers; I != 0; --I) {
  1052. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  1053. EmitBlockAfterUses(CatchBlock);
  1054. // Catch the exception if this isn't a catch-all.
  1055. const CXXCatchStmt *C = S.getHandler(I-1);
  1056. // Enter a cleanup scope, including the catch variable and the
  1057. // end-catch.
  1058. RunCleanupsScope CatchScope(*this);
  1059. // Initialize the catch variable and set up the cleanups.
  1060. BeginCatch(*this, C);
  1061. // If there's an implicit rethrow, push a normal "cleanup" to call
  1062. // _cxa_rethrow. This needs to happen before __cxa_end_catch is
  1063. // called, and so it is pushed after BeginCatch.
  1064. if (ImplicitRethrow)
  1065. EHStack.pushCleanup<CallRethrow>(NormalCleanup);
  1066. // Perform the body of the catch.
  1067. EmitStmt(C->getHandlerBlock());
  1068. // Fall out through the catch cleanups.
  1069. CatchScope.ForceCleanup();
  1070. // Branch out of the try.
  1071. if (HaveInsertPoint())
  1072. Builder.CreateBr(ContBB);
  1073. }
  1074. EmitBlock(ContBB);
  1075. }
  1076. namespace {
  1077. struct CallEndCatchForFinally : EHScopeStack::Cleanup {
  1078. llvm::Value *ForEHVar;
  1079. llvm::Value *EndCatchFn;
  1080. CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
  1081. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  1082. void Emit(CodeGenFunction &CGF, Flags flags) {
  1083. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  1084. llvm::BasicBlock *CleanupContBB =
  1085. CGF.createBasicBlock("finally.cleanup.cont");
  1086. llvm::Value *ShouldEndCatch =
  1087. CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
  1088. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  1089. CGF.EmitBlock(EndCatchBB);
  1090. CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
  1091. CGF.EmitBlock(CleanupContBB);
  1092. }
  1093. };
  1094. struct PerformFinally : EHScopeStack::Cleanup {
  1095. const Stmt *Body;
  1096. llvm::Value *ForEHVar;
  1097. llvm::Value *EndCatchFn;
  1098. llvm::Value *RethrowFn;
  1099. llvm::Value *SavedExnVar;
  1100. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  1101. llvm::Value *EndCatchFn,
  1102. llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
  1103. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  1104. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  1105. void Emit(CodeGenFunction &CGF, Flags flags) {
  1106. // Enter a cleanup to call the end-catch function if one was provided.
  1107. if (EndCatchFn)
  1108. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  1109. ForEHVar, EndCatchFn);
  1110. // Save the current cleanup destination in case there are
  1111. // cleanups in the finally block.
  1112. llvm::Value *SavedCleanupDest =
  1113. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  1114. "cleanup.dest.saved");
  1115. // Emit the finally block.
  1116. CGF.EmitStmt(Body);
  1117. // If the end of the finally is reachable, check whether this was
  1118. // for EH. If so, rethrow.
  1119. if (CGF.HaveInsertPoint()) {
  1120. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  1121. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  1122. llvm::Value *ShouldRethrow =
  1123. CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
  1124. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  1125. CGF.EmitBlock(RethrowBB);
  1126. if (SavedExnVar) {
  1127. CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
  1128. } else {
  1129. CGF.EmitCallOrInvoke(RethrowFn);
  1130. }
  1131. CGF.Builder.CreateUnreachable();
  1132. CGF.EmitBlock(ContBB);
  1133. // Restore the cleanup destination.
  1134. CGF.Builder.CreateStore(SavedCleanupDest,
  1135. CGF.getNormalCleanupDestSlot());
  1136. }
  1137. // Leave the end-catch cleanup. As an optimization, pretend that
  1138. // the fallthrough path was inaccessible; we've dynamically proven
  1139. // that we're not in the EH case along that path.
  1140. if (EndCatchFn) {
  1141. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  1142. CGF.PopCleanupBlock();
  1143. CGF.Builder.restoreIP(SavedIP);
  1144. }
  1145. // Now make sure we actually have an insertion point or the
  1146. // cleanup gods will hate us.
  1147. CGF.EnsureInsertPoint();
  1148. }
  1149. };
  1150. }
  1151. /// Enters a finally block for an implementation using zero-cost
  1152. /// exceptions. This is mostly general, but hard-codes some
  1153. /// language/ABI-specific behavior in the catch-all sections.
  1154. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
  1155. const Stmt *body,
  1156. llvm::Constant *beginCatchFn,
  1157. llvm::Constant *endCatchFn,
  1158. llvm::Constant *rethrowFn) {
  1159. assert((beginCatchFn != 0) == (endCatchFn != 0) &&
  1160. "begin/end catch functions not paired");
  1161. assert(rethrowFn && "rethrow function is required");
  1162. BeginCatchFn = beginCatchFn;
  1163. // The rethrow function has one of the following two types:
  1164. // void (*)()
  1165. // void (*)(void*)
  1166. // In the latter case we need to pass it the exception object.
  1167. // But we can't use the exception slot because the @finally might
  1168. // have a landing pad (which would overwrite the exception slot).
  1169. llvm::FunctionType *rethrowFnTy =
  1170. cast<llvm::FunctionType>(
  1171. cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
  1172. SavedExnVar = 0;
  1173. if (rethrowFnTy->getNumParams())
  1174. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1175. // A finally block is a statement which must be executed on any edge
  1176. // out of a given scope. Unlike a cleanup, the finally block may
  1177. // contain arbitrary control flow leading out of itself. In
  1178. // addition, finally blocks should always be executed, even if there
  1179. // are no catch handlers higher on the stack. Therefore, we
  1180. // surround the protected scope with a combination of a normal
  1181. // cleanup (to catch attempts to break out of the block via normal
  1182. // control flow) and an EH catch-all (semantically "outside" any try
  1183. // statement to which the finally block might have been attached).
  1184. // The finally block itself is generated in the context of a cleanup
  1185. // which conditionally leaves the catch-all.
  1186. // Jump destination for performing the finally block on an exception
  1187. // edge. We'll never actually reach this block, so unreachable is
  1188. // fine.
  1189. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1190. // Whether the finally block is being executed for EH purposes.
  1191. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1192. CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
  1193. // Enter a normal cleanup which will perform the @finally block.
  1194. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1195. ForEHVar, endCatchFn,
  1196. rethrowFn, SavedExnVar);
  1197. // Enter a catch-all scope.
  1198. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1199. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1200. catchScope->setCatchAllHandler(0, catchBB);
  1201. }
  1202. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1203. // Leave the finally catch-all.
  1204. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1205. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1206. CGF.popCatchScope();
  1207. // If there are any references to the catch-all block, emit it.
  1208. if (catchBB->use_empty()) {
  1209. delete catchBB;
  1210. } else {
  1211. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1212. CGF.EmitBlock(catchBB);
  1213. llvm::Value *exn = 0;
  1214. // If there's a begin-catch function, call it.
  1215. if (BeginCatchFn) {
  1216. exn = CGF.getExceptionFromSlot();
  1217. CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
  1218. }
  1219. // If we need to remember the exception pointer to rethrow later, do so.
  1220. if (SavedExnVar) {
  1221. if (!exn) exn = CGF.getExceptionFromSlot();
  1222. CGF.Builder.CreateStore(exn, SavedExnVar);
  1223. }
  1224. // Tell the cleanups in the finally block that we're do this for EH.
  1225. CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
  1226. // Thread a jump through the finally cleanup.
  1227. CGF.EmitBranchThroughCleanup(RethrowDest);
  1228. CGF.Builder.restoreIP(savedIP);
  1229. }
  1230. // Finally, leave the @finally cleanup.
  1231. CGF.PopCleanupBlock();
  1232. }
  1233. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1234. if (TerminateLandingPad)
  1235. return TerminateLandingPad;
  1236. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1237. // This will get inserted at the end of the function.
  1238. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1239. Builder.SetInsertPoint(TerminateLandingPad);
  1240. // Tell the backend that this is a landing pad.
  1241. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
  1242. llvm::LandingPadInst *LPadInst =
  1243. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
  1244. getOpaquePersonalityFn(CGM, Personality), 0);
  1245. LPadInst->addClause(getCatchAllValue(*this));
  1246. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1247. TerminateCall->setDoesNotReturn();
  1248. TerminateCall->setDoesNotThrow();
  1249. Builder.CreateUnreachable();
  1250. // Restore the saved insertion state.
  1251. Builder.restoreIP(SavedIP);
  1252. return TerminateLandingPad;
  1253. }
  1254. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1255. if (TerminateHandler)
  1256. return TerminateHandler;
  1257. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1258. // Set up the terminate handler. This block is inserted at the very
  1259. // end of the function by FinishFunction.
  1260. TerminateHandler = createBasicBlock("terminate.handler");
  1261. Builder.SetInsertPoint(TerminateHandler);
  1262. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1263. TerminateCall->setDoesNotReturn();
  1264. TerminateCall->setDoesNotThrow();
  1265. Builder.CreateUnreachable();
  1266. // Restore the saved insertion state.
  1267. Builder.restoreIP(SavedIP);
  1268. return TerminateHandler;
  1269. }
  1270. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
  1271. if (EHResumeBlock) return EHResumeBlock;
  1272. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1273. // We emit a jump to a notional label at the outermost unwind state.
  1274. EHResumeBlock = createBasicBlock("eh.resume");
  1275. Builder.SetInsertPoint(EHResumeBlock);
  1276. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
  1277. // This can always be a call because we necessarily didn't find
  1278. // anything on the EH stack which needs our help.
  1279. const char *RethrowName = Personality.CatchallRethrowFn;
  1280. if (RethrowName != 0) {
  1281. Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
  1282. getExceptionFromSlot())
  1283. ->setDoesNotReturn();
  1284. } else {
  1285. switch (CleanupHackLevel) {
  1286. case CHL_MandatoryCatchall:
  1287. // In mandatory-catchall mode, we need to use
  1288. // _Unwind_Resume_or_Rethrow, or whatever the personality's
  1289. // equivalent is.
  1290. Builder.CreateCall(getUnwindResumeOrRethrowFn(),
  1291. getExceptionFromSlot())
  1292. ->setDoesNotReturn();
  1293. break;
  1294. case CHL_MandatoryCleanup: {
  1295. // In mandatory-cleanup mode, we should use 'resume'.
  1296. // Recreate the landingpad's return value for the 'resume' instruction.
  1297. llvm::Value *Exn = getExceptionFromSlot();
  1298. llvm::Value *Sel = getSelectorFromSlot();
  1299. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
  1300. Sel->getType(), NULL);
  1301. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1302. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1303. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1304. Builder.CreateResume(LPadVal);
  1305. Builder.restoreIP(SavedIP);
  1306. return EHResumeBlock;
  1307. }
  1308. case CHL_Ideal:
  1309. // In an idealized mode where we don't have to worry about the
  1310. // optimizer combining landing pads, we should just use
  1311. // _Unwind_Resume (or the personality's equivalent).
  1312. Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
  1313. ->setDoesNotReturn();
  1314. break;
  1315. }
  1316. }
  1317. Builder.CreateUnreachable();
  1318. Builder.restoreIP(SavedIP);
  1319. return EHResumeBlock;
  1320. }