CGException.cpp 77 KB

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