CGException.cpp 76 KB

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