CGException.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  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. LLVM_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;
  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<llvm::Instruction *> RestoreCurrentFuncletPad(
  1040. CurrentFuncletPad);
  1041. llvm::BasicBlock *WasmCatchStartBlock = nullptr;
  1042. if (EHPersonality::get(*this).isWasmPersonality()) {
  1043. auto *CatchSwitch =
  1044. cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
  1045. WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
  1046. ? CatchSwitch->getSuccessor(1)
  1047. : CatchSwitch->getSuccessor(0);
  1048. auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
  1049. CurrentFuncletPad = CPI;
  1050. }
  1051. // Perversely, we emit the handlers backwards precisely because we
  1052. // want them to appear in source order. In all of these cases, the
  1053. // catch block will have exactly one predecessor, which will be a
  1054. // particular block in the catch dispatch. However, in the case of
  1055. // a catch-all, one of the dispatch blocks will branch to two
  1056. // different handlers, and EmitBlockAfterUses will cause the second
  1057. // handler to be moved before the first.
  1058. bool HasCatchAll = false;
  1059. for (unsigned I = NumHandlers; I != 0; --I) {
  1060. HasCatchAll |= Handlers[I - 1].isCatchAll();
  1061. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  1062. EmitBlockAfterUses(CatchBlock);
  1063. // Catch the exception if this isn't a catch-all.
  1064. const CXXCatchStmt *C = S.getHandler(I-1);
  1065. // Enter a cleanup scope, including the catch variable and the
  1066. // end-catch.
  1067. RunCleanupsScope CatchScope(*this);
  1068. // Initialize the catch variable and set up the cleanups.
  1069. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  1070. CurrentFuncletPad);
  1071. CGM.getCXXABI().emitBeginCatch(*this, C);
  1072. // Emit the PGO counter increment.
  1073. incrementProfileCounter(C);
  1074. // Perform the body of the catch.
  1075. EmitStmt(C->getHandlerBlock());
  1076. // [except.handle]p11:
  1077. // The currently handled exception is rethrown if control
  1078. // reaches the end of a handler of the function-try-block of a
  1079. // constructor or destructor.
  1080. // It is important that we only do this on fallthrough and not on
  1081. // return. Note that it's illegal to put a return in a
  1082. // constructor function-try-block's catch handler (p14), so this
  1083. // really only applies to destructors.
  1084. if (doImplicitRethrow && HaveInsertPoint()) {
  1085. CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
  1086. Builder.CreateUnreachable();
  1087. Builder.ClearInsertionPoint();
  1088. }
  1089. // Fall out through the catch cleanups.
  1090. CatchScope.ForceCleanup();
  1091. // Branch out of the try.
  1092. if (HaveInsertPoint())
  1093. Builder.CreateBr(ContBB);
  1094. }
  1095. // Because in wasm we merge all catch clauses into one big catchpad, in case
  1096. // none of the types in catch handlers matches after we test against each of
  1097. // them, we should unwind to the next EH enclosing scope. We generate a call
  1098. // to rethrow function here to do that.
  1099. if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
  1100. assert(WasmCatchStartBlock);
  1101. // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
  1102. // Wasm uses landingpad-style conditional branches to compare selectors, so
  1103. // we follow the false destination for each of the cond branches to reach
  1104. // the rethrow block.
  1105. llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
  1106. while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
  1107. auto *BI = cast<llvm::BranchInst>(TI);
  1108. assert(BI->isConditional());
  1109. RethrowBlock = BI->getSuccessor(1);
  1110. }
  1111. assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
  1112. Builder.SetInsertPoint(RethrowBlock);
  1113. llvm::Function *RethrowInCatchFn =
  1114. CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow);
  1115. EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
  1116. }
  1117. EmitBlock(ContBB);
  1118. incrementProfileCounter(&S);
  1119. }
  1120. namespace {
  1121. struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
  1122. llvm::Value *ForEHVar;
  1123. llvm::FunctionCallee EndCatchFn;
  1124. CallEndCatchForFinally(llvm::Value *ForEHVar,
  1125. llvm::FunctionCallee EndCatchFn)
  1126. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  1127. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1128. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  1129. llvm::BasicBlock *CleanupContBB =
  1130. CGF.createBasicBlock("finally.cleanup.cont");
  1131. llvm::Value *ShouldEndCatch =
  1132. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
  1133. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  1134. CGF.EmitBlock(EndCatchBB);
  1135. CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
  1136. CGF.EmitBlock(CleanupContBB);
  1137. }
  1138. };
  1139. struct PerformFinally final : EHScopeStack::Cleanup {
  1140. const Stmt *Body;
  1141. llvm::Value *ForEHVar;
  1142. llvm::FunctionCallee EndCatchFn;
  1143. llvm::FunctionCallee RethrowFn;
  1144. llvm::Value *SavedExnVar;
  1145. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  1146. llvm::FunctionCallee EndCatchFn,
  1147. llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
  1148. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  1149. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  1150. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1151. // Enter a cleanup to call the end-catch function if one was provided.
  1152. if (EndCatchFn)
  1153. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  1154. ForEHVar, EndCatchFn);
  1155. // Save the current cleanup destination in case there are
  1156. // cleanups in the finally block.
  1157. llvm::Value *SavedCleanupDest =
  1158. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  1159. "cleanup.dest.saved");
  1160. // Emit the finally block.
  1161. CGF.EmitStmt(Body);
  1162. // If the end of the finally is reachable, check whether this was
  1163. // for EH. If so, rethrow.
  1164. if (CGF.HaveInsertPoint()) {
  1165. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  1166. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  1167. llvm::Value *ShouldRethrow =
  1168. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
  1169. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  1170. CGF.EmitBlock(RethrowBB);
  1171. if (SavedExnVar) {
  1172. CGF.EmitRuntimeCallOrInvoke(RethrowFn,
  1173. CGF.Builder.CreateAlignedLoad(CGF.Int8PtrTy, SavedExnVar,
  1174. CGF.getPointerAlign()));
  1175. } else {
  1176. CGF.EmitRuntimeCallOrInvoke(RethrowFn);
  1177. }
  1178. CGF.Builder.CreateUnreachable();
  1179. CGF.EmitBlock(ContBB);
  1180. // Restore the cleanup destination.
  1181. CGF.Builder.CreateStore(SavedCleanupDest,
  1182. CGF.getNormalCleanupDestSlot());
  1183. }
  1184. // Leave the end-catch cleanup. As an optimization, pretend that
  1185. // the fallthrough path was inaccessible; we've dynamically proven
  1186. // that we're not in the EH case along that path.
  1187. if (EndCatchFn) {
  1188. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  1189. CGF.PopCleanupBlock();
  1190. CGF.Builder.restoreIP(SavedIP);
  1191. }
  1192. // Now make sure we actually have an insertion point or the
  1193. // cleanup gods will hate us.
  1194. CGF.EnsureInsertPoint();
  1195. }
  1196. };
  1197. } // end anonymous namespace
  1198. /// Enters a finally block for an implementation using zero-cost
  1199. /// exceptions. This is mostly general, but hard-codes some
  1200. /// language/ABI-specific behavior in the catch-all sections.
  1201. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
  1202. llvm::FunctionCallee beginCatchFn,
  1203. llvm::FunctionCallee endCatchFn,
  1204. llvm::FunctionCallee rethrowFn) {
  1205. assert((!!beginCatchFn) == (!!endCatchFn) &&
  1206. "begin/end catch functions not paired");
  1207. assert(rethrowFn && "rethrow function is required");
  1208. BeginCatchFn = beginCatchFn;
  1209. // The rethrow function has one of the following two types:
  1210. // void (*)()
  1211. // void (*)(void*)
  1212. // In the latter case we need to pass it the exception object.
  1213. // But we can't use the exception slot because the @finally might
  1214. // have a landing pad (which would overwrite the exception slot).
  1215. llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
  1216. SavedExnVar = nullptr;
  1217. if (rethrowFnTy->getNumParams())
  1218. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1219. // A finally block is a statement which must be executed on any edge
  1220. // out of a given scope. Unlike a cleanup, the finally block may
  1221. // contain arbitrary control flow leading out of itself. In
  1222. // addition, finally blocks should always be executed, even if there
  1223. // are no catch handlers higher on the stack. Therefore, we
  1224. // surround the protected scope with a combination of a normal
  1225. // cleanup (to catch attempts to break out of the block via normal
  1226. // control flow) and an EH catch-all (semantically "outside" any try
  1227. // statement to which the finally block might have been attached).
  1228. // The finally block itself is generated in the context of a cleanup
  1229. // which conditionally leaves the catch-all.
  1230. // Jump destination for performing the finally block on an exception
  1231. // edge. We'll never actually reach this block, so unreachable is
  1232. // fine.
  1233. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1234. // Whether the finally block is being executed for EH purposes.
  1235. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1236. CGF.Builder.CreateFlagStore(false, ForEHVar);
  1237. // Enter a normal cleanup which will perform the @finally block.
  1238. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1239. ForEHVar, endCatchFn,
  1240. rethrowFn, SavedExnVar);
  1241. // Enter a catch-all scope.
  1242. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1243. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1244. catchScope->setCatchAllHandler(0, catchBB);
  1245. }
  1246. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1247. // Leave the finally catch-all.
  1248. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1249. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1250. CGF.popCatchScope();
  1251. // If there are any references to the catch-all block, emit it.
  1252. if (catchBB->use_empty()) {
  1253. delete catchBB;
  1254. } else {
  1255. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1256. CGF.EmitBlock(catchBB);
  1257. llvm::Value *exn = nullptr;
  1258. // If there's a begin-catch function, call it.
  1259. if (BeginCatchFn) {
  1260. exn = CGF.getExceptionFromSlot();
  1261. CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
  1262. }
  1263. // If we need to remember the exception pointer to rethrow later, do so.
  1264. if (SavedExnVar) {
  1265. if (!exn) exn = CGF.getExceptionFromSlot();
  1266. CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
  1267. }
  1268. // Tell the cleanups in the finally block that we're do this for EH.
  1269. CGF.Builder.CreateFlagStore(true, ForEHVar);
  1270. // Thread a jump through the finally cleanup.
  1271. CGF.EmitBranchThroughCleanup(RethrowDest);
  1272. CGF.Builder.restoreIP(savedIP);
  1273. }
  1274. // Finally, leave the @finally cleanup.
  1275. CGF.PopCleanupBlock();
  1276. }
  1277. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1278. if (TerminateLandingPad)
  1279. return TerminateLandingPad;
  1280. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1281. // This will get inserted at the end of the function.
  1282. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1283. Builder.SetInsertPoint(TerminateLandingPad);
  1284. // Tell the backend that this is a landing pad.
  1285. const EHPersonality &Personality = EHPersonality::get(*this);
  1286. if (!CurFn->hasPersonalityFn())
  1287. CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
  1288. llvm::LandingPadInst *LPadInst =
  1289. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
  1290. LPadInst->addClause(getCatchAllValue(*this));
  1291. llvm::Value *Exn = nullptr;
  1292. if (getLangOpts().CPlusPlus)
  1293. Exn = Builder.CreateExtractValue(LPadInst, 0);
  1294. llvm::CallInst *terminateCall =
  1295. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1296. terminateCall->setDoesNotReturn();
  1297. Builder.CreateUnreachable();
  1298. // Restore the saved insertion state.
  1299. Builder.restoreIP(SavedIP);
  1300. return TerminateLandingPad;
  1301. }
  1302. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1303. if (TerminateHandler)
  1304. return TerminateHandler;
  1305. // Set up the terminate handler. This block is inserted at the very
  1306. // end of the function by FinishFunction.
  1307. TerminateHandler = createBasicBlock("terminate.handler");
  1308. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1309. Builder.SetInsertPoint(TerminateHandler);
  1310. llvm::Value *Exn = nullptr;
  1311. if (getLangOpts().CPlusPlus)
  1312. Exn = getExceptionFromSlot();
  1313. llvm::CallInst *terminateCall =
  1314. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1315. terminateCall->setDoesNotReturn();
  1316. Builder.CreateUnreachable();
  1317. // Restore the saved insertion state.
  1318. Builder.restoreIP(SavedIP);
  1319. return TerminateHandler;
  1320. }
  1321. llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
  1322. assert(EHPersonality::get(*this).usesFuncletPads() &&
  1323. "use getTerminateLandingPad for non-funclet EH");
  1324. llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
  1325. if (TerminateFunclet)
  1326. return TerminateFunclet;
  1327. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1328. // Set up the terminate handler. This block is inserted at the very
  1329. // end of the function by FinishFunction.
  1330. TerminateFunclet = createBasicBlock("terminate.handler");
  1331. Builder.SetInsertPoint(TerminateFunclet);
  1332. // Create the cleanuppad using the current parent pad as its token. Use 'none'
  1333. // if this is a top-level terminate scope, which is the common case.
  1334. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  1335. CurrentFuncletPad);
  1336. llvm::Value *ParentPad = CurrentFuncletPad;
  1337. if (!ParentPad)
  1338. ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
  1339. CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
  1340. // Emit the __std_terminate call.
  1341. llvm::CallInst *terminateCall =
  1342. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
  1343. terminateCall->setDoesNotReturn();
  1344. Builder.CreateUnreachable();
  1345. // Restore the saved insertion state.
  1346. Builder.restoreIP(SavedIP);
  1347. return TerminateFunclet;
  1348. }
  1349. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
  1350. if (EHResumeBlock) return EHResumeBlock;
  1351. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1352. // We emit a jump to a notional label at the outermost unwind state.
  1353. EHResumeBlock = createBasicBlock("eh.resume");
  1354. Builder.SetInsertPoint(EHResumeBlock);
  1355. const EHPersonality &Personality = EHPersonality::get(*this);
  1356. // This can always be a call because we necessarily didn't find
  1357. // anything on the EH stack which needs our help.
  1358. const char *RethrowName = Personality.CatchallRethrowFn;
  1359. if (RethrowName != nullptr && !isCleanup) {
  1360. EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
  1361. getExceptionFromSlot())->setDoesNotReturn();
  1362. Builder.CreateUnreachable();
  1363. Builder.restoreIP(SavedIP);
  1364. return EHResumeBlock;
  1365. }
  1366. // Recreate the landingpad's return value for the 'resume' instruction.
  1367. llvm::Value *Exn = getExceptionFromSlot();
  1368. llvm::Value *Sel = getSelectorFromSlot();
  1369. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
  1370. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1371. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1372. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1373. Builder.CreateResume(LPadVal);
  1374. Builder.restoreIP(SavedIP);
  1375. return EHResumeBlock;
  1376. }
  1377. void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
  1378. EnterSEHTryStmt(S);
  1379. {
  1380. JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
  1381. SEHTryEpilogueStack.push_back(&TryExit);
  1382. llvm::BasicBlock *TryBB = nullptr;
  1383. // IsEHa: emit an invoke to _seh_try_begin() runtime for -EHa
  1384. if (getLangOpts().EHAsynch) {
  1385. EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
  1386. if (SEHTryEpilogueStack.size() == 1) // outermost only
  1387. TryBB = Builder.GetInsertBlock();
  1388. }
  1389. EmitStmt(S.getTryBlock());
  1390. // Volatilize all blocks in Try, till current insert point
  1391. if (TryBB) {
  1392. llvm::SmallPtrSet<llvm::BasicBlock *, 10> Visited;
  1393. VolatilizeTryBlocks(TryBB, Visited);
  1394. }
  1395. SEHTryEpilogueStack.pop_back();
  1396. if (!TryExit.getBlock()->use_empty())
  1397. EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
  1398. else
  1399. delete TryExit.getBlock();
  1400. }
  1401. ExitSEHTryStmt(S);
  1402. }
  1403. // Recursively walk through blocks in a _try
  1404. // and make all memory instructions volatile
  1405. void CodeGenFunction::VolatilizeTryBlocks(
  1406. llvm::BasicBlock *BB, llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V) {
  1407. if (BB == SEHTryEpilogueStack.back()->getBlock() /* end of Try */ ||
  1408. !V.insert(BB).second /* already visited */ ||
  1409. !BB->getParent() /* not emitted */ || BB->empty())
  1410. return;
  1411. if (!BB->isEHPad()) {
  1412. for (llvm::BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE;
  1413. ++J) {
  1414. if (auto LI = dyn_cast<llvm::LoadInst>(J)) {
  1415. LI->setVolatile(true);
  1416. } else if (auto SI = dyn_cast<llvm::StoreInst>(J)) {
  1417. SI->setVolatile(true);
  1418. } else if (auto* MCI = dyn_cast<llvm::MemIntrinsic>(J)) {
  1419. MCI->setVolatile(llvm::ConstantInt::get(Builder.getInt1Ty(), 1));
  1420. }
  1421. }
  1422. }
  1423. const llvm::Instruction *TI = BB->getTerminator();
  1424. if (TI) {
  1425. unsigned N = TI->getNumSuccessors();
  1426. for (unsigned I = 0; I < N; I++)
  1427. VolatilizeTryBlocks(TI->getSuccessor(I), V);
  1428. }
  1429. }
  1430. namespace {
  1431. struct PerformSEHFinally final : EHScopeStack::Cleanup {
  1432. llvm::Function *OutlinedFinally;
  1433. PerformSEHFinally(llvm::Function *OutlinedFinally)
  1434. : OutlinedFinally(OutlinedFinally) {}
  1435. void Emit(CodeGenFunction &CGF, Flags F) override {
  1436. ASTContext &Context = CGF.getContext();
  1437. CodeGenModule &CGM = CGF.CGM;
  1438. CallArgList Args;
  1439. // Compute the two argument values.
  1440. QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
  1441. llvm::Value *FP = nullptr;
  1442. // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
  1443. if (CGF.IsOutlinedSEHHelper) {
  1444. FP = &CGF.CurFn->arg_begin()[1];
  1445. } else {
  1446. llvm::Function *LocalAddrFn =
  1447. CGM.getIntrinsic(llvm::Intrinsic::localaddress);
  1448. FP = CGF.Builder.CreateCall(LocalAddrFn);
  1449. }
  1450. llvm::Value *IsForEH =
  1451. llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
  1452. // Except _leave and fall-through at the end, all other exits in a _try
  1453. // (return/goto/continue/break) are considered as abnormal terminations
  1454. // since _leave/fall-through is always Indexed 0,
  1455. // just use NormalCleanupDestSlot (>= 1 for goto/return/..),
  1456. // as 1st Arg to indicate abnormal termination
  1457. if (!F.isForEHCleanup() && F.hasExitSwitch()) {
  1458. Address Addr = CGF.getNormalCleanupDestSlot();
  1459. llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
  1460. llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
  1461. IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
  1462. }
  1463. Args.add(RValue::get(IsForEH), ArgTys[0]);
  1464. Args.add(RValue::get(FP), ArgTys[1]);
  1465. // Arrange a two-arg function info and type.
  1466. const CGFunctionInfo &FnInfo =
  1467. CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
  1468. auto Callee = CGCallee::forDirect(OutlinedFinally);
  1469. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  1470. }
  1471. };
  1472. } // end anonymous namespace
  1473. namespace {
  1474. /// Find all local variable captures in the statement.
  1475. struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
  1476. CodeGenFunction &ParentCGF;
  1477. const VarDecl *ParentThis;
  1478. llvm::SmallSetVector<const VarDecl *, 4> Captures;
  1479. Address SEHCodeSlot = Address::invalid();
  1480. CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
  1481. : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
  1482. // Return true if we need to do any capturing work.
  1483. bool foundCaptures() {
  1484. return !Captures.empty() || SEHCodeSlot.isValid();
  1485. }
  1486. void Visit(const Stmt *S) {
  1487. // See if this is a capture, then recurse.
  1488. ConstStmtVisitor<CaptureFinder>::Visit(S);
  1489. for (const Stmt *Child : S->children())
  1490. if (Child)
  1491. Visit(Child);
  1492. }
  1493. void VisitDeclRefExpr(const DeclRefExpr *E) {
  1494. // If this is already a capture, just make sure we capture 'this'.
  1495. if (E->refersToEnclosingVariableOrCapture())
  1496. Captures.insert(ParentThis);
  1497. const auto *D = dyn_cast<VarDecl>(E->getDecl());
  1498. if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
  1499. Captures.insert(D);
  1500. }
  1501. void VisitCXXThisExpr(const CXXThisExpr *E) {
  1502. Captures.insert(ParentThis);
  1503. }
  1504. void VisitCallExpr(const CallExpr *E) {
  1505. // We only need to add parent frame allocations for these builtins in x86.
  1506. if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
  1507. return;
  1508. unsigned ID = E->getBuiltinCallee();
  1509. switch (ID) {
  1510. case Builtin::BI__exception_code:
  1511. case Builtin::BI_exception_code:
  1512. // This is the simple case where we are the outermost finally. All we
  1513. // have to do here is make sure we escape this and recover it in the
  1514. // outlined handler.
  1515. if (!SEHCodeSlot.isValid())
  1516. SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
  1517. break;
  1518. }
  1519. }
  1520. };
  1521. } // end anonymous namespace
  1522. Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1523. Address ParentVar,
  1524. llvm::Value *ParentFP) {
  1525. llvm::CallInst *RecoverCall = nullptr;
  1526. CGBuilderTy Builder(*this, AllocaInsertPt);
  1527. if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
  1528. // Mark the variable escaped if nobody else referenced it and compute the
  1529. // localescape index.
  1530. auto InsertPair = ParentCGF.EscapedLocals.insert(
  1531. std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
  1532. int FrameEscapeIdx = InsertPair.first->second;
  1533. // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
  1534. llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
  1535. &CGM.getModule(), llvm::Intrinsic::localrecover);
  1536. llvm::Constant *ParentI8Fn =
  1537. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1538. RecoverCall = Builder.CreateCall(
  1539. FrameRecoverFn, {ParentI8Fn, ParentFP,
  1540. llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
  1541. } else {
  1542. // If the parent didn't have an alloca, we're doing some nested outlining.
  1543. // Just clone the existing localrecover call, but tweak the FP argument to
  1544. // use our FP value. All other arguments are constants.
  1545. auto *ParentRecover =
  1546. cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
  1547. assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
  1548. "expected alloca or localrecover in parent LocalDeclMap");
  1549. RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
  1550. RecoverCall->setArgOperand(1, ParentFP);
  1551. RecoverCall->insertBefore(AllocaInsertPt);
  1552. }
  1553. // Bitcast the variable, rename it, and insert it in the local decl map.
  1554. llvm::Value *ChildVar =
  1555. Builder.CreateBitCast(RecoverCall, ParentVar.getType());
  1556. ChildVar->setName(ParentVar.getName());
  1557. return Address(ChildVar, ParentVar.getAlignment());
  1558. }
  1559. void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
  1560. const Stmt *OutlinedStmt,
  1561. bool IsFilter) {
  1562. // Find all captures in the Stmt.
  1563. CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
  1564. Finder.Visit(OutlinedStmt);
  1565. // We can exit early on x86_64 when there are no captures. We just have to
  1566. // save the exception code in filters so that __exception_code() works.
  1567. if (!Finder.foundCaptures() &&
  1568. CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1569. if (IsFilter)
  1570. EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
  1571. return;
  1572. }
  1573. llvm::Value *EntryFP = nullptr;
  1574. CGBuilderTy Builder(CGM, AllocaInsertPt);
  1575. if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
  1576. // 32-bit SEH filters need to be careful about FP recovery. The end of the
  1577. // EH registration is passed in as the EBP physical register. We can
  1578. // recover that with llvm.frameaddress(1).
  1579. EntryFP = Builder.CreateCall(
  1580. CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
  1581. {Builder.getInt32(1)});
  1582. } else {
  1583. // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
  1584. // second parameter.
  1585. auto AI = CurFn->arg_begin();
  1586. ++AI;
  1587. EntryFP = &*AI;
  1588. }
  1589. llvm::Value *ParentFP = EntryFP;
  1590. if (IsFilter) {
  1591. // Given whatever FP the runtime provided us in EntryFP, recover the true
  1592. // frame pointer of the parent function. We only need to do this in filters,
  1593. // since finally funclets recover the parent FP for us.
  1594. llvm::Function *RecoverFPIntrin =
  1595. CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
  1596. llvm::Constant *ParentI8Fn =
  1597. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1598. ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
  1599. // if the parent is a _finally, the passed-in ParentFP is the FP
  1600. // of parent _finally, not Establisher's FP (FP of outermost function).
  1601. // Establkisher FP is 2nd paramenter passed into parent _finally.
  1602. // Fortunately, it's always saved in parent's frame. The following
  1603. // code retrieves it, and escapes it so that spill instruction won't be
  1604. // optimized away.
  1605. if (ParentCGF.ParentCGF != nullptr) {
  1606. // Locate and escape Parent's frame_pointer.addr alloca
  1607. // Depending on target, should be 1st/2nd one in LocalDeclMap.
  1608. // Let's just scan for ImplicitParamDecl with VoidPtrTy.
  1609. llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
  1610. for (auto &I : ParentCGF.LocalDeclMap) {
  1611. const VarDecl *D = cast<VarDecl>(I.first);
  1612. if (isa<ImplicitParamDecl>(D) &&
  1613. D->getType() == getContext().VoidPtrTy) {
  1614. assert(D->getName().startswith("frame_pointer"));
  1615. FramePtrAddrAlloca = cast<llvm::AllocaInst>(I.second.getPointer());
  1616. break;
  1617. }
  1618. }
  1619. assert(FramePtrAddrAlloca);
  1620. auto InsertPair = ParentCGF.EscapedLocals.insert(
  1621. std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
  1622. int FrameEscapeIdx = InsertPair.first->second;
  1623. // an example of a filter's prolog::
  1624. // %0 = call i8* @llvm.eh.recoverfp(bitcast(@"?fin$0@0@main@@"),..)
  1625. // %1 = call i8* @llvm.localrecover(bitcast(@"?fin$0@0@main@@"),..)
  1626. // %2 = bitcast i8* %1 to i8**
  1627. // %3 = load i8*, i8* *%2, align 8
  1628. // ==> %3 is the frame-pointer of outermost host function
  1629. llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
  1630. &CGM.getModule(), llvm::Intrinsic::localrecover);
  1631. llvm::Constant *ParentI8Fn =
  1632. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1633. ParentFP = Builder.CreateCall(
  1634. FrameRecoverFn, {ParentI8Fn, ParentFP,
  1635. llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
  1636. ParentFP = Builder.CreateBitCast(ParentFP, CGM.VoidPtrPtrTy);
  1637. ParentFP = Builder.CreateLoad(Address(ParentFP, getPointerAlign()));
  1638. }
  1639. }
  1640. // Create llvm.localrecover calls for all captures.
  1641. for (const VarDecl *VD : Finder.Captures) {
  1642. if (VD->getType()->isVariablyModifiedType()) {
  1643. CGM.ErrorUnsupported(VD, "VLA captured by SEH");
  1644. continue;
  1645. }
  1646. assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
  1647. "captured non-local variable");
  1648. auto L = ParentCGF.LambdaCaptureFields.find(VD);
  1649. if (L != ParentCGF.LambdaCaptureFields.end()) {
  1650. LambdaCaptureFields[VD] = L->second;
  1651. continue;
  1652. }
  1653. // If this decl hasn't been declared yet, it will be declared in the
  1654. // OutlinedStmt.
  1655. auto I = ParentCGF.LocalDeclMap.find(VD);
  1656. if (I == ParentCGF.LocalDeclMap.end())
  1657. continue;
  1658. Address ParentVar = I->second;
  1659. Address Recovered =
  1660. recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
  1661. setAddrOfLocalVar(VD, Recovered);
  1662. if (isa<ImplicitParamDecl>(VD)) {
  1663. CXXABIThisAlignment = ParentCGF.CXXABIThisAlignment;
  1664. CXXThisAlignment = ParentCGF.CXXThisAlignment;
  1665. CXXABIThisValue = Builder.CreateLoad(Recovered, "this");
  1666. if (ParentCGF.LambdaThisCaptureField) {
  1667. LambdaThisCaptureField = ParentCGF.LambdaThisCaptureField;
  1668. // We are in a lambda function where "this" is captured so the
  1669. // CXXThisValue need to be loaded from the lambda capture
  1670. LValue ThisFieldLValue =
  1671. EmitLValueForLambdaField(LambdaThisCaptureField);
  1672. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  1673. CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
  1674. } else {
  1675. CXXThisValue = EmitLoadOfLValue(ThisFieldLValue, SourceLocation())
  1676. .getScalarVal();
  1677. }
  1678. } else {
  1679. CXXThisValue = CXXABIThisValue;
  1680. }
  1681. }
  1682. }
  1683. if (Finder.SEHCodeSlot.isValid()) {
  1684. SEHCodeSlotStack.push_back(
  1685. recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
  1686. }
  1687. if (IsFilter)
  1688. EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
  1689. }
  1690. /// Arrange a function prototype that can be called by Windows exception
  1691. /// handling personalities. On Win64, the prototype looks like:
  1692. /// RetTy func(void *EHPtrs, void *ParentFP);
  1693. void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
  1694. bool IsFilter,
  1695. const Stmt *OutlinedStmt) {
  1696. SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
  1697. // Get the mangled function name.
  1698. SmallString<128> Name;
  1699. {
  1700. llvm::raw_svector_ostream OS(Name);
  1701. const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
  1702. assert(ParentSEHFn && "No CurSEHParent!");
  1703. MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
  1704. if (IsFilter)
  1705. Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
  1706. else
  1707. Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
  1708. }
  1709. FunctionArgList Args;
  1710. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
  1711. // All SEH finally functions take two parameters. Win64 filters take two
  1712. // parameters. Win32 filters take no parameters.
  1713. if (IsFilter) {
  1714. Args.push_back(ImplicitParamDecl::Create(
  1715. getContext(), /*DC=*/nullptr, StartLoc,
  1716. &getContext().Idents.get("exception_pointers"),
  1717. getContext().VoidPtrTy, ImplicitParamDecl::Other));
  1718. } else {
  1719. Args.push_back(ImplicitParamDecl::Create(
  1720. getContext(), /*DC=*/nullptr, StartLoc,
  1721. &getContext().Idents.get("abnormal_termination"),
  1722. getContext().UnsignedCharTy, ImplicitParamDecl::Other));
  1723. }
  1724. Args.push_back(ImplicitParamDecl::Create(
  1725. getContext(), /*DC=*/nullptr, StartLoc,
  1726. &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
  1727. ImplicitParamDecl::Other));
  1728. }
  1729. QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
  1730. const CGFunctionInfo &FnInfo =
  1731. CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
  1732. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1733. llvm::Function *Fn = llvm::Function::Create(
  1734. FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
  1735. IsOutlinedSEHHelper = true;
  1736. StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
  1737. OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
  1738. CurSEHParent = ParentCGF.CurSEHParent;
  1739. CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
  1740. EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
  1741. }
  1742. /// Create a stub filter function that will ultimately hold the code of the
  1743. /// filter expression. The EH preparation passes in LLVM will outline the code
  1744. /// from the main function body into this stub.
  1745. llvm::Function *
  1746. CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1747. const SEHExceptStmt &Except) {
  1748. const Expr *FilterExpr = Except.getFilterExpr();
  1749. startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
  1750. // Emit the original filter expression, convert to i32, and return.
  1751. llvm::Value *R = EmitScalarExpr(FilterExpr);
  1752. R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
  1753. FilterExpr->getType()->isSignedIntegerType());
  1754. Builder.CreateStore(R, ReturnValue);
  1755. FinishFunction(FilterExpr->getEndLoc());
  1756. return CurFn;
  1757. }
  1758. llvm::Function *
  1759. CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1760. const SEHFinallyStmt &Finally) {
  1761. const Stmt *FinallyBlock = Finally.getBlock();
  1762. startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
  1763. // Emit the original filter expression, convert to i32, and return.
  1764. EmitStmt(FinallyBlock);
  1765. FinishFunction(FinallyBlock->getEndLoc());
  1766. return CurFn;
  1767. }
  1768. void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1769. llvm::Value *ParentFP,
  1770. llvm::Value *EntryFP) {
  1771. // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
  1772. // __exception_info intrinsic.
  1773. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1774. // On Win64, the info is passed as the first parameter to the filter.
  1775. SEHInfo = &*CurFn->arg_begin();
  1776. SEHCodeSlotStack.push_back(
  1777. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1778. } else {
  1779. // On Win32, the EBP on entry to the filter points to the end of an
  1780. // exception registration object. It contains 6 32-bit fields, and the info
  1781. // pointer is stored in the second field. So, GEP 20 bytes backwards and
  1782. // load the pointer.
  1783. SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
  1784. SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
  1785. SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
  1786. SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
  1787. ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
  1788. }
  1789. // Save the exception code in the exception slot to unify exception access in
  1790. // the filter function and the landing pad.
  1791. // struct EXCEPTION_POINTERS {
  1792. // EXCEPTION_RECORD *ExceptionRecord;
  1793. // CONTEXT *ContextRecord;
  1794. // };
  1795. // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
  1796. llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
  1797. llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
  1798. llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
  1799. llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
  1800. Rec = Builder.CreateAlignedLoad(RecordTy, Rec, getPointerAlign());
  1801. llvm::Value *Code = Builder.CreateAlignedLoad(Int32Ty, Rec, getIntAlign());
  1802. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1803. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1804. }
  1805. llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
  1806. // Sema should diagnose calling this builtin outside of a filter context, but
  1807. // don't crash if we screw up.
  1808. if (!SEHInfo)
  1809. return llvm::UndefValue::get(Int8PtrTy);
  1810. assert(SEHInfo->getType() == Int8PtrTy);
  1811. return SEHInfo;
  1812. }
  1813. llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
  1814. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1815. return Builder.CreateLoad(SEHCodeSlotStack.back());
  1816. }
  1817. llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
  1818. // Abnormal termination is just the first parameter to the outlined finally
  1819. // helper.
  1820. auto AI = CurFn->arg_begin();
  1821. return Builder.CreateZExt(&*AI, Int32Ty);
  1822. }
  1823. void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
  1824. llvm::Function *FinallyFunc) {
  1825. EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
  1826. }
  1827. void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
  1828. CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
  1829. HelperCGF.ParentCGF = this;
  1830. if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
  1831. // Outline the finally block.
  1832. llvm::Function *FinallyFunc =
  1833. HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
  1834. // Push a cleanup for __finally blocks.
  1835. EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
  1836. return;
  1837. }
  1838. // Otherwise, we must have an __except block.
  1839. const SEHExceptStmt *Except = S.getExceptHandler();
  1840. assert(Except);
  1841. EHCatchScope *CatchScope = EHStack.pushCatch(1);
  1842. SEHCodeSlotStack.push_back(
  1843. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1844. // If the filter is known to evaluate to 1, then we can use the clause
  1845. // "catch i8* null". We can't do this on x86 because the filter has to save
  1846. // the exception code.
  1847. llvm::Constant *C =
  1848. ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
  1849. getContext().IntTy);
  1850. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
  1851. C->isOneValue()) {
  1852. CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
  1853. return;
  1854. }
  1855. // In general, we have to emit an outlined filter function. Use the function
  1856. // in place of the RTTI typeinfo global that C++ EH uses.
  1857. llvm::Function *FilterFunc =
  1858. HelperCGF.GenerateSEHFilterFunction(*this, *Except);
  1859. llvm::Constant *OpaqueFunc =
  1860. llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
  1861. CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
  1862. }
  1863. void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
  1864. // Just pop the cleanup if it's a __finally block.
  1865. if (S.getFinallyHandler()) {
  1866. PopCleanupBlock();
  1867. return;
  1868. }
  1869. // IsEHa: emit an invoke _seh_try_end() to mark end of FT flow
  1870. if (getLangOpts().EHAsynch && Builder.GetInsertBlock()) {
  1871. llvm::FunctionCallee SehTryEnd = getSehTryEndFn(CGM);
  1872. EmitRuntimeCallOrInvoke(SehTryEnd);
  1873. }
  1874. // Otherwise, we must have an __except block.
  1875. const SEHExceptStmt *Except = S.getExceptHandler();
  1876. assert(Except && "__try must have __finally xor __except");
  1877. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1878. // Don't emit the __except block if the __try block lacked invokes.
  1879. // TODO: Model unwind edges from instructions, either with iload / istore or
  1880. // a try body function.
  1881. if (!CatchScope.hasEHBranches()) {
  1882. CatchScope.clearHandlerBlocks();
  1883. EHStack.popCatch();
  1884. SEHCodeSlotStack.pop_back();
  1885. return;
  1886. }
  1887. // The fall-through block.
  1888. llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
  1889. // We just emitted the body of the __try; jump to the continue block.
  1890. if (HaveInsertPoint())
  1891. Builder.CreateBr(ContBB);
  1892. // Check if our filter function returned true.
  1893. emitCatchDispatchBlock(*this, CatchScope);
  1894. // Grab the block before we pop the handler.
  1895. llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
  1896. EHStack.popCatch();
  1897. EmitBlockAfterUses(CatchPadBB);
  1898. // __except blocks don't get outlined into funclets, so immediately do a
  1899. // catchret.
  1900. llvm::CatchPadInst *CPI =
  1901. cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
  1902. llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
  1903. Builder.CreateCatchRet(CPI, ExceptBB);
  1904. EmitBlock(ExceptBB);
  1905. // On Win64, the exception code is returned in EAX. Copy it into the slot.
  1906. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1907. llvm::Function *SEHCodeIntrin =
  1908. CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
  1909. llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
  1910. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1911. }
  1912. // Emit the __except body.
  1913. EmitStmt(Except->getBlock());
  1914. // End the lifetime of the exception code.
  1915. SEHCodeSlotStack.pop_back();
  1916. if (HaveInsertPoint())
  1917. Builder.CreateBr(ContBB);
  1918. EmitBlock(ContBB);
  1919. }
  1920. void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
  1921. // If this code is reachable then emit a stop point (if generating
  1922. // debug info). We have to do this ourselves because we are on the
  1923. // "simple" statement path.
  1924. if (HaveInsertPoint())
  1925. EmitStopPoint(&S);
  1926. // This must be a __leave from a __finally block, which we warn on and is UB.
  1927. // Just emit unreachable.
  1928. if (!isSEHTryScope()) {
  1929. Builder.CreateUnreachable();
  1930. Builder.ClearInsertionPoint();
  1931. return;
  1932. }
  1933. EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
  1934. }