clang  10.0.0svn
EHScopeStack.h
Go to the documentation of this file.
1 //===-- EHScopeStack.h - Stack for cleanup 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 should be the minimum interface required for other parts of
10 // CodeGen to emit cleanups. The implementation is in CGCleanup.cpp and other
11 // implemenentation details that are not widely needed are in CGCleanup.h.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
16 #define LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
17 
18 #include "clang/Basic/LLVM.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Value.h"
24 
25 namespace clang {
26 namespace CodeGen {
27 
28 class CodeGenFunction;
29 
30 /// A branch fixup. These are required when emitting a goto to a
31 /// label which hasn't been emitted yet. The goto is optimistically
32 /// emitted as a branch to the basic block for the label, and (if it
33 /// occurs in a scope with non-trivial cleanups) a fixup is added to
34 /// the innermost cleanup. When a (normal) cleanup is popped, any
35 /// unresolved fixups in that scope are threaded through the cleanup.
36 struct BranchFixup {
37  /// The block containing the terminator which needs to be modified
38  /// into a switch if this fixup is resolved into the current scope.
39  /// If null, LatestBranch points directly to the destination.
40  llvm::BasicBlock *OptimisticBranchBlock;
41 
42  /// The ultimate destination of the branch.
43  ///
44  /// This can be set to null to indicate that this fixup was
45  /// successfully resolved.
46  llvm::BasicBlock *Destination;
47 
48  /// The destination index value.
49  unsigned DestinationIndex;
50 
51  /// The initial branch of the fixup.
52  llvm::BranchInst *InitialBranch;
53 };
54 
55 template <class T> struct InvariantValue {
56  typedef T type;
57  typedef T saved_type;
58  static bool needsSaving(type value) { return false; }
59  static saved_type save(CodeGenFunction &CGF, type value) { return value; }
60  static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
61 };
62 
63 /// A metaprogramming class for ensuring that a value will dominate an
64 /// arbitrary position in a function.
65 template <class T> struct DominatingValue : InvariantValue<T> {};
66 
67 template <class T, bool mightBeInstruction =
68  std::is_base_of<llvm::Value, T>::value &&
69  !std::is_base_of<llvm::Constant, T>::value &&
70  !std::is_base_of<llvm::BasicBlock, T>::value>
72 template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
73 // template <class T> struct DominatingPointer<T,true> at end of file
74 
75 template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
76 
77 enum CleanupKind : unsigned {
78  /// Denotes a cleanup that should run when a scope is exited using exceptional
79  /// control flow (a throw statement leading to stack unwinding, ).
80  EHCleanup = 0x1,
81 
82  /// Denotes a cleanup that should run when a scope is exited using normal
83  /// control flow (falling off the end of the scope, return, goto, ...).
85 
87 
92 
95 };
96 
97 /// A stack of scopes which respond to exceptions, including cleanups
98 /// and catch blocks.
99 class EHScopeStack {
100 public:
101  /* Should switch to alignof(uint64_t) instead of 8, when EHCleanupScope can */
102  enum { ScopeStackAlignment = 8 };
103 
104  /// A saved depth on the scope stack. This is necessary because
105  /// pushing scopes onto the stack invalidates iterators.
107  friend class EHScopeStack;
108 
109  /// Offset from StartOfData to EndOfBuffer.
110  ptrdiff_t Size;
111 
112  stable_iterator(ptrdiff_t Size) : Size(Size) {}
113 
114  public:
115  static stable_iterator invalid() { return stable_iterator(-1); }
116  stable_iterator() : Size(-1) {}
117 
118  bool isValid() const { return Size >= 0; }
119 
120  /// Returns true if this scope encloses I.
121  /// Returns false if I is invalid.
122  /// This scope must be valid.
123  bool encloses(stable_iterator I) const { return Size <= I.Size; }
124 
125  /// Returns true if this scope strictly encloses I: that is,
126  /// if it encloses I and is not I.
127  /// Returns false is I is invalid.
128  /// This scope must be valid.
129  bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
130 
132  return A.Size == B.Size;
133  }
135  return A.Size != B.Size;
136  }
137  };
138 
139  /// Information for lazily generating a cleanup. Subclasses must be
140  /// POD-like: cleanups will not be destructed, and they will be
141  /// allocated on the cleanup stack and freely copied and moved
142  /// around.
143  ///
144  /// Cleanup implementations should generally be declared in an
145  /// anonymous namespace.
146  class Cleanup {
147  // Anchor the construction vtable.
148  virtual void anchor();
149 
150  protected:
151  ~Cleanup() = default;
152 
153  public:
154  Cleanup(const Cleanup &) = default;
156  Cleanup() = default;
157 
158  /// Generation flags.
159  class Flags {
160  enum {
161  F_IsForEH = 0x1,
162  F_IsNormalCleanupKind = 0x2,
163  F_IsEHCleanupKind = 0x4
164  };
165  unsigned flags;
166 
167  public:
168  Flags() : flags(0) {}
169 
170  /// isForEH - true if the current emission is for an EH cleanup.
171  bool isForEHCleanup() const { return flags & F_IsForEH; }
172  bool isForNormalCleanup() const { return !isForEHCleanup(); }
173  void setIsForEHCleanup() { flags |= F_IsForEH; }
174 
175  bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
176  void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
177 
178  /// isEHCleanupKind - true if the cleanup was pushed as an EH
179  /// cleanup.
180  bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
181  void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
182  };
183 
184 
185  /// Emit the cleanup. For normal cleanups, this is run in the
186  /// same EH context as when the cleanup was pushed, i.e. the
187  /// immediately-enclosing context of the cleanup scope. For
188  /// EH cleanups, this is run in a terminate context.
189  ///
190  // \param flags cleanup kind.
191  virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
192  };
193 
194  /// ConditionalCleanup stores the saved form of its parameters,
195  /// then restores them and performs the cleanup.
196  template <class T, class... As>
197  class ConditionalCleanup final : public Cleanup {
198  typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
199  SavedTuple Saved;
200 
201  template <std::size_t... Is>
202  T restore(CodeGenFunction &CGF, std::index_sequence<Is...>) {
203  // It's important that the restores are emitted in order. The braced init
204  // list guarantees that.
205  return T{DominatingValue<As>::restore(CGF, std::get<Is>(Saved))...};
206  }
207 
208  void Emit(CodeGenFunction &CGF, Flags flags) override {
209  restore(CGF, std::index_sequence_for<As...>()).Emit(CGF, flags);
210  }
211 
212  public:
214  : Saved(A...) {}
215 
216  ConditionalCleanup(SavedTuple Tuple) : Saved(std::move(Tuple)) {}
217  };
218 
219 private:
220  // The implementation for this class is in CGException.h and
221  // CGException.cpp; the definition is here because it's used as a
222  // member of CodeGenFunction.
223 
224  /// The start of the scope-stack buffer, i.e. the allocated pointer
225  /// for the buffer. All of these pointers are either simultaneously
226  /// null or simultaneously valid.
227  char *StartOfBuffer;
228 
229  /// The end of the buffer.
230  char *EndOfBuffer;
231 
232  /// The first valid entry in the buffer.
233  char *StartOfData;
234 
235  /// The innermost normal cleanup on the stack.
236  stable_iterator InnermostNormalCleanup;
237 
238  /// The innermost EH scope on the stack.
239  stable_iterator InnermostEHScope;
240 
241  /// The current set of branch fixups. A branch fixup is a jump to
242  /// an as-yet unemitted label, i.e. a label for which we don't yet
243  /// know the EH stack depth. Whenever we pop a cleanup, we have
244  /// to thread all the current branch fixups through it.
245  ///
246  /// Fixups are recorded as the Use of the respective branch or
247  /// switch statement. The use points to the final destination.
248  /// When popping out of a cleanup, these uses are threaded through
249  /// the cleanup and adjusted to point to the new cleanup.
250  ///
251  /// Note that branches are allowed to jump into protected scopes
252  /// in certain situations; e.g. the following code is legal:
253  /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
254  /// goto foo;
255  /// A a;
256  /// foo:
257  /// bar();
258  SmallVector<BranchFixup, 8> BranchFixups;
259 
260  char *allocate(size_t Size);
261  void deallocate(size_t Size);
262 
263  void *pushCleanup(CleanupKind K, size_t DataSize);
264 
265 public:
266  EHScopeStack() : StartOfBuffer(nullptr), EndOfBuffer(nullptr),
267  StartOfData(nullptr), InnermostNormalCleanup(stable_end()),
268  InnermostEHScope(stable_end()) {}
269  ~EHScopeStack() { delete[] StartOfBuffer; }
270 
271  /// Push a lazily-created cleanup on the stack.
272  template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
273  static_assert(alignof(T) <= ScopeStackAlignment,
274  "Cleanup's alignment is too large.");
275  void *Buffer = pushCleanup(Kind, sizeof(T));
276  Cleanup *Obj = new (Buffer) T(A...);
277  (void) Obj;
278  }
279 
280  /// Push a lazily-created cleanup on the stack. Tuple version.
281  template <class T, class... As>
282  void pushCleanupTuple(CleanupKind Kind, std::tuple<As...> A) {
283  static_assert(alignof(T) <= ScopeStackAlignment,
284  "Cleanup's alignment is too large.");
285  void *Buffer = pushCleanup(Kind, sizeof(T));
286  Cleanup *Obj = new (Buffer) T(std::move(A));
287  (void) Obj;
288  }
289 
290  // Feel free to add more variants of the following:
291 
292  /// Push a cleanup with non-constant storage requirements on the
293  /// stack. The cleanup type must provide an additional static method:
294  /// static size_t getExtraSize(size_t);
295  /// The argument to this method will be the value N, which will also
296  /// be passed as the first argument to the constructor.
297  ///
298  /// The data stored in the extra storage must obey the same
299  /// restrictions as normal cleanup member data.
300  ///
301  /// The pointer returned from this method is valid until the cleanup
302  /// stack is modified.
303  template <class T, class... As>
304  T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) {
305  static_assert(alignof(T) <= ScopeStackAlignment,
306  "Cleanup's alignment is too large.");
307  void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
308  return new (Buffer) T(N, A...);
309  }
310 
311  void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
312  void *Buffer = pushCleanup(Kind, Size);
313  std::memcpy(Buffer, Cleanup, Size);
314  }
315 
316  /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
317  void popCleanup();
318 
319  /// Push a set of catch handlers on the stack. The catch is
320  /// uninitialized and will need to have the given number of handlers
321  /// set on it.
322  class EHCatchScope *pushCatch(unsigned NumHandlers);
323 
324  /// Pops a catch scope off the stack. This is private to CGException.cpp.
325  void popCatch();
326 
327  /// Push an exceptions filter on the stack.
328  class EHFilterScope *pushFilter(unsigned NumFilters);
329 
330  /// Pops an exceptions filter off the stack.
331  void popFilter();
332 
333  /// Push a terminate handler on the stack.
334  void pushTerminate();
335 
336  /// Pops a terminate handler off the stack.
337  void popTerminate();
338 
339  // Returns true iff the current scope is either empty or contains only
340  // lifetime markers, i.e. no real cleanup code
341  bool containsOnlyLifetimeMarkers(stable_iterator Old) const;
342 
343  /// Determines whether the exception-scopes stack is empty.
344  bool empty() const { return StartOfData == EndOfBuffer; }
345 
346  bool requiresLandingPad() const;
347 
348  /// Determines whether there are any normal cleanups on the stack.
349  bool hasNormalCleanups() const {
350  return InnermostNormalCleanup != stable_end();
351  }
352 
353  /// Returns the innermost normal cleanup on the stack, or
354  /// stable_end() if there are no normal cleanups.
356  return InnermostNormalCleanup;
357  }
358  stable_iterator getInnermostActiveNormalCleanup() const;
359 
361  return InnermostEHScope;
362  }
363 
364 
365  /// An unstable reference to a scope-stack depth. Invalidated by
366  /// pushes but not pops.
367  class iterator;
368 
369  /// Returns an iterator pointing to the innermost EH scope.
370  iterator begin() const;
371 
372  /// Returns an iterator pointing to the outermost EH scope.
373  iterator end() const;
374 
375  /// Create a stable reference to the top of the EH stack. The
376  /// returned reference is valid until that scope is popped off the
377  /// stack.
379  return stable_iterator(EndOfBuffer - StartOfData);
380  }
381 
382  /// Create a stable reference to the bottom of the EH stack.
384  return stable_iterator(0);
385  }
386 
387  /// Translates an iterator into a stable_iterator.
388  stable_iterator stabilize(iterator it) const;
389 
390  /// Turn a stable reference to a scope depth into a unstable pointer
391  /// to the EH stack.
392  iterator find(stable_iterator save) const;
393 
394  /// Add a branch fixup to the current cleanup scope.
396  assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
397  BranchFixups.push_back(BranchFixup());
398  return BranchFixups.back();
399  }
400 
401  unsigned getNumBranchFixups() const { return BranchFixups.size(); }
403  assert(I < getNumBranchFixups());
404  return BranchFixups[I];
405  }
406 
407  /// Pops lazily-removed fixups from the end of the list. This
408  /// should only be called by procedures which have just popped a
409  /// cleanup or resolved one or more fixups.
410  void popNullFixups();
411 
412  /// Clears the branch-fixups list. This should only be called by
413  /// ResolveAllBranchFixups.
414  void clearFixups() { BranchFixups.clear(); }
415 };
416 
417 } // namespace CodeGen
418 } // namespace clang
419 
420 #endif
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
Definition: EHScopeStack.h:383
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:378
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:344
static saved_type save(CodeGenFunction &CGF, type value)
Definition: EHScopeStack.h:59
A scope which attempts to handle some, possibly all, types of exceptions.
Definition: CGCleanup.h:147
ConditionalCleanup stores the saved form of its parameters, then restores them and performs the clean...
Definition: EHScopeStack.h:197
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Definition: Format.h:2392
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c-base.h:40
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function...
Definition: EHScopeStack.h:65
unsigned getNumBranchFixups() const
Definition: EHScopeStack.h:401
bool isForEHCleanup() const
isForEH - true if the current emission is for an EH cleanup.
Definition: EHScopeStack.h:171
BranchFixup & getBranchFixup(unsigned I)
Definition: EHScopeStack.h:402
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
bool hasNormalCleanups() const
Determines whether there are any normal cleanups on the stack.
Definition: EHScopeStack.h:349
A stack of scopes which respond to exceptions, including cleanups and catch blocks.
Definition: EHScopeStack.h:99
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
bool strictlyEncloses(stable_iterator I) const
Returns true if this scope strictly encloses I: that is, if it encloses I and is not I...
Definition: EHScopeStack.h:129
void pushCleanup(CleanupKind Kind, As... A)
Push a lazily-created cleanup on the stack.
Definition: EHScopeStack.h:272
static type restore(CodeGenFunction &CGF, saved_type value)
Definition: EHScopeStack.h:60
llvm::BranchInst * InitialBranch
The initial branch of the fixup.
Definition: EHScopeStack.h:52
void clearFixups()
Clears the branch-fixups list.
Definition: EHScopeStack.h:414
stable_iterator getInnermostNormalCleanup() const
Returns the innermost normal cleanup on the stack, or stable_end() if there are no normal cleanups...
Definition: EHScopeStack.h:355
bool encloses(stable_iterator I) const
Returns true if this scope encloses I.
Definition: EHScopeStack.h:123
llvm::BasicBlock * OptimisticBranchBlock
The block containing the terminator which needs to be modified into a switch if this fixup is resolve...
Definition: EHScopeStack.h:40
#define false
Definition: stdbool.h:17
llvm::BasicBlock * Destination
The ultimate destination of the branch.
Definition: EHScopeStack.h:46
Kind
A saved depth on the scope stack.
Definition: EHScopeStack.h:106
static bool needsSaving(type value)
Definition: EHScopeStack.h:58
void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size)
Definition: EHScopeStack.h:311
unsigned DestinationIndex
The destination index value.
Definition: EHScopeStack.h:49
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
friend bool operator==(stable_iterator A, stable_iterator B)
Definition: EHScopeStack.h:131
Dataflow Directional Tag Classes.
BranchFixup & addBranchFixup()
Add a branch fixup to the current cleanup scope.
Definition: EHScopeStack.h:395
friend bool operator!=(stable_iterator A, stable_iterator B)
Definition: EHScopeStack.h:134
void pushCleanupTuple(CleanupKind Kind, std::tuple< As... > A)
Push a lazily-created cleanup on the stack. Tuple version.
Definition: EHScopeStack.h:282
ConditionalCleanup(typename DominatingValue< As >::saved_type... A)
Definition: EHScopeStack.h:213
__PTRDIFF_TYPE__ ptrdiff_t
A signed integer type that is the result of subtracting two pointers.
Definition: opencl-c-base.h:48
T * pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A)
Push a cleanup with non-constant storage requirements on the stack.
Definition: EHScopeStack.h:304
bool isEHCleanupKind() const
isEHCleanupKind - true if the cleanup was pushed as an EH cleanup.
Definition: EHScopeStack.h:180
stable_iterator getInnermostEHScope() const
Definition: EHScopeStack.h:360
An exceptions scope which filters exceptions thrown through it.
Definition: CGCleanup.h:437
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:146
A non-stable pointer into the scope stack.
Definition: CGCleanup.h:502