CGException.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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.getLangOpts().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.getLangOpts().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.getLangOpts().CPlusPlus)
  93. name = "_ZSt9terminatev"; // FIXME: mangling!
  94. else if (CGF.getLangOpts().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 (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
  248. return;
  249. const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
  250. const EHPersonality &CXX = getCXXPersonality(LangOpts);
  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.getLangOpts().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.getLangOpts().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.getLangOpts().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(getLangOpts());
  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. }
  1005. // Otherwise we need to emit and continue at that block.
  1006. CGF.EmitBlock(nextBlock);
  1007. }
  1008. }
  1009. void CodeGenFunction::popCatchScope() {
  1010. EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
  1011. if (catchScope.hasEHBranches())
  1012. emitCatchDispatchBlock(*this, catchScope);
  1013. EHStack.popCatch();
  1014. }
  1015. void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  1016. unsigned NumHandlers = S.getNumHandlers();
  1017. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1018. assert(CatchScope.getNumHandlers() == NumHandlers);
  1019. // If the catch was not required, bail out now.
  1020. if (!CatchScope.hasEHBranches()) {
  1021. EHStack.popCatch();
  1022. return;
  1023. }
  1024. // Emit the structure of the EH dispatch for this catch.
  1025. emitCatchDispatchBlock(*this, CatchScope);
  1026. // Copy the handler blocks off before we pop the EH stack. Emitting
  1027. // the handlers might scribble on this memory.
  1028. SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
  1029. memcpy(Handlers.data(), CatchScope.begin(),
  1030. NumHandlers * sizeof(EHCatchScope::Handler));
  1031. EHStack.popCatch();
  1032. // The fall-through block.
  1033. llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
  1034. // We just emitted the body of the try; jump to the continue block.
  1035. if (HaveInsertPoint())
  1036. Builder.CreateBr(ContBB);
  1037. // Determine if we need an implicit rethrow for all these catch handlers.
  1038. bool ImplicitRethrow = false;
  1039. if (IsFnTryBlock)
  1040. ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
  1041. isa<CXXConstructorDecl>(CurCodeDecl);
  1042. // Perversely, we emit the handlers backwards precisely because we
  1043. // want them to appear in source order. In all of these cases, the
  1044. // catch block will have exactly one predecessor, which will be a
  1045. // particular block in the catch dispatch. However, in the case of
  1046. // a catch-all, one of the dispatch blocks will branch to two
  1047. // different handlers, and EmitBlockAfterUses will cause the second
  1048. // handler to be moved before the first.
  1049. for (unsigned I = NumHandlers; I != 0; --I) {
  1050. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  1051. EmitBlockAfterUses(CatchBlock);
  1052. // Catch the exception if this isn't a catch-all.
  1053. const CXXCatchStmt *C = S.getHandler(I-1);
  1054. // Enter a cleanup scope, including the catch variable and the
  1055. // end-catch.
  1056. RunCleanupsScope CatchScope(*this);
  1057. // Initialize the catch variable and set up the cleanups.
  1058. BeginCatch(*this, C);
  1059. // If there's an implicit rethrow, push a normal "cleanup" to call
  1060. // _cxa_rethrow. This needs to happen before __cxa_end_catch is
  1061. // called, and so it is pushed after BeginCatch.
  1062. if (ImplicitRethrow)
  1063. EHStack.pushCleanup<CallRethrow>(NormalCleanup);
  1064. // Perform the body of the catch.
  1065. EmitStmt(C->getHandlerBlock());
  1066. // Fall out through the catch cleanups.
  1067. CatchScope.ForceCleanup();
  1068. // Branch out of the try.
  1069. if (HaveInsertPoint())
  1070. Builder.CreateBr(ContBB);
  1071. }
  1072. EmitBlock(ContBB);
  1073. }
  1074. namespace {
  1075. struct CallEndCatchForFinally : EHScopeStack::Cleanup {
  1076. llvm::Value *ForEHVar;
  1077. llvm::Value *EndCatchFn;
  1078. CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
  1079. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  1080. void Emit(CodeGenFunction &CGF, Flags flags) {
  1081. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  1082. llvm::BasicBlock *CleanupContBB =
  1083. CGF.createBasicBlock("finally.cleanup.cont");
  1084. llvm::Value *ShouldEndCatch =
  1085. CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
  1086. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  1087. CGF.EmitBlock(EndCatchBB);
  1088. CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
  1089. CGF.EmitBlock(CleanupContBB);
  1090. }
  1091. };
  1092. struct PerformFinally : EHScopeStack::Cleanup {
  1093. const Stmt *Body;
  1094. llvm::Value *ForEHVar;
  1095. llvm::Value *EndCatchFn;
  1096. llvm::Value *RethrowFn;
  1097. llvm::Value *SavedExnVar;
  1098. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  1099. llvm::Value *EndCatchFn,
  1100. llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
  1101. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  1102. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  1103. void Emit(CodeGenFunction &CGF, Flags flags) {
  1104. // Enter a cleanup to call the end-catch function if one was provided.
  1105. if (EndCatchFn)
  1106. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  1107. ForEHVar, EndCatchFn);
  1108. // Save the current cleanup destination in case there are
  1109. // cleanups in the finally block.
  1110. llvm::Value *SavedCleanupDest =
  1111. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  1112. "cleanup.dest.saved");
  1113. // Emit the finally block.
  1114. CGF.EmitStmt(Body);
  1115. // If the end of the finally is reachable, check whether this was
  1116. // for EH. If so, rethrow.
  1117. if (CGF.HaveInsertPoint()) {
  1118. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  1119. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  1120. llvm::Value *ShouldRethrow =
  1121. CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
  1122. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  1123. CGF.EmitBlock(RethrowBB);
  1124. if (SavedExnVar) {
  1125. CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
  1126. } else {
  1127. CGF.EmitCallOrInvoke(RethrowFn);
  1128. }
  1129. CGF.Builder.CreateUnreachable();
  1130. CGF.EmitBlock(ContBB);
  1131. // Restore the cleanup destination.
  1132. CGF.Builder.CreateStore(SavedCleanupDest,
  1133. CGF.getNormalCleanupDestSlot());
  1134. }
  1135. // Leave the end-catch cleanup. As an optimization, pretend that
  1136. // the fallthrough path was inaccessible; we've dynamically proven
  1137. // that we're not in the EH case along that path.
  1138. if (EndCatchFn) {
  1139. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  1140. CGF.PopCleanupBlock();
  1141. CGF.Builder.restoreIP(SavedIP);
  1142. }
  1143. // Now make sure we actually have an insertion point or the
  1144. // cleanup gods will hate us.
  1145. CGF.EnsureInsertPoint();
  1146. }
  1147. };
  1148. }
  1149. /// Enters a finally block for an implementation using zero-cost
  1150. /// exceptions. This is mostly general, but hard-codes some
  1151. /// language/ABI-specific behavior in the catch-all sections.
  1152. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
  1153. const Stmt *body,
  1154. llvm::Constant *beginCatchFn,
  1155. llvm::Constant *endCatchFn,
  1156. llvm::Constant *rethrowFn) {
  1157. assert((beginCatchFn != 0) == (endCatchFn != 0) &&
  1158. "begin/end catch functions not paired");
  1159. assert(rethrowFn && "rethrow function is required");
  1160. BeginCatchFn = beginCatchFn;
  1161. // The rethrow function has one of the following two types:
  1162. // void (*)()
  1163. // void (*)(void*)
  1164. // In the latter case we need to pass it the exception object.
  1165. // But we can't use the exception slot because the @finally might
  1166. // have a landing pad (which would overwrite the exception slot).
  1167. llvm::FunctionType *rethrowFnTy =
  1168. cast<llvm::FunctionType>(
  1169. cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
  1170. SavedExnVar = 0;
  1171. if (rethrowFnTy->getNumParams())
  1172. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1173. // A finally block is a statement which must be executed on any edge
  1174. // out of a given scope. Unlike a cleanup, the finally block may
  1175. // contain arbitrary control flow leading out of itself. In
  1176. // addition, finally blocks should always be executed, even if there
  1177. // are no catch handlers higher on the stack. Therefore, we
  1178. // surround the protected scope with a combination of a normal
  1179. // cleanup (to catch attempts to break out of the block via normal
  1180. // control flow) and an EH catch-all (semantically "outside" any try
  1181. // statement to which the finally block might have been attached).
  1182. // The finally block itself is generated in the context of a cleanup
  1183. // which conditionally leaves the catch-all.
  1184. // Jump destination for performing the finally block on an exception
  1185. // edge. We'll never actually reach this block, so unreachable is
  1186. // fine.
  1187. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1188. // Whether the finally block is being executed for EH purposes.
  1189. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1190. CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
  1191. // Enter a normal cleanup which will perform the @finally block.
  1192. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1193. ForEHVar, endCatchFn,
  1194. rethrowFn, SavedExnVar);
  1195. // Enter a catch-all scope.
  1196. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1197. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1198. catchScope->setCatchAllHandler(0, catchBB);
  1199. }
  1200. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1201. // Leave the finally catch-all.
  1202. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1203. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1204. CGF.popCatchScope();
  1205. // If there are any references to the catch-all block, emit it.
  1206. if (catchBB->use_empty()) {
  1207. delete catchBB;
  1208. } else {
  1209. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1210. CGF.EmitBlock(catchBB);
  1211. llvm::Value *exn = 0;
  1212. // If there's a begin-catch function, call it.
  1213. if (BeginCatchFn) {
  1214. exn = CGF.getExceptionFromSlot();
  1215. CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
  1216. }
  1217. // If we need to remember the exception pointer to rethrow later, do so.
  1218. if (SavedExnVar) {
  1219. if (!exn) exn = CGF.getExceptionFromSlot();
  1220. CGF.Builder.CreateStore(exn, SavedExnVar);
  1221. }
  1222. // Tell the cleanups in the finally block that we're do this for EH.
  1223. CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
  1224. // Thread a jump through the finally cleanup.
  1225. CGF.EmitBranchThroughCleanup(RethrowDest);
  1226. CGF.Builder.restoreIP(savedIP);
  1227. }
  1228. // Finally, leave the @finally cleanup.
  1229. CGF.PopCleanupBlock();
  1230. }
  1231. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1232. if (TerminateLandingPad)
  1233. return TerminateLandingPad;
  1234. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1235. // This will get inserted at the end of the function.
  1236. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1237. Builder.SetInsertPoint(TerminateLandingPad);
  1238. // Tell the backend that this is a landing pad.
  1239. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
  1240. llvm::LandingPadInst *LPadInst =
  1241. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
  1242. getOpaquePersonalityFn(CGM, Personality), 0);
  1243. LPadInst->addClause(getCatchAllValue(*this));
  1244. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1245. TerminateCall->setDoesNotReturn();
  1246. TerminateCall->setDoesNotThrow();
  1247. Builder.CreateUnreachable();
  1248. // Restore the saved insertion state.
  1249. Builder.restoreIP(SavedIP);
  1250. return TerminateLandingPad;
  1251. }
  1252. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1253. if (TerminateHandler)
  1254. return TerminateHandler;
  1255. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1256. // Set up the terminate handler. This block is inserted at the very
  1257. // end of the function by FinishFunction.
  1258. TerminateHandler = createBasicBlock("terminate.handler");
  1259. Builder.SetInsertPoint(TerminateHandler);
  1260. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1261. TerminateCall->setDoesNotReturn();
  1262. TerminateCall->setDoesNotThrow();
  1263. Builder.CreateUnreachable();
  1264. // Restore the saved insertion state.
  1265. Builder.restoreIP(SavedIP);
  1266. return TerminateHandler;
  1267. }
  1268. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
  1269. if (EHResumeBlock) return EHResumeBlock;
  1270. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1271. // We emit a jump to a notional label at the outermost unwind state.
  1272. EHResumeBlock = createBasicBlock("eh.resume");
  1273. Builder.SetInsertPoint(EHResumeBlock);
  1274. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
  1275. // This can always be a call because we necessarily didn't find
  1276. // anything on the EH stack which needs our help.
  1277. const char *RethrowName = Personality.CatchallRethrowFn;
  1278. if (RethrowName != 0) {
  1279. Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
  1280. getExceptionFromSlot())
  1281. ->setDoesNotReturn();
  1282. } else {
  1283. switch (CleanupHackLevel) {
  1284. case CHL_MandatoryCatchall:
  1285. // In mandatory-catchall mode, we need to use
  1286. // _Unwind_Resume_or_Rethrow, or whatever the personality's
  1287. // equivalent is.
  1288. Builder.CreateCall(getUnwindResumeOrRethrowFn(),
  1289. getExceptionFromSlot())
  1290. ->setDoesNotReturn();
  1291. break;
  1292. case CHL_MandatoryCleanup: {
  1293. // In mandatory-cleanup mode, we should use 'resume'.
  1294. // Recreate the landingpad's return value for the 'resume' instruction.
  1295. llvm::Value *Exn = getExceptionFromSlot();
  1296. llvm::Value *Sel = getSelectorFromSlot();
  1297. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
  1298. Sel->getType(), NULL);
  1299. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1300. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1301. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1302. Builder.CreateResume(LPadVal);
  1303. Builder.restoreIP(SavedIP);
  1304. return EHResumeBlock;
  1305. }
  1306. case CHL_Ideal:
  1307. // In an idealized mode where we don't have to worry about the
  1308. // optimizer combining landing pads, we should just use
  1309. // _Unwind_Resume (or the personality's equivalent).
  1310. Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
  1311. ->setDoesNotReturn();
  1312. break;
  1313. }
  1314. }
  1315. Builder.CreateUnreachable();
  1316. Builder.restoreIP(SavedIP);
  1317. return EHResumeBlock;
  1318. }