CGException.cpp 85 KB

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