1//===-- CGCleanup.h - Classes for cleanups IR generation --------*- 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// These classes support the generation of LLVM IR for cleanups.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
14#define LLVM_CLANG_LIB_CODEGEN_CGCLEANUP_H
15
16#include "EHScopeStack.h"
17
18#include "Address.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21
22namespace llvm {
23class BasicBlock;
24class Value;
25class ConstantInt;
26}
27
28namespace clang {
29class FunctionDecl;
30namespace CodeGen {
31class CodeGenModule;
32class CodeGenFunction;
33
34/// The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the
35/// type of a catch handler, so we use this wrapper.
36struct CatchTypeInfo {
37 llvm::Constant *RTTI;
38 unsigned Flags;
39};
40
41/// A protected scope for zero-cost EH handling.
42class EHScope {
43public:
44 enum Kind { Cleanup, Catch, Terminate, Filter };
45
46private:
47 llvm::BasicBlock *CachedLandingPad;
48 llvm::BasicBlock *CachedEHDispatchBlock;
49
50 EHScopeStack::stable_iterator EnclosingEHScope;
51
52 class CommonBitFields {
53 friend class EHScope;
54 LLVM_PREFERRED_TYPE(Kind)
55 unsigned Kind : 3;
56 };
57 enum { NumCommonBits = 3 };
58
59protected:
60 class CatchBitFields {
61 friend class EHCatchScope;
62 unsigned : NumCommonBits;
63
64 unsigned NumHandlers : 32 - NumCommonBits;
65 };
66
67 class CleanupBitFields {
68 friend class EHCleanupScope;
69 unsigned : NumCommonBits;
70
71 /// Whether this cleanup needs to be run along normal edges.
72 LLVM_PREFERRED_TYPE(bool)
73 unsigned IsNormalCleanup : 1;
74
75 /// Whether this cleanup needs to be run along exception edges.
76 LLVM_PREFERRED_TYPE(bool)
77 unsigned IsEHCleanup : 1;
78
79 /// Whether this cleanup is currently active.
80 LLVM_PREFERRED_TYPE(bool)
81 unsigned IsActive : 1;
82
83 /// Whether this cleanup is a lifetime marker
84 LLVM_PREFERRED_TYPE(bool)
85 unsigned IsLifetimeMarker : 1;
86
87 /// Whether the normal cleanup should test the activation flag.
88 LLVM_PREFERRED_TYPE(bool)
89 unsigned TestFlagInNormalCleanup : 1;
90
91 /// Whether the EH cleanup should test the activation flag.
92 LLVM_PREFERRED_TYPE(bool)
93 unsigned TestFlagInEHCleanup : 1;
94
95 /// The amount of extra storage needed by the Cleanup.
96 /// Always a multiple of the scope-stack alignment.
97 unsigned CleanupSize : 12;
98 };
99
100 class FilterBitFields {
101 friend class EHFilterScope;
102 unsigned : NumCommonBits;
103
104 unsigned NumFilters : 32 - NumCommonBits;
105 };
106
107 union {
108 CommonBitFields CommonBits;
109 CatchBitFields CatchBits;
110 CleanupBitFields CleanupBits;
111 FilterBitFields FilterBits;
112 };
113
114public:
115 EHScope(Kind kind, EHScopeStack::stable_iterator enclosingEHScope)
116 : CachedLandingPad(nullptr), CachedEHDispatchBlock(nullptr),
117 EnclosingEHScope(enclosingEHScope) {
118 CommonBits.Kind = kind;
119 }
120
121 Kind getKind() const { return static_cast<Kind>(CommonBits.Kind); }
122
123 llvm::BasicBlock *getCachedLandingPad() const {
124 return CachedLandingPad;
125 }
126
127 void setCachedLandingPad(llvm::BasicBlock *block) {
128 CachedLandingPad = block;
129 }
130
131 llvm::BasicBlock *getCachedEHDispatchBlock() const {
132 return CachedEHDispatchBlock;
133 }
134
135 void setCachedEHDispatchBlock(llvm::BasicBlock *block) {
136 CachedEHDispatchBlock = block;
137 }
138
139 bool hasEHBranches() const {
140 if (llvm::BasicBlock *block = getCachedEHDispatchBlock())
141 return !block->use_empty();
142 return false;
143 }
144
145 EHScopeStack::stable_iterator getEnclosingEHScope() const {
146 return EnclosingEHScope;
147 }
148};
149
150/// A scope which attempts to handle some, possibly all, types of
151/// exceptions.
152///
153/// Objective C \@finally blocks are represented using a cleanup scope
154/// after the catch scope.
155class EHCatchScope : public EHScope {
156 // In effect, we have a flexible array member
157 // Handler Handlers[0];
158 // But that's only standard in C99, not C++, so we have to do
159 // annoying pointer arithmetic instead.
160
161public:
162 struct Handler {
163 /// A type info value, or null (C++ null, not an LLVM null pointer)
164 /// for a catch-all.
165 CatchTypeInfo Type;
166
167 /// The catch handler for this type.
168 llvm::BasicBlock *Block;
169
170 bool isCatchAll() const { return Type.RTTI == nullptr; }
171 };
172
173private:
174 friend class EHScopeStack;
175
176 Handler *getHandlers() {
177 return reinterpret_cast<Handler*>(this+1);
178 }
179
180 const Handler *getHandlers() const {
181 return reinterpret_cast<const Handler*>(this+1);
182 }
183
184public:
185 static size_t getSizeForNumHandlers(unsigned N) {
186 return sizeof(EHCatchScope) + N * sizeof(Handler);
187 }
188
189 EHCatchScope(unsigned numHandlers,
190 EHScopeStack::stable_iterator enclosingEHScope)
191 : EHScope(Catch, enclosingEHScope) {
192 CatchBits.NumHandlers = numHandlers;
193 assert(CatchBits.NumHandlers == numHandlers && "NumHandlers overflow?");
194 }
195
196 unsigned getNumHandlers() const {
197 return CatchBits.NumHandlers;
198 }
199
200 void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block) {
201 setHandler(I, Type: CatchTypeInfo{.RTTI: nullptr, .Flags: 0}, Block);
202 }
203
204 void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block) {
205 assert(I < getNumHandlers());
206 getHandlers()[I].Type = CatchTypeInfo{.RTTI: Type, .Flags: 0};
207 getHandlers()[I].Block = Block;
208 }
209
210 void setHandler(unsigned I, CatchTypeInfo Type, llvm::BasicBlock *Block) {
211 assert(I < getNumHandlers());
212 getHandlers()[I].Type = Type;
213 getHandlers()[I].Block = Block;
214 }
215
216 const Handler &getHandler(unsigned I) const {
217 assert(I < getNumHandlers());
218 return getHandlers()[I];
219 }
220
221 // Clear all handler blocks.
222 // FIXME: it's better to always call clearHandlerBlocks in DTOR and have a
223 // 'takeHandler' or some such function which removes ownership from the
224 // EHCatchScope object if the handlers should live longer than EHCatchScope.
225 void clearHandlerBlocks() {
226 for (unsigned I = 0, N = getNumHandlers(); I != N; ++I)
227 delete getHandler(I).Block;
228 }
229
230 typedef const Handler *iterator;
231 iterator begin() const { return getHandlers(); }
232 iterator end() const { return getHandlers() + getNumHandlers(); }
233
234 static bool classof(const EHScope *Scope) {
235 return Scope->getKind() == Catch;
236 }
237};
238
239/// A cleanup scope which generates the cleanup blocks lazily.
240class alignas(8) EHCleanupScope : public EHScope {
241 /// The nearest normal cleanup scope enclosing this one.
242 EHScopeStack::stable_iterator EnclosingNormal;
243
244 /// The nearest EH scope enclosing this one.
245 EHScopeStack::stable_iterator EnclosingEH;
246
247 /// The dual entry/exit block along the normal edge. This is lazily
248 /// created if needed before the cleanup is popped.
249 llvm::BasicBlock *NormalBlock;
250
251 /// An optional i1 variable indicating whether this cleanup has been
252 /// activated yet.
253 Address ActiveFlag;
254
255 /// Extra information required for cleanups that have resolved
256 /// branches through them. This has to be allocated on the side
257 /// because everything on the cleanup stack has be trivially
258 /// movable.
259 struct ExtInfo {
260 /// The destinations of normal branch-afters and branch-throughs.
261 llvm::SmallPtrSet<llvm::BasicBlock*, 4> Branches;
262
263 /// Normal branch-afters.
264 SmallVector<std::pair<llvm::BasicBlock*,llvm::ConstantInt*>, 4>
265 BranchAfters;
266 };
267 mutable struct ExtInfo *ExtInfo;
268
269 /// The number of fixups required by enclosing scopes (not including
270 /// this one). If this is the top cleanup scope, all the fixups
271 /// from this index onwards belong to this scope.
272 unsigned FixupDepth;
273
274 struct ExtInfo &getExtInfo() {
275 if (!ExtInfo) ExtInfo = new struct ExtInfo();
276 return *ExtInfo;
277 }
278
279 const struct ExtInfo &getExtInfo() const {
280 if (!ExtInfo) ExtInfo = new struct ExtInfo();
281 return *ExtInfo;
282 }
283
284public:
285 /// Gets the size required for a lazy cleanup scope with the given
286 /// cleanup-data requirements.
287 static size_t getSizeForCleanupSize(size_t Size) {
288 return sizeof(EHCleanupScope) + Size;
289 }
290
291 size_t getAllocatedSize() const {
292 return sizeof(EHCleanupScope) + CleanupBits.CleanupSize;
293 }
294
295 EHCleanupScope(bool isNormal, bool isEH, unsigned cleanupSize,
296 unsigned fixupDepth,
297 EHScopeStack::stable_iterator enclosingNormal,
298 EHScopeStack::stable_iterator enclosingEH)
299 : EHScope(EHScope::Cleanup, enclosingEH),
300 EnclosingNormal(enclosingNormal), NormalBlock(nullptr),
301 ActiveFlag(Address::invalid()), ExtInfo(nullptr),
302 FixupDepth(fixupDepth) {
303 CleanupBits.IsNormalCleanup = isNormal;
304 CleanupBits.IsEHCleanup = isEH;
305 CleanupBits.IsActive = true;
306 CleanupBits.IsLifetimeMarker = false;
307 CleanupBits.TestFlagInNormalCleanup = false;
308 CleanupBits.TestFlagInEHCleanup = false;
309 CleanupBits.CleanupSize = cleanupSize;
310
311 assert(CleanupBits.CleanupSize == cleanupSize && "cleanup size overflow");
312 }
313
314 void Destroy() {
315 delete ExtInfo;
316 }
317 // Objects of EHCleanupScope are not destructed. Use Destroy().
318 ~EHCleanupScope() = delete;
319
320 bool isNormalCleanup() const { return CleanupBits.IsNormalCleanup; }
321 llvm::BasicBlock *getNormalBlock() const { return NormalBlock; }
322 void setNormalBlock(llvm::BasicBlock *BB) { NormalBlock = BB; }
323
324 bool isEHCleanup() const { return CleanupBits.IsEHCleanup; }
325
326 bool isActive() const { return CleanupBits.IsActive; }
327 void setActive(bool A) { CleanupBits.IsActive = A; }
328
329 bool isLifetimeMarker() const { return CleanupBits.IsLifetimeMarker; }
330 void setLifetimeMarker() { CleanupBits.IsLifetimeMarker = true; }
331
332 bool hasActiveFlag() const { return ActiveFlag.isValid(); }
333 Address getActiveFlag() const {
334 return ActiveFlag;
335 }
336 void setActiveFlag(Address Var) {
337 assert(Var.getAlignment().isOne());
338 ActiveFlag = Var;
339 }
340
341 void setTestFlagInNormalCleanup() {
342 CleanupBits.TestFlagInNormalCleanup = true;
343 }
344 bool shouldTestFlagInNormalCleanup() const {
345 return CleanupBits.TestFlagInNormalCleanup;
346 }
347
348 void setTestFlagInEHCleanup() {
349 CleanupBits.TestFlagInEHCleanup = true;
350 }
351 bool shouldTestFlagInEHCleanup() const {
352 return CleanupBits.TestFlagInEHCleanup;
353 }
354
355 unsigned getFixupDepth() const { return FixupDepth; }
356 EHScopeStack::stable_iterator getEnclosingNormalCleanup() const {
357 return EnclosingNormal;
358 }
359
360 size_t getCleanupSize() const { return CleanupBits.CleanupSize; }
361 void *getCleanupBuffer() { return this + 1; }
362
363 EHScopeStack::Cleanup *getCleanup() {
364 return reinterpret_cast<EHScopeStack::Cleanup*>(getCleanupBuffer());
365 }
366
367 /// True if this cleanup scope has any branch-afters or branch-throughs.
368 bool hasBranches() const { return ExtInfo && !ExtInfo->Branches.empty(); }
369
370 /// Add a branch-after to this cleanup scope. A branch-after is a
371 /// branch from a point protected by this (normal) cleanup to a
372 /// point in the normal cleanup scope immediately containing it.
373 /// For example,
374 /// for (;;) { A a; break; }
375 /// contains a branch-after.
376 ///
377 /// Branch-afters each have their own destination out of the
378 /// cleanup, guaranteed distinct from anything else threaded through
379 /// it. Therefore branch-afters usually force a switch after the
380 /// cleanup.
381 void addBranchAfter(llvm::ConstantInt *Index,
382 llvm::BasicBlock *Block) {
383 struct ExtInfo &ExtInfo = getExtInfo();
384 if (ExtInfo.Branches.insert(Ptr: Block).second)
385 ExtInfo.BranchAfters.push_back(Elt: std::make_pair(x&: Block, y&: Index));
386 }
387
388 /// Return the number of unique branch-afters on this scope.
389 unsigned getNumBranchAfters() const {
390 return ExtInfo ? ExtInfo->BranchAfters.size() : 0;
391 }
392
393 llvm::BasicBlock *getBranchAfterBlock(unsigned I) const {
394 assert(I < getNumBranchAfters());
395 return ExtInfo->BranchAfters[I].first;
396 }
397
398 llvm::ConstantInt *getBranchAfterIndex(unsigned I) const {
399 assert(I < getNumBranchAfters());
400 return ExtInfo->BranchAfters[I].second;
401 }
402
403 /// Add a branch-through to this cleanup scope. A branch-through is
404 /// a branch from a scope protected by this (normal) cleanup to an
405 /// enclosing scope other than the immediately-enclosing normal
406 /// cleanup scope.
407 ///
408 /// In the following example, the branch through B's scope is a
409 /// branch-through, while the branch through A's scope is a
410 /// branch-after:
411 /// for (;;) { A a; B b; break; }
412 ///
413 /// All branch-throughs have a common destination out of the
414 /// cleanup, one possibly shared with the fall-through. Therefore
415 /// branch-throughs usually don't force a switch after the cleanup.
416 ///
417 /// \return true if the branch-through was new to this scope
418 bool addBranchThrough(llvm::BasicBlock *Block) {
419 return getExtInfo().Branches.insert(Ptr: Block).second;
420 }
421
422 /// Determines if this cleanup scope has any branch throughs.
423 bool hasBranchThroughs() const {
424 if (!ExtInfo) return false;
425 return (ExtInfo->BranchAfters.size() != ExtInfo->Branches.size());
426 }
427
428 static bool classof(const EHScope *Scope) {
429 return (Scope->getKind() == Cleanup);
430 }
431};
432// NOTE: there's a bunch of different data classes tacked on after an
433// EHCleanupScope. It is asserted (in EHScopeStack::pushCleanup*) that
434// they don't require greater alignment than ScopeStackAlignment. So,
435// EHCleanupScope ought to have alignment equal to that -- not more
436// (would be misaligned by the stack allocator), and not less (would
437// break the appended classes).
438static_assert(alignof(EHCleanupScope) == EHScopeStack::ScopeStackAlignment,
439 "EHCleanupScope expected alignment");
440
441/// An exceptions scope which filters exceptions thrown through it.
442/// Only exceptions matching the filter types will be permitted to be
443/// thrown.
444///
445/// This is used to implement C++ exception specifications.
446class EHFilterScope : public EHScope {
447 // Essentially ends in a flexible array member:
448 // llvm::Value *FilterTypes[0];
449
450 llvm::Value **getFilters() {
451 return reinterpret_cast<llvm::Value**>(this+1);
452 }
453
454 llvm::Value * const *getFilters() const {
455 return reinterpret_cast<llvm::Value* const *>(this+1);
456 }
457
458public:
459 EHFilterScope(unsigned numFilters)
460 : EHScope(Filter, EHScopeStack::stable_end()) {
461 FilterBits.NumFilters = numFilters;
462 assert(FilterBits.NumFilters == numFilters && "NumFilters overflow");
463 }
464
465 static size_t getSizeForNumFilters(unsigned numFilters) {
466 return sizeof(EHFilterScope) + numFilters * sizeof(llvm::Value*);
467 }
468
469 unsigned getNumFilters() const { return FilterBits.NumFilters; }
470
471 void setFilter(unsigned i, llvm::Value *filterValue) {
472 assert(i < getNumFilters());
473 getFilters()[i] = filterValue;
474 }
475
476 llvm::Value *getFilter(unsigned i) const {
477 assert(i < getNumFilters());
478 return getFilters()[i];
479 }
480
481 static bool classof(const EHScope *scope) {
482 return scope->getKind() == Filter;
483 }
484};
485
486/// An exceptions scope which calls std::terminate if any exception
487/// reaches it.
488class EHTerminateScope : public EHScope {
489public:
490 EHTerminateScope(EHScopeStack::stable_iterator enclosingEHScope)
491 : EHScope(Terminate, enclosingEHScope) {}
492 static size_t getSize() { return sizeof(EHTerminateScope); }
493
494 static bool classof(const EHScope *scope) {
495 return scope->getKind() == Terminate;
496 }
497};
498
499/// A non-stable pointer into the scope stack.
500class EHScopeStack::iterator {
501 char *Ptr;
502
503 friend class EHScopeStack;
504 explicit iterator(char *Ptr) : Ptr(Ptr) {}
505
506public:
507 iterator() : Ptr(nullptr) {}
508
509 EHScope *get() const {
510 return reinterpret_cast<EHScope*>(Ptr);
511 }
512
513 EHScope *operator->() const { return get(); }
514 EHScope &operator*() const { return *get(); }
515
516 iterator &operator++() {
517 size_t Size;
518 switch (get()->getKind()) {
519 case EHScope::Catch:
520 Size = EHCatchScope::getSizeForNumHandlers(
521 N: static_cast<const EHCatchScope *>(get())->getNumHandlers());
522 break;
523
524 case EHScope::Filter:
525 Size = EHFilterScope::getSizeForNumFilters(
526 numFilters: static_cast<const EHFilterScope *>(get())->getNumFilters());
527 break;
528
529 case EHScope::Cleanup:
530 Size = static_cast<const EHCleanupScope *>(get())->getAllocatedSize();
531 break;
532
533 case EHScope::Terminate:
534 Size = EHTerminateScope::getSize();
535 break;
536 }
537 Ptr += llvm::alignTo(Value: Size, Align: ScopeStackAlignment);
538 return *this;
539 }
540
541 iterator next() {
542 iterator copy = *this;
543 ++copy;
544 return copy;
545 }
546
547 iterator operator++(int) {
548 iterator copy = *this;
549 operator++();
550 return copy;
551 }
552
553 bool encloses(iterator other) const { return Ptr >= other.Ptr; }
554 bool strictlyEncloses(iterator other) const { return Ptr > other.Ptr; }
555
556 bool operator==(iterator other) const { return Ptr == other.Ptr; }
557 bool operator!=(iterator other) const { return Ptr != other.Ptr; }
558};
559
560inline EHScopeStack::iterator EHScopeStack::begin() const {
561 return iterator(StartOfData);
562}
563
564inline EHScopeStack::iterator EHScopeStack::end() const {
565 return iterator(EndOfBuffer);
566}
567
568inline void EHScopeStack::popCatch() {
569 assert(!empty() && "popping exception stack when not empty");
570
571 EHCatchScope &scope = cast<EHCatchScope>(Val&: *begin());
572 InnermostEHScope = scope.getEnclosingEHScope();
573 deallocate(Size: EHCatchScope::getSizeForNumHandlers(N: scope.getNumHandlers()));
574}
575
576inline void EHScopeStack::popTerminate() {
577 assert(!empty() && "popping exception stack when not empty");
578
579 EHTerminateScope &scope = cast<EHTerminateScope>(Val&: *begin());
580 InnermostEHScope = scope.getEnclosingEHScope();
581 deallocate(Size: EHTerminateScope::getSize());
582}
583
584inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
585 assert(sp.isValid() && "finding invalid savepoint");
586 assert(sp.Size <= stable_begin().Size && "finding savepoint after pop");
587 return iterator(EndOfBuffer - sp.Size);
588}
589
590inline EHScopeStack::stable_iterator
591EHScopeStack::stabilize(iterator ir) const {
592 assert(StartOfData <= ir.Ptr && ir.Ptr <= EndOfBuffer);
593 return stable_iterator(EndOfBuffer - ir.Ptr);
594}
595
596/// The exceptions personality for a function.
597struct EHPersonality {
598 const char *PersonalityFn;
599
600 // If this is non-null, this personality requires a non-standard
601 // function for rethrowing an exception after a catchall cleanup.
602 // This function must have prototype void(void*).
603 const char *CatchallRethrowFn;
604
605 static const EHPersonality &get(CodeGenModule &CGM, const FunctionDecl *FD);
606 static const EHPersonality &get(CodeGenFunction &CGF);
607
608 static const EHPersonality GNU_C;
609 static const EHPersonality GNU_C_SJLJ;
610 static const EHPersonality GNU_C_SEH;
611 static const EHPersonality GNU_ObjC;
612 static const EHPersonality GNU_ObjC_SJLJ;
613 static const EHPersonality GNU_ObjC_SEH;
614 static const EHPersonality GNUstep_ObjC;
615 static const EHPersonality GNU_ObjCXX;
616 static const EHPersonality NeXT_ObjC;
617 static const EHPersonality GNU_CPlusPlus;
618 static const EHPersonality GNU_CPlusPlus_SJLJ;
619 static const EHPersonality GNU_CPlusPlus_SEH;
620 static const EHPersonality MSVC_except_handler;
621 static const EHPersonality MSVC_C_specific_handler;
622 static const EHPersonality MSVC_CxxFrameHandler3;
623 static const EHPersonality GNU_Wasm_CPlusPlus;
624 static const EHPersonality XL_CPlusPlus;
625 static const EHPersonality ZOS_CPlusPlus;
626
627 /// Does this personality use landingpads or the family of pad instructions
628 /// designed to form funclets?
629 bool usesFuncletPads() const {
630 return isMSVCPersonality() || isWasmPersonality();
631 }
632
633 bool isMSVCPersonality() const {
634 return this == &MSVC_except_handler || this == &MSVC_C_specific_handler ||
635 this == &MSVC_CxxFrameHandler3;
636 }
637
638 bool isWasmPersonality() const { return this == &GNU_Wasm_CPlusPlus; }
639
640 bool isMSVCXXPersonality() const { return this == &MSVC_CxxFrameHandler3; }
641};
642}
643}
644
645#endif
646

source code of clang/lib/CodeGen/CGCleanup.h