blob: 8bad58d78b7df34cb64b71a35994ffed131e5c2b [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
Reid Kleckner2586aac2015-09-10 22:11:13 +0000265void EHScopeStack::pushPadEnd(llvm::BasicBlock *PadEndBB) {
266 char *Buffer = allocate(EHPadEndScope::getSize());
267 auto *CES = new (Buffer) EHPadEndScope(InnermostEHScope);
268 CES->setCachedEHDispatchBlock(PadEndBB);
David Majnemerdbf10452015-07-31 17:58:45 +0000269 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) {
John McCalled1ae862011-01-28 11:13:47 +0000524 // If there's an active flag, load it and skip the cleanup if it's
525 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000526 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000527 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000528 ContBB = CGF.createBasicBlock("cleanup.done");
529 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
530 llvm::Value *IsActive
531 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
532 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
533 CGF.EmitBlock(CleanupBB);
534 }
535
536 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000537 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000538 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
539
540 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000541 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000542 CGF.EmitBlock(ContBB);
John McCalled1ae862011-01-28 11:13:47 +0000543}
544
545static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
546 llvm::BasicBlock *From,
547 llvm::BasicBlock *To) {
548 // Exit is the exit block of a cleanup, so it always terminates in
549 // an unconditional branch or a switch.
550 llvm::TerminatorInst *Term = Exit->getTerminator();
551
552 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
553 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
554 Br->setSuccessor(0, To);
555 } else {
556 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
557 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
558 if (Switch->getSuccessor(I) == From)
559 Switch->setSuccessor(I, To);
560 }
561}
562
John McCallf82bdf62011-08-06 06:53:52 +0000563/// We don't need a normal entry block for the given cleanup.
564/// Optimistic fixup branches can cause these blocks to come into
565/// existence anyway; if so, destroy it.
566///
567/// The validity of this transformation is very much specific to the
568/// exact ways in which we form branches to cleanup entries.
569static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
570 EHCleanupScope &scope) {
571 llvm::BasicBlock *entry = scope.getNormalBlock();
572 if (!entry) return;
573
574 // Replace all the uses with unreachable.
575 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
576 for (llvm::BasicBlock::use_iterator
577 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000578 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000579 ++i;
580
581 use.set(unreachableBB);
582
583 // The only uses should be fixup switches.
584 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000585 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000586 // Replace the switch with a branch.
Stepan Dyatkovskiyfe3b0692012-03-11 06:09:37 +0000587 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000588
589 // The switch operand is a load from the cleanup-dest alloca.
590 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
591
592 // Destroy the switch.
593 si->eraseFromParent();
594
595 // Destroy the load.
596 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
597 assert(condition->use_empty());
598 condition->eraseFromParent();
599 }
600 }
601
602 assert(entry->use_empty());
603 delete entry;
604}
605
John McCalled1ae862011-01-28 11:13:47 +0000606/// Pops a cleanup block. If the block includes a normal cleanup, the
607/// current insertion point is threaded through the cleanup, as are
608/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000609void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000610 assert(!EHStack.empty() && "cleanup stack is empty!");
611 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
612 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
613 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
614
615 // Remember activation information.
616 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000617 Address NormalActiveFlag =
618 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
619 : Address::invalid();
620 Address EHActiveFlag =
621 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
622 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000623
624 // Check whether we need an EH cleanup. This is only true if we've
625 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000626 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000627 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
628 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000629 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000630
631 // Check the three conditions which might require a normal cleanup:
632
633 // - whether there are branch fix-ups through this cleanup
634 unsigned FixupDepth = Scope.getFixupDepth();
635 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
636
637 // - whether there are branch-throughs or branch-afters
638 bool HasExistingBranches = Scope.hasBranches();
639
640 // - whether there's a fallthrough
641 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000642 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000643
644 // Branch-through fall-throughs leave the insertion point set to the
645 // end of the last cleanup, which points to the current scope. The
646 // rest of IR gen doesn't need to worry about this; it only happens
647 // during the execution of PopCleanupBlocks().
648 bool HasPrebranchedFallthrough =
649 (FallthroughSource && FallthroughSource->getTerminator());
650
651 // If this is a normal cleanup, then having a prebranched
652 // fallthrough implies that the fallthrough source unconditionally
653 // jumps here.
654 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
655 (Scope.getNormalBlock() &&
656 FallthroughSource->getTerminator()->getSuccessor(0)
657 == Scope.getNormalBlock()));
658
659 bool RequiresNormalCleanup = false;
660 if (Scope.isNormalCleanup() &&
661 (HasFixups || HasExistingBranches || HasFallthrough)) {
662 RequiresNormalCleanup = true;
663 }
664
John McCall45e42952011-08-07 07:05:57 +0000665 // If we have a prebranched fallthrough into an inactive normal
666 // cleanup, rewrite it so that it leads to the appropriate place.
667 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
668 llvm::BasicBlock *prebranchDest;
669
670 // If the prebranch is semantically branching through the next
671 // cleanup, just forward it to the next block, leaving the
672 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000673 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000674 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
675 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000676
John McCall45e42952011-08-07 07:05:57 +0000677 // Otherwise, we need to make a new block. If the normal cleanup
678 // isn't being used at all, we could actually reuse the normal
679 // entry block, but this is simpler, and it avoids conflicts with
680 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000681 } else {
John McCall45e42952011-08-07 07:05:57 +0000682 prebranchDest = createBasicBlock("forwarded-prebranch");
683 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000684 }
John McCall45e42952011-08-07 07:05:57 +0000685
686 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
687 assert(normalEntry && !normalEntry->use_empty());
688
689 ForwardPrebranchedFallthrough(FallthroughSource,
690 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000691 }
692
693 // If we don't need the cleanup at all, we're done.
694 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000695 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000696 EHStack.popCleanup(); // safe because there are no fixups
697 assert(EHStack.getNumBranchFixups() == 0 ||
698 EHStack.hasNormalCleanups());
699 return;
700 }
701
702 // Copy the cleanup emission data out. Note that SmallVector
703 // guarantees maximal alignment for its buffer regardless of its
704 // type parameter.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000705 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
706 SmallVector<char, 8 * sizeof(void *)> CleanupBuffer(
707 CleanupSource, CleanupSource + Scope.getCleanupSize());
708 auto *Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBuffer.data());
John McCalled1ae862011-01-28 11:13:47 +0000709
John McCall8e4c74b2011-08-11 02:22:43 +0000710 EHScopeStack::Cleanup::Flags cleanupFlags;
711 if (Scope.isNormalCleanup())
712 cleanupFlags.setIsNormalCleanupKind();
713 if (Scope.isEHCleanup())
714 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000715
716 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000717 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000718 EHStack.popCleanup();
719 } else {
720 // If we have a fallthrough and no other need for the cleanup,
721 // emit it directly.
722 if (HasFallthrough && !HasPrebranchedFallthrough &&
723 !HasFixups && !HasExistingBranches) {
724
John McCallf82bdf62011-08-06 06:53:52 +0000725 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000726 EHStack.popCleanup();
727
John McCall30317fd2011-07-12 20:27:29 +0000728 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000729
730 // Otherwise, the best approach is to thread everything through
731 // the cleanup block and then try to clean up after ourselves.
732 } else {
733 // Force the entry block to exist.
734 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
735
736 // I. Set up the fallthrough edge in.
737
John McCalla3654e32011-08-10 04:11:11 +0000738 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000739
John McCalled1ae862011-01-28 11:13:47 +0000740 // If there's a fallthrough, we need to store the cleanup
741 // destination index. For fall-throughs this is always zero.
742 if (HasFallthrough) {
743 if (!HasPrebranchedFallthrough)
744 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
745
John McCall45e42952011-08-07 07:05:57 +0000746 // Otherwise, save and clear the IP if we don't have fallthrough
747 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000748 } else if (FallthroughSource) {
749 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000750 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000751 }
752
753 // II. Emit the entry block. This implicitly branches to it if
754 // we have fallthrough. All the fixups and existing branches
755 // should already be branched to it.
756 EmitBlock(NormalEntry);
757
758 // III. Figure out where we're going and build the cleanup
759 // epilogue.
760
761 bool HasEnclosingCleanups =
762 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
763
764 // Compute the branch-through dest if we need it:
765 // - if there are branch-throughs threaded through the scope
766 // - if fall-through is a branch-through
767 // - if there are fixups that will be optimistically forwarded
768 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000769 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000770 if (Scope.hasBranchThroughs() ||
771 (FallthroughSource && FallthroughIsBranchThrough) ||
772 (HasFixups && HasEnclosingCleanups)) {
773 assert(HasEnclosingCleanups);
774 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
775 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
776 }
777
Craig Topper8a13c412014-05-21 05:09:00 +0000778 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000779 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000780
781 // If there's exactly one branch-after and no other threads,
782 // we can route it without a switch.
783 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
784 Scope.getNumBranchAfters() == 1) {
785 assert(!BranchThroughDest || !IsActive);
786
David Majnemerdc012fa2015-04-22 21:38:15 +0000787 // Clean up the possibly dead store to the cleanup dest slot.
788 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000789 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000790 if (NormalCleanupDestSlot->hasOneUse()) {
791 NormalCleanupDestSlot->user_back()->eraseFromParent();
792 NormalCleanupDestSlot->eraseFromParent();
793 NormalCleanupDest = nullptr;
794 }
795
John McCalled1ae862011-01-28 11:13:47 +0000796 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
797 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
798
799 // Build a switch-out if we need it:
800 // - if there are branch-afters threaded through the scope
801 // - if fall-through is a branch-after
802 // - if there are fixups that have nowhere left to go and
803 // so must be immediately resolved
804 } else if (Scope.getNumBranchAfters() ||
805 (HasFallthrough && !FallthroughIsBranchThrough) ||
806 (HasFixups && !HasEnclosingCleanups)) {
807
808 llvm::BasicBlock *Default =
809 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
810
811 // TODO: base this on the number of branch-afters and fixups
812 const unsigned SwitchCapacity = 10;
813
814 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000815 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
816 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000817 llvm::SwitchInst *Switch =
818 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
819
820 InstsToAppend.push_back(Load);
821 InstsToAppend.push_back(Switch);
822
823 // Branch-after fallthrough.
824 if (FallthroughSource && !FallthroughIsBranchThrough) {
825 FallthroughDest = createBasicBlock("cleanup.cont");
826 if (HasFallthrough)
827 Switch->addCase(Builder.getInt32(0), FallthroughDest);
828 }
829
830 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
831 Switch->addCase(Scope.getBranchAfterIndex(I),
832 Scope.getBranchAfterBlock(I));
833 }
834
835 // If there aren't any enclosing cleanups, we can resolve all
836 // the fixups now.
837 if (HasFixups && !HasEnclosingCleanups)
838 ResolveAllBranchFixups(*this, Switch, NormalEntry);
839 } else {
840 // We should always have a branch-through destination in this case.
841 assert(BranchThroughDest);
842 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
843 }
844
845 // IV. Pop the cleanup and emit it.
846 EHStack.popCleanup();
847 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
848
John McCall30317fd2011-07-12 20:27:29 +0000849 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000850
851 // Append the prepared cleanup prologue from above.
852 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000853 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
854 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000855
856 // Optimistically hope that any fixups will continue falling through.
857 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
858 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000859 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000860 if (!Fixup.Destination) continue;
861 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000862 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
863 getNormalCleanupDestSlot(),
864 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000865 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
866 }
867 Fixup.OptimisticBranchBlock = NormalExit;
868 }
869
870 // V. Set up the fallthrough edge out.
871
John McCall45e42952011-08-07 07:05:57 +0000872 // Case 1: a fallthrough source exists but doesn't branch to the
873 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000874 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000875 // Prebranched fallthrough was forwarded earlier.
876 // Non-prebranched fallthrough doesn't need to be forwarded.
877 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000878 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000879 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000880
881 // Case 2: a fallthrough source exists and should branch to the
882 // cleanup, but we're not supposed to branch through to the next
883 // cleanup.
884 } else if (HasFallthrough && FallthroughDest) {
885 assert(!FallthroughIsBranchThrough);
886 EmitBlock(FallthroughDest);
887
888 // Case 3: a fallthrough source exists and should branch to the
889 // cleanup and then through to the next.
890 } else if (HasFallthrough) {
891 // Everything is already set up for this.
892
893 // Case 4: no fallthrough source exists.
894 } else {
895 Builder.ClearInsertionPoint();
896 }
897
898 // VI. Assorted cleaning.
899
900 // Check whether we can merge NormalEntry into a single predecessor.
901 // This might invalidate (non-IR) pointers to NormalEntry.
902 llvm::BasicBlock *NewNormalEntry =
903 SimplifyCleanupEntry(*this, NormalEntry);
904
905 // If it did invalidate those pointers, and NormalEntry was the same
906 // as NormalExit, go back and patch up the fixups.
907 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
908 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
909 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000910 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000911 }
912 }
913
914 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
915
916 // Emit the EH cleanup if required.
917 if (RequiresEHCleanup) {
918 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
919
920 EmitBlock(EHEntry);
Reid Kleckner55391522015-10-08 21:14:56 +0000921
922 // Push terminate scopes around the potentially throwing destructor calls.
923 // We don't emit these when using funclets, because the runtime does it for
924 // us as part of unwinding out of a cleanuppad.
925 bool PushedTerminate = false;
926 if (!EHPersonality::get(*this).usesFuncletPads()) {
927 EHStack.pushTerminate();
928 PushedTerminate = true;
929 }
930
David Majnemere888a2f2015-08-15 03:21:08 +0000931 llvm::CleanupPadInst *CPI = nullptr;
Reid Kleckner55391522015-10-08 21:14:56 +0000932 llvm::BasicBlock *CleanupEndBB = nullptr;
David Majnemerdbf10452015-07-31 17:58:45 +0000933 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
Reid Kleckner55391522015-10-08 21:14:56 +0000934 if (EHPersonality::get(*this).usesFuncletPads()) {
Joseph Tremouletce536a52015-08-23 00:26:48 +0000935 CPI = Builder.CreateCleanupPad({});
John McCall30317fd2011-07-12 20:27:29 +0000936
Reid Kleckner55391522015-10-08 21:14:56 +0000937 // Build a cleanupendpad to unwind through. Our insertion point should be
938 // in the cleanuppad block.
939 CleanupEndBB = createBasicBlock("ehcleanup.end");
940 CGBuilderTy(*this, CleanupEndBB).CreateCleanupEndPad(CPI, NextAction);
941 EHStack.pushPadEnd(CleanupEndBB);
942 }
943
Eli Friedmanabab7762012-08-02 00:10:24 +0000944 // We only actually emit the cleanup code if the cleanup is either
945 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +0000946 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +0000947 cleanupFlags.setIsForEHCleanup();
948 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
949 }
John McCalled1ae862011-01-28 11:13:47 +0000950
David Majnemere888a2f2015-08-15 03:21:08 +0000951 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +0000952 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +0000953 else
954 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000955
Reid Kleckner55391522015-10-08 21:14:56 +0000956 // Insert the cleanupendpad block here, if it has any uses.
957 if (CleanupEndBB) {
958 EHStack.popPadEnd();
959 if (CleanupEndBB->hasNUsesOrMore(1)) {
960 CurFn->getBasicBlockList().insertAfter(Builder.GetInsertBlock(),
961 CleanupEndBB);
962 } else {
963 delete CleanupEndBB;
964 }
965 }
966
967 // Leave the terminate scope.
968 if (PushedTerminate)
969 EHStack.popTerminate();
970
John McCalled1ae862011-01-28 11:13:47 +0000971 Builder.restoreIP(SavedIP);
972
973 SimplifyCleanupEntry(*this, EHEntry);
974 }
975}
976
Justin Bognere25ffdf2014-01-21 00:35:11 +0000977/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
978/// specified destination obviously has no cleanups to run. 'false' is always
979/// a conservatively correct answer for this method.
980bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
981 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
982 && "stale jump destination");
983
984 // Calculate the innermost active normal cleanup.
985 EHScopeStack::stable_iterator TopCleanup =
986 EHStack.getInnermostActiveNormalCleanup();
987
988 // If we're not in an active normal cleanup scope, or if the
989 // destination scope is within the innermost active normal cleanup
990 // scope, we don't need to worry about fixups.
991 if (TopCleanup == EHStack.stable_end() ||
992 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
993 return true;
994
995 // Otherwise, we might need some cleanups.
996 return false;
997}
998
999
John McCalled1ae862011-01-28 11:13:47 +00001000/// Terminate the current block by emitting a branch which might leave
1001/// the current cleanup-protected scope. The target scope may not yet
1002/// be known, in which case this will require a fixup.
1003///
1004/// As a side-effect, this method clears the insertion point.
1005void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +00001006 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +00001007 && "stale jump destination");
1008
1009 if (!HaveInsertPoint())
1010 return;
1011
1012 // Create the branch.
1013 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1014
1015 // Calculate the innermost active normal cleanup.
1016 EHScopeStack::stable_iterator
1017 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1018
1019 // If we're not in an active normal cleanup scope, or if the
1020 // destination scope is within the innermost active normal cleanup
1021 // scope, we don't need to worry about fixups.
1022 if (TopCleanup == EHStack.stable_end() ||
1023 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1024 Builder.ClearInsertionPoint();
1025 return;
1026 }
1027
1028 // If we can't resolve the destination cleanup scope, just add this
1029 // to the current cleanup scope as a branch fixup.
1030 if (!Dest.getScopeDepth().isValid()) {
1031 BranchFixup &Fixup = EHStack.addBranchFixup();
1032 Fixup.Destination = Dest.getBlock();
1033 Fixup.DestinationIndex = Dest.getDestIndex();
1034 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001035 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001036
1037 Builder.ClearInsertionPoint();
1038 return;
1039 }
1040
1041 // Otherwise, thread through all the normal cleanups in scope.
1042
1043 // Store the index at the start.
1044 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001045 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001046
1047 // Adjust BI to point to the first cleanup block.
1048 {
1049 EHCleanupScope &Scope =
1050 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1051 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1052 }
1053
1054 // Add this destination to all the scopes involved.
1055 EHScopeStack::stable_iterator I = TopCleanup;
1056 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1057 if (E.strictlyEncloses(I)) {
1058 while (true) {
1059 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1060 assert(Scope.isNormalCleanup());
1061 I = Scope.getEnclosingNormalCleanup();
1062
1063 // If this is the last cleanup we're propagating through, tell it
1064 // that there's a resolved jump moving through it.
1065 if (!E.strictlyEncloses(I)) {
1066 Scope.addBranchAfter(Index, Dest.getBlock());
1067 break;
1068 }
1069
1070 // Otherwise, tell the scope that there's a jump propoagating
1071 // through it. If this isn't new information, all the rest of
1072 // the work has been done before.
1073 if (!Scope.addBranchThrough(Dest.getBlock()))
1074 break;
1075 }
1076 }
1077
1078 Builder.ClearInsertionPoint();
1079}
1080
John McCalled1ae862011-01-28 11:13:47 +00001081static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1082 EHScopeStack::stable_iterator C) {
1083 // If we needed a normal block for any reason, that counts.
1084 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1085 return true;
1086
1087 // Check whether any enclosed cleanups were needed.
1088 for (EHScopeStack::stable_iterator
1089 I = EHStack.getInnermostNormalCleanup();
1090 I != C; ) {
1091 assert(C.strictlyEncloses(I));
1092 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1093 if (S.getNormalBlock()) return true;
1094 I = S.getEnclosingNormalCleanup();
1095 }
1096
1097 return false;
1098}
1099
1100static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001101 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001102 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001103 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001104 return true;
1105
1106 // Check whether any enclosed cleanups were needed.
1107 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001108 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1109 assert(cleanup.strictlyEncloses(i));
1110
1111 EHScope &scope = *EHStack.find(i);
1112 if (scope.hasEHBranches())
1113 return true;
1114
1115 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001116 }
1117
1118 return false;
1119}
1120
1121enum ForActivation_t {
1122 ForActivation,
1123 ForDeactivation
1124};
1125
1126/// The given cleanup block is changing activation state. Configure a
1127/// cleanup variable if necessary.
1128///
1129/// It would be good if we had some way of determining if there were
1130/// extra uses *after* the change-over point.
1131static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1132 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001133 ForActivation_t kind,
1134 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001135 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1136
John McCalle63abb52011-11-10 09:22:44 +00001137 // We always need the flag if we're activating the cleanup in a
1138 // conditional context, because we have to assume that the current
1139 // location doesn't necessarily dominate the cleanup's code.
1140 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001141 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001142
1143 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001144
1145 // Calculate whether the cleanup was used:
1146
1147 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001148 if (Scope.isNormalCleanup() &&
1149 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001150 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001151 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001152 }
1153
1154 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001155 if (Scope.isEHCleanup() &&
1156 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001157 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001158 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001159 }
1160
1161 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001162 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001163
John McCall7f416cc2015-09-08 08:05:57 +00001164 Address var = Scope.getActiveFlag();
1165 if (!var.isValid()) {
1166 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1167 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001168 Scope.setActiveFlag(var);
1169
1170 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001171
1172 // Initialize to true or false depending on whether it was
1173 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001174 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001175
1176 // If we're in a conditional block, ignore the dominating IP and
1177 // use the outermost conditional branch.
1178 if (CGF.isInConditionalBranch()) {
1179 CGF.setBeforeOutermostConditional(value, var);
1180 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001181 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001182 }
John McCalled1ae862011-01-28 11:13:47 +00001183 }
1184
John McCallf4beacd2011-11-10 10:43:54 +00001185 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001186}
1187
1188/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001189void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1190 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001191 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1192 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1193 assert(!Scope.isActive() && "double activation");
1194
John McCallf4beacd2011-11-10 10:43:54 +00001195 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001196
1197 Scope.setActive(true);
1198}
1199
1200/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001201void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1202 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001203 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1204 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1205 assert(Scope.isActive() && "double deactivation");
1206
1207 // If it's the top of the stack, just pop it.
1208 if (C == EHStack.stable_begin()) {
1209 // If it's a normal cleanup, we need to pretend that the
1210 // fallthrough is unreachable.
1211 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1212 PopCleanupBlock();
1213 Builder.restoreIP(SavedIP);
1214 return;
1215 }
1216
1217 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001218 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001219
1220 Scope.setActive(false);
1221}
1222
John McCall7f416cc2015-09-08 08:05:57 +00001223Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCalled1ae862011-01-28 11:13:47 +00001224 if (!NormalCleanupDest)
1225 NormalCleanupDest =
1226 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
John McCall7f416cc2015-09-08 08:05:57 +00001227 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
John McCalled1ae862011-01-28 11:13:47 +00001228}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001229
1230/// Emits all the code to cause the given temporary to be cleaned up.
1231void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1232 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001233 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001234 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001235 /*useEHCleanup*/ true);
1236}