CGException.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  1. //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
  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 "CGCXXABI.h"
  15. #include "CGCleanup.h"
  16. #include "CGObjCRuntime.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/Mangle.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/AST/StmtObjC.h"
  21. #include "clang/AST/StmtVisitor.h"
  22. #include "clang/Basic/TargetBuiltins.h"
  23. #include "llvm/IR/CallSite.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/Support/SaveAndRestore.h"
  27. using namespace clang;
  28. using namespace CodeGen;
  29. static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
  30. // void __cxa_free_exception(void *thrown_exception);
  31. llvm::FunctionType *FTy =
  32. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  33. return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
  34. }
  35. static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
  36. // void __cxa_call_unexpected(void *thrown_exception);
  37. llvm::FunctionType *FTy =
  38. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  39. return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
  40. }
  41. llvm::Constant *CodeGenModule::getTerminateFn() {
  42. // void __terminate();
  43. llvm::FunctionType *FTy =
  44. llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
  45. StringRef name;
  46. // In C++, use std::terminate().
  47. if (getLangOpts().CPlusPlus &&
  48. getTarget().getCXXABI().isItaniumFamily()) {
  49. name = "_ZSt9terminatev";
  50. } else if (getLangOpts().CPlusPlus &&
  51. getTarget().getCXXABI().isMicrosoft()) {
  52. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  53. name = "__std_terminate";
  54. else
  55. name = "\01?terminate@@YAXXZ";
  56. } else if (getLangOpts().ObjC1 &&
  57. getLangOpts().ObjCRuntime.hasTerminate())
  58. name = "objc_terminate";
  59. else
  60. name = "abort";
  61. return CreateRuntimeFunction(FTy, name);
  62. }
  63. static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
  64. StringRef Name) {
  65. llvm::FunctionType *FTy =
  66. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  67. return CGM.CreateRuntimeFunction(FTy, Name);
  68. }
  69. const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
  70. const EHPersonality
  71. EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
  72. const EHPersonality
  73. EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
  74. const EHPersonality
  75. EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
  76. const EHPersonality
  77. EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
  78. const EHPersonality
  79. EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
  80. const EHPersonality
  81. EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
  82. const EHPersonality
  83. EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
  84. const EHPersonality
  85. EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
  86. const EHPersonality
  87. EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
  88. const EHPersonality
  89. EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
  90. const EHPersonality
  91. EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
  92. const EHPersonality
  93. EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
  94. const EHPersonality
  95. EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
  96. const EHPersonality
  97. EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
  98. /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
  99. /// other platforms, unless the user asked for SjLj exceptions.
  100. static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
  101. return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
  102. }
  103. static const EHPersonality &getCPersonality(const llvm::Triple &T,
  104. const LangOptions &L) {
  105. if (L.SjLjExceptions)
  106. return EHPersonality::GNU_C_SJLJ;
  107. else if (useLibGCCSEHPersonality(T))
  108. return EHPersonality::GNU_C_SEH;
  109. return EHPersonality::GNU_C;
  110. }
  111. static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
  112. const LangOptions &L) {
  113. switch (L.ObjCRuntime.getKind()) {
  114. case ObjCRuntime::FragileMacOSX:
  115. return getCPersonality(T, L);
  116. case ObjCRuntime::MacOSX:
  117. case ObjCRuntime::iOS:
  118. case ObjCRuntime::WatchOS:
  119. return EHPersonality::NeXT_ObjC;
  120. case ObjCRuntime::GNUstep:
  121. if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
  122. return EHPersonality::GNUstep_ObjC;
  123. // fallthrough
  124. case ObjCRuntime::GCC:
  125. case ObjCRuntime::ObjFW:
  126. if (L.SjLjExceptions)
  127. return EHPersonality::GNU_ObjC_SJLJ;
  128. else if (useLibGCCSEHPersonality(T))
  129. return EHPersonality::GNU_ObjC_SEH;
  130. return EHPersonality::GNU_ObjC;
  131. }
  132. llvm_unreachable("bad runtime kind");
  133. }
  134. static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
  135. const LangOptions &L) {
  136. if (L.SjLjExceptions)
  137. return EHPersonality::GNU_CPlusPlus_SJLJ;
  138. else if (useLibGCCSEHPersonality(T))
  139. return EHPersonality::GNU_CPlusPlus_SEH;
  140. return EHPersonality::GNU_CPlusPlus;
  141. }
  142. /// Determines the personality function to use when both C++
  143. /// and Objective-C exceptions are being caught.
  144. static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
  145. const LangOptions &L) {
  146. switch (L.ObjCRuntime.getKind()) {
  147. // The ObjC personality defers to the C++ personality for non-ObjC
  148. // handlers. Unlike the C++ case, we use the same personality
  149. // function on targets using (backend-driven) SJLJ EH.
  150. case ObjCRuntime::MacOSX:
  151. case ObjCRuntime::iOS:
  152. case ObjCRuntime::WatchOS:
  153. return EHPersonality::NeXT_ObjC;
  154. // In the fragile ABI, just use C++ exception handling and hope
  155. // they're not doing crazy exception mixing.
  156. case ObjCRuntime::FragileMacOSX:
  157. return getCXXPersonality(T, L);
  158. // The GCC runtime's personality function inherently doesn't support
  159. // mixed EH. Use the C++ personality just to avoid returning null.
  160. case ObjCRuntime::GCC:
  161. case ObjCRuntime::ObjFW:
  162. return getObjCPersonality(T, L);
  163. case ObjCRuntime::GNUstep:
  164. return EHPersonality::GNU_ObjCXX;
  165. }
  166. llvm_unreachable("bad runtime kind");
  167. }
  168. static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
  169. if (T.getArch() == llvm::Triple::x86)
  170. return EHPersonality::MSVC_except_handler;
  171. return EHPersonality::MSVC_C_specific_handler;
  172. }
  173. const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
  174. const FunctionDecl *FD) {
  175. const llvm::Triple &T = CGM.getTarget().getTriple();
  176. const LangOptions &L = CGM.getLangOpts();
  177. // Functions using SEH get an SEH personality.
  178. if (FD && FD->usesSEHTry())
  179. return getSEHPersonalityMSVC(T);
  180. // Try to pick a personality function that is compatible with MSVC if we're
  181. // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
  182. // the GCC-style personality function.
  183. if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
  184. if (L.SjLjExceptions)
  185. return EHPersonality::GNU_CPlusPlus_SJLJ;
  186. else
  187. return EHPersonality::MSVC_CxxFrameHandler3;
  188. }
  189. if (L.CPlusPlus && L.ObjC1)
  190. return getObjCXXPersonality(T, L);
  191. else if (L.CPlusPlus)
  192. return getCXXPersonality(T, L);
  193. else if (L.ObjC1)
  194. return getObjCPersonality(T, L);
  195. else
  196. return getCPersonality(T, L);
  197. }
  198. const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
  199. return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
  200. }
  201. static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
  202. const EHPersonality &Personality) {
  203. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
  204. Personality.PersonalityFn,
  205. llvm::AttributeList(), /*Local=*/true);
  206. }
  207. static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
  208. const EHPersonality &Personality) {
  209. llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
  210. return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  211. }
  212. /// Check whether a landingpad instruction only uses C++ features.
  213. static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
  214. for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
  215. // Look for something that would've been returned by the ObjC
  216. // runtime's GetEHType() method.
  217. llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
  218. if (LPI->isCatch(I)) {
  219. // Check if the catch value has the ObjC prefix.
  220. if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
  221. // ObjC EH selector entries are always global variables with
  222. // names starting like this.
  223. if (GV->getName().startswith("OBJC_EHTYPE"))
  224. return false;
  225. } else {
  226. // Check if any of the filter values have the ObjC prefix.
  227. llvm::Constant *CVal = cast<llvm::Constant>(Val);
  228. for (llvm::User::op_iterator
  229. II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
  230. if (llvm::GlobalVariable *GV =
  231. cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
  232. // ObjC EH selector entries are always global variables with
  233. // names starting like this.
  234. if (GV->getName().startswith("OBJC_EHTYPE"))
  235. return false;
  236. }
  237. }
  238. }
  239. return true;
  240. }
  241. /// Check whether a personality function could reasonably be swapped
  242. /// for a C++ personality function.
  243. static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
  244. for (llvm::User *U : Fn->users()) {
  245. // Conditionally white-list bitcasts.
  246. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
  247. if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
  248. if (!PersonalityHasOnlyCXXUses(CE))
  249. return false;
  250. continue;
  251. }
  252. // Otherwise it must be a function.
  253. llvm::Function *F = dyn_cast<llvm::Function>(U);
  254. if (!F) return false;
  255. for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
  256. if (BB->isLandingPad())
  257. if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
  258. return false;
  259. }
  260. }
  261. return true;
  262. }
  263. /// Try to use the C++ personality function in ObjC++. Not doing this
  264. /// can cause some incompatibilities with gcc, which is more
  265. /// aggressive about only using the ObjC++ personality in a function
  266. /// when it really needs it.
  267. void CodeGenModule::SimplifyPersonality() {
  268. // If we're not in ObjC++ -fexceptions, there's nothing to do.
  269. if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
  270. return;
  271. // Both the problem this endeavors to fix and the way the logic
  272. // above works is specific to the NeXT runtime.
  273. if (!LangOpts.ObjCRuntime.isNeXTFamily())
  274. return;
  275. const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
  276. const EHPersonality &CXX =
  277. getCXXPersonality(getTarget().getTriple(), LangOpts);
  278. if (&ObjCXX == &CXX)
  279. return;
  280. assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
  281. "Different EHPersonalities using the same personality function.");
  282. llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
  283. // Nothing to do if it's unused.
  284. if (!Fn || Fn->use_empty()) return;
  285. // Can't do the optimization if it has non-C++ uses.
  286. if (!PersonalityHasOnlyCXXUses(Fn)) return;
  287. // Create the C++ personality function and kill off the old
  288. // function.
  289. llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
  290. // This can happen if the user is screwing with us.
  291. if (Fn->getType() != CXXFn->getType()) return;
  292. Fn->replaceAllUsesWith(CXXFn);
  293. Fn->eraseFromParent();
  294. }
  295. /// Returns the value to inject into a selector to indicate the
  296. /// presence of a catch-all.
  297. static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
  298. // Possibly we should use @llvm.eh.catch.all.value here.
  299. return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  300. }
  301. namespace {
  302. /// A cleanup to free the exception object if its initialization
  303. /// throws.
  304. struct FreeException final : EHScopeStack::Cleanup {
  305. llvm::Value *exn;
  306. FreeException(llvm::Value *exn) : exn(exn) {}
  307. void Emit(CodeGenFunction &CGF, Flags flags) override {
  308. CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
  309. }
  310. };
  311. } // end anonymous namespace
  312. // Emits an exception expression into the given location. This
  313. // differs from EmitAnyExprToMem only in that, if a final copy-ctor
  314. // call is required, an exception within that copy ctor causes
  315. // std::terminate to be invoked.
  316. void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
  317. // Make sure the exception object is cleaned up if there's an
  318. // exception during initialization.
  319. pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
  320. EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
  321. // __cxa_allocate_exception returns a void*; we need to cast this
  322. // to the appropriate type for the object.
  323. llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
  324. Address typedAddr = Builder.CreateBitCast(addr, ty);
  325. // FIXME: this isn't quite right! If there's a final unelided call
  326. // to a copy constructor, then according to [except.terminate]p1 we
  327. // must call std::terminate() if that constructor throws, because
  328. // technically that copy occurs after the exception expression is
  329. // evaluated but before the exception is caught. But the best way
  330. // to handle that is to teach EmitAggExpr to do the final copy
  331. // differently if it can't be elided.
  332. EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
  333. /*IsInit*/ true);
  334. // Deactivate the cleanup block.
  335. DeactivateCleanupBlock(cleanup,
  336. cast<llvm::Instruction>(typedAddr.getPointer()));
  337. }
  338. Address CodeGenFunction::getExceptionSlot() {
  339. if (!ExceptionSlot)
  340. ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
  341. return Address(ExceptionSlot, getPointerAlign());
  342. }
  343. Address CodeGenFunction::getEHSelectorSlot() {
  344. if (!EHSelectorSlot)
  345. EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
  346. return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
  347. }
  348. llvm::Value *CodeGenFunction::getExceptionFromSlot() {
  349. return Builder.CreateLoad(getExceptionSlot(), "exn");
  350. }
  351. llvm::Value *CodeGenFunction::getSelectorFromSlot() {
  352. return Builder.CreateLoad(getEHSelectorSlot(), "sel");
  353. }
  354. void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
  355. bool KeepInsertionPoint) {
  356. if (const Expr *SubExpr = E->getSubExpr()) {
  357. QualType ThrowType = SubExpr->getType();
  358. if (ThrowType->isObjCObjectPointerType()) {
  359. const Stmt *ThrowStmt = E->getSubExpr();
  360. const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
  361. CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
  362. } else {
  363. CGM.getCXXABI().emitThrow(*this, E);
  364. }
  365. } else {
  366. CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
  367. }
  368. // throw is an expression, and the expression emitters expect us
  369. // to leave ourselves at a valid insertion point.
  370. if (KeepInsertionPoint)
  371. EmitBlock(createBasicBlock("throw.cont"));
  372. }
  373. void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
  374. if (!CGM.getLangOpts().CXXExceptions)
  375. return;
  376. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  377. if (!FD) {
  378. // Check if CapturedDecl is nothrow and create terminate scope for it.
  379. if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
  380. if (CD->isNothrow())
  381. EHStack.pushTerminate();
  382. }
  383. return;
  384. }
  385. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  386. if (!Proto)
  387. return;
  388. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  389. if (isNoexceptExceptionSpec(EST)) {
  390. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  391. // noexcept functions are simple terminate scopes.
  392. EHStack.pushTerminate();
  393. }
  394. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  395. // TODO: Revisit exception specifications for the MS ABI. There is a way to
  396. // encode these in an object file but MSVC doesn't do anything with it.
  397. if (getTarget().getCXXABI().isMicrosoft())
  398. return;
  399. unsigned NumExceptions = Proto->getNumExceptions();
  400. EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
  401. for (unsigned I = 0; I != NumExceptions; ++I) {
  402. QualType Ty = Proto->getExceptionType(I);
  403. QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
  404. llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
  405. /*ForEH=*/true);
  406. Filter->setFilter(I, EHType);
  407. }
  408. }
  409. }
  410. /// Emit the dispatch block for a filter scope if necessary.
  411. static void emitFilterDispatchBlock(CodeGenFunction &CGF,
  412. EHFilterScope &filterScope) {
  413. llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
  414. if (!dispatchBlock) return;
  415. if (dispatchBlock->use_empty()) {
  416. delete dispatchBlock;
  417. return;
  418. }
  419. CGF.EmitBlockAfterUses(dispatchBlock);
  420. // If this isn't a catch-all filter, we need to check whether we got
  421. // here because the filter triggered.
  422. if (filterScope.getNumFilters()) {
  423. // Load the selector value.
  424. llvm::Value *selector = CGF.getSelectorFromSlot();
  425. llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
  426. llvm::Value *zero = CGF.Builder.getInt32(0);
  427. llvm::Value *failsFilter =
  428. CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
  429. CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
  430. CGF.getEHResumeBlock(false));
  431. CGF.EmitBlock(unexpectedBB);
  432. }
  433. // Call __cxa_call_unexpected. This doesn't need to be an invoke
  434. // because __cxa_call_unexpected magically filters exceptions
  435. // according to the last landing pad the exception was thrown
  436. // into. Seriously.
  437. llvm::Value *exn = CGF.getExceptionFromSlot();
  438. CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
  439. ->setDoesNotReturn();
  440. CGF.Builder.CreateUnreachable();
  441. }
  442. void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
  443. if (!CGM.getLangOpts().CXXExceptions)
  444. return;
  445. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  446. if (!FD) {
  447. // Check if CapturedDecl is nothrow and pop terminate scope for it.
  448. if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
  449. if (CD->isNothrow())
  450. EHStack.popTerminate();
  451. }
  452. return;
  453. }
  454. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  455. if (!Proto)
  456. return;
  457. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  458. if (isNoexceptExceptionSpec(EST)) {
  459. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  460. EHStack.popTerminate();
  461. }
  462. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  463. // TODO: Revisit exception specifications for the MS ABI. There is a way to
  464. // encode these in an object file but MSVC doesn't do anything with it.
  465. if (getTarget().getCXXABI().isMicrosoft())
  466. return;
  467. EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
  468. emitFilterDispatchBlock(*this, filterScope);
  469. EHStack.popFilter();
  470. }
  471. }
  472. void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
  473. EnterCXXTryStmt(S);
  474. EmitStmt(S.getTryBlock());
  475. ExitCXXTryStmt(S);
  476. }
  477. void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  478. unsigned NumHandlers = S.getNumHandlers();
  479. EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
  480. for (unsigned I = 0; I != NumHandlers; ++I) {
  481. const CXXCatchStmt *C = S.getHandler(I);
  482. llvm::BasicBlock *Handler = createBasicBlock("catch");
  483. if (C->getExceptionDecl()) {
  484. // FIXME: Dropping the reference type on the type into makes it
  485. // impossible to correctly implement catch-by-reference
  486. // semantics for pointers. Unfortunately, this is what all
  487. // existing compilers do, and it's not clear that the standard
  488. // personality routine is capable of doing this right. See C++ DR 388:
  489. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
  490. Qualifiers CaughtTypeQuals;
  491. QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
  492. C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
  493. CatchTypeInfo TypeInfo{nullptr, 0};
  494. if (CaughtType->isObjCObjectPointerType())
  495. TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
  496. else
  497. TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
  498. CaughtType, C->getCaughtType());
  499. CatchScope->setHandler(I, TypeInfo, Handler);
  500. } else {
  501. // No exception decl indicates '...', a catch-all.
  502. CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
  503. }
  504. }
  505. }
  506. llvm::BasicBlock *
  507. CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
  508. if (EHPersonality::get(*this).usesFuncletPads())
  509. return getMSVCDispatchBlock(si);
  510. // The dispatch block for the end of the scope chain is a block that
  511. // just resumes unwinding.
  512. if (si == EHStack.stable_end())
  513. return getEHResumeBlock(true);
  514. // Otherwise, we should look at the actual scope.
  515. EHScope &scope = *EHStack.find(si);
  516. llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
  517. if (!dispatchBlock) {
  518. switch (scope.getKind()) {
  519. case EHScope::Catch: {
  520. // Apply a special case to a single catch-all.
  521. EHCatchScope &catchScope = cast<EHCatchScope>(scope);
  522. if (catchScope.getNumHandlers() == 1 &&
  523. catchScope.getHandler(0).isCatchAll()) {
  524. dispatchBlock = catchScope.getHandler(0).Block;
  525. // Otherwise, make a dispatch block.
  526. } else {
  527. dispatchBlock = createBasicBlock("catch.dispatch");
  528. }
  529. break;
  530. }
  531. case EHScope::Cleanup:
  532. dispatchBlock = createBasicBlock("ehcleanup");
  533. break;
  534. case EHScope::Filter:
  535. dispatchBlock = createBasicBlock("filter.dispatch");
  536. break;
  537. case EHScope::Terminate:
  538. dispatchBlock = getTerminateHandler();
  539. break;
  540. case EHScope::PadEnd:
  541. llvm_unreachable("PadEnd unnecessary for Itanium!");
  542. }
  543. scope.setCachedEHDispatchBlock(dispatchBlock);
  544. }
  545. return dispatchBlock;
  546. }
  547. llvm::BasicBlock *
  548. CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
  549. // Returning nullptr indicates that the previous dispatch block should unwind
  550. // to caller.
  551. if (SI == EHStack.stable_end())
  552. return nullptr;
  553. // Otherwise, we should look at the actual scope.
  554. EHScope &EHS = *EHStack.find(SI);
  555. llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
  556. if (DispatchBlock)
  557. return DispatchBlock;
  558. if (EHS.getKind() == EHScope::Terminate)
  559. DispatchBlock = getTerminateHandler();
  560. else
  561. DispatchBlock = createBasicBlock();
  562. CGBuilderTy Builder(*this, DispatchBlock);
  563. switch (EHS.getKind()) {
  564. case EHScope::Catch:
  565. DispatchBlock->setName("catch.dispatch");
  566. break;
  567. case EHScope::Cleanup:
  568. DispatchBlock->setName("ehcleanup");
  569. break;
  570. case EHScope::Filter:
  571. llvm_unreachable("exception specifications not handled yet!");
  572. case EHScope::Terminate:
  573. DispatchBlock->setName("terminate");
  574. break;
  575. case EHScope::PadEnd:
  576. llvm_unreachable("PadEnd dispatch block missing!");
  577. }
  578. EHS.setCachedEHDispatchBlock(DispatchBlock);
  579. return DispatchBlock;
  580. }
  581. /// Check whether this is a non-EH scope, i.e. a scope which doesn't
  582. /// affect exception handling. Currently, the only non-EH scopes are
  583. /// normal-only cleanup scopes.
  584. static bool isNonEHScope(const EHScope &S) {
  585. switch (S.getKind()) {
  586. case EHScope::Cleanup:
  587. return !cast<EHCleanupScope>(S).isEHCleanup();
  588. case EHScope::Filter:
  589. case EHScope::Catch:
  590. case EHScope::Terminate:
  591. case EHScope::PadEnd:
  592. return false;
  593. }
  594. llvm_unreachable("Invalid EHScope Kind!");
  595. }
  596. llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
  597. assert(EHStack.requiresLandingPad());
  598. assert(!EHStack.empty());
  599. // If exceptions are disabled and SEH is not in use, then there is no invoke
  600. // destination. SEH "works" even if exceptions are off. In practice, this
  601. // means that C++ destructors and other EH cleanups don't run, which is
  602. // consistent with MSVC's behavior.
  603. const LangOptions &LO = CGM.getLangOpts();
  604. if (!LO.Exceptions) {
  605. if (!LO.Borland && !LO.MicrosoftExt)
  606. return nullptr;
  607. if (!currentFunctionUsesSEHTry())
  608. return nullptr;
  609. }
  610. // CUDA device code doesn't have exceptions.
  611. if (LO.CUDA && LO.CUDAIsDevice)
  612. return nullptr;
  613. // Check the innermost scope for a cached landing pad. If this is
  614. // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
  615. llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
  616. if (LP) return LP;
  617. const EHPersonality &Personality = EHPersonality::get(*this);
  618. if (!CurFn->hasPersonalityFn())
  619. CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
  620. if (Personality.usesFuncletPads()) {
  621. // We don't need separate landing pads in the funclet model.
  622. LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
  623. } else {
  624. // Build the landing pad for this scope.
  625. LP = EmitLandingPad();
  626. }
  627. assert(LP);
  628. // Cache the landing pad on the innermost scope. If this is a
  629. // non-EH scope, cache the landing pad on the enclosing scope, too.
  630. for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
  631. ir->setCachedLandingPad(LP);
  632. if (!isNonEHScope(*ir)) break;
  633. }
  634. return LP;
  635. }
  636. llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
  637. assert(EHStack.requiresLandingPad());
  638. EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
  639. switch (innermostEHScope.getKind()) {
  640. case EHScope::Terminate:
  641. return getTerminateLandingPad();
  642. case EHScope::PadEnd:
  643. llvm_unreachable("PadEnd unnecessary for Itanium!");
  644. case EHScope::Catch:
  645. case EHScope::Cleanup:
  646. case EHScope::Filter:
  647. if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
  648. return lpad;
  649. }
  650. // Save the current IR generation state.
  651. CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
  652. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
  653. // Create and configure the landing pad.
  654. llvm::BasicBlock *lpad = createBasicBlock("lpad");
  655. EmitBlock(lpad);
  656. llvm::LandingPadInst *LPadInst =
  657. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
  658. llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
  659. Builder.CreateStore(LPadExn, getExceptionSlot());
  660. llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
  661. Builder.CreateStore(LPadSel, getEHSelectorSlot());
  662. // Save the exception pointer. It's safe to use a single exception
  663. // pointer per function because EH cleanups can never have nested
  664. // try/catches.
  665. // Build the landingpad instruction.
  666. // Accumulate all the handlers in scope.
  667. bool hasCatchAll = false;
  668. bool hasCleanup = false;
  669. bool hasFilter = false;
  670. SmallVector<llvm::Value*, 4> filterTypes;
  671. llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
  672. for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
  673. ++I) {
  674. switch (I->getKind()) {
  675. case EHScope::Cleanup:
  676. // If we have a cleanup, remember that.
  677. hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
  678. continue;
  679. case EHScope::Filter: {
  680. assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
  681. assert(!hasCatchAll && "EH filter reached after catch-all");
  682. // Filter scopes get added to the landingpad in weird ways.
  683. EHFilterScope &filter = cast<EHFilterScope>(*I);
  684. hasFilter = true;
  685. // Add all the filter values.
  686. for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
  687. filterTypes.push_back(filter.getFilter(i));
  688. goto done;
  689. }
  690. case EHScope::Terminate:
  691. // Terminate scopes are basically catch-alls.
  692. assert(!hasCatchAll);
  693. hasCatchAll = true;
  694. goto done;
  695. case EHScope::Catch:
  696. break;
  697. case EHScope::PadEnd:
  698. llvm_unreachable("PadEnd unnecessary for Itanium!");
  699. }
  700. EHCatchScope &catchScope = cast<EHCatchScope>(*I);
  701. for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
  702. EHCatchScope::Handler handler = catchScope.getHandler(hi);
  703. assert(handler.Type.Flags == 0 &&
  704. "landingpads do not support catch handler flags");
  705. // If this is a catch-all, register that and abort.
  706. if (!handler.Type.RTTI) {
  707. assert(!hasCatchAll);
  708. hasCatchAll = true;
  709. goto done;
  710. }
  711. // Check whether we already have a handler for this type.
  712. if (catchTypes.insert(handler.Type.RTTI).second)
  713. // If not, add it directly to the landingpad.
  714. LPadInst->addClause(handler.Type.RTTI);
  715. }
  716. }
  717. done:
  718. // If we have a catch-all, add null to the landingpad.
  719. assert(!(hasCatchAll && hasFilter));
  720. if (hasCatchAll) {
  721. LPadInst->addClause(getCatchAllValue(*this));
  722. // If we have an EH filter, we need to add those handlers in the
  723. // right place in the landingpad, which is to say, at the end.
  724. } else if (hasFilter) {
  725. // Create a filter expression: a constant array indicating which filter
  726. // types there are. The personality routine only lands here if the filter
  727. // doesn't match.
  728. SmallVector<llvm::Constant*, 8> Filters;
  729. llvm::ArrayType *AType =
  730. llvm::ArrayType::get(!filterTypes.empty() ?
  731. filterTypes[0]->getType() : Int8PtrTy,
  732. filterTypes.size());
  733. for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
  734. Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
  735. llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
  736. LPadInst->addClause(FilterArray);
  737. // Also check whether we need a cleanup.
  738. if (hasCleanup)
  739. LPadInst->setCleanup(true);
  740. // Otherwise, signal that we at least have cleanups.
  741. } else if (hasCleanup) {
  742. LPadInst->setCleanup(true);
  743. }
  744. assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
  745. "landingpad instruction has no clauses!");
  746. // Tell the backend how to generate the landing pad.
  747. Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
  748. // Restore the old IR generation state.
  749. Builder.restoreIP(savedIP);
  750. return lpad;
  751. }
  752. static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
  753. llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
  754. assert(DispatchBlock);
  755. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
  756. CGF.EmitBlockAfterUses(DispatchBlock);
  757. llvm::Value *ParentPad = CGF.CurrentFuncletPad;
  758. if (!ParentPad)
  759. ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
  760. llvm::BasicBlock *UnwindBB =
  761. CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
  762. unsigned NumHandlers = CatchScope.getNumHandlers();
  763. llvm::CatchSwitchInst *CatchSwitch =
  764. CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
  765. // Test against each of the exception types we claim to catch.
  766. for (unsigned I = 0; I < NumHandlers; ++I) {
  767. const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
  768. CatchTypeInfo TypeInfo = Handler.Type;
  769. if (!TypeInfo.RTTI)
  770. TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
  771. CGF.Builder.SetInsertPoint(Handler.Block);
  772. if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
  773. CGF.Builder.CreateCatchPad(
  774. CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
  775. llvm::Constant::getNullValue(CGF.VoidPtrTy)});
  776. } else {
  777. CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
  778. }
  779. CatchSwitch->addHandler(Handler.Block);
  780. }
  781. CGF.Builder.restoreIP(SavedIP);
  782. }
  783. /// Emit the structure of the dispatch block for the given catch scope.
  784. /// It is an invariant that the dispatch block already exists.
  785. static void emitCatchDispatchBlock(CodeGenFunction &CGF,
  786. EHCatchScope &catchScope) {
  787. if (EHPersonality::get(CGF).usesFuncletPads())
  788. return emitCatchPadBlock(CGF, catchScope);
  789. llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
  790. assert(dispatchBlock);
  791. // If there's only a single catch-all, getEHDispatchBlock returned
  792. // that catch-all as the dispatch block.
  793. if (catchScope.getNumHandlers() == 1 &&
  794. catchScope.getHandler(0).isCatchAll()) {
  795. assert(dispatchBlock == catchScope.getHandler(0).Block);
  796. return;
  797. }
  798. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
  799. CGF.EmitBlockAfterUses(dispatchBlock);
  800. // Select the right handler.
  801. llvm::Value *llvm_eh_typeid_for =
  802. CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
  803. // Load the selector value.
  804. llvm::Value *selector = CGF.getSelectorFromSlot();
  805. // Test against each of the exception types we claim to catch.
  806. for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
  807. assert(i < e && "ran off end of handlers!");
  808. const EHCatchScope::Handler &handler = catchScope.getHandler(i);
  809. llvm::Value *typeValue = handler.Type.RTTI;
  810. assert(handler.Type.Flags == 0 &&
  811. "landingpads do not support catch handler flags");
  812. assert(typeValue && "fell into catch-all case!");
  813. typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
  814. // Figure out the next block.
  815. bool nextIsEnd;
  816. llvm::BasicBlock *nextBlock;
  817. // If this is the last handler, we're at the end, and the next
  818. // block is the block for the enclosing EH scope.
  819. if (i + 1 == e) {
  820. nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
  821. nextIsEnd = true;
  822. // If the next handler is a catch-all, we're at the end, and the
  823. // next block is that handler.
  824. } else if (catchScope.getHandler(i+1).isCatchAll()) {
  825. nextBlock = catchScope.getHandler(i+1).Block;
  826. nextIsEnd = true;
  827. // Otherwise, we're not at the end and we need a new block.
  828. } else {
  829. nextBlock = CGF.createBasicBlock("catch.fallthrough");
  830. nextIsEnd = false;
  831. }
  832. // Figure out the catch type's index in the LSDA's type table.
  833. llvm::CallInst *typeIndex =
  834. CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
  835. typeIndex->setDoesNotThrow();
  836. llvm::Value *matchesTypeIndex =
  837. CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
  838. CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
  839. // If the next handler is a catch-all, we're completely done.
  840. if (nextIsEnd) {
  841. CGF.Builder.restoreIP(savedIP);
  842. return;
  843. }
  844. // Otherwise we need to emit and continue at that block.
  845. CGF.EmitBlock(nextBlock);
  846. }
  847. }
  848. void CodeGenFunction::popCatchScope() {
  849. EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
  850. if (catchScope.hasEHBranches())
  851. emitCatchDispatchBlock(*this, catchScope);
  852. EHStack.popCatch();
  853. }
  854. void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  855. unsigned NumHandlers = S.getNumHandlers();
  856. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  857. assert(CatchScope.getNumHandlers() == NumHandlers);
  858. // If the catch was not required, bail out now.
  859. if (!CatchScope.hasEHBranches()) {
  860. CatchScope.clearHandlerBlocks();
  861. EHStack.popCatch();
  862. return;
  863. }
  864. // Emit the structure of the EH dispatch for this catch.
  865. emitCatchDispatchBlock(*this, CatchScope);
  866. // Copy the handler blocks off before we pop the EH stack. Emitting
  867. // the handlers might scribble on this memory.
  868. SmallVector<EHCatchScope::Handler, 8> Handlers(
  869. CatchScope.begin(), CatchScope.begin() + NumHandlers);
  870. EHStack.popCatch();
  871. // The fall-through block.
  872. llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
  873. // We just emitted the body of the try; jump to the continue block.
  874. if (HaveInsertPoint())
  875. Builder.CreateBr(ContBB);
  876. // Determine if we need an implicit rethrow for all these catch handlers;
  877. // see the comment below.
  878. bool doImplicitRethrow = false;
  879. if (IsFnTryBlock)
  880. doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
  881. isa<CXXConstructorDecl>(CurCodeDecl);
  882. // Perversely, we emit the handlers backwards precisely because we
  883. // want them to appear in source order. In all of these cases, the
  884. // catch block will have exactly one predecessor, which will be a
  885. // particular block in the catch dispatch. However, in the case of
  886. // a catch-all, one of the dispatch blocks will branch to two
  887. // different handlers, and EmitBlockAfterUses will cause the second
  888. // handler to be moved before the first.
  889. for (unsigned I = NumHandlers; I != 0; --I) {
  890. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  891. EmitBlockAfterUses(CatchBlock);
  892. // Catch the exception if this isn't a catch-all.
  893. const CXXCatchStmt *C = S.getHandler(I-1);
  894. // Enter a cleanup scope, including the catch variable and the
  895. // end-catch.
  896. RunCleanupsScope CatchScope(*this);
  897. // Initialize the catch variable and set up the cleanups.
  898. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  899. CurrentFuncletPad);
  900. CGM.getCXXABI().emitBeginCatch(*this, C);
  901. // Emit the PGO counter increment.
  902. incrementProfileCounter(C);
  903. // Perform the body of the catch.
  904. EmitStmt(C->getHandlerBlock());
  905. // [except.handle]p11:
  906. // The currently handled exception is rethrown if control
  907. // reaches the end of a handler of the function-try-block of a
  908. // constructor or destructor.
  909. // It is important that we only do this on fallthrough and not on
  910. // return. Note that it's illegal to put a return in a
  911. // constructor function-try-block's catch handler (p14), so this
  912. // really only applies to destructors.
  913. if (doImplicitRethrow && HaveInsertPoint()) {
  914. CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
  915. Builder.CreateUnreachable();
  916. Builder.ClearInsertionPoint();
  917. }
  918. // Fall out through the catch cleanups.
  919. CatchScope.ForceCleanup();
  920. // Branch out of the try.
  921. if (HaveInsertPoint())
  922. Builder.CreateBr(ContBB);
  923. }
  924. EmitBlock(ContBB);
  925. incrementProfileCounter(&S);
  926. }
  927. namespace {
  928. struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
  929. llvm::Value *ForEHVar;
  930. llvm::Value *EndCatchFn;
  931. CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
  932. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  933. void Emit(CodeGenFunction &CGF, Flags flags) override {
  934. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  935. llvm::BasicBlock *CleanupContBB =
  936. CGF.createBasicBlock("finally.cleanup.cont");
  937. llvm::Value *ShouldEndCatch =
  938. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
  939. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  940. CGF.EmitBlock(EndCatchBB);
  941. CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
  942. CGF.EmitBlock(CleanupContBB);
  943. }
  944. };
  945. struct PerformFinally final : EHScopeStack::Cleanup {
  946. const Stmt *Body;
  947. llvm::Value *ForEHVar;
  948. llvm::Value *EndCatchFn;
  949. llvm::Value *RethrowFn;
  950. llvm::Value *SavedExnVar;
  951. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  952. llvm::Value *EndCatchFn,
  953. llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
  954. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  955. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  956. void Emit(CodeGenFunction &CGF, Flags flags) override {
  957. // Enter a cleanup to call the end-catch function if one was provided.
  958. if (EndCatchFn)
  959. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  960. ForEHVar, EndCatchFn);
  961. // Save the current cleanup destination in case there are
  962. // cleanups in the finally block.
  963. llvm::Value *SavedCleanupDest =
  964. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  965. "cleanup.dest.saved");
  966. // Emit the finally block.
  967. CGF.EmitStmt(Body);
  968. // If the end of the finally is reachable, check whether this was
  969. // for EH. If so, rethrow.
  970. if (CGF.HaveInsertPoint()) {
  971. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  972. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  973. llvm::Value *ShouldRethrow =
  974. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
  975. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  976. CGF.EmitBlock(RethrowBB);
  977. if (SavedExnVar) {
  978. CGF.EmitRuntimeCallOrInvoke(RethrowFn,
  979. CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
  980. } else {
  981. CGF.EmitRuntimeCallOrInvoke(RethrowFn);
  982. }
  983. CGF.Builder.CreateUnreachable();
  984. CGF.EmitBlock(ContBB);
  985. // Restore the cleanup destination.
  986. CGF.Builder.CreateStore(SavedCleanupDest,
  987. CGF.getNormalCleanupDestSlot());
  988. }
  989. // Leave the end-catch cleanup. As an optimization, pretend that
  990. // the fallthrough path was inaccessible; we've dynamically proven
  991. // that we're not in the EH case along that path.
  992. if (EndCatchFn) {
  993. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  994. CGF.PopCleanupBlock();
  995. CGF.Builder.restoreIP(SavedIP);
  996. }
  997. // Now make sure we actually have an insertion point or the
  998. // cleanup gods will hate us.
  999. CGF.EnsureInsertPoint();
  1000. }
  1001. };
  1002. } // end anonymous namespace
  1003. /// Enters a finally block for an implementation using zero-cost
  1004. /// exceptions. This is mostly general, but hard-codes some
  1005. /// language/ABI-specific behavior in the catch-all sections.
  1006. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
  1007. const Stmt *body,
  1008. llvm::Constant *beginCatchFn,
  1009. llvm::Constant *endCatchFn,
  1010. llvm::Constant *rethrowFn) {
  1011. assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
  1012. "begin/end catch functions not paired");
  1013. assert(rethrowFn && "rethrow function is required");
  1014. BeginCatchFn = beginCatchFn;
  1015. // The rethrow function has one of the following two types:
  1016. // void (*)()
  1017. // void (*)(void*)
  1018. // In the latter case we need to pass it the exception object.
  1019. // But we can't use the exception slot because the @finally might
  1020. // have a landing pad (which would overwrite the exception slot).
  1021. llvm::FunctionType *rethrowFnTy =
  1022. cast<llvm::FunctionType>(
  1023. cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
  1024. SavedExnVar = nullptr;
  1025. if (rethrowFnTy->getNumParams())
  1026. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1027. // A finally block is a statement which must be executed on any edge
  1028. // out of a given scope. Unlike a cleanup, the finally block may
  1029. // contain arbitrary control flow leading out of itself. In
  1030. // addition, finally blocks should always be executed, even if there
  1031. // are no catch handlers higher on the stack. Therefore, we
  1032. // surround the protected scope with a combination of a normal
  1033. // cleanup (to catch attempts to break out of the block via normal
  1034. // control flow) and an EH catch-all (semantically "outside" any try
  1035. // statement to which the finally block might have been attached).
  1036. // The finally block itself is generated in the context of a cleanup
  1037. // which conditionally leaves the catch-all.
  1038. // Jump destination for performing the finally block on an exception
  1039. // edge. We'll never actually reach this block, so unreachable is
  1040. // fine.
  1041. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1042. // Whether the finally block is being executed for EH purposes.
  1043. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1044. CGF.Builder.CreateFlagStore(false, ForEHVar);
  1045. // Enter a normal cleanup which will perform the @finally block.
  1046. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1047. ForEHVar, endCatchFn,
  1048. rethrowFn, SavedExnVar);
  1049. // Enter a catch-all scope.
  1050. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1051. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1052. catchScope->setCatchAllHandler(0, catchBB);
  1053. }
  1054. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1055. // Leave the finally catch-all.
  1056. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1057. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1058. CGF.popCatchScope();
  1059. // If there are any references to the catch-all block, emit it.
  1060. if (catchBB->use_empty()) {
  1061. delete catchBB;
  1062. } else {
  1063. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1064. CGF.EmitBlock(catchBB);
  1065. llvm::Value *exn = nullptr;
  1066. // If there's a begin-catch function, call it.
  1067. if (BeginCatchFn) {
  1068. exn = CGF.getExceptionFromSlot();
  1069. CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
  1070. }
  1071. // If we need to remember the exception pointer to rethrow later, do so.
  1072. if (SavedExnVar) {
  1073. if (!exn) exn = CGF.getExceptionFromSlot();
  1074. CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
  1075. }
  1076. // Tell the cleanups in the finally block that we're do this for EH.
  1077. CGF.Builder.CreateFlagStore(true, ForEHVar);
  1078. // Thread a jump through the finally cleanup.
  1079. CGF.EmitBranchThroughCleanup(RethrowDest);
  1080. CGF.Builder.restoreIP(savedIP);
  1081. }
  1082. // Finally, leave the @finally cleanup.
  1083. CGF.PopCleanupBlock();
  1084. }
  1085. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1086. if (TerminateLandingPad)
  1087. return TerminateLandingPad;
  1088. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1089. // This will get inserted at the end of the function.
  1090. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1091. Builder.SetInsertPoint(TerminateLandingPad);
  1092. // Tell the backend that this is a landing pad.
  1093. const EHPersonality &Personality = EHPersonality::get(*this);
  1094. if (!CurFn->hasPersonalityFn())
  1095. CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
  1096. llvm::LandingPadInst *LPadInst =
  1097. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
  1098. LPadInst->addClause(getCatchAllValue(*this));
  1099. llvm::Value *Exn = nullptr;
  1100. if (getLangOpts().CPlusPlus)
  1101. Exn = Builder.CreateExtractValue(LPadInst, 0);
  1102. llvm::CallInst *terminateCall =
  1103. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1104. terminateCall->setDoesNotReturn();
  1105. Builder.CreateUnreachable();
  1106. // Restore the saved insertion state.
  1107. Builder.restoreIP(SavedIP);
  1108. return TerminateLandingPad;
  1109. }
  1110. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1111. if (TerminateHandler)
  1112. return TerminateHandler;
  1113. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1114. // Set up the terminate handler. This block is inserted at the very
  1115. // end of the function by FinishFunction.
  1116. TerminateHandler = createBasicBlock("terminate.handler");
  1117. Builder.SetInsertPoint(TerminateHandler);
  1118. llvm::Value *Exn = nullptr;
  1119. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  1120. CurrentFuncletPad);
  1121. if (EHPersonality::get(*this).usesFuncletPads()) {
  1122. llvm::Value *ParentPad = CurrentFuncletPad;
  1123. if (!ParentPad)
  1124. ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
  1125. CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
  1126. } else {
  1127. if (getLangOpts().CPlusPlus)
  1128. Exn = getExceptionFromSlot();
  1129. }
  1130. llvm::CallInst *terminateCall =
  1131. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1132. terminateCall->setDoesNotReturn();
  1133. Builder.CreateUnreachable();
  1134. // Restore the saved insertion state.
  1135. Builder.restoreIP(SavedIP);
  1136. return TerminateHandler;
  1137. }
  1138. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
  1139. if (EHResumeBlock) return EHResumeBlock;
  1140. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1141. // We emit a jump to a notional label at the outermost unwind state.
  1142. EHResumeBlock = createBasicBlock("eh.resume");
  1143. Builder.SetInsertPoint(EHResumeBlock);
  1144. const EHPersonality &Personality = EHPersonality::get(*this);
  1145. // This can always be a call because we necessarily didn't find
  1146. // anything on the EH stack which needs our help.
  1147. const char *RethrowName = Personality.CatchallRethrowFn;
  1148. if (RethrowName != nullptr && !isCleanup) {
  1149. EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
  1150. getExceptionFromSlot())->setDoesNotReturn();
  1151. Builder.CreateUnreachable();
  1152. Builder.restoreIP(SavedIP);
  1153. return EHResumeBlock;
  1154. }
  1155. // Recreate the landingpad's return value for the 'resume' instruction.
  1156. llvm::Value *Exn = getExceptionFromSlot();
  1157. llvm::Value *Sel = getSelectorFromSlot();
  1158. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
  1159. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1160. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1161. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1162. Builder.CreateResume(LPadVal);
  1163. Builder.restoreIP(SavedIP);
  1164. return EHResumeBlock;
  1165. }
  1166. void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
  1167. EnterSEHTryStmt(S);
  1168. {
  1169. JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
  1170. SEHTryEpilogueStack.push_back(&TryExit);
  1171. EmitStmt(S.getTryBlock());
  1172. SEHTryEpilogueStack.pop_back();
  1173. if (!TryExit.getBlock()->use_empty())
  1174. EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
  1175. else
  1176. delete TryExit.getBlock();
  1177. }
  1178. ExitSEHTryStmt(S);
  1179. }
  1180. namespace {
  1181. struct PerformSEHFinally final : EHScopeStack::Cleanup {
  1182. llvm::Function *OutlinedFinally;
  1183. PerformSEHFinally(llvm::Function *OutlinedFinally)
  1184. : OutlinedFinally(OutlinedFinally) {}
  1185. void Emit(CodeGenFunction &CGF, Flags F) override {
  1186. ASTContext &Context = CGF.getContext();
  1187. CodeGenModule &CGM = CGF.CGM;
  1188. CallArgList Args;
  1189. // Compute the two argument values.
  1190. QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
  1191. llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
  1192. llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
  1193. llvm::Value *IsForEH =
  1194. llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
  1195. Args.add(RValue::get(IsForEH), ArgTys[0]);
  1196. Args.add(RValue::get(FP), ArgTys[1]);
  1197. // Arrange a two-arg function info and type.
  1198. const CGFunctionInfo &FnInfo =
  1199. CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
  1200. auto Callee = CGCallee::forDirect(OutlinedFinally);
  1201. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  1202. }
  1203. };
  1204. } // end anonymous namespace
  1205. namespace {
  1206. /// Find all local variable captures in the statement.
  1207. struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
  1208. CodeGenFunction &ParentCGF;
  1209. const VarDecl *ParentThis;
  1210. llvm::SmallSetVector<const VarDecl *, 4> Captures;
  1211. Address SEHCodeSlot = Address::invalid();
  1212. CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
  1213. : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
  1214. // Return true if we need to do any capturing work.
  1215. bool foundCaptures() {
  1216. return !Captures.empty() || SEHCodeSlot.isValid();
  1217. }
  1218. void Visit(const Stmt *S) {
  1219. // See if this is a capture, then recurse.
  1220. ConstStmtVisitor<CaptureFinder>::Visit(S);
  1221. for (const Stmt *Child : S->children())
  1222. if (Child)
  1223. Visit(Child);
  1224. }
  1225. void VisitDeclRefExpr(const DeclRefExpr *E) {
  1226. // If this is already a capture, just make sure we capture 'this'.
  1227. if (E->refersToEnclosingVariableOrCapture()) {
  1228. Captures.insert(ParentThis);
  1229. return;
  1230. }
  1231. const auto *D = dyn_cast<VarDecl>(E->getDecl());
  1232. if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
  1233. Captures.insert(D);
  1234. }
  1235. void VisitCXXThisExpr(const CXXThisExpr *E) {
  1236. Captures.insert(ParentThis);
  1237. }
  1238. void VisitCallExpr(const CallExpr *E) {
  1239. // We only need to add parent frame allocations for these builtins in x86.
  1240. if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
  1241. return;
  1242. unsigned ID = E->getBuiltinCallee();
  1243. switch (ID) {
  1244. case Builtin::BI__exception_code:
  1245. case Builtin::BI_exception_code:
  1246. // This is the simple case where we are the outermost finally. All we
  1247. // have to do here is make sure we escape this and recover it in the
  1248. // outlined handler.
  1249. if (!SEHCodeSlot.isValid())
  1250. SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
  1251. break;
  1252. }
  1253. }
  1254. };
  1255. } // end anonymous namespace
  1256. Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1257. Address ParentVar,
  1258. llvm::Value *ParentFP) {
  1259. llvm::CallInst *RecoverCall = nullptr;
  1260. CGBuilderTy Builder(*this, AllocaInsertPt);
  1261. if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
  1262. // Mark the variable escaped if nobody else referenced it and compute the
  1263. // localescape index.
  1264. auto InsertPair = ParentCGF.EscapedLocals.insert(
  1265. std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
  1266. int FrameEscapeIdx = InsertPair.first->second;
  1267. // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
  1268. llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
  1269. &CGM.getModule(), llvm::Intrinsic::localrecover);
  1270. llvm::Constant *ParentI8Fn =
  1271. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1272. RecoverCall = Builder.CreateCall(
  1273. FrameRecoverFn, {ParentI8Fn, ParentFP,
  1274. llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
  1275. } else {
  1276. // If the parent didn't have an alloca, we're doing some nested outlining.
  1277. // Just clone the existing localrecover call, but tweak the FP argument to
  1278. // use our FP value. All other arguments are constants.
  1279. auto *ParentRecover =
  1280. cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
  1281. assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
  1282. "expected alloca or localrecover in parent LocalDeclMap");
  1283. RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
  1284. RecoverCall->setArgOperand(1, ParentFP);
  1285. RecoverCall->insertBefore(AllocaInsertPt);
  1286. }
  1287. // Bitcast the variable, rename it, and insert it in the local decl map.
  1288. llvm::Value *ChildVar =
  1289. Builder.CreateBitCast(RecoverCall, ParentVar.getType());
  1290. ChildVar->setName(ParentVar.getName());
  1291. return Address(ChildVar, ParentVar.getAlignment());
  1292. }
  1293. void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
  1294. const Stmt *OutlinedStmt,
  1295. bool IsFilter) {
  1296. // Find all captures in the Stmt.
  1297. CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
  1298. Finder.Visit(OutlinedStmt);
  1299. // We can exit early on x86_64 when there are no captures. We just have to
  1300. // save the exception code in filters so that __exception_code() works.
  1301. if (!Finder.foundCaptures() &&
  1302. CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1303. if (IsFilter)
  1304. EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
  1305. return;
  1306. }
  1307. llvm::Value *EntryFP = nullptr;
  1308. CGBuilderTy Builder(CGM, AllocaInsertPt);
  1309. if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
  1310. // 32-bit SEH filters need to be careful about FP recovery. The end of the
  1311. // EH registration is passed in as the EBP physical register. We can
  1312. // recover that with llvm.frameaddress(1).
  1313. EntryFP = Builder.CreateCall(
  1314. CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
  1315. } else {
  1316. // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
  1317. // second parameter.
  1318. auto AI = CurFn->arg_begin();
  1319. ++AI;
  1320. EntryFP = &*AI;
  1321. }
  1322. llvm::Value *ParentFP = EntryFP;
  1323. if (IsFilter) {
  1324. // Given whatever FP the runtime provided us in EntryFP, recover the true
  1325. // frame pointer of the parent function. We only need to do this in filters,
  1326. // since finally funclets recover the parent FP for us.
  1327. llvm::Function *RecoverFPIntrin =
  1328. CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
  1329. llvm::Constant *ParentI8Fn =
  1330. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1331. ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
  1332. }
  1333. // Create llvm.localrecover calls for all captures.
  1334. for (const VarDecl *VD : Finder.Captures) {
  1335. if (isa<ImplicitParamDecl>(VD)) {
  1336. CGM.ErrorUnsupported(VD, "'this' captured by SEH");
  1337. CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
  1338. continue;
  1339. }
  1340. if (VD->getType()->isVariablyModifiedType()) {
  1341. CGM.ErrorUnsupported(VD, "VLA captured by SEH");
  1342. continue;
  1343. }
  1344. assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
  1345. "captured non-local variable");
  1346. // If this decl hasn't been declared yet, it will be declared in the
  1347. // OutlinedStmt.
  1348. auto I = ParentCGF.LocalDeclMap.find(VD);
  1349. if (I == ParentCGF.LocalDeclMap.end())
  1350. continue;
  1351. Address ParentVar = I->second;
  1352. setAddrOfLocalVar(
  1353. VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
  1354. }
  1355. if (Finder.SEHCodeSlot.isValid()) {
  1356. SEHCodeSlotStack.push_back(
  1357. recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
  1358. }
  1359. if (IsFilter)
  1360. EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
  1361. }
  1362. /// Arrange a function prototype that can be called by Windows exception
  1363. /// handling personalities. On Win64, the prototype looks like:
  1364. /// RetTy func(void *EHPtrs, void *ParentFP);
  1365. void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
  1366. bool IsFilter,
  1367. const Stmt *OutlinedStmt) {
  1368. SourceLocation StartLoc = OutlinedStmt->getLocStart();
  1369. // Get the mangled function name.
  1370. SmallString<128> Name;
  1371. {
  1372. llvm::raw_svector_ostream OS(Name);
  1373. const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
  1374. assert(ParentSEHFn && "No CurSEHParent!");
  1375. MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
  1376. if (IsFilter)
  1377. Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
  1378. else
  1379. Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
  1380. }
  1381. FunctionArgList Args;
  1382. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
  1383. // All SEH finally functions take two parameters. Win64 filters take two
  1384. // parameters. Win32 filters take no parameters.
  1385. if (IsFilter) {
  1386. Args.push_back(ImplicitParamDecl::Create(
  1387. getContext(), /*DC=*/nullptr, StartLoc,
  1388. &getContext().Idents.get("exception_pointers"),
  1389. getContext().VoidPtrTy, ImplicitParamDecl::Other));
  1390. } else {
  1391. Args.push_back(ImplicitParamDecl::Create(
  1392. getContext(), /*DC=*/nullptr, StartLoc,
  1393. &getContext().Idents.get("abnormal_termination"),
  1394. getContext().UnsignedCharTy, ImplicitParamDecl::Other));
  1395. }
  1396. Args.push_back(ImplicitParamDecl::Create(
  1397. getContext(), /*DC=*/nullptr, StartLoc,
  1398. &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
  1399. ImplicitParamDecl::Other));
  1400. }
  1401. QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
  1402. const CGFunctionInfo &FnInfo =
  1403. CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
  1404. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1405. llvm::Function *Fn = llvm::Function::Create(
  1406. FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
  1407. IsOutlinedSEHHelper = true;
  1408. StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
  1409. OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
  1410. CurSEHParent = ParentCGF.CurSEHParent;
  1411. CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
  1412. EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
  1413. }
  1414. /// Create a stub filter function that will ultimately hold the code of the
  1415. /// filter expression. The EH preparation passes in LLVM will outline the code
  1416. /// from the main function body into this stub.
  1417. llvm::Function *
  1418. CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1419. const SEHExceptStmt &Except) {
  1420. const Expr *FilterExpr = Except.getFilterExpr();
  1421. startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
  1422. // Emit the original filter expression, convert to i32, and return.
  1423. llvm::Value *R = EmitScalarExpr(FilterExpr);
  1424. R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
  1425. FilterExpr->getType()->isSignedIntegerType());
  1426. Builder.CreateStore(R, ReturnValue);
  1427. FinishFunction(FilterExpr->getLocEnd());
  1428. return CurFn;
  1429. }
  1430. llvm::Function *
  1431. CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1432. const SEHFinallyStmt &Finally) {
  1433. const Stmt *FinallyBlock = Finally.getBlock();
  1434. startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
  1435. // Emit the original filter expression, convert to i32, and return.
  1436. EmitStmt(FinallyBlock);
  1437. FinishFunction(FinallyBlock->getLocEnd());
  1438. return CurFn;
  1439. }
  1440. void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1441. llvm::Value *ParentFP,
  1442. llvm::Value *EntryFP) {
  1443. // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
  1444. // __exception_info intrinsic.
  1445. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1446. // On Win64, the info is passed as the first parameter to the filter.
  1447. SEHInfo = &*CurFn->arg_begin();
  1448. SEHCodeSlotStack.push_back(
  1449. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1450. } else {
  1451. // On Win32, the EBP on entry to the filter points to the end of an
  1452. // exception registration object. It contains 6 32-bit fields, and the info
  1453. // pointer is stored in the second field. So, GEP 20 bytes backwards and
  1454. // load the pointer.
  1455. SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
  1456. SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
  1457. SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
  1458. SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
  1459. ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
  1460. }
  1461. // Save the exception code in the exception slot to unify exception access in
  1462. // the filter function and the landing pad.
  1463. // struct EXCEPTION_POINTERS {
  1464. // EXCEPTION_RECORD *ExceptionRecord;
  1465. // CONTEXT *ContextRecord;
  1466. // };
  1467. // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
  1468. llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
  1469. llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
  1470. llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
  1471. llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
  1472. Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
  1473. llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
  1474. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1475. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1476. }
  1477. llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
  1478. // Sema should diagnose calling this builtin outside of a filter context, but
  1479. // don't crash if we screw up.
  1480. if (!SEHInfo)
  1481. return llvm::UndefValue::get(Int8PtrTy);
  1482. assert(SEHInfo->getType() == Int8PtrTy);
  1483. return SEHInfo;
  1484. }
  1485. llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
  1486. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1487. return Builder.CreateLoad(SEHCodeSlotStack.back());
  1488. }
  1489. llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
  1490. // Abnormal termination is just the first parameter to the outlined finally
  1491. // helper.
  1492. auto AI = CurFn->arg_begin();
  1493. return Builder.CreateZExt(&*AI, Int32Ty);
  1494. }
  1495. void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
  1496. CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
  1497. if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
  1498. // Outline the finally block.
  1499. llvm::Function *FinallyFunc =
  1500. HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
  1501. // Push a cleanup for __finally blocks.
  1502. EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
  1503. return;
  1504. }
  1505. // Otherwise, we must have an __except block.
  1506. const SEHExceptStmt *Except = S.getExceptHandler();
  1507. assert(Except);
  1508. EHCatchScope *CatchScope = EHStack.pushCatch(1);
  1509. SEHCodeSlotStack.push_back(
  1510. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1511. // If the filter is known to evaluate to 1, then we can use the clause
  1512. // "catch i8* null". We can't do this on x86 because the filter has to save
  1513. // the exception code.
  1514. llvm::Constant *C =
  1515. CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
  1516. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
  1517. C->isOneValue()) {
  1518. CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
  1519. return;
  1520. }
  1521. // In general, we have to emit an outlined filter function. Use the function
  1522. // in place of the RTTI typeinfo global that C++ EH uses.
  1523. llvm::Function *FilterFunc =
  1524. HelperCGF.GenerateSEHFilterFunction(*this, *Except);
  1525. llvm::Constant *OpaqueFunc =
  1526. llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
  1527. CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
  1528. }
  1529. void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
  1530. // Just pop the cleanup if it's a __finally block.
  1531. if (S.getFinallyHandler()) {
  1532. PopCleanupBlock();
  1533. return;
  1534. }
  1535. // Otherwise, we must have an __except block.
  1536. const SEHExceptStmt *Except = S.getExceptHandler();
  1537. assert(Except && "__try must have __finally xor __except");
  1538. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1539. // Don't emit the __except block if the __try block lacked invokes.
  1540. // TODO: Model unwind edges from instructions, either with iload / istore or
  1541. // a try body function.
  1542. if (!CatchScope.hasEHBranches()) {
  1543. CatchScope.clearHandlerBlocks();
  1544. EHStack.popCatch();
  1545. SEHCodeSlotStack.pop_back();
  1546. return;
  1547. }
  1548. // The fall-through block.
  1549. llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
  1550. // We just emitted the body of the __try; jump to the continue block.
  1551. if (HaveInsertPoint())
  1552. Builder.CreateBr(ContBB);
  1553. // Check if our filter function returned true.
  1554. emitCatchDispatchBlock(*this, CatchScope);
  1555. // Grab the block before we pop the handler.
  1556. llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
  1557. EHStack.popCatch();
  1558. EmitBlockAfterUses(CatchPadBB);
  1559. // __except blocks don't get outlined into funclets, so immediately do a
  1560. // catchret.
  1561. llvm::CatchPadInst *CPI =
  1562. cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
  1563. llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
  1564. Builder.CreateCatchRet(CPI, ExceptBB);
  1565. EmitBlock(ExceptBB);
  1566. // On Win64, the exception code is returned in EAX. Copy it into the slot.
  1567. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1568. llvm::Function *SEHCodeIntrin =
  1569. CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
  1570. llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
  1571. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1572. }
  1573. // Emit the __except body.
  1574. EmitStmt(Except->getBlock());
  1575. // End the lifetime of the exception code.
  1576. SEHCodeSlotStack.pop_back();
  1577. if (HaveInsertPoint())
  1578. Builder.CreateBr(ContBB);
  1579. EmitBlock(ContBB);
  1580. }
  1581. void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
  1582. // If this code is reachable then emit a stop point (if generating
  1583. // debug info). We have to do this ourselves because we are on the
  1584. // "simple" statement path.
  1585. if (HaveInsertPoint())
  1586. EmitStopPoint(&S);
  1587. // This must be a __leave from a __finally block, which we warn on and is UB.
  1588. // Just emit unreachable.
  1589. if (!isSEHTryScope()) {
  1590. Builder.CreateUnreachable();
  1591. Builder.ClearInsertionPoint();
  1592. return;
  1593. }
  1594. EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
  1595. }