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