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 CLANG_CODEGEN_EHSCOPESTACK_H
17#define CLANG_CODEGEN_EHSCOPESTACK_H
18
19#include "clang/Basic/LLVM.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
25namespace clang {
26namespace CodeGen {
27
28class 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.
36struct 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
55template <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.
65template <class T> struct DominatingValue : InvariantValue<T> {};
66
67template <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>
71struct DominatingPointer;
72template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
73// template <class T> struct DominatingPointer<T,true> at end of file
74
75template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
76
77enum CleanupKind {
78  EHCleanup = 0x1,
79  NormalCleanup = 0x2,
80  NormalAndEHCleanup = EHCleanup | NormalCleanup,
81
82  InactiveCleanup = 0x4,
83  InactiveEHCleanup = EHCleanup | InactiveCleanup,
84  InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
85  InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
86};
87
88/// A stack of scopes which respond to exceptions, including cleanups
89/// and catch blocks.
90class EHScopeStack {
91public:
92  /// A saved depth on the scope stack.  This is necessary because
93  /// pushing scopes onto the stack invalidates iterators.
94  class stable_iterator {
95    friend class EHScopeStack;
96
97    /// Offset from StartOfData to EndOfBuffer.
98    ptrdiff_t Size;
99
100    stable_iterator(ptrdiff_t Size) : Size(Size) {}
101
102  public:
103    static stable_iterator invalid() { return stable_iterator(-1); }
104    stable_iterator() : Size(-1) {}
105
106    bool isValid() const { return Size >= 0; }
107
108    /// Returns true if this scope encloses I.
109    /// Returns false if I is invalid.
110    /// This scope must be valid.
111    bool encloses(stable_iterator I) const { return Size <= I.Size; }
112
113    /// Returns true if this scope strictly encloses I: that is,
114    /// if it encloses I and is not I.
115    /// Returns false is I is invalid.
116    /// This scope must be valid.
117    bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
118
119    friend bool operator==(stable_iterator A, stable_iterator B) {
120      return A.Size == B.Size;
121    }
122    friend bool operator!=(stable_iterator A, stable_iterator B) {
123      return A.Size != B.Size;
124    }
125  };
126
127  /// Information for lazily generating a cleanup.  Subclasses must be
128  /// POD-like: cleanups will not be destructed, and they will be
129  /// allocated on the cleanup stack and freely copied and moved
130  /// around.
131  ///
132  /// Cleanup implementations should generally be declared in an
133  /// anonymous namespace.
134  class Cleanup {
135    // Anchor the construction vtable.
136    virtual void anchor();
137  public:
138    /// Generation flags.
139    class Flags {
140      enum {
141        F_IsForEH             = 0x1,
142        F_IsNormalCleanupKind = 0x2,
143        F_IsEHCleanupKind     = 0x4
144      };
145      unsigned flags;
146
147    public:
148      Flags() : flags(0) {}
149
150      /// isForEH - true if the current emission is for an EH cleanup.
151      bool isForEHCleanup() const { return flags & F_IsForEH; }
152      bool isForNormalCleanup() const { return !isForEHCleanup(); }
153      void setIsForEHCleanup() { flags |= F_IsForEH; }
154
155      bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
156      void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
157
158      /// isEHCleanupKind - true if the cleanup was pushed as an EH
159      /// cleanup.
160      bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
161      void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
162    };
163
164    // Provide a virtual destructor to suppress a very common warning
165    // that unfortunately cannot be suppressed without this.  Cleanups
166    // should not rely on this destructor ever being called.
167    virtual ~Cleanup() {}
168
169    /// Emit the cleanup.  For normal cleanups, this is run in the
170    /// same EH context as when the cleanup was pushed, i.e. the
171    /// immediately-enclosing context of the cleanup scope.  For
172    /// EH cleanups, this is run in a terminate context.
173    ///
174    // \param flags cleanup kind.
175    virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
176  };
177
178  /// ConditionalCleanupN stores the saved form of its N parameters,
179  /// then restores them and performs the cleanup.
180  template <class T, class A0>
181  class ConditionalCleanup1 : public Cleanup {
182    typedef typename DominatingValue<A0>::saved_type A0_saved;
183    A0_saved a0_saved;
184
185    void Emit(CodeGenFunction &CGF, Flags flags) override {
186      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
187      T(a0).Emit(CGF, flags);
188    }
189
190  public:
191    ConditionalCleanup1(A0_saved a0)
192      : a0_saved(a0) {}
193  };
194
195  template <class T, class A0, class A1>
196  class ConditionalCleanup2 : public Cleanup {
197    typedef typename DominatingValue<A0>::saved_type A0_saved;
198    typedef typename DominatingValue<A1>::saved_type A1_saved;
199    A0_saved a0_saved;
200    A1_saved a1_saved;
201
202    void Emit(CodeGenFunction &CGF, Flags flags) override {
203      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
204      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
205      T(a0, a1).Emit(CGF, flags);
206    }
207
208  public:
209    ConditionalCleanup2(A0_saved a0, A1_saved a1)
210      : a0_saved(a0), a1_saved(a1) {}
211  };
212
213  template <class T, class A0, class A1, class A2>
214  class ConditionalCleanup3 : public Cleanup {
215    typedef typename DominatingValue<A0>::saved_type A0_saved;
216    typedef typename DominatingValue<A1>::saved_type A1_saved;
217    typedef typename DominatingValue<A2>::saved_type A2_saved;
218    A0_saved a0_saved;
219    A1_saved a1_saved;
220    A2_saved a2_saved;
221
222    void Emit(CodeGenFunction &CGF, Flags flags) override {
223      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
224      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
225      A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
226      T(a0, a1, a2).Emit(CGF, flags);
227    }
228
229  public:
230    ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
231      : a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
232  };
233
234  template <class T, class A0, class A1, class A2, class A3>
235  class ConditionalCleanup4 : public Cleanup {
236    typedef typename DominatingValue<A0>::saved_type A0_saved;
237    typedef typename DominatingValue<A1>::saved_type A1_saved;
238    typedef typename DominatingValue<A2>::saved_type A2_saved;
239    typedef typename DominatingValue<A3>::saved_type A3_saved;
240    A0_saved a0_saved;
241    A1_saved a1_saved;
242    A2_saved a2_saved;
243    A3_saved a3_saved;
244
245    void Emit(CodeGenFunction &CGF, Flags flags) override {
246      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
247      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
248      A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
249      A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
250      T(a0, a1, a2, a3).Emit(CGF, flags);
251    }
252
253  public:
254    ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
255      : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
256  };
257
258private:
259  // The implementation for this class is in CGException.h and
260  // CGException.cpp; the definition is here because it's used as a
261  // member of CodeGenFunction.
262
263  /// The start of the scope-stack buffer, i.e. the allocated pointer
264  /// for the buffer.  All of these pointers are either simultaneously
265  /// null or simultaneously valid.
266  char *StartOfBuffer;
267
268  /// The end of the buffer.
269  char *EndOfBuffer;
270
271  /// The first valid entry in the buffer.
272  char *StartOfData;
273
274  /// The innermost normal cleanup on the stack.
275  stable_iterator InnermostNormalCleanup;
276
277  /// The innermost EH scope on the stack.
278  stable_iterator InnermostEHScope;
279
280  /// The current set of branch fixups.  A branch fixup is a jump to
281  /// an as-yet unemitted label, i.e. a label for which we don't yet
282  /// know the EH stack depth.  Whenever we pop a cleanup, we have
283  /// to thread all the current branch fixups through it.
284  ///
285  /// Fixups are recorded as the Use of the respective branch or
286  /// switch statement.  The use points to the final destination.
287  /// When popping out of a cleanup, these uses are threaded through
288  /// the cleanup and adjusted to point to the new cleanup.
289  ///
290  /// Note that branches are allowed to jump into protected scopes
291  /// in certain situations;  e.g. the following code is legal:
292  ///     struct A { ~A(); }; // trivial ctor, non-trivial dtor
293  ///     goto foo;
294  ///     A a;
295  ///    foo:
296  ///     bar();
297  SmallVector<BranchFixup, 8> BranchFixups;
298
299  char *allocate(size_t Size);
300
301  void *pushCleanup(CleanupKind K, size_t DataSize);
302
303public:
304  EHScopeStack() : StartOfBuffer(nullptr), EndOfBuffer(nullptr),
305                   StartOfData(nullptr), InnermostNormalCleanup(stable_end()),
306                   InnermostEHScope(stable_end()) {}
307  ~EHScopeStack() { delete[] StartOfBuffer; }
308
309  // Variadic templates would make this not terrible.
310
311  /// Push a lazily-created cleanup on the stack.
312  template <class T>
313  void pushCleanup(CleanupKind Kind) {
314    void *Buffer = pushCleanup(Kind, sizeof(T));
315    Cleanup *Obj = new(Buffer) T();
316    (void) Obj;
317  }
318
319  /// Push a lazily-created cleanup on the stack.
320  template <class T, class A0>
321  void pushCleanup(CleanupKind Kind, A0 a0) {
322    void *Buffer = pushCleanup(Kind, sizeof(T));
323    Cleanup *Obj = new(Buffer) T(a0);
324    (void) Obj;
325  }
326
327  /// Push a lazily-created cleanup on the stack.
328  template <class T, class A0, class A1>
329  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
330    void *Buffer = pushCleanup(Kind, sizeof(T));
331    Cleanup *Obj = new(Buffer) T(a0, a1);
332    (void) Obj;
333  }
334
335  /// Push a lazily-created cleanup on the stack.
336  template <class T, class A0, class A1, class A2>
337  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
338    void *Buffer = pushCleanup(Kind, sizeof(T));
339    Cleanup *Obj = new(Buffer) T(a0, a1, a2);
340    (void) Obj;
341  }
342
343  /// Push a lazily-created cleanup on the stack.
344  template <class T, class A0, class A1, class A2, class A3>
345  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
346    void *Buffer = pushCleanup(Kind, sizeof(T));
347    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
348    (void) Obj;
349  }
350
351  /// Push a lazily-created cleanup on the stack.
352  template <class T, class A0, class A1, class A2, class A3, class A4>
353  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
354    void *Buffer = pushCleanup(Kind, sizeof(T));
355    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
356    (void) Obj;
357  }
358
359  // Feel free to add more variants of the following:
360
361  /// Push a cleanup with non-constant storage requirements on the
362  /// stack.  The cleanup type must provide an additional static method:
363  ///   static size_t getExtraSize(size_t);
364  /// The argument to this method will be the value N, which will also
365  /// be passed as the first argument to the constructor.
366  ///
367  /// The data stored in the extra storage must obey the same
368  /// restrictions as normal cleanup member data.
369  ///
370  /// The pointer returned from this method is valid until the cleanup
371  /// stack is modified.
372  template <class T, class A0, class A1, class A2>
373  T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
374    void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
375    return new (Buffer) T(N, a0, a1, a2);
376  }
377
378  void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
379    void *Buffer = pushCleanup(Kind, Size);
380    std::memcpy(Buffer, Cleanup, Size);
381  }
382
383  /// Pops a cleanup scope off the stack.  This is private to CGCleanup.cpp.
384  void popCleanup();
385
386  /// Push a set of catch handlers on the stack.  The catch is
387  /// uninitialized and will need to have the given number of handlers
388  /// set on it.
389  class EHCatchScope *pushCatch(unsigned NumHandlers);
390
391  /// Pops a catch scope off the stack.  This is private to CGException.cpp.
392  void popCatch();
393
394  /// Push an exceptions filter on the stack.
395  class EHFilterScope *pushFilter(unsigned NumFilters);
396
397  /// Pops an exceptions filter off the stack.
398  void popFilter();
399
400  /// Push a terminate handler on the stack.
401  void pushTerminate();
402
403  /// Pops a terminate handler off the stack.
404  void popTerminate();
405
406  /// Determines whether the exception-scopes stack is empty.
407  bool empty() const { return StartOfData == EndOfBuffer; }
408
409  bool requiresLandingPad() const {
410    return InnermostEHScope != stable_end();
411  }
412
413  /// Determines whether there are any normal cleanups on the stack.
414  bool hasNormalCleanups() const {
415    return InnermostNormalCleanup != stable_end();
416  }
417
418  /// Returns the innermost normal cleanup on the stack, or
419  /// stable_end() if there are no normal cleanups.
420  stable_iterator getInnermostNormalCleanup() const {
421    return InnermostNormalCleanup;
422  }
423  stable_iterator getInnermostActiveNormalCleanup() const;
424
425  stable_iterator getInnermostEHScope() const {
426    return InnermostEHScope;
427  }
428
429  stable_iterator getInnermostActiveEHScope() const;
430
431  /// An unstable reference to a scope-stack depth.  Invalidated by
432  /// pushes but not pops.
433  class iterator;
434
435  /// Returns an iterator pointing to the innermost EH scope.
436  iterator begin() const;
437
438  /// Returns an iterator pointing to the outermost EH scope.
439  iterator end() const;
440
441  /// Create a stable reference to the top of the EH stack.  The
442  /// returned reference is valid until that scope is popped off the
443  /// stack.
444  stable_iterator stable_begin() const {
445    return stable_iterator(EndOfBuffer - StartOfData);
446  }
447
448  /// Create a stable reference to the bottom of the EH stack.
449  static stable_iterator stable_end() {
450    return stable_iterator(0);
451  }
452
453  /// Translates an iterator into a stable_iterator.
454  stable_iterator stabilize(iterator it) const;
455
456  /// Turn a stable reference to a scope depth into a unstable pointer
457  /// to the EH stack.
458  iterator find(stable_iterator save) const;
459
460  /// Removes the cleanup pointed to by the given stable_iterator.
461  void removeCleanup(stable_iterator save);
462
463  /// Add a branch fixup to the current cleanup scope.
464  BranchFixup &addBranchFixup() {
465    assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
466    BranchFixups.push_back(BranchFixup());
467    return BranchFixups.back();
468  }
469
470  unsigned getNumBranchFixups() const { return BranchFixups.size(); }
471  BranchFixup &getBranchFixup(unsigned I) {
472    assert(I < getNumBranchFixups());
473    return BranchFixups[I];
474  }
475
476  /// Pops lazily-removed fixups from the end of the list.  This
477  /// should only be called by procedures which have just popped a
478  /// cleanup or resolved one or more fixups.
479  void popNullFixups();
480
481  /// Clears the branch-fixups list.  This should only be called by
482  /// ResolveAllBranchFixups.
483  void clearFixups() { BranchFixups.clear(); }
484};
485
486} // namespace CodeGen
487} // namespace clang
488
489#endif
490