EHScopeStack.h 14 KB

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