blob: b5a64d0a28a7742ba84d9d098aa23f36badb33ce [file] [log] [blame]
John McCalled1ae862011-01-28 11:13:47 +00001//===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
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// This file contains code dealing with the IR generation for cleanups
11// and related information.
12//
13// A "cleanup" is a piece of code which needs to be executed whenever
14// control transfers out of a particular scope. This can be
15// conditionalized to occur only on exceptional control flow, only on
16// normal control flow, or both.
17//
18//===----------------------------------------------------------------------===//
19
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Reid Kleckner2da7fcd2013-06-09 16:56:53 +000021#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000022
23using namespace clang;
24using namespace CodeGen;
25
26bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27 if (rv.isScalar())
28 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29 if (rv.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +000030 return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
John McCalled1ae862011-01-28 11:13:47 +000031 return true;
32}
33
34DominatingValue<RValue>::saved_type
35DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36 if (rv.isScalar()) {
37 llvm::Value *V = rv.getScalarVal();
38
39 // These automatically dominate and don't need to be saved.
40 if (!DominatingLLVMValue::needsSaving(V))
41 return saved_type(V, ScalarLiteral);
42
43 // Everything else needs an alloca.
John McCall7f416cc2015-09-08 08:05:57 +000044 Address addr =
45 CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
John McCalled1ae862011-01-28 11:13:47 +000046 CGF.Builder.CreateStore(V, addr);
John McCall7f416cc2015-09-08 08:05:57 +000047 return saved_type(addr.getPointer(), ScalarAddress);
John McCalled1ae862011-01-28 11:13:47 +000048 }
49
50 if (rv.isComplex()) {
51 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
Chris Lattner2192fe52011-07-18 04:24:23 +000052 llvm::Type *ComplexTy =
Chris Lattner845511f2011-06-18 22:49:11 +000053 llvm::StructType::get(V.first->getType(), V.second->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +000054 (void*) nullptr);
John McCall7f416cc2015-09-08 08:05:57 +000055 Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
David Blaikie1ed728c2015-04-05 22:45:47 +000056 CGF.Builder.CreateStore(V.first,
John McCall7f416cc2015-09-08 08:05:57 +000057 CGF.Builder.CreateStructGEP(addr, 0, CharUnits()));
58 CharUnits offset = CharUnits::fromQuantity(
59 CGF.CGM.getDataLayout().getTypeAllocSize(V.first->getType()));
David Blaikie1ed728c2015-04-05 22:45:47 +000060 CGF.Builder.CreateStore(V.second,
John McCall7f416cc2015-09-08 08:05:57 +000061 CGF.Builder.CreateStructGEP(addr, 1, offset));
62 return saved_type(addr.getPointer(), ComplexAddress);
John McCalled1ae862011-01-28 11:13:47 +000063 }
64
65 assert(rv.isAggregate());
John McCall7f416cc2015-09-08 08:05:57 +000066 Address V = rv.getAggregateAddress(); // TODO: volatile?
67 if (!DominatingLLVMValue::needsSaving(V.getPointer()))
68 return saved_type(V.getPointer(), AggregateLiteral,
69 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000070
John McCall7f416cc2015-09-08 08:05:57 +000071 Address addr =
72 CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
73 CGF.Builder.CreateStore(V.getPointer(), addr);
74 return saved_type(addr.getPointer(), AggregateAddress,
75 V.getAlignment().getQuantity());
John McCalled1ae862011-01-28 11:13:47 +000076}
77
78/// Given a saved r-value produced by SaveRValue, perform the code
79/// necessary to restore it to usability at the current insertion
80/// point.
81RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +000082 auto getSavingAddress = [&](llvm::Value *value) {
83 auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
84 return Address(value, CharUnits::fromQuantity(alignment));
85 };
John McCalled1ae862011-01-28 11:13:47 +000086 switch (K) {
87 case ScalarLiteral:
88 return RValue::get(Value);
89 case ScalarAddress:
John McCall7f416cc2015-09-08 08:05:57 +000090 return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
John McCalled1ae862011-01-28 11:13:47 +000091 case AggregateLiteral:
John McCall7f416cc2015-09-08 08:05:57 +000092 return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
93 case AggregateAddress: {
94 auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
95 return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
96 }
John McCall47fb9502013-03-07 21:37:08 +000097 case ComplexAddress: {
John McCall7f416cc2015-09-08 08:05:57 +000098 Address address = getSavingAddress(Value);
99 llvm::Value *real = CGF.Builder.CreateLoad(
100 CGF.Builder.CreateStructGEP(address, 0, CharUnits()));
101 CharUnits offset = CharUnits::fromQuantity(
102 CGF.CGM.getDataLayout().getTypeAllocSize(real->getType()));
103 llvm::Value *imag = CGF.Builder.CreateLoad(
104 CGF.Builder.CreateStructGEP(address, 1, offset));
John McCall47fb9502013-03-07 21:37:08 +0000105 return RValue::getComplex(real, imag);
106 }
John McCalled1ae862011-01-28 11:13:47 +0000107 }
108
109 llvm_unreachable("bad saved r-value kind");
John McCalled1ae862011-01-28 11:13:47 +0000110}
111
112/// Push an entry of the given size onto this protected-scope stack.
113char *EHScopeStack::allocate(size_t Size) {
James Y Knight53c76162015-07-17 18:21:37 +0000114 Size = llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
John McCalled1ae862011-01-28 11:13:47 +0000115 if (!StartOfBuffer) {
116 unsigned Capacity = 1024;
117 while (Capacity < Size) Capacity *= 2;
118 StartOfBuffer = new char[Capacity];
119 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
120 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
121 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
122 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
123
124 unsigned NewCapacity = CurrentCapacity;
125 do {
126 NewCapacity *= 2;
127 } while (NewCapacity < UsedCapacity + Size);
128
129 char *NewStartOfBuffer = new char[NewCapacity];
130 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
131 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
132 memcpy(NewStartOfData, StartOfData, UsedCapacity);
133 delete [] StartOfBuffer;
134 StartOfBuffer = NewStartOfBuffer;
135 EndOfBuffer = NewEndOfBuffer;
136 StartOfData = NewStartOfData;
137 }
138
139 assert(StartOfBuffer + Size <= StartOfData);
140 StartOfData -= Size;
141 return StartOfData;
142}
143
James Y Knight53c76162015-07-17 18:21:37 +0000144void EHScopeStack::deallocate(size_t Size) {
145 StartOfData += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
146}
147
David Majnemerdc012fa2015-04-22 21:38:15 +0000148bool EHScopeStack::containsOnlyLifetimeMarkers(
149 EHScopeStack::stable_iterator Old) const {
150 for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
151 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
152 if (!cleanup || !cleanup->isLifetimeMarker())
153 return false;
154 }
155
156 return true;
157}
158
John McCalled1ae862011-01-28 11:13:47 +0000159EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000160EHScopeStack::getInnermostActiveNormalCleanup() const {
161 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
162 si != se; ) {
163 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
164 if (cleanup.isActive()) return si;
165 si = cleanup.getEnclosingNormalCleanup();
166 }
167 return stable_end();
168}
169
170EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
171 for (stable_iterator si = getInnermostEHScope(), se = stable_end();
172 si != se; ) {
173 // Skip over inactive cleanups.
174 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
175 if (cleanup && !cleanup->isActive()) {
176 si = cleanup->getEnclosingEHScope();
177 continue;
John McCalled1ae862011-01-28 11:13:47 +0000178 }
John McCall8e4c74b2011-08-11 02:22:43 +0000179
180 // All other scopes are always active.
181 return si;
182 }
183
John McCalled1ae862011-01-28 11:13:47 +0000184 return stable_end();
185}
186
187
188void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCalled1ae862011-01-28 11:13:47 +0000189 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
190 bool IsNormalCleanup = Kind & NormalCleanup;
191 bool IsEHCleanup = Kind & EHCleanup;
192 bool IsActive = !(Kind & InactiveCleanup);
193 EHCleanupScope *Scope =
194 new (Buffer) EHCleanupScope(IsNormalCleanup,
195 IsEHCleanup,
196 IsActive,
197 Size,
198 BranchFixups.size(),
199 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000200 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000201 if (IsNormalCleanup)
202 InnermostNormalCleanup = stable_begin();
203 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000204 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000205
206 return Scope->getCleanupBuffer();
207}
208
209void EHScopeStack::popCleanup() {
210 assert(!empty() && "popping exception stack when not empty");
211
212 assert(isa<EHCleanupScope>(*begin()));
213 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
214 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
John McCall8e4c74b2011-08-11 02:22:43 +0000215 InnermostEHScope = Cleanup.getEnclosingEHScope();
James Y Knight53c76162015-07-17 18:21:37 +0000216 deallocate(Cleanup.getAllocatedSize());
John McCalled1ae862011-01-28 11:13:47 +0000217
John McCalled1ae862011-01-28 11:13:47 +0000218 // Destroy the cleanup.
Kostya Serebryanyb21aa762014-10-08 18:31:54 +0000219 Cleanup.Destroy();
John McCalled1ae862011-01-28 11:13:47 +0000220
221 // Check whether we can shrink the branch-fixups stack.
222 if (!BranchFixups.empty()) {
223 // If we no longer have any normal cleanups, all the fixups are
224 // complete.
225 if (!hasNormalCleanups())
226 BranchFixups.clear();
227
228 // Otherwise we can still trim out unnecessary nulls.
229 else
230 popNullFixups();
231 }
232}
233
John McCall8e4c74b2011-08-11 02:22:43 +0000234EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
235 assert(getInnermostEHScope() == stable_end());
236 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
237 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
238 InnermostEHScope = stable_begin();
239 return filter;
John McCalled1ae862011-01-28 11:13:47 +0000240}
241
242void EHScopeStack::popFilter() {
243 assert(!empty() && "popping exception stack when not empty");
244
John McCall8e4c74b2011-08-11 02:22:43 +0000245 EHFilterScope &filter = cast<EHFilterScope>(*begin());
James Y Knight53c76162015-07-17 18:21:37 +0000246 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
John McCalled1ae862011-01-28 11:13:47 +0000247
John McCall8e4c74b2011-08-11 02:22:43 +0000248 InnermostEHScope = filter.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000249}
250
John McCall8e4c74b2011-08-11 02:22:43 +0000251EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
252 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
253 EHCatchScope *scope =
254 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
255 InnermostEHScope = stable_begin();
256 return scope;
John McCalled1ae862011-01-28 11:13:47 +0000257}
258
259void EHScopeStack::pushTerminate() {
260 char *Buffer = allocate(EHTerminateScope::getSize());
John McCall8e4c74b2011-08-11 02:22:43 +0000261 new (Buffer) EHTerminateScope(InnermostEHScope);
262 InnermostEHScope = stable_begin();
John McCalled1ae862011-01-28 11:13:47 +0000263}
264
David Majnemerdbf10452015-07-31 17:58:45 +0000265void EHScopeStack::pushCatchEnd(llvm::BasicBlock *CatchEndBlockBB) {
266 char *Buffer = allocate(EHCatchEndScope::getSize());
267 auto *CES = new (Buffer) EHCatchEndScope(InnermostEHScope);
268 CES->setCachedEHDispatchBlock(CatchEndBlockBB);
269 InnermostEHScope = stable_begin();
270}
271
John McCalled1ae862011-01-28 11:13:47 +0000272/// Remove any 'null' fixups on the stack. However, we can't pop more
273/// fixups than the fixup depth on the innermost normal cleanup, or
274/// else fixups that we try to add to that cleanup will end up in the
275/// wrong place. We *could* try to shrink fixup depths, but that's
276/// actually a lot of work for little benefit.
277void EHScopeStack::popNullFixups() {
278 // We expect this to only be called when there's still an innermost
279 // normal cleanup; otherwise there really shouldn't be any fixups.
280 assert(hasNormalCleanups());
281
282 EHScopeStack::iterator it = find(InnermostNormalCleanup);
283 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
284 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
285
286 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000287 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000288 BranchFixups.pop_back();
289}
290
291void CodeGenFunction::initFullExprCleanup() {
292 // Create a variable to decide whether the cleanup needs to be run.
John McCall7f416cc2015-09-08 08:05:57 +0000293 Address active = CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
294 "cleanup.cond");
John McCalled1ae862011-01-28 11:13:47 +0000295
296 // Initialize it to false at a site that's guaranteed to be run
297 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000298 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000299
300 // Initialize it to true at the current location.
301 Builder.CreateStore(Builder.getTrue(), active);
302
303 // Set that as the active flag in the cleanup.
304 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
John McCall7f416cc2015-09-08 08:05:57 +0000305 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000306 cleanup.setActiveFlag(active);
307
308 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
309 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
310}
311
John McCall5fcf8da2011-07-12 00:15:30 +0000312void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000313
John McCall7f416cc2015-09-08 08:05:57 +0000314static void createStoreInstBefore(llvm::Value *value, Address addr,
315 llvm::Instruction *beforeInst) {
316 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
317 store->setAlignment(addr.getAlignment().getQuantity());
318}
319
320static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
321 llvm::Instruction *beforeInst) {
322 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
323 load->setAlignment(addr.getAlignment().getQuantity());
324 return load;
325}
326
John McCalled1ae862011-01-28 11:13:47 +0000327/// All the branch fixups on the EH stack have propagated out past the
328/// outermost normal cleanup; resolve them all by adding cases to the
329/// given switch instruction.
330static void ResolveAllBranchFixups(CodeGenFunction &CGF,
331 llvm::SwitchInst *Switch,
332 llvm::BasicBlock *CleanupEntry) {
333 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
334
335 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
336 // Skip this fixup if its destination isn't set.
337 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000338 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000339
340 // If there isn't an OptimisticBranchBlock, then InitialBranch is
341 // still pointing directly to its destination; forward it to the
342 // appropriate cleanup entry. This is required in the specific
343 // case of
344 // { std::string s; goto lbl; }
345 // lbl:
346 // i.e. where there's an unresolved fixup inside a single cleanup
347 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000348 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +0000349 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
350 CGF.getNormalCleanupDestSlot(),
351 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000352 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
353 }
354
355 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000356 if (!CasesAdded.insert(Fixup.Destination).second)
357 continue;
John McCalled1ae862011-01-28 11:13:47 +0000358
359 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
360 Fixup.Destination);
361 }
362
363 CGF.EHStack.clearFixups();
364}
365
366/// Transitions the terminator of the given exit-block of a cleanup to
367/// be a cleanup switch.
368static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
369 llvm::BasicBlock *Block) {
370 // If it's a branch, turn it into a switch whose default
371 // destination is its original target.
372 llvm::TerminatorInst *Term = Block->getTerminator();
373 assert(Term && "can't transition block without terminator");
374
375 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
376 assert(Br->isUnconditional());
John McCall7f416cc2015-09-08 08:05:57 +0000377 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
378 "cleanup.dest", Term);
John McCalled1ae862011-01-28 11:13:47 +0000379 llvm::SwitchInst *Switch =
380 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
381 Br->eraseFromParent();
382 return Switch;
383 } else {
384 return cast<llvm::SwitchInst>(Term);
385 }
386}
387
388void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
389 assert(Block && "resolving a null target block");
390 if (!EHStack.getNumBranchFixups()) return;
391
392 assert(EHStack.hasNormalCleanups() &&
393 "branch fixups exist with no normal cleanups on stack");
394
395 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
396 bool ResolvedAny = false;
397
398 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
399 // Skip this fixup if its destination doesn't match.
400 BranchFixup &Fixup = EHStack.getBranchFixup(I);
401 if (Fixup.Destination != Block) continue;
402
Craig Topper8a13c412014-05-21 05:09:00 +0000403 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000404 ResolvedAny = true;
405
406 // If it doesn't have an optimistic branch block, LatestBranch is
407 // already pointing to the right place.
408 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
409 if (!BranchBB)
410 continue;
411
412 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000413 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000414 continue;
415
416 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
417
418 // Add a case to the switch.
419 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
420 }
421
422 if (ResolvedAny)
423 EHStack.popNullFixups();
424}
425
426/// Pops cleanup blocks until the given savepoint is reached.
Adrian Prantldc237b52013-05-16 00:41:26 +0000427void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
John McCalled1ae862011-01-28 11:13:47 +0000428 assert(Old.isValid());
429
430 while (EHStack.stable_begin() != Old) {
431 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
432
433 // As long as Old strictly encloses the scope's enclosing normal
434 // cleanup, we're going to emit another normal cleanup which
435 // fallthrough can propagate through.
436 bool FallThroughIsBranchThrough =
437 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
438
Adrian Prantldc237b52013-05-16 00:41:26 +0000439 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000440 }
441}
442
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000443/// Pops cleanup blocks until the given savepoint is reached, then add the
444/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Richard Smith736a9472013-06-12 20:42:33 +0000445void
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000446CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
447 size_t OldLifetimeExtendedSize) {
448 PopCleanupBlocks(Old);
449
450 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000451 for (size_t I = OldLifetimeExtendedSize,
452 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
453 // Alignment should be guaranteed by the vptrs in the individual cleanups.
454 assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
455 "misaligned cleanup stack entry");
456
457 LifetimeExtendedCleanupHeader &Header =
458 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
459 LifetimeExtendedCleanupStack[I]);
460 I += sizeof(Header);
461
462 EHStack.pushCopyOfCleanup(Header.getKind(),
463 &LifetimeExtendedCleanupStack[I],
464 Header.getSize());
465 I += Header.getSize();
466 }
467 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
468}
469
John McCalled1ae862011-01-28 11:13:47 +0000470static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
471 EHCleanupScope &Scope) {
472 assert(Scope.isNormalCleanup());
473 llvm::BasicBlock *Entry = Scope.getNormalBlock();
474 if (!Entry) {
475 Entry = CGF.createBasicBlock("cleanup");
476 Scope.setNormalBlock(Entry);
477 }
478 return Entry;
479}
480
John McCalled1ae862011-01-28 11:13:47 +0000481/// Attempts to reduce a cleanup's entry block to a fallthrough. This
482/// is basically llvm::MergeBlockIntoPredecessor, except
483/// simplified/optimized for the tighter constraints on cleanup blocks.
484///
485/// Returns the new block, whatever it is.
486static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
487 llvm::BasicBlock *Entry) {
488 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
489 if (!Pred) return Entry;
490
491 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
492 if (!Br || Br->isConditional()) return Entry;
493 assert(Br->getSuccessor(0) == Entry);
494
495 // If we were previously inserting at the end of the cleanup entry
496 // block, we'll need to continue inserting at the end of the
497 // predecessor.
498 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
499 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
500
501 // Kill the branch.
502 Br->eraseFromParent();
503
John McCalled1ae862011-01-28 11:13:47 +0000504 // Replace all uses of the entry with the predecessor, in case there
505 // are phis in the cleanup.
506 Entry->replaceAllUsesWith(Pred);
507
Jay Foade03c05c2011-06-20 14:38:01 +0000508 // Merge the blocks.
509 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
510
John McCalled1ae862011-01-28 11:13:47 +0000511 // Kill the entry block.
512 Entry->eraseFromParent();
513
514 if (WasInsertBlock)
515 CGF.Builder.SetInsertPoint(Pred);
516
517 return Pred;
518}
519
520static void EmitCleanup(CodeGenFunction &CGF,
521 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000522 EHScopeStack::Cleanup::Flags flags,
John McCall7f416cc2015-09-08 08:05:57 +0000523 Address ActiveFlag) {
Reid Klecknere5b06422015-04-08 22:48:50 +0000524 // Itanium EH cleanups occur within a terminate scope. Microsoft SEH doesn't
525 // have this behavior, and the Microsoft C++ runtime will call terminate for
526 // us if the cleanup throws.
527 bool PushedTerminate = false;
528 if (flags.isForEHCleanup() && !CGF.getTarget().getCXXABI().isMicrosoft()) {
529 CGF.EHStack.pushTerminate();
530 PushedTerminate = true;
531 }
John McCalled1ae862011-01-28 11:13:47 +0000532
533 // If there's an active flag, load it and skip the cleanup if it's
534 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000535 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000536 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000537 ContBB = CGF.createBasicBlock("cleanup.done");
538 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
539 llvm::Value *IsActive
540 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
541 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
542 CGF.EmitBlock(CleanupBB);
543 }
544
545 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000546 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000547 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
548
549 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000550 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000551 CGF.EmitBlock(ContBB);
552
553 // Leave the terminate scope.
Reid Klecknere5b06422015-04-08 22:48:50 +0000554 if (PushedTerminate)
555 CGF.EHStack.popTerminate();
John McCalled1ae862011-01-28 11:13:47 +0000556}
557
558static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
559 llvm::BasicBlock *From,
560 llvm::BasicBlock *To) {
561 // Exit is the exit block of a cleanup, so it always terminates in
562 // an unconditional branch or a switch.
563 llvm::TerminatorInst *Term = Exit->getTerminator();
564
565 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
566 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
567 Br->setSuccessor(0, To);
568 } else {
569 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
570 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
571 if (Switch->getSuccessor(I) == From)
572 Switch->setSuccessor(I, To);
573 }
574}
575
John McCallf82bdf62011-08-06 06:53:52 +0000576/// We don't need a normal entry block for the given cleanup.
577/// Optimistic fixup branches can cause these blocks to come into
578/// existence anyway; if so, destroy it.
579///
580/// The validity of this transformation is very much specific to the
581/// exact ways in which we form branches to cleanup entries.
582static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
583 EHCleanupScope &scope) {
584 llvm::BasicBlock *entry = scope.getNormalBlock();
585 if (!entry) return;
586
587 // Replace all the uses with unreachable.
588 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
589 for (llvm::BasicBlock::use_iterator
590 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000591 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000592 ++i;
593
594 use.set(unreachableBB);
595
596 // The only uses should be fixup switches.
597 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000598 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000599 // Replace the switch with a branch.
Stepan Dyatkovskiyfe3b0692012-03-11 06:09:37 +0000600 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000601
602 // The switch operand is a load from the cleanup-dest alloca.
603 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
604
605 // Destroy the switch.
606 si->eraseFromParent();
607
608 // Destroy the load.
609 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
610 assert(condition->use_empty());
611 condition->eraseFromParent();
612 }
613 }
614
615 assert(entry->use_empty());
616 delete entry;
617}
618
John McCalled1ae862011-01-28 11:13:47 +0000619/// Pops a cleanup block. If the block includes a normal cleanup, the
620/// current insertion point is threaded through the cleanup, as are
621/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000622void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000623 assert(!EHStack.empty() && "cleanup stack is empty!");
624 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
625 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
626 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
627
628 // Remember activation information.
629 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address NormalActiveFlag =
631 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
632 : Address::invalid();
633 Address EHActiveFlag =
634 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
635 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000636
637 // Check whether we need an EH cleanup. This is only true if we've
638 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000639 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000640 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
641 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000642 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000643
644 // Check the three conditions which might require a normal cleanup:
645
646 // - whether there are branch fix-ups through this cleanup
647 unsigned FixupDepth = Scope.getFixupDepth();
648 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
649
650 // - whether there are branch-throughs or branch-afters
651 bool HasExistingBranches = Scope.hasBranches();
652
653 // - whether there's a fallthrough
654 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000655 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000656
657 // Branch-through fall-throughs leave the insertion point set to the
658 // end of the last cleanup, which points to the current scope. The
659 // rest of IR gen doesn't need to worry about this; it only happens
660 // during the execution of PopCleanupBlocks().
661 bool HasPrebranchedFallthrough =
662 (FallthroughSource && FallthroughSource->getTerminator());
663
664 // If this is a normal cleanup, then having a prebranched
665 // fallthrough implies that the fallthrough source unconditionally
666 // jumps here.
667 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
668 (Scope.getNormalBlock() &&
669 FallthroughSource->getTerminator()->getSuccessor(0)
670 == Scope.getNormalBlock()));
671
672 bool RequiresNormalCleanup = false;
673 if (Scope.isNormalCleanup() &&
674 (HasFixups || HasExistingBranches || HasFallthrough)) {
675 RequiresNormalCleanup = true;
676 }
677
John McCall45e42952011-08-07 07:05:57 +0000678 // If we have a prebranched fallthrough into an inactive normal
679 // cleanup, rewrite it so that it leads to the appropriate place.
680 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
681 llvm::BasicBlock *prebranchDest;
682
683 // If the prebranch is semantically branching through the next
684 // cleanup, just forward it to the next block, leaving the
685 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000686 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000687 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
688 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000689
John McCall45e42952011-08-07 07:05:57 +0000690 // Otherwise, we need to make a new block. If the normal cleanup
691 // isn't being used at all, we could actually reuse the normal
692 // entry block, but this is simpler, and it avoids conflicts with
693 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000694 } else {
John McCall45e42952011-08-07 07:05:57 +0000695 prebranchDest = createBasicBlock("forwarded-prebranch");
696 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000697 }
John McCall45e42952011-08-07 07:05:57 +0000698
699 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
700 assert(normalEntry && !normalEntry->use_empty());
701
702 ForwardPrebranchedFallthrough(FallthroughSource,
703 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000704 }
705
706 // If we don't need the cleanup at all, we're done.
707 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000708 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000709 EHStack.popCleanup(); // safe because there are no fixups
710 assert(EHStack.getNumBranchFixups() == 0 ||
711 EHStack.hasNormalCleanups());
712 return;
713 }
714
715 // Copy the cleanup emission data out. Note that SmallVector
716 // guarantees maximal alignment for its buffer regardless of its
717 // type parameter.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000718 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
719 SmallVector<char, 8 * sizeof(void *)> CleanupBuffer(
720 CleanupSource, CleanupSource + Scope.getCleanupSize());
721 auto *Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBuffer.data());
John McCalled1ae862011-01-28 11:13:47 +0000722
John McCall8e4c74b2011-08-11 02:22:43 +0000723 EHScopeStack::Cleanup::Flags cleanupFlags;
724 if (Scope.isNormalCleanup())
725 cleanupFlags.setIsNormalCleanupKind();
726 if (Scope.isEHCleanup())
727 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000728
729 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000730 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000731 EHStack.popCleanup();
732 } else {
733 // If we have a fallthrough and no other need for the cleanup,
734 // emit it directly.
735 if (HasFallthrough && !HasPrebranchedFallthrough &&
736 !HasFixups && !HasExistingBranches) {
737
John McCallf82bdf62011-08-06 06:53:52 +0000738 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000739 EHStack.popCleanup();
740
John McCall30317fd2011-07-12 20:27:29 +0000741 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000742
743 // Otherwise, the best approach is to thread everything through
744 // the cleanup block and then try to clean up after ourselves.
745 } else {
746 // Force the entry block to exist.
747 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
748
749 // I. Set up the fallthrough edge in.
750
John McCalla3654e32011-08-10 04:11:11 +0000751 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000752
John McCalled1ae862011-01-28 11:13:47 +0000753 // If there's a fallthrough, we need to store the cleanup
754 // destination index. For fall-throughs this is always zero.
755 if (HasFallthrough) {
756 if (!HasPrebranchedFallthrough)
757 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
758
John McCall45e42952011-08-07 07:05:57 +0000759 // Otherwise, save and clear the IP if we don't have fallthrough
760 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000761 } else if (FallthroughSource) {
762 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000763 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000764 }
765
766 // II. Emit the entry block. This implicitly branches to it if
767 // we have fallthrough. All the fixups and existing branches
768 // should already be branched to it.
769 EmitBlock(NormalEntry);
770
771 // III. Figure out where we're going and build the cleanup
772 // epilogue.
773
774 bool HasEnclosingCleanups =
775 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
776
777 // Compute the branch-through dest if we need it:
778 // - if there are branch-throughs threaded through the scope
779 // - if fall-through is a branch-through
780 // - if there are fixups that will be optimistically forwarded
781 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000782 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000783 if (Scope.hasBranchThroughs() ||
784 (FallthroughSource && FallthroughIsBranchThrough) ||
785 (HasFixups && HasEnclosingCleanups)) {
786 assert(HasEnclosingCleanups);
787 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
788 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
789 }
790
Craig Topper8a13c412014-05-21 05:09:00 +0000791 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000792 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000793
794 // If there's exactly one branch-after and no other threads,
795 // we can route it without a switch.
796 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
797 Scope.getNumBranchAfters() == 1) {
798 assert(!BranchThroughDest || !IsActive);
799
David Majnemerdc012fa2015-04-22 21:38:15 +0000800 // Clean up the possibly dead store to the cleanup dest slot.
801 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000802 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000803 if (NormalCleanupDestSlot->hasOneUse()) {
804 NormalCleanupDestSlot->user_back()->eraseFromParent();
805 NormalCleanupDestSlot->eraseFromParent();
806 NormalCleanupDest = nullptr;
807 }
808
John McCalled1ae862011-01-28 11:13:47 +0000809 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
810 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
811
812 // Build a switch-out if we need it:
813 // - if there are branch-afters threaded through the scope
814 // - if fall-through is a branch-after
815 // - if there are fixups that have nowhere left to go and
816 // so must be immediately resolved
817 } else if (Scope.getNumBranchAfters() ||
818 (HasFallthrough && !FallthroughIsBranchThrough) ||
819 (HasFixups && !HasEnclosingCleanups)) {
820
821 llvm::BasicBlock *Default =
822 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
823
824 // TODO: base this on the number of branch-afters and fixups
825 const unsigned SwitchCapacity = 10;
826
827 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000828 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
829 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000830 llvm::SwitchInst *Switch =
831 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
832
833 InstsToAppend.push_back(Load);
834 InstsToAppend.push_back(Switch);
835
836 // Branch-after fallthrough.
837 if (FallthroughSource && !FallthroughIsBranchThrough) {
838 FallthroughDest = createBasicBlock("cleanup.cont");
839 if (HasFallthrough)
840 Switch->addCase(Builder.getInt32(0), FallthroughDest);
841 }
842
843 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
844 Switch->addCase(Scope.getBranchAfterIndex(I),
845 Scope.getBranchAfterBlock(I));
846 }
847
848 // If there aren't any enclosing cleanups, we can resolve all
849 // the fixups now.
850 if (HasFixups && !HasEnclosingCleanups)
851 ResolveAllBranchFixups(*this, Switch, NormalEntry);
852 } else {
853 // We should always have a branch-through destination in this case.
854 assert(BranchThroughDest);
855 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
856 }
857
858 // IV. Pop the cleanup and emit it.
859 EHStack.popCleanup();
860 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
861
John McCall30317fd2011-07-12 20:27:29 +0000862 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000863
864 // Append the prepared cleanup prologue from above.
865 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000866 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
867 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000868
869 // Optimistically hope that any fixups will continue falling through.
870 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
871 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000872 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000873 if (!Fixup.Destination) continue;
874 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000875 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
876 getNormalCleanupDestSlot(),
877 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000878 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
879 }
880 Fixup.OptimisticBranchBlock = NormalExit;
881 }
882
883 // V. Set up the fallthrough edge out.
884
John McCall45e42952011-08-07 07:05:57 +0000885 // Case 1: a fallthrough source exists but doesn't branch to the
886 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000887 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000888 // Prebranched fallthrough was forwarded earlier.
889 // Non-prebranched fallthrough doesn't need to be forwarded.
890 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000891 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000892 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000893
894 // Case 2: a fallthrough source exists and should branch to the
895 // cleanup, but we're not supposed to branch through to the next
896 // cleanup.
897 } else if (HasFallthrough && FallthroughDest) {
898 assert(!FallthroughIsBranchThrough);
899 EmitBlock(FallthroughDest);
900
901 // Case 3: a fallthrough source exists and should branch to the
902 // cleanup and then through to the next.
903 } else if (HasFallthrough) {
904 // Everything is already set up for this.
905
906 // Case 4: no fallthrough source exists.
907 } else {
908 Builder.ClearInsertionPoint();
909 }
910
911 // VI. Assorted cleaning.
912
913 // Check whether we can merge NormalEntry into a single predecessor.
914 // This might invalidate (non-IR) pointers to NormalEntry.
915 llvm::BasicBlock *NewNormalEntry =
916 SimplifyCleanupEntry(*this, NormalEntry);
917
918 // If it did invalidate those pointers, and NormalEntry was the same
919 // as NormalExit, go back and patch up the fixups.
920 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
921 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
922 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000923 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000924 }
925 }
926
927 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
928
929 // Emit the EH cleanup if required.
930 if (RequiresEHCleanup) {
931 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
932
933 EmitBlock(EHEntry);
David Majnemere888a2f2015-08-15 03:21:08 +0000934 llvm::CleanupPadInst *CPI = nullptr;
David Majnemerdbf10452015-07-31 17:58:45 +0000935 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
936 if (CGM.getCodeGenOpts().NewMSEH &&
David Majnemere888a2f2015-08-15 03:21:08 +0000937 EHPersonality::get(*this).isMSVCPersonality())
Joseph Tremouletce536a52015-08-23 00:26:48 +0000938 CPI = Builder.CreateCleanupPad({});
John McCall30317fd2011-07-12 20:27:29 +0000939
Eli Friedmanabab7762012-08-02 00:10:24 +0000940 // We only actually emit the cleanup code if the cleanup is either
941 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +0000942 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +0000943 cleanupFlags.setIsForEHCleanup();
944 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
945 }
John McCalled1ae862011-01-28 11:13:47 +0000946
David Majnemere888a2f2015-08-15 03:21:08 +0000947 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +0000948 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +0000949 else
950 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000951
952 Builder.restoreIP(SavedIP);
953
954 SimplifyCleanupEntry(*this, EHEntry);
955 }
956}
957
Justin Bognere25ffdf2014-01-21 00:35:11 +0000958/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
959/// specified destination obviously has no cleanups to run. 'false' is always
960/// a conservatively correct answer for this method.
961bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
962 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
963 && "stale jump destination");
964
965 // Calculate the innermost active normal cleanup.
966 EHScopeStack::stable_iterator TopCleanup =
967 EHStack.getInnermostActiveNormalCleanup();
968
969 // If we're not in an active normal cleanup scope, or if the
970 // destination scope is within the innermost active normal cleanup
971 // scope, we don't need to worry about fixups.
972 if (TopCleanup == EHStack.stable_end() ||
973 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
974 return true;
975
976 // Otherwise, we might need some cleanups.
977 return false;
978}
979
980
John McCalled1ae862011-01-28 11:13:47 +0000981/// Terminate the current block by emitting a branch which might leave
982/// the current cleanup-protected scope. The target scope may not yet
983/// be known, in which case this will require a fixup.
984///
985/// As a side-effect, this method clears the insertion point.
986void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +0000987 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +0000988 && "stale jump destination");
989
990 if (!HaveInsertPoint())
991 return;
992
993 // Create the branch.
994 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
995
996 // Calculate the innermost active normal cleanup.
997 EHScopeStack::stable_iterator
998 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
999
1000 // If we're not in an active normal cleanup scope, or if the
1001 // destination scope is within the innermost active normal cleanup
1002 // scope, we don't need to worry about fixups.
1003 if (TopCleanup == EHStack.stable_end() ||
1004 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1005 Builder.ClearInsertionPoint();
1006 return;
1007 }
1008
1009 // If we can't resolve the destination cleanup scope, just add this
1010 // to the current cleanup scope as a branch fixup.
1011 if (!Dest.getScopeDepth().isValid()) {
1012 BranchFixup &Fixup = EHStack.addBranchFixup();
1013 Fixup.Destination = Dest.getBlock();
1014 Fixup.DestinationIndex = Dest.getDestIndex();
1015 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001016 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001017
1018 Builder.ClearInsertionPoint();
1019 return;
1020 }
1021
1022 // Otherwise, thread through all the normal cleanups in scope.
1023
1024 // Store the index at the start.
1025 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001026 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001027
1028 // Adjust BI to point to the first cleanup block.
1029 {
1030 EHCleanupScope &Scope =
1031 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1032 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1033 }
1034
1035 // Add this destination to all the scopes involved.
1036 EHScopeStack::stable_iterator I = TopCleanup;
1037 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1038 if (E.strictlyEncloses(I)) {
1039 while (true) {
1040 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1041 assert(Scope.isNormalCleanup());
1042 I = Scope.getEnclosingNormalCleanup();
1043
1044 // If this is the last cleanup we're propagating through, tell it
1045 // that there's a resolved jump moving through it.
1046 if (!E.strictlyEncloses(I)) {
1047 Scope.addBranchAfter(Index, Dest.getBlock());
1048 break;
1049 }
1050
1051 // Otherwise, tell the scope that there's a jump propoagating
1052 // through it. If this isn't new information, all the rest of
1053 // the work has been done before.
1054 if (!Scope.addBranchThrough(Dest.getBlock()))
1055 break;
1056 }
1057 }
1058
1059 Builder.ClearInsertionPoint();
1060}
1061
John McCalled1ae862011-01-28 11:13:47 +00001062static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1063 EHScopeStack::stable_iterator C) {
1064 // If we needed a normal block for any reason, that counts.
1065 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1066 return true;
1067
1068 // Check whether any enclosed cleanups were needed.
1069 for (EHScopeStack::stable_iterator
1070 I = EHStack.getInnermostNormalCleanup();
1071 I != C; ) {
1072 assert(C.strictlyEncloses(I));
1073 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1074 if (S.getNormalBlock()) return true;
1075 I = S.getEnclosingNormalCleanup();
1076 }
1077
1078 return false;
1079}
1080
1081static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001082 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001083 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001084 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001085 return true;
1086
1087 // Check whether any enclosed cleanups were needed.
1088 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001089 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1090 assert(cleanup.strictlyEncloses(i));
1091
1092 EHScope &scope = *EHStack.find(i);
1093 if (scope.hasEHBranches())
1094 return true;
1095
1096 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001097 }
1098
1099 return false;
1100}
1101
1102enum ForActivation_t {
1103 ForActivation,
1104 ForDeactivation
1105};
1106
1107/// The given cleanup block is changing activation state. Configure a
1108/// cleanup variable if necessary.
1109///
1110/// It would be good if we had some way of determining if there were
1111/// extra uses *after* the change-over point.
1112static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1113 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001114 ForActivation_t kind,
1115 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001116 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1117
John McCalle63abb52011-11-10 09:22:44 +00001118 // We always need the flag if we're activating the cleanup in a
1119 // conditional context, because we have to assume that the current
1120 // location doesn't necessarily dominate the cleanup's code.
1121 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001122 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001123
1124 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001125
1126 // Calculate whether the cleanup was used:
1127
1128 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001129 if (Scope.isNormalCleanup() &&
1130 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001131 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001132 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001133 }
1134
1135 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001136 if (Scope.isEHCleanup() &&
1137 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001138 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001139 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001140 }
1141
1142 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001143 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001144
John McCall7f416cc2015-09-08 08:05:57 +00001145 Address var = Scope.getActiveFlag();
1146 if (!var.isValid()) {
1147 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1148 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001149 Scope.setActiveFlag(var);
1150
1151 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001152
1153 // Initialize to true or false depending on whether it was
1154 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001155 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001156
1157 // If we're in a conditional block, ignore the dominating IP and
1158 // use the outermost conditional branch.
1159 if (CGF.isInConditionalBranch()) {
1160 CGF.setBeforeOutermostConditional(value, var);
1161 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001162 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001163 }
John McCalled1ae862011-01-28 11:13:47 +00001164 }
1165
John McCallf4beacd2011-11-10 10:43:54 +00001166 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001167}
1168
1169/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001170void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1171 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001172 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1173 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1174 assert(!Scope.isActive() && "double activation");
1175
John McCallf4beacd2011-11-10 10:43:54 +00001176 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001177
1178 Scope.setActive(true);
1179}
1180
1181/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001182void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1183 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001184 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1185 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1186 assert(Scope.isActive() && "double deactivation");
1187
1188 // If it's the top of the stack, just pop it.
1189 if (C == EHStack.stable_begin()) {
1190 // If it's a normal cleanup, we need to pretend that the
1191 // fallthrough is unreachable.
1192 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1193 PopCleanupBlock();
1194 Builder.restoreIP(SavedIP);
1195 return;
1196 }
1197
1198 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001199 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001200
1201 Scope.setActive(false);
1202}
1203
John McCall7f416cc2015-09-08 08:05:57 +00001204Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCalled1ae862011-01-28 11:13:47 +00001205 if (!NormalCleanupDest)
1206 NormalCleanupDest =
1207 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
John McCall7f416cc2015-09-08 08:05:57 +00001208 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
John McCalled1ae862011-01-28 11:13:47 +00001209}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001210
1211/// Emits all the code to cause the given temporary to be cleaned up.
1212void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1213 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001214 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001215 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001216 /*useEHCleanup*/ true);
1217}