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