EHScopeStack.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. LifetimeMarker = 0x8,
  73. NormalEHLifetimeMarker = LifetimeMarker | NormalAndEHCleanup,
  74. };
  75. /// A stack of scopes which respond to exceptions, including cleanups
  76. /// and catch blocks.
  77. class EHScopeStack {
  78. public:
  79. /* Should switch to alignof(uint64_t) instead of 8, when EHCleanupScope can */
  80. enum { ScopeStackAlignment = 8 };
  81. /// A saved depth on the scope stack. This is necessary because
  82. /// pushing scopes onto the stack invalidates iterators.
  83. class stable_iterator {
  84. friend class EHScopeStack;
  85. /// Offset from StartOfData to EndOfBuffer.
  86. ptrdiff_t Size;
  87. stable_iterator(ptrdiff_t Size) : Size(Size) {}
  88. public:
  89. static stable_iterator invalid() { return stable_iterator(-1); }
  90. stable_iterator() : Size(-1) {}
  91. bool isValid() const { return Size >= 0; }
  92. /// Returns true if this scope encloses I.
  93. /// Returns false if I is invalid.
  94. /// This scope must be valid.
  95. bool encloses(stable_iterator I) const { return Size <= I.Size; }
  96. /// Returns true if this scope strictly encloses I: that is,
  97. /// if it encloses I and is not I.
  98. /// Returns false is I is invalid.
  99. /// This scope must be valid.
  100. bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
  101. friend bool operator==(stable_iterator A, stable_iterator B) {
  102. return A.Size == B.Size;
  103. }
  104. friend bool operator!=(stable_iterator A, stable_iterator B) {
  105. return A.Size != B.Size;
  106. }
  107. };
  108. /// Information for lazily generating a cleanup. Subclasses must be
  109. /// POD-like: cleanups will not be destructed, and they will be
  110. /// allocated on the cleanup stack and freely copied and moved
  111. /// around.
  112. ///
  113. /// Cleanup implementations should generally be declared in an
  114. /// anonymous namespace.
  115. class Cleanup {
  116. // Anchor the construction vtable.
  117. virtual void anchor();
  118. protected:
  119. ~Cleanup() = default;
  120. public:
  121. Cleanup(const Cleanup &) = default;
  122. Cleanup(Cleanup &&) {}
  123. Cleanup() = default;
  124. virtual bool isRedundantBeforeReturn() { return false; }
  125. /// Generation flags.
  126. class Flags {
  127. enum {
  128. F_IsForEH = 0x1,
  129. F_IsNormalCleanupKind = 0x2,
  130. F_IsEHCleanupKind = 0x4,
  131. F_HasExitSwitch = 0x8,
  132. };
  133. unsigned flags;
  134. public:
  135. Flags() : flags(0) {}
  136. /// isForEH - true if the current emission is for an EH cleanup.
  137. bool isForEHCleanup() const { return flags & F_IsForEH; }
  138. bool isForNormalCleanup() const { return !isForEHCleanup(); }
  139. void setIsForEHCleanup() { flags |= F_IsForEH; }
  140. bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
  141. void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
  142. /// isEHCleanupKind - true if the cleanup was pushed as an EH
  143. /// cleanup.
  144. bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
  145. void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
  146. bool hasExitSwitch() const { return flags & F_HasExitSwitch; }
  147. void setHasExitSwitch() { flags |= F_HasExitSwitch; }
  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 CGF this Stack belong to
  194. CodeGenFunction* CGF;
  195. /// The current set of branch fixups. A branch fixup is a jump to
  196. /// an as-yet unemitted label, i.e. a label for which we don't yet
  197. /// know the EH stack depth. Whenever we pop a cleanup, we have
  198. /// to thread all the current branch fixups through it.
  199. ///
  200. /// Fixups are recorded as the Use of the respective branch or
  201. /// switch statement. The use points to the final destination.
  202. /// When popping out of a cleanup, these uses are threaded through
  203. /// the cleanup and adjusted to point to the new cleanup.
  204. ///
  205. /// Note that branches are allowed to jump into protected scopes
  206. /// in certain situations; e.g. the following code is legal:
  207. /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
  208. /// goto foo;
  209. /// A a;
  210. /// foo:
  211. /// bar();
  212. SmallVector<BranchFixup, 8> BranchFixups;
  213. char *allocate(size_t Size);
  214. void deallocate(size_t Size);
  215. void *pushCleanup(CleanupKind K, size_t DataSize);
  216. public:
  217. EHScopeStack()
  218. : StartOfBuffer(nullptr), EndOfBuffer(nullptr), StartOfData(nullptr),
  219. InnermostNormalCleanup(stable_end()), InnermostEHScope(stable_end()),
  220. CGF(nullptr) {}
  221. ~EHScopeStack() { delete[] StartOfBuffer; }
  222. /// Push a lazily-created cleanup on the stack.
  223. template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
  224. static_assert(alignof(T) <= ScopeStackAlignment,
  225. "Cleanup's alignment is too large.");
  226. void *Buffer = pushCleanup(Kind, sizeof(T));
  227. Cleanup *Obj = new (Buffer) T(A...);
  228. (void) Obj;
  229. }
  230. /// Push a lazily-created cleanup on the stack. Tuple version.
  231. template <class T, class... As>
  232. void pushCleanupTuple(CleanupKind Kind, std::tuple<As...> A) {
  233. static_assert(alignof(T) <= ScopeStackAlignment,
  234. "Cleanup's alignment is too large.");
  235. void *Buffer = pushCleanup(Kind, sizeof(T));
  236. Cleanup *Obj = new (Buffer) T(std::move(A));
  237. (void) Obj;
  238. }
  239. // Feel free to add more variants of the following:
  240. /// Push a cleanup with non-constant storage requirements on the
  241. /// stack. The cleanup type must provide an additional static method:
  242. /// static size_t getExtraSize(size_t);
  243. /// The argument to this method will be the value N, which will also
  244. /// be passed as the first argument to the constructor.
  245. ///
  246. /// The data stored in the extra storage must obey the same
  247. /// restrictions as normal cleanup member data.
  248. ///
  249. /// The pointer returned from this method is valid until the cleanup
  250. /// stack is modified.
  251. template <class T, class... As>
  252. T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) {
  253. static_assert(alignof(T) <= ScopeStackAlignment,
  254. "Cleanup's alignment is too large.");
  255. void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
  256. return new (Buffer) T(N, A...);
  257. }
  258. void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
  259. void *Buffer = pushCleanup(Kind, Size);
  260. std::memcpy(Buffer, Cleanup, Size);
  261. }
  262. void setCGF(CodeGenFunction *inCGF) { CGF = inCGF; }
  263. /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
  264. void popCleanup();
  265. /// Push a set of catch handlers on the stack. The catch is
  266. /// uninitialized and will need to have the given number of handlers
  267. /// set on it.
  268. class EHCatchScope *pushCatch(unsigned NumHandlers);
  269. /// Pops a catch scope off the stack. This is private to CGException.cpp.
  270. void popCatch();
  271. /// Push an exceptions filter on the stack.
  272. class EHFilterScope *pushFilter(unsigned NumFilters);
  273. /// Pops an exceptions filter off the stack.
  274. void popFilter();
  275. /// Push a terminate handler on the stack.
  276. void pushTerminate();
  277. /// Pops a terminate handler off the stack.
  278. void popTerminate();
  279. // Returns true iff the current scope is either empty or contains only
  280. // lifetime markers, i.e. no real cleanup code
  281. bool containsOnlyLifetimeMarkers(stable_iterator Old) const;
  282. /// Determines whether the exception-scopes stack is empty.
  283. bool empty() const { return StartOfData == EndOfBuffer; }
  284. bool requiresLandingPad() const;
  285. /// Determines whether there are any normal cleanups on the stack.
  286. bool hasNormalCleanups() const {
  287. return InnermostNormalCleanup != stable_end();
  288. }
  289. /// Returns the innermost normal cleanup on the stack, or
  290. /// stable_end() if there are no normal cleanups.
  291. stable_iterator getInnermostNormalCleanup() const {
  292. return InnermostNormalCleanup;
  293. }
  294. stable_iterator getInnermostActiveNormalCleanup() const;
  295. stable_iterator getInnermostEHScope() const {
  296. return InnermostEHScope;
  297. }
  298. /// An unstable reference to a scope-stack depth. Invalidated by
  299. /// pushes but not pops.
  300. class iterator;
  301. /// Returns an iterator pointing to the innermost EH scope.
  302. iterator begin() const;
  303. /// Returns an iterator pointing to the outermost EH scope.
  304. iterator end() const;
  305. /// Create a stable reference to the top of the EH stack. The
  306. /// returned reference is valid until that scope is popped off the
  307. /// stack.
  308. stable_iterator stable_begin() const {
  309. return stable_iterator(EndOfBuffer - StartOfData);
  310. }
  311. /// Create a stable reference to the bottom of the EH stack.
  312. static stable_iterator stable_end() {
  313. return stable_iterator(0);
  314. }
  315. /// Translates an iterator into a stable_iterator.
  316. stable_iterator stabilize(iterator it) const;
  317. /// Turn a stable reference to a scope depth into a unstable pointer
  318. /// to the EH stack.
  319. iterator find(stable_iterator save) const;
  320. /// Add a branch fixup to the current cleanup scope.
  321. BranchFixup &addBranchFixup() {
  322. assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
  323. BranchFixups.push_back(BranchFixup());
  324. return BranchFixups.back();
  325. }
  326. unsigned getNumBranchFixups() const { return BranchFixups.size(); }
  327. BranchFixup &getBranchFixup(unsigned I) {
  328. assert(I < getNumBranchFixups());
  329. return BranchFixups[I];
  330. }
  331. /// Pops lazily-removed fixups from the end of the list. This
  332. /// should only be called by procedures which have just popped a
  333. /// cleanup or resolved one or more fixups.
  334. void popNullFixups();
  335. /// Clears the branch-fixups list. This should only be called by
  336. /// ResolveAllBranchFixups.
  337. void clearFixups() { BranchFixups.clear(); }
  338. };
  339. } // namespace CodeGen
  340. } // namespace clang
  341. #endif