CGException.cpp 59 KB

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