blob: c147fcefafbc9d95a47d77fe6324625aaf371a97 [file] [log] [blame]
Reid Klecknerd29f1342013-06-19 17:07:50 +00001//===-- 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
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +000016#ifndef LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
17#define LLVM_CLANG_LIB_CODEGEN_EHSCOPESTACK_H
Reid Klecknerd29f1342013-06-19 17:07:50 +000018
19#include "clang/Basic/LLVM.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/IR/BasicBlock.h"
Reid Klecknerd29f1342013-06-19 17:07:50 +000022#include "llvm/IR/Instructions.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "llvm/IR/Value.h"
Reid Klecknerd29f1342013-06-19 17:07:50 +000024
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 =
Benjamin Kramered2f4762014-03-07 14:30:23 +000068 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>
Reid Klecknerd29f1342013-06-19 17:07:50 +000071struct 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
Reid Klecknerc311aba2014-10-31 23:33:56 +000077enum CleanupKind : unsigned {
Reid Klecknerd29f1342013-06-19 17:07:50 +000078 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
Craig Topper4f12f102014-03-12 06:41:41 +0000185 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000186 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
Craig Topper4f12f102014-03-12 06:41:41 +0000202 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000203 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
Craig Topper4f12f102014-03-12 06:41:41 +0000222 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000223 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
Craig Topper4f12f102014-03-12 06:41:41 +0000245 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000246 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:
Craig Topper8a13c412014-05-21 05:09:00 +0000304 EHScopeStack() : StartOfBuffer(nullptr), EndOfBuffer(nullptr),
305 StartOfData(nullptr), InnermostNormalCleanup(stable_end()),
Reid Klecknerd29f1342013-06-19 17:07:50 +0000306 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.
Benjamin Kramerc582c892015-02-15 20:11:22 +0000312 template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000313 void *Buffer = pushCleanup(Kind, sizeof(T));
Benjamin Kramerc582c892015-02-15 20:11:22 +0000314 Cleanup *Obj = new (Buffer) T(A...);
Reid Klecknerd29f1342013-06-19 17:07:50 +0000315 (void) Obj;
316 }
317
318 // Feel free to add more variants of the following:
319
320 /// Push a cleanup with non-constant storage requirements on the
321 /// stack. The cleanup type must provide an additional static method:
322 /// static size_t getExtraSize(size_t);
323 /// The argument to this method will be the value N, which will also
324 /// be passed as the first argument to the constructor.
325 ///
326 /// The data stored in the extra storage must obey the same
327 /// restrictions as normal cleanup member data.
328 ///
329 /// The pointer returned from this method is valid until the cleanup
330 /// stack is modified.
Benjamin Kramerc582c892015-02-15 20:11:22 +0000331 template <class T, class... As>
Benjamin Kramer583089c2015-02-15 20:24:47 +0000332 T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) {
Reid Klecknerd29f1342013-06-19 17:07:50 +0000333 void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
Benjamin Kramerc582c892015-02-15 20:11:22 +0000334 return new (Buffer) T(N, A...);
Reid Klecknerd29f1342013-06-19 17:07:50 +0000335 }
336
337 void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
338 void *Buffer = pushCleanup(Kind, Size);
339 std::memcpy(Buffer, Cleanup, Size);
340 }
341
342 /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
343 void popCleanup();
344
345 /// Push a set of catch handlers on the stack. The catch is
346 /// uninitialized and will need to have the given number of handlers
347 /// set on it.
348 class EHCatchScope *pushCatch(unsigned NumHandlers);
349
350 /// Pops a catch scope off the stack. This is private to CGException.cpp.
351 void popCatch();
352
353 /// Push an exceptions filter on the stack.
354 class EHFilterScope *pushFilter(unsigned NumFilters);
355
356 /// Pops an exceptions filter off the stack.
357 void popFilter();
358
359 /// Push a terminate handler on the stack.
360 void pushTerminate();
361
362 /// Pops a terminate handler off the stack.
363 void popTerminate();
364
365 /// Determines whether the exception-scopes stack is empty.
366 bool empty() const { return StartOfData == EndOfBuffer; }
367
368 bool requiresLandingPad() const {
369 return InnermostEHScope != stable_end();
370 }
371
372 /// Determines whether there are any normal cleanups on the stack.
373 bool hasNormalCleanups() const {
374 return InnermostNormalCleanup != stable_end();
375 }
376
377 /// Returns the innermost normal cleanup on the stack, or
378 /// stable_end() if there are no normal cleanups.
379 stable_iterator getInnermostNormalCleanup() const {
380 return InnermostNormalCleanup;
381 }
382 stable_iterator getInnermostActiveNormalCleanup() const;
383
384 stable_iterator getInnermostEHScope() const {
385 return InnermostEHScope;
386 }
387
388 stable_iterator getInnermostActiveEHScope() const;
389
390 /// An unstable reference to a scope-stack depth. Invalidated by
391 /// pushes but not pops.
392 class iterator;
393
394 /// Returns an iterator pointing to the innermost EH scope.
395 iterator begin() const;
396
397 /// Returns an iterator pointing to the outermost EH scope.
398 iterator end() const;
399
400 /// Create a stable reference to the top of the EH stack. The
401 /// returned reference is valid until that scope is popped off the
402 /// stack.
403 stable_iterator stable_begin() const {
404 return stable_iterator(EndOfBuffer - StartOfData);
405 }
406
407 /// Create a stable reference to the bottom of the EH stack.
408 static stable_iterator stable_end() {
409 return stable_iterator(0);
410 }
411
412 /// Translates an iterator into a stable_iterator.
413 stable_iterator stabilize(iterator it) const;
414
415 /// Turn a stable reference to a scope depth into a unstable pointer
416 /// to the EH stack.
417 iterator find(stable_iterator save) const;
418
419 /// Removes the cleanup pointed to by the given stable_iterator.
420 void removeCleanup(stable_iterator save);
421
422 /// Add a branch fixup to the current cleanup scope.
423 BranchFixup &addBranchFixup() {
424 assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
425 BranchFixups.push_back(BranchFixup());
426 return BranchFixups.back();
427 }
428
429 unsigned getNumBranchFixups() const { return BranchFixups.size(); }
430 BranchFixup &getBranchFixup(unsigned I) {
431 assert(I < getNumBranchFixups());
432 return BranchFixups[I];
433 }
434
435 /// Pops lazily-removed fixups from the end of the list. This
436 /// should only be called by procedures which have just popped a
437 /// cleanup or resolved one or more fixups.
438 void popNullFixups();
439
440 /// Clears the branch-fixups list. This should only be called by
441 /// ResolveAllBranchFixups.
442 void clearFixups() { BranchFixups.clear(); }
443};
444
445} // namespace CodeGen
446} // namespace clang
447
448#endif